RuleSetService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. <?php
  2. namespace App\Service;
  3. use App\Model\CalendarDetails;
  4. use App\Model\Device;
  5. use App\Model\Employee;
  6. use App\Model\Item;
  7. use App\Model\ItemDetails;
  8. use App\Model\RuleSet;
  9. use App\Model\RuleSetDetails;
  10. use Illuminate\Support\Facades\DB;
  11. class RuleSetService extends Service
  12. {
  13. public function ruleSetEdit($data,$user){
  14. list($status,$msg) = $this->ruleSetRule($data, $user, false);
  15. if(!$status) return [$status,$msg];
  16. try {
  17. DB::beginTransaction();
  18. $model = RuleSet::where('id',$data['id'])->first();
  19. // $model->code = $data['code'] ?? '';
  20. // $model->month = $data['month'] ?? 0;
  21. // $model->save();
  22. $time = time();
  23. RuleSetDetails::where('del_time',0)
  24. ->where('main_id', $model->id)
  25. ->update(['del_time' => $time]);
  26. $this->saveDetail($model->id, $time, $data);
  27. DB::commit();
  28. }catch (\Exception $exception){
  29. DB::rollBack();
  30. return [false,$exception->getMessage()];
  31. }
  32. return [true, ''];
  33. }
  34. public function ruleSetAdd($data,$user){
  35. list($status,$msg) = $this->ruleSetRule($data, $user);
  36. if(!$status) return [$status,$msg];
  37. try {
  38. DB::beginTransaction();
  39. $model = new RuleSet();
  40. $model->code = $this->generateBillNo([
  41. 'top_depart_id' => $user['top_depart_id'],
  42. 'type' => RuleSet::Order_type,
  43. 'period' => date("Ym", $data['month'])
  44. ]);
  45. $model->month = $data['month'] ?? 0;
  46. $model->crt_id = $user['id'];
  47. $model->top_depart_id = $data['top_depart_id'];
  48. $model->save();
  49. $this->saveDetail($model->id, time(), $data);
  50. DB::commit();
  51. }catch (\Exception $exception){
  52. DB::rollBack();
  53. return [false,$exception->getMessage()];
  54. }
  55. return [true, ''];
  56. }
  57. private function saveDetail($id, $time, $data){
  58. if(! empty($data['man_list'])){
  59. $unit = [];
  60. foreach ($data['man_list'] as $value){
  61. $unit[] = [
  62. 'main_id' => $id,
  63. 'item_id' => $value['item_id'],
  64. 'type' => $value['type'],
  65. 'data_id' => $value['data_id'],
  66. 'rate' => $value['rate'],
  67. 'crt_time' => $time,
  68. 'top_depart_id' => $value['top_depart_id'],
  69. ];
  70. }
  71. if(! empty($unit)) RuleSetDetails::insert($unit);
  72. }
  73. if(! empty($data['device_list'])){
  74. $receipt = [];
  75. foreach ($data['device_list'] as $value){
  76. $receipt[] = [
  77. 'main_id' => $id,
  78. 'item_id' => $value['item_id'],
  79. 'type' => $value['type'],
  80. 'data_id' => $value['data_id'],
  81. 'rate' => $value['rate'],
  82. 'crt_time' => $time,
  83. 'top_depart_id' => $value['top_depart_id'],
  84. ];
  85. }
  86. if(! empty($receipt)) RuleSetDetails::insert($receipt);
  87. }
  88. }
  89. private function getDetail($id){
  90. $data = RuleSetDetails::where('del_time',0)
  91. ->where('main_id', $id)
  92. ->get()->toArray();
  93. $id = $id2 = $item_id = [];
  94. foreach ($data as $value){
  95. if($value['type'] == RuleSetDetails::type_one) {
  96. $id[] = $value['data_id'];
  97. }else{
  98. $id2[] = $value['data_id'];
  99. }
  100. if(! in_array($value['item_id'], $item_id)) $item_id[] = $value['item_id'];
  101. }
  102. $map = Employee::whereIn('id', $id)->select('title','id','number')->get()->toArray();
  103. $map = array_column($map,null,'id');
  104. $map2 = Device::whereIn('id', $id2)->select('code','id','title')->get()->toArray();
  105. $map2 = array_column($map2,null,'id');
  106. $map3 = Item::whereIn('id', $item_id)->select('title','id','code')->get()->toArray();
  107. $map3 = array_column($map3,null,'id');
  108. $unit = $receipt = [];
  109. foreach ($data as $value){
  110. $item = $map3[$value['item_id']] ?? [];
  111. if($value['type'] == RuleSetDetails::type_one) {
  112. $tmp = $map[$value['data_id']] ?? [];
  113. $unit[] = [
  114. 'type' => $value['type'],
  115. 'rate' => $value['rate'],
  116. 'data_id' => $value['data_id'],
  117. 'data_title' => $tmp['title'],
  118. 'data_code' => $tmp['number'],
  119. 'item_id' => $value['item_id'],
  120. 'item_title' => $item['title'] ?? "",
  121. 'item_code' => $item['code'] ?? "",
  122. ];
  123. }else{
  124. $tmp = $map2[$value['data_id']] ?? [];
  125. $receipt[] = [
  126. 'type' => $value['type'],
  127. 'rate' => $value['rate'],
  128. 'data_id' => $value['data_id'],
  129. 'data_title' => $tmp['title'] ?? "",
  130. 'data_code' => $tmp['code'] ?? "",
  131. 'item_id' => $value['item_id'],
  132. 'item_title' => $item['title'] ?? "",
  133. 'item_code' => $item['code'] ?? "",
  134. ];
  135. }
  136. }
  137. $detail = [
  138. 'man_list' => $unit,
  139. 'device_list' => $receipt,
  140. ];
  141. //foreach ($detail as $key => $value) {
  142. // if (empty($value)) {
  143. //$detail[$key] = (object)[]; // 转成 stdClass 对象
  144. //}
  145. //}
  146. return $detail;
  147. }
  148. public function ruleSetDel($data){
  149. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  150. try {
  151. DB::beginTransaction();
  152. $time = time();
  153. RuleSet::where('del_time',0)
  154. ->whereIn('id',$data['id'])
  155. ->update(['del_time' => $time]);
  156. RuleSetDetails::where('del_time',0)
  157. ->whereIn('main_id', $data['id'])
  158. ->update(['del_time' => $time]);
  159. DB::commit();
  160. }catch (\Exception $exception){
  161. DB::rollBack();
  162. return [false,$exception->getMessage()];
  163. }
  164. return [true, ''];
  165. }
  166. public function ruleSetDetail($data, $user){
  167. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  168. $customer = RuleSet::where('del_time',0)
  169. ->where('id',$data['id'])
  170. ->first();
  171. if(empty($customer)) return [false,'规则配置单不存在或已被删除'];
  172. $customer = $customer->toArray();
  173. $customer['month'] = ! empty($customer['month']) ? date("Y-m", $customer['month']) : "";
  174. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  175. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  176. $details = $this->getDetail($data['id']);
  177. $customer = array_merge($customer, $details);
  178. return [true, $customer];
  179. }
  180. public function ruleSetCommon($data,$user, $field = []){
  181. if(empty($field)) $field = RuleSet::$field;
  182. $model = RuleSet::Clear($user,$data);
  183. $model = $model->where('del_time',0)
  184. ->select($field)
  185. ->orderby('id', 'desc');
  186. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  187. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  188. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  189. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  190. $model->where('crt_time','>=',$return[0]);
  191. $model->where('crt_time','<=',$return[1]);
  192. }
  193. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  194. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  195. $model->where('month','>=',$return[0]);
  196. $model->where('month','<=',$return[1]);
  197. }
  198. return $model;
  199. }
  200. public function ruleSetList($data,$user){
  201. $model = $this->ruleSetCommon($data, $user);
  202. $list = $this->limit($model,'',$data);
  203. $list = $this->fillData($list);
  204. return [true, $list];
  205. }
  206. public function ruleSetRule(&$data, $user, $is_add = true)
  207. {
  208. $data['top_depart_id'] = $user['top_depart_id'];
  209. if (empty($data['month'])) return [false, '月份不能为空'];
  210. $data['month'] = $this->changeDateToDate($data['month']);
  211. // --- 0. 批量预加载档案用于错误提示 (核心优化点) ---
  212. $manIds = array_unique(array_column($data['man_list'] ?? [], 'data_id'));
  213. $devIds = array_unique(array_column($data['device_list'] ?? [], 'data_id'));
  214. $manMap = Employee::whereIn('id', $manIds)->get(['id', 'number', 'title'])
  215. ->mapWithKeys(fn($item) => [$item->id => "[{$item->number}]{$item->title}"]);
  216. $devMap = Device::whereIn('id', $devIds)->get(['id', 'code', 'title'])
  217. ->mapWithKeys(fn($item) => [$item->id => "[{$item->code}]{$item->title}"]);
  218. // --- 1. 人员列表校验 ---
  219. if (empty($data['man_list'])) return [false, '人员不能为空'];
  220. $manRates = [];
  221. foreach ($data['man_list'] as $key => $value) {
  222. if (empty($value['type'])) return [false, '类型不能为空'];
  223. if (empty($value['data_id'])) return [false, '人员不能为空'];
  224. if (empty($value['item_id'])) return [false, '项目不能为空'];
  225. $res = $this->checkNumber($value['rate'], 2, 'non-negative');
  226. if (!$res['valid']) return [false, '人员工时分摊比例:' . $res['error']];
  227. $data['man_list'][$key]['top_depart_id'] = $data['top_depart_id'];
  228. $manId = $value['data_id'];
  229. $manRates[$manId] = ($manRates[$manId] ?? 0) + $value['rate'];
  230. }
  231. // 校验人员比例 (错误提示加入人名)
  232. foreach ($manRates as $mId => $total) {
  233. if (abs($total - 100) > 0.0001) {
  234. $displayName = $manMap[$mId] ?? "ID:{$mId}";
  235. return [false, "人员{$displayName}的分摊比例合计为{$total}%,必须等于100%"];
  236. }
  237. }
  238. // --- 2. 设备列表校验 ---
  239. if (! empty($data['device_list'])){
  240. $deviceRates = [];
  241. foreach ($data['device_list'] as $key => $value) {
  242. if (empty($value['type'])) return [false, '类型不能为空'];
  243. if (empty($value['data_id'])) return [false, '设备ID不能为空'];
  244. if (empty($value['item_id'])) return [false, '项目不能为空'];
  245. $res = $this->checkNumber($value['rate'], 2, 'non-negative');
  246. if (!$res['valid']) return [false, '设备工时分摊比例:' . $res['error']];
  247. $data['device_list'][$key]['top_depart_id'] = $data['top_depart_id'];
  248. $devId = $value['data_id'];
  249. $deviceRates[$devId] = ($deviceRates[$devId] ?? 0) + $value['rate'];
  250. }
  251. // 校验设备比例 (错误提示加入设备名称)
  252. foreach ($deviceRates as $dId => $total) {
  253. if (abs($total - 100) > 0.0001) {
  254. $displayName = $devMap[$dId] ?? "ID:{$dId}";
  255. return [false, "设备{$displayName}的分摊比例合计为{$total}%,必须等于100%"];
  256. }
  257. }
  258. }
  259. // --- 3. 重复单据校验 ---
  260. if ($is_add) {
  261. $bool = RuleSet::where('month', $data['month'])
  262. ->where('top_depart_id', $data['top_depart_id'])
  263. ->where('del_time', 0)
  264. ->exists();
  265. } else {
  266. if (empty($data['id'])) return [false, 'ID不能为空'];
  267. $bool = RuleSet::where('month', $data['month'])
  268. ->where('top_depart_id', $data['top_depart_id'])
  269. ->where('id', '<>', $data['id'])
  270. ->where('del_time', 0)
  271. ->exists();
  272. }
  273. if ($bool) return [false, date("Y-m", $data['month']) . '的规则配置单已存在'];
  274. return [true, ''];
  275. }
  276. public function fillData($data){
  277. if(empty($data['data'])) return $data;
  278. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  279. foreach ($data['data'] as $key => $value){
  280. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  281. $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
  282. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  283. }
  284. return $data;
  285. }
  286. public function fillDataForExport($data, $column, &$return)
  287. {
  288. if (empty($data)) return;
  289. $mainIds = array_column($data, 'id');
  290. // 1. 获取详情映射 [main_id => [ [code_2=>..., title=>..., item_code=>...], ... ]]
  291. $detailsMap = $this->getDetailsMap($mainIds);
  292. foreach ($data as $main) {
  293. $mainId = $main['id'];
  294. $details = $detailsMap[$mainId] ?? [];
  295. // 2. 提取并格式化主表共有信息
  296. $mainInfo = [
  297. 'code' => $main['code'],
  298. 'month' => !empty($main['month']) ? date('Y-m', $main['month']) : '',
  299. ];
  300. if (empty($details)) {
  301. // 如果单据没有明细,则只导出一行主表信息(确保数据完整)
  302. $tempRow = [];
  303. foreach ($column as $col) {
  304. $tempRow[] = $mainInfo[$col] ?? '';
  305. }
  306. $return[] = $tempRow;
  307. } else {
  308. // 3. 核心平铺逻辑:每一行详情都带上主表单号
  309. foreach ($details as $sub) {
  310. // 合并主表数据和详情数据
  311. $fullRowData = array_merge($mainInfo, $sub);
  312. $tempRow = [];
  313. // 严格按照导出 Excel 的列顺序填充数据
  314. foreach ($column as $col) {
  315. $tempRow[] = $fullRowData[$col] ?? '';
  316. }
  317. $return[] = $tempRow;
  318. }
  319. }
  320. }
  321. }
  322. public function getDetailsMap($mainIds)
  323. {
  324. $details = RuleSetDetails::where('del_time', 0)
  325. ->whereIn('main_id', $mainIds)
  326. ->get();
  327. if ($details->isEmpty()) return [];
  328. // 1. 提取所有需要关联的 ID
  329. $empIds = $details->where('type', RuleSetDetails::type_one)->pluck('data_id')->unique();
  330. $devIds = $details->where('type', RuleSetDetails::type_two)->pluck('data_id')->unique();
  331. $itemIds = $details->pluck('item_id')->unique();
  332. // 2. 批量获取档案 Map
  333. $empMap = Employee::whereIn('id', $empIds)->get()->keyBy('id');
  334. $devMap = Device::whereIn('id', $devIds)->get()->keyBy('id');
  335. $itemMap = Item::whereIn('id', $itemIds)->get()->keyBy('id');
  336. $typeNames = RuleSetDetails::$type_name;
  337. $res = [];
  338. foreach ($details as $item) {
  339. $detailRow = [];
  340. // 类型名称(明细类型列)
  341. $detailRow['type_title'] = $typeNames[$item->type] ?? '';
  342. // 处理人员或设备的编码与名称(影子列)
  343. if ($item->type == RuleSetDetails::type_one) {
  344. $emp = $empMap[$item->data_id] ?? null;
  345. $detailRow['code_2'] = $emp ? $emp->number : ''; // 明细编码
  346. $detailRow['title'] = $emp ? $emp->title : ''; // 明细名称
  347. } else {
  348. $dev = $devMap[$item->data_id] ?? null;
  349. $detailRow['code_2'] = $dev ? $dev->code : ''; // 明细编码
  350. $detailRow['title'] = $dev ? $dev->title : ''; // 明细名称
  351. }
  352. // 处理项目编码与名称
  353. $project = $itemMap[$item->item_id] ?? null;
  354. $detailRow['item_code'] = $project ? $project->code : '';
  355. $detailRow['item_title'] = $project ? $project->title : '';
  356. // 比例
  357. $detailRow['rate'] = $item->rate;
  358. // 归档到对应的单据下
  359. $res[$item->main_id][] = $detailRow;
  360. }
  361. return $res;
  362. }
  363. public function isSetMonthCalendar($data, $user){
  364. $data['top_depart_id'] = $user['top_depart_id'];
  365. if(empty($data['month'])) return [false, '月份不能为空'];
  366. // 1. 月份初始化
  367. $monthStart = $this->changeDateToDate($data['month']);
  368. $monthStr = date("Y-m", $monthStart);
  369. $endTime = strtotime("+1 month", $monthStart) - 1;
  370. // 2. 获取当月标准工作日天数 (基数)
  371. $standardWorkDays = DB::table('calendar_details')
  372. ->where('top_depart_id', $data['top_depart_id'])
  373. ->where('del_time', 0)
  374. ->where('time', '>=', $monthStart)
  375. ->where('time', '<=', $endTime)
  376. ->where('is_work', CalendarDetails::TYPE_ONE)
  377. ->count();
  378. if ($standardWorkDays <= 0) return [false, $monthStr . '还未设置工作日'];
  379. return [true, ''];
  380. }
  381. public function ruleSetCreate($data, $user){
  382. $data['top_depart_id'] = $user['top_depart_id'];
  383. if(empty($data['month'])) return [false, '月份不能为空'];
  384. $monthStart = $this->changeDateToDate($data['month']);
  385. $data['month'] = $monthStart;
  386. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  387. // 1. 获取在该月份有效期内的项目及其信息 (ID, 标题, 编号)
  388. $itemsData = DB::table('item')
  389. ->where('top_depart_id', $data['top_depart_id'])
  390. ->where('del_time', 0)
  391. ->where('start_time', '<=', $monthEnd)
  392. ->where('end_time', '>=', $monthStart)
  393. ->get(['id', 'title', 'code']) // 获取项目 ID, 标题, 编号
  394. ->keyBy('id')
  395. ->toArray();
  396. if (empty($itemsData)) return [false, "该月份下无项目信息"];
  397. $itemIds = array_keys($itemsData);
  398. // 2. 获取项目明细
  399. $details = DB::table('item_details')
  400. ->whereIn('item_id', $itemIds)
  401. ->where('top_depart_id', $data['top_depart_id'])
  402. ->where('del_time', 0)
  403. ->get();
  404. $manIds = []; $devIds = [];
  405. $manMap = []; $deviceMap = [];
  406. foreach ($details as $row) {
  407. if ($row->type == ItemDetails::type_one) {
  408. $manMap[$row->data_id][] = $row->item_id;
  409. $manIds[] = $row->data_id;
  410. } elseif ($row->type == ItemDetails::type_two) {
  411. $deviceMap[$row->data_id][] = $row->item_id;
  412. $devIds[] = $row->data_id;
  413. }
  414. }
  415. // 3. 批量获取人员和设备信息 (含编号)
  416. $manInfos = DB::table('employee')
  417. ->whereIn('id', array_unique($manIds))
  418. ->get(['id', 'title', 'number']) // 这里的 number 是工号
  419. ->keyBy('id')->toArray();
  420. $devInfos = DB::table('device')
  421. ->whereIn('id', array_unique($devIds))
  422. ->get(['id', 'title', 'code']) // 这里的 code 是资产编号
  423. ->keyBy('id')->toArray();
  424. // 4. 生成分配列表
  425. $man_list = $this->distributeRates($manMap, RuleSetDetails::type_one, $manInfos, $itemsData);
  426. $device_list = $this->distributeRates($deviceMap, RuleSetDetails::type_two, $devInfos, $itemsData);
  427. return [true, [
  428. 'month' => date('Y-m', $monthStart),
  429. 'man_list' => $man_list,
  430. 'device_list' => $device_list
  431. ]];
  432. }
  433. private function distributeRates($map, $type, $infoMap, $itemsData)
  434. {
  435. $result = [];
  436. foreach ($map as $dataId => $items) {
  437. $count = count($items);
  438. $rates = [];
  439. // --- 随机分配逻辑 (保持不变) ---
  440. if ($count === 1) {
  441. $rates = [100];
  442. } else {
  443. $sum = 0; $temp = [];
  444. for ($i = 0; $i < $count; $i++) {
  445. $rand = rand(10, 100);
  446. $temp[] = $rand; $sum += $rand;
  447. }
  448. $currentTotal = 0;
  449. foreach ($temp as $i => $weight) {
  450. if ($i === $count - 1) {
  451. $rates[] = 100 - $currentTotal;
  452. } else {
  453. $val = (int)round(($weight / $sum) * 100);
  454. $val = $val <= 0 ? 1 : $val;
  455. $rates[] = $val; $currentTotal += $val;
  456. }
  457. }
  458. }
  459. // --- 数据组装 ---
  460. foreach ($items as $index => $itemId) {
  461. $info = $infoMap[$dataId] ?? null;
  462. $itemInfo = $itemsData[$itemId] ?? null;
  463. $result[] = [
  464. 'type' => $type,
  465. 'data_id' => $dataId,
  466. 'data_title' => $info->title ?? '',
  467. 'data_code' => ($type == RuleSetDetails::type_one) ? ($info->number ?? '') : ($info->code ?? ''),
  468. 'item_id' => $itemId,
  469. 'item_title' => $itemInfo->title ?? '',
  470. 'item_code' => $itemInfo->code ?? '', // 项目编号
  471. 'rate' => $rates[$index]
  472. ];
  473. }
  474. }
  475. return $result;
  476. }
  477. }