RuleSetService.php 19 KB

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