RuleSetService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. $data['top_depart_id'] = $user['top_depart_id'];
  202. if(empty($data['month'])) return [false, '月份不能为空'];
  203. $data['month'] = $this->changeDateToDate($data['month']);
  204. // --- 1. 人员列表校验 ---
  205. if(empty($data['man_list'])) return [false, '人员不能为空'];
  206. $manRates = []; // 用于累加每个人员的比例
  207. foreach ($data['man_list'] as $key => $value){
  208. if(empty($value['type'])) return [false, '类型不能为空'];
  209. if(empty($value['data_id'])) return [false, '人员不能为空'];
  210. if(empty($value['item_id'])) return [false, '项目不能为空'];
  211. $res = $this->checkNumber($value['rate'], 2, 'non-negative');
  212. if(! $res['valid']) return [false, '人员工时分摊比例:' . $res['error']];
  213. $data['man_list'][$key]['top_depart_id'] = $data['top_depart_id'];
  214. // 累加比例 (以 data_id 为 key)
  215. $manId = $value['data_id'];
  216. $manRates[$manId] = ($manRates[$manId] ?? 0) + $value['rate'];
  217. }
  218. // 校验每个人员的比例之和是否为 100
  219. foreach ($manRates as $mId => $total) {
  220. if (abs($total - 100) > 0.0001) {
  221. return [false, "ID为[{$mId}]的人员分摊比例合计为{$total}%,必须等于100%"];
  222. }
  223. }
  224. // --- 2. 设备列表校验 ---
  225. if(empty($data['device_list'])) return [false, '设备不能为空'];
  226. $deviceRates = []; // 用于累加每个设备的比例
  227. foreach ($data['device_list'] as $key => $value){
  228. if(empty($value['type'])) return [false, '类型不能为空'];
  229. if(empty($value['data_id'])) return [false, '设备ID不能为空'];
  230. if(empty($value['item_id'])) return [false, '项目不能为空'];
  231. $res = $this->checkNumber($value['rate'], 2, 'non-negative');
  232. if(! $res['valid']) return [false, '设备工时分摊比例:' . $res['error']];
  233. $data['device_list'][$key]['top_depart_id'] = $data['top_depart_id'];
  234. // 累加比例
  235. $devId = $value['data_id'];
  236. $deviceRates[$devId] = ($deviceRates[$devId] ?? 0) + $value['rate'];
  237. }
  238. // 校验每个设备的比例之和是否为 100
  239. foreach ($deviceRates as $dId => $total) {
  240. if (abs($total - 100) > 0.0001) {
  241. return [false, "ID为[{$dId}]的设备分摊比例合计为{$total}%,必须等于100%"];
  242. }
  243. }
  244. // --- 3. 重复单据校验 ---
  245. if($is_add){
  246. $bool = RuleSet::where('month',$data['month'])
  247. ->where('top_depart_id', $data['top_depart_id'])
  248. ->where('del_time',0)
  249. ->exists();
  250. }else{
  251. if(empty($data['id'])) return [false,'ID不能为空'];
  252. $bool = RuleSet::where('month',$data['month'])
  253. ->where('top_depart_id', $data['top_depart_id'])
  254. ->where('id','<>',$data['id'])
  255. ->where('del_time',0)
  256. ->exists();
  257. }
  258. if($bool) return [false, date("Y-m", $data['month']) . '的规则配置单已存在'];
  259. return [true, ''];
  260. }
  261. public function fillData($data){
  262. if(empty($data['data'])) return $data;
  263. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  264. foreach ($data['data'] as $key => $value){
  265. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  266. $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
  267. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  268. }
  269. return $data;
  270. }
  271. public function fillDataForExport($data, $column, &$return)
  272. {
  273. if (empty($data)) return;
  274. $mainIds = array_column($data, 'id');
  275. // 1. 获取详情映射 [main_id => [ [code_2=>..., title=>..., item_code=>...], ... ]]
  276. $detailsMap = $this->getDetailsMap($mainIds);
  277. foreach ($data as $main) {
  278. $mainId = $main['id'];
  279. $details = $detailsMap[$mainId] ?? [];
  280. // 2. 提取并格式化主表共有信息
  281. $mainInfo = [
  282. 'code' => $main['code'],
  283. 'month' => !empty($main['month']) ? date('Y-m', $main['month']) : '',
  284. ];
  285. if (empty($details)) {
  286. // 如果单据没有明细,则只导出一行主表信息(确保数据完整)
  287. $tempRow = [];
  288. foreach ($column as $col) {
  289. $tempRow[] = $mainInfo[$col] ?? '';
  290. }
  291. $return[] = $tempRow;
  292. } else {
  293. // 3. 核心平铺逻辑:每一行详情都带上主表单号
  294. foreach ($details as $sub) {
  295. // 合并主表数据和详情数据
  296. $fullRowData = array_merge($mainInfo, $sub);
  297. $tempRow = [];
  298. // 严格按照导出 Excel 的列顺序填充数据
  299. foreach ($column as $col) {
  300. $tempRow[] = $fullRowData[$col] ?? '';
  301. }
  302. $return[] = $tempRow;
  303. }
  304. }
  305. }
  306. }
  307. public function getDetailsMap($mainIds)
  308. {
  309. $details = RuleSetDetails::where('del_time', 0)
  310. ->whereIn('main_id', $mainIds)
  311. ->get();
  312. if ($details->isEmpty()) return [];
  313. // 1. 提取所有需要关联的 ID
  314. $empIds = $details->where('type', RuleSetDetails::type_one)->pluck('data_id')->unique();
  315. $devIds = $details->where('type', RuleSetDetails::type_two)->pluck('data_id')->unique();
  316. $itemIds = $details->pluck('item_id')->unique();
  317. // 2. 批量获取档案 Map
  318. $empMap = Employee::whereIn('id', $empIds)->get()->keyBy('id');
  319. $devMap = Device::whereIn('id', $devIds)->get()->keyBy('id');
  320. $itemMap = Item::whereIn('id', $itemIds)->get()->keyBy('id');
  321. $typeNames = RuleSetDetails::$type_name;
  322. $res = [];
  323. foreach ($details as $item) {
  324. $detailRow = [];
  325. // 类型名称(明细类型列)
  326. $detailRow['type_title'] = $typeNames[$item->type] ?? '';
  327. // 处理人员或设备的编码与名称(影子列)
  328. if ($item->type == RuleSetDetails::type_one) {
  329. $emp = $empMap[$item->data_id] ?? null;
  330. $detailRow['code_2'] = $emp ? $emp->number : ''; // 明细编码
  331. $detailRow['title'] = $emp ? $emp->title : ''; // 明细名称
  332. } else {
  333. $dev = $devMap[$item->data_id] ?? null;
  334. $detailRow['code_2'] = $dev ? $dev->code : ''; // 明细编码
  335. $detailRow['title'] = $dev ? $dev->title : ''; // 明细名称
  336. }
  337. // 处理项目编码与名称
  338. $project = $itemMap[$item->item_id] ?? null;
  339. $detailRow['item_code'] = $project ? $project->code : '';
  340. $detailRow['item_title'] = $project ? $project->title : '';
  341. // 比例
  342. $detailRow['rate'] = $item->rate;
  343. // 归档到对应的单据下
  344. $res[$item->main_id][] = $detailRow;
  345. }
  346. return $res;
  347. }
  348. public function ruleSetCreate($data, $user){
  349. $data['top_depart_id'] = $user['top_depart_id'];
  350. if(empty($data['month'])) return [false, '月份不能为空'];
  351. $monthStart = $this->changeDateToDate($data['month']);
  352. $data['month'] = $monthStart;
  353. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  354. // 1. 获取在该月份有效期内的项目及其信息 (ID, 标题, 编号)
  355. $itemsData = DB::table('item')
  356. ->where('top_depart_id', $data['top_depart_id'])
  357. ->where('del_time', 0)
  358. ->where('start_time', '<=', $monthEnd)
  359. ->where('end_time', '>=', $monthStart)
  360. ->get(['id', 'title', 'code']) // 获取项目 ID, 标题, 编号
  361. ->keyBy('id')
  362. ->toArray();
  363. if (empty($itemsData)) return [false, "该月份下无项目信息"];
  364. $itemIds = array_keys($itemsData);
  365. // 2. 获取项目明细
  366. $details = DB::table('item_details')
  367. ->whereIn('item_id', $itemIds)
  368. ->where('top_depart_id', $data['top_depart_id'])
  369. ->where('del_time', 0)
  370. ->get();
  371. $manIds = []; $devIds = [];
  372. $manMap = []; $deviceMap = [];
  373. foreach ($details as $row) {
  374. if ($row->type == ItemDetails::type_one) {
  375. $manMap[$row->data_id][] = $row->item_id;
  376. $manIds[] = $row->data_id;
  377. } elseif ($row->type == ItemDetails::type_two) {
  378. $deviceMap[$row->data_id][] = $row->item_id;
  379. $devIds[] = $row->data_id;
  380. }
  381. }
  382. // 3. 批量获取人员和设备信息 (含编号)
  383. $manInfos = DB::table('employee')
  384. ->whereIn('id', array_unique($manIds))
  385. ->get(['id', 'title', 'number']) // 这里的 number 是工号
  386. ->keyBy('id')->toArray();
  387. $devInfos = DB::table('device')
  388. ->whereIn('id', array_unique($devIds))
  389. ->get(['id', 'title', 'code']) // 这里的 code 是资产编号
  390. ->keyBy('id')->toArray();
  391. // 4. 生成分配列表
  392. $man_list = $this->distributeRates($manMap, RuleSetDetails::type_one, $manInfos, $itemsData);
  393. $device_list = $this->distributeRates($deviceMap, RuleSetDetails::type_two, $devInfos, $itemsData);
  394. return [true, [
  395. 'month' => date('Y-m', $monthStart),
  396. 'man_list' => $man_list,
  397. 'device_list' => $device_list
  398. ]];
  399. }
  400. private function distributeRates($map, $type, $infoMap, $itemsData)
  401. {
  402. $result = [];
  403. foreach ($map as $dataId => $items) {
  404. $count = count($items);
  405. $rates = [];
  406. // --- 随机分配逻辑 (保持不变) ---
  407. if ($count === 1) {
  408. $rates = [100];
  409. } else {
  410. $sum = 0; $temp = [];
  411. for ($i = 0; $i < $count; $i++) {
  412. $rand = rand(10, 100);
  413. $temp[] = $rand; $sum += $rand;
  414. }
  415. $currentTotal = 0;
  416. foreach ($temp as $i => $weight) {
  417. if ($i === $count - 1) {
  418. $rates[] = 100 - $currentTotal;
  419. } else {
  420. $val = (int)round(($weight / $sum) * 100);
  421. $val = $val <= 0 ? 1 : $val;
  422. $rates[] = $val; $currentTotal += $val;
  423. }
  424. }
  425. }
  426. // --- 数据组装 ---
  427. foreach ($items as $index => $itemId) {
  428. $info = $infoMap[$dataId] ?? null;
  429. $itemInfo = $itemsData[$itemId] ?? null;
  430. $result[] = [
  431. 'type' => $type,
  432. 'data_id' => $dataId,
  433. 'data_title' => $info->title ?? '',
  434. 'data_code' => ($type == RuleSetDetails::type_one) ? ($info->number ?? '') : ($info->code ?? ''),
  435. 'item_id' => $itemId,
  436. 'item_title' => $itemInfo->title ?? '',
  437. 'item_code' => $itemInfo->code ?? '', // 项目编号
  438. 'rate' => $rates[$index]
  439. ];
  440. }
  441. }
  442. return $result;
  443. }
  444. }