RuleSetService.php 21 KB

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