RuleSetService.php 22 KB

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