RuleSetService.php 20 KB

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