StatisticService.php 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  1. <?php
  2. namespace App\Service;
  3. use App\Model\AuxiliaryAccountDetails;
  4. use App\Model\Depart;
  5. use App\Model\Device;
  6. use App\Model\DeviceDepartDetails;
  7. use App\Model\Employee;
  8. use App\Model\EmployeeDepartPermission;
  9. use App\Model\ExpenseClaimsDetails;
  10. use App\Model\Fee;
  11. use App\Model\Item;
  12. use App\Model\ItemDetails;
  13. use App\Model\MonthlyPsOrder;
  14. use App\Model\MonthlyPsOrderDetails;
  15. use App\Model\MonthlyPwOrder;
  16. use App\Model\MonthlyPwOrderDetails;
  17. use App\Service\Statistic\StatisticCommonService;
  18. use Illuminate\Support\Facades\DB;
  19. class StatisticService extends StatisticCommonService
  20. {
  21. public function employeeDayHourStatistic($data, $user)
  22. {
  23. // 1. 验证并获取月份边界
  24. list($status, $month_start, $month_end) = $this->commonRule($data);
  25. if (!$status) return [false, $month_start];
  26. // 2. 获取原始数据
  27. $dayEmployeeList = $this->getItemEmployeeDayWorkList($user, $data, $month_start, $month_end);
  28. if (empty($dayEmployeeList)) {
  29. return [true, []];
  30. }
  31. // 3. 提取 ID 批量查询关联数据(合并 Item 查询)
  32. $itemIds = array_unique(array_filter(array_column($dayEmployeeList, 'item_id')));
  33. $employeeIds = array_unique(array_filter(array_column($dayEmployeeList, 'employee_id')));
  34. $items = Item::whereIn('id', $itemIds)->get(['id', 'title', 'code'])->keyBy('id');
  35. $employeeKeyList = Employee::whereIn('id', $employeeIds)->pluck('title', 'id')->toArray();
  36. // 4. 【核心优化】单次遍历:同时计算 count、sum 并补全基础信息
  37. $employeeCounts = [];
  38. $sums = [];
  39. foreach ($dayEmployeeList as &$item) {
  40. $employeeId = $item['employee_id'] ?? null;
  41. $itemId = $item['item_id'] ?? null;
  42. $orderDate = $item['order_date'] ?? '';
  43. // 补全名称(避免在 map 里重复调用集合)
  44. $item['employee_name'] = $employeeKeyList[$employeeId] ?? "未知员工({$employeeId})";
  45. $itemProject = $items->get($itemId);
  46. $item['item_title'] = $itemProject->title ?? "未知项目({$itemId})";
  47. $item['item_code'] = $itemProject->code ?? "未知项目({$itemId})";
  48. // 组装唯一 Key: "employeeId_orderDate"
  49. $groupKey = "{$employeeId}_{$orderDate}";
  50. // 累加计数
  51. $employeeCounts['employee_work_count'][$groupKey] = ($employeeCounts['employee_work_count'][$groupKey] ?? 0) + 1;
  52. // 累加小时工时(转为分位整数存储,防止浮点数失真)
  53. $hours = round(($item['total_work'] ?? 0) / 60, 2);
  54. $sums['employee_work_count'][$groupKey] = ($sums['employee_work_count'][$groupKey] ?? 0) + (int)round($hours * 100);
  55. }
  56. unset($item); // 释放引用避免后续污染
  57. $wordKeys = [
  58. "employee_work_count" => [
  59. "key" => "total_work",
  60. "value" => "total_work_hours",
  61. "type" => "hour",
  62. ]
  63. ];
  64. // 5. 第二次遍历:倒扣尾差计算
  65. // 因为这里需要倒扣,必须按顺序执行 calculateClosure
  66. foreach ($dayEmployeeList as &$item) {
  67. $groupKey = "{$item['employee_id']}_{$item['order_date']}";
  68. $this->calculateClosure($groupKey, $item, $employeeCounts, $sums, $wordKeys);
  69. }
  70. unset($item);
  71. return [true, $dayEmployeeList];
  72. }
  73. public function employeeDayHourStatistic1($data, $user)
  74. {
  75. //传参月份、项目编码、项目名称 不允许跨年查询月份
  76. //项目编码、项目名称、人员名称、工时、日期
  77. list($status, $month_start, $month_end) = $this->commonRule($data);
  78. if (!$status) return [false, $month_start];
  79. $day_employee_list = $this->getItemEmployeeDayWorkList($user,$data,$month_start,$month_end);
  80. $dataCollection = collect($day_employee_list);
  81. $item_ids = $dataCollection->pluck('item_id')->unique()->values()->all();
  82. $employee_ids = $dataCollection->pluck('employee_id')->unique()->values()->all();
  83. $employee_key_list = Employee::wherein('id', $employee_ids)->pluck("title", "id")->toArray();
  84. $item_title_key_list = Item::wherein('id', $item_ids)->pluck("title", "id")->toArray();
  85. $item_code_key_list = Item::wherein('id', $item_ids)->pluck("code", "id")->toArray();
  86. $keys = ["employee_id","order_date"];
  87. $employee_count = $this->calculateCount($day_employee_list,$keys);
  88. $employee_work_count = $this->calculateSumForHour($day_employee_list,$keys,"total_work");
  89. $collection = collect($day_employee_list);
  90. $sums = ["employee_work_count"=>$employee_work_count];
  91. $word_keys = [
  92. "employee_work_count" =>
  93. [
  94. "key" => "total_work",
  95. "value" => "total_work_hours",
  96. "type" => "hour",
  97. ]
  98. ];
  99. $employee_counts = ['employee_work_count' => $employee_count];
  100. $month_employee_list = $collection->transform(function ($item) use ($employee_key_list, $item_title_key_list, $item_code_key_list, &$employee_work_count, &$employee_counts,$keys,$word_keys,&$sums) {
  101. $item['employee_name'] = $employee_key_list[$item['employee_id']] ?? "未知员工({$item['employee_id']})";
  102. $item['item_title'] = $item_title_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  103. $item['item_code'] = $item_code_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  104. // 如果不是最后一条
  105. $key = collect($keys)->map(fn($k) => $item[$k] ?? '')->implode('_');
  106. $this->calculateClosure($key,$item,$employee_counts,$sums,$word_keys);
  107. return $item;
  108. })->all();
  109. return [true, $month_employee_list];
  110. }
  111. public function employeeMonthSalaryStatistic($data, $user)
  112. {
  113. //项目编码、项目名称、天数、工资、日期
  114. list($status, $month_start, $month_end) = $this->commonRule($data);
  115. if (!$status) return [false, $month_start];
  116. //确认所有项目、人员、人员工时
  117. $month_employee_list = $this->getItemEmployeeMonthWorkList($user, $data, $month_start, $month_end);
  118. //查询所有人员工资
  119. $salary_map = $this->getEmployeeSalary($user, $data, $month_start, $month_end);
  120. //查询所有项目人员的工时比例
  121. // 2. 计算每个员工在每个月的全月总工时
  122. $keys = ["employee_id","order_month"];
  123. $employee_monthly_total_min = $this->calculateSum($month_employee_list,$keys,"total_work");
  124. // 3. 计算分摊比例
  125. list($item_month_list,$all_salary) = $this->calculateRatioForMonth($month_employee_list,$employee_monthly_total_min,$salary_map,["employee_id","order_month"],["order_month","item_id"]);
  126. //计算天数
  127. foreach ($item_month_list as $k => $v) {
  128. $item_month_list[$k]['days'] = round($v['work_minutes'] / 8 / 60);
  129. }
  130. $item_month_list = collect($item_month_list)->sortBy('month')->values()->all();
  131. $items = collect($item_month_list)->pluck('item_id')->unique()->values()->all();
  132. $item = Item::TopClear($user, $data);
  133. $item_title_key_list = $item->wherein('id', $items)->pluck("title", "id")->toArray();
  134. $item_code_key_list = $item->wherein('id', $items)->pluck("code", "id")->toArray();
  135. $collect = collect($item_month_list);
  136. $item_count = $collect->groupBy(function ($item) {
  137. // 这里的 $item 是集合中的每一行数据
  138. return $item['month'];
  139. })->map(function ($group) {
  140. return $group->count();
  141. })->toArray();
  142. $item_day_count = $collect->groupBy(fn($item) => $item['month'])
  143. ->map(fn($group) => round($group->sum('work_minutes') / 8 / 60)*100)
  144. ->toArray();
  145. // $all_salary = collect($salary_map)
  146. // ->groupBy(function ($value, $key) {
  147. // // 1. 提取下划线后面的内容 (例如: 2024-02)
  148. // return explode('_', $key)[1];
  149. // })
  150. // ->map(function ($group) {
  151. // // 2. 对每个分组内的数值进行求和
  152. // return $group->sum();
  153. // })
  154. // ->toArray();
  155. $item_counts = [
  156. "all_salary" => $item_count,
  157. "item_day_sum" => $item_count,
  158. ];
  159. $sums = ["item_day_sum"=>$item_day_count,"all_salary"=>$all_salary];
  160. $word_keys = [
  161. "all_salary" =>
  162. [
  163. "key" => "allocated_salary",
  164. "value" => "allocated_salary",
  165. "type" => "money",
  166. ],
  167. "item_day_sum" =>
  168. [
  169. "key" => "days",
  170. "value" => "days",
  171. "type" => "",
  172. ],
  173. ];
  174. $item_month_list = collect($item_month_list)->transform(function ($item) use ($item_title_key_list, $item_code_key_list, &$item_counts,&$sums,&$word_keys) {
  175. $item['item_title'] = $item_title_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  176. $item['item_code'] = $item_code_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  177. $key = $item['month'];
  178. $this->calculateClosure($key,$item,$item_counts,$sums,$word_keys);
  179. return $item;
  180. })->all();
  181. return [true, $item_month_list];
  182. }
  183. public function itemDaySalaryStatistic($data, $user)
  184. {
  185. //项目编码、项目名称、人员名称、研发工时、研发工资、当月总工时、总计工资、年月
  186. list($status, $month_start, $month_end) = $this->commonRule($data);
  187. if (!$status) return [false, $month_start];
  188. //确认所有项目、人员、人员工时
  189. $month_employee_list = $this->getItemEmployeeMonthWorkList($user, $data, $month_start, $month_end);
  190. //查询所有人员工资
  191. $salary_map = $this->getEmployeeSalary($user, $data, $month_start, $month_end);
  192. // 2. 计算每个员工在每个月的全月总工时
  193. $keys = ["employee_id","order_month"];
  194. $employee_monthly_total_min = $this->calculateSum($month_employee_list,$keys,"total_work");
  195. //查询所有项目人员的工时比例
  196. // 3. 计算分摊比例
  197. list($item_month_list,) = $this->calculateRatioForMonth($month_employee_list,$employee_monthly_total_min,$salary_map,["employee_id","order_month"],["order_month","item_id","employee_id"]);
  198. $collect = collect($item_month_list);
  199. $employee_count = $collect->groupBy(function ($item) {
  200. // 这里的 $item 是集合中的每一行数据
  201. return $item['employee_id'] . '_' . $item['month'];
  202. })->map(function ($group) {
  203. return $group->count();
  204. })->toArray();
  205. $item_month_list = collect($item_month_list)->sortBy('month')->values()->all();
  206. $items = collect($item_month_list)->pluck('item_id')->unique()->values()->all();
  207. $item = Item::TopClear($user, $data);
  208. $item_title_key_list = $item->wherein('id', $items)->pluck("title", "id")->toArray();
  209. $item_code_key_list = $item->wherein('id', $items)->pluck("code", "id")->toArray();
  210. $employee_ids = collect($item_month_list)->pluck('employee_id')->unique()->values()->all();
  211. $employee = Employee::TopClear($user, $data);
  212. $employee_key_list = $employee->wherein('id', $employee_ids)->pluck("title", "id")->toArray();
  213. $month_total_hour = collect($employee_monthly_total_min)->map(function ($value) {
  214. // 逻辑:除以 60,取两位小数,乘以 100
  215. // 注意:round 会根据你的精度要求处理小数
  216. return round($value / 60) * 100;
  217. })->toArray();
  218. $sums = ["work_hours"=>$month_total_hour,"allocated_salary"=>$salary_map];
  219. $word_keys = [
  220. "allocated_salary" =>
  221. [
  222. "key" => "allocated_salary",
  223. "value" => "allocated_salary",
  224. "type" => "100b",
  225. ],
  226. "work_hours" =>
  227. [
  228. "key" => "work_minutes",
  229. "value" => "work_hours",
  230. "type" => "hour",
  231. ],
  232. ];
  233. $counts = [];
  234. foreach ($word_keys as $k=>$v){
  235. $counts[$k] = $employee_count;
  236. }
  237. $item_month_list = collect($item_month_list)->transform(function ($item) use ($item_title_key_list, $item_code_key_list, $employee_key_list, &$sums, &$counts,$word_keys) {
  238. $item['item_title'] = $item_title_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  239. $item['item_code'] = $item_code_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  240. $item['employee_title'] = $employee_key_list[$item['employee_id']] ?? "未知人员({$item['employee_id']})";
  241. // $item['total_hours'] = round($item['work_minutes'] / 60,2);
  242. $item['total_salary'] = round($item['total_salary'] / 100,2);
  243. $key = $item['employee_id'] . '_' . $item['month'];
  244. // // 如果不是最后一条
  245. $this->calculateClosure($key,$item,$counts,$sums,$word_keys);
  246. return $item;
  247. })->all();
  248. return [true, $item_month_list];
  249. }
  250. public function itemDeviceMonthStatistic($data, $user)
  251. {
  252. //项目编码、项目名称、设备名称、项目工时、研发工时占比、设备原值、设备折旧额、本项目帐面归集的折旧额、确定的本项目折旧额、加计调整金额、当月工时、日期
  253. list($status, $month_start, $month_end) = $this->commonRule($data);
  254. if (!$status) return [false, $month_start];
  255. //确认所有项目、设备、设备工时
  256. $month_device_list = $this->getItemDeviceMonthWorkList($user, $data, $month_start, $month_end);
  257. //查询所有设备工资
  258. $depreciation_map = $this->getDeviceAmount($user, $data, $month_start, $month_end);
  259. // 2. 计算每个设备在每个月的全月总工时
  260. $keys = ["device_id","order_month"];
  261. $device_monthly_total_min = $this->calculateSum($month_device_list,$keys,"total_work");
  262. // 3. 计算设备分摊天数与工资
  263. list($item_month_list,$device_total_depreciation) = $this->calculateDeviceRatioForMonth($month_device_list,$device_monthly_total_min,$depreciation_map,["device_id","order_month"],["order_month","item_id","device_id"]);
  264. $item_month_list = collect($item_month_list)->sortBy('month')->values()->all();
  265. $items = collect($item_month_list)->pluck('item_id')->unique()->values()->all();
  266. $item = Item::TopClear($user, $data);
  267. $item_title_key_list = $item->wherein('id', $items)->pluck("title", "id")->toArray();
  268. $item_code_key_list = $item->wherein('id', $items)->pluck("code", "id")->toArray();
  269. $device_ids = collect($item_month_list)->pluck('device_id')->unique()->values()->all();
  270. $device = Device::TopClear($user, $data);
  271. $devices = $device->whereIn('id', $device_ids)
  272. ->get(['id', 'title', 'total_depreciation', 'in_time', 'device_type']);
  273. $timestamps = $devices->pluck('in_time')->unique()->toArray();
  274. $yearsMap = $this->getBatchDiffYears($timestamps);
  275. $depart_map = $this->getDepart($devices->pluck('id')->unique()->toArray());
  276. $device_key_list = [];
  277. foreach ($devices as $d) {
  278. $useYear = $d->in_time ? $yearsMap[$d->in_time] : 0;
  279. $depart_title = $depart_map[$d->id] ?? "";
  280. $device_key_list[$d->id] = [
  281. 'id' => $d->id,
  282. 'title' => $d->title,
  283. 'now_depreciation' => $d->total_depreciation,
  284. 'in_time' => $d->in_time,
  285. 'device_type_title' => Device::$device_type[$d->device_type] ?? "",
  286. 'use_year' => $useYear,
  287. 'depart_title' => $depart_title,
  288. ];
  289. }
  290. // $device_key_list = $device->wherein('id', $device_ids)->pluck("title", "id")->toArray();
  291. $device_original_value_key_list = $device->wherein('id', $device_ids)->pluck("original_value", "id")->toArray();
  292. $collect = collect($item_month_list);
  293. $word_keys = [
  294. "total_depreciation" =>
  295. [
  296. "key" => "allocated_depreciatio",
  297. "value" => "allocated_depreciatio",
  298. "type" => "money",
  299. ],
  300. "total_hours" =>
  301. [
  302. "key" => "hours",
  303. "value" => "hours",
  304. "type" => "",
  305. ],
  306. "ratio" =>
  307. [
  308. "key" => "ratio",
  309. "value" => "ratio",
  310. "type" => "ratio",
  311. ],
  312. ];
  313. $device_count = $collect->groupBy(function ($item) {
  314. // 这里的 $item 是集合中的每一行数据
  315. return $item['device_id'] . '_' . $item['month'];
  316. })->map(function ($group) {
  317. return $group->count();
  318. })->toArray();
  319. $device_counts = [];
  320. foreach ($word_keys as $k=>$v){
  321. $device_counts[$k] = $device_count;
  322. }
  323. $device_total_depreciation['ratio'] = [];
  324. $item_month_list = collect($item_month_list)->transform(function ($item) use ($item_title_key_list, $item_code_key_list, $device_key_list, $device_original_value_key_list, &$device_total_depreciation, &$device_counts,&$rate_list,$word_keys) {
  325. $item['item_title'] = $item_title_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  326. $item['item_code'] = $item_code_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  327. $tmp = $device_key_list[$item['device_id']] ?? [];
  328. $item['device_title'] = $tmp['title'] ?? "";
  329. $item['device_type_title'] = $tmp['device_type_title'] ?? "";
  330. $item['use_year'] = $tmp['use_year'] ?? 0;
  331. $item['depart_title'] = $tmp['depart_title'] ?? "";
  332. $item['now_depreciation'] = $tmp['now_depreciation'] ?? 0;
  333. $item['allocated_depreciatio'] = $item['allocated_depreciation'];
  334. $item['total_depreciatio'] = round($item['total_depreciation']/100,2);
  335. $item['device_original'] = $device_original_value_key_list[$item['device_id']] ?? "未知人员({$item['device_id']})";
  336. $item['hours'] = round($item['work_minutes'] / 60, 1);
  337. $item['total_hours'] = round($item['total_min'] / 60, 1);
  338. $key = $item['device_id'] . '_' . $item['month'];
  339. $this->calculateClosure($key,$item,$device_counts,$device_total_depreciation,$word_keys);
  340. return $item;
  341. })->all();
  342. return [true, $item_month_list];
  343. }
  344. public function getDepart($id){
  345. $details = DeviceDepartDetails::where('del_time', 0)
  346. ->whereIn('main_id', $id)
  347. ->select(['main_id as device_id', 'depart_id'])
  348. ->get();
  349. $departIds = $details->pluck('depart_id')->unique()->toArray();
  350. $departMap = Depart::whereIn('id', $departIds)
  351. ->pluck('title', 'id')
  352. ->toArray();
  353. $result = [];
  354. foreach ($details as $value) {
  355. $deviceId = $value['device_id'];
  356. $departId = $value['depart_id'];
  357. $t = $departMap[$departId] ?? '';
  358. if(empty($t)) continue;
  359. if(isset($result[$deviceId])){
  360. $result[$deviceId] .= ',' . $t;
  361. }else{
  362. $result[$deviceId] = $t;
  363. }
  364. }
  365. return $result;
  366. }
  367. public function employeeAttendanceMonthStatistic($data, $user)
  368. {
  369. //项目编码、项目名称、项目状态、支出类型、允许加计扣除金额合计、人员人工费用、折旧费用、其他费用、前N项小计、其他相关费用合计、委内费用、委外费用、
  370. list($status, $month_start, $month_end) = $this->commonRule($data);
  371. if (!$status) {
  372. return [false, $month_start];
  373. }
  374. //第一步确定项目
  375. $item = Item::TopClear($user, $data);
  376. // $item_list = $item->where('del_time', 0)
  377. // ->where(function ($query) use ($month_start, $month_end) {
  378. // $query->where('start_time', '>=', $month_start)
  379. // ->where('end_time', '<', $month_end);
  380. // })->select("code", "title", "start_time", "end_time", "id", "state")->orderby("start_time", "asc")->get()->toArray();
  381. $item_list = $item->where('del_time', 0)
  382. /*->where(function ($query) use ($month_start, $month_end) {
  383. $query->where('start_time', '>=', $month_start)
  384. ->orWhere('end_time', '<', $month_end);
  385. })*/->where('end_time', '<', $month_end)->where('end_time', '>=', $month_start)->select("code", "title", "start_time", "end_time", "id", "state")->orderby("start_time", "asc")->get()->toArray();
  386. $item_key_list = [];
  387. foreach ($item_list as $v) {
  388. $item_key_list[$v['id']] = $v;
  389. }
  390. //第二步确定人员费用
  391. $item_employee_list = $this->getEmployeeItemSalary($month_start, $month_end, $data, $user);
  392. //第三步确定折旧费用
  393. $item_device_list = $this->getDeviceItemSalary($month_start, $month_end, $data, $user);
  394. //第四步其他费用
  395. list($item_fee_list, $fee_type_list) = $this->getFeeItemSalary($month_start, $month_end, $data, $user);
  396. // dd($item_device_list);
  397. //组合所有数据
  398. $return = [];
  399. foreach ($item_key_list as $v) {
  400. $other = collect($item_fee_list[$v['id']] ?? [])->values()->all();
  401. $employee_salary = isset($item_employee_list[$v['id']]['salary']) ? round($item_employee_list[$v['id']]['salary'],2) : 0;
  402. $device_depreciation = isset($item_device_list[$v['id']]['allocated_depreciation']) ? round($item_device_list[$v['id']]['allocated_depreciation'],2): 0;
  403. $other_amount = 0;
  404. $total_amount = $employee_salary + $device_depreciation;
  405. $jj_total_amount = $employee_salary + $device_depreciation;
  406. foreach ($other as $vv){
  407. if($vv['is_other'] == 1) $other_amount += $vv['total_amount'];
  408. else {
  409. $total_amount += $vv['total_amount'];
  410. $jj_total_amount += $vv['total_amount'];
  411. }
  412. }
  413. //限额调整其他费用
  414. $jj_other_amount = round(($total_amount+$other_amount)*0.2);
  415. if($other_amount <= $jj_other_amount) $jj_other_amount = $other_amount;
  416. //加计其他费用
  417. $jj_amount = ($total_amount+$other_amount)*0.1;
  418. if($other_amount <= $jj_amount) $jj_amount = $other_amount;
  419. //允许加计扣除项 : 其他费用 <= (其他费用+费用)*10% +费用
  420. // 经限额调整后的其他相关费用 : 其他费用 <= (其他费用+费用)*20%
  421. //其他费用是个数组
  422. $item_value = [
  423. "code" => $v['code'],
  424. "title" => $v['title'],
  425. "state" => $v['state'] == 3 ? "完结" : "进行中",
  426. "employee_salary" => $employee_salary,
  427. "device_depreciation" => $device_depreciation,
  428. "expense_type" => "费用化支出",
  429. "fee_list" => $other,
  430. "other_amount" => $other_amount,
  431. "jj_other_amount" => $jj_other_amount,
  432. "jj_total_amount" => round($jj_amount+$jj_total_amount,2),
  433. "start_time" => date('Y-m-d', $v['start_time']),
  434. "end_time" => date('Y-m-d', $v['end_time']),
  435. ];
  436. $return[] = $item_value;
  437. }
  438. return [true, ["list" => $return, "fee_type_list" => array_values($fee_type_list)]];
  439. }
  440. private function getEmployeeItemSalary($month_start, $month_end, $data, $user)
  441. {
  442. $month_employee_list = $this->getItemEmployeeMonthWorkList($user, $data, $month_start, $month_end);
  443. //查询所有人员工资
  444. $salary_map = $this->getEmployeeSalary($user, $data, $month_start, $month_end);
  445. // 2. 计算每个员工在每个月的全月总工时
  446. $employee_monthly_total_min = $this->calculateSum($month_employee_list,["employee_id","order_month"],"total_work");
  447. // 2. 计算分摊天数与工资
  448. list($item_list,) = $this->calculateRatioForMonth($month_employee_list,$employee_monthly_total_min,$salary_map,["employee_id","order_month"],["order_month","item_id","employee_id"]);
  449. $collect = collect($item_list);
  450. $employee_count = $collect->groupBy(function ($item) {
  451. // 这里的 $item 是集合中的每一行数据
  452. return $item['employee_id'] . '_' . $item['month'];
  453. })->map(function ($group) {
  454. return $group->count();
  455. })->toArray();
  456. $sums = [
  457. "salary_map" => $salary_map
  458. ];
  459. $employee_counts = [
  460. "salary_map" => $employee_count
  461. ];
  462. $word_keys = [
  463. "salary_map" => [
  464. "key" => "allocated_salary",
  465. "value" => "allocated_salary",
  466. "type" => "money",
  467. ]
  468. ];
  469. $month_employee_list = $collect->transform(function ($item) use (&$employee_counts,&$sums,$word_keys) {
  470. // 如果不是最后一条
  471. $key = $item['employee_id'] . '_' . $item['month'];
  472. $this->calculateClosure($key,$item,$employee_counts,$sums,$word_keys);
  473. return $item;
  474. })->all();
  475. $return_item_list = [];
  476. foreach ($month_employee_list as $v){
  477. $key = $v['item_id'];
  478. if(!isset($return_item_list[$key])) $return_item_list[$key]['salary'] = 0;
  479. $return_item_list[$key]['salary'] += $v['allocated_salary'];
  480. }
  481. return $return_item_list;
  482. }
  483. private function getDeviceItemSalary($month_start, $month_end, $data, $user)
  484. {
  485. //确认所有项目、设备、设备工时
  486. $month_device_list = $this->getItemDeviceMonthWorkList($user, $data, $month_start, $month_end);
  487. //查询所有设备工资
  488. $month_device_salary = $this->getDeviceAmount($user, $data, $month_start, $month_end);
  489. //查询所有项目人员的工时比例
  490. // 2. 计算每个设备在每个月的全月总工时
  491. $keys = ["device_id","order_month"];
  492. $device_monthly_total_min = $this->calculateSum($month_device_list,$keys,"total_work");
  493. //汇总设备每个月损耗金额
  494. list($item_list,) = $this->calculateDeviceRatioForMonth($month_device_list,$device_monthly_total_min,$month_device_salary,["device_id","order_month"],["order_month","item_id","device_id"]);
  495. $collect = collect($item_list);
  496. $device_count = $collect->groupBy(function ($item) {
  497. // 这里的 $item 是集合中的每一行数据
  498. return $item['device_id'] . '_' . $item['month'];
  499. })->map(function ($group) {
  500. return $group->count();
  501. })->toArray();
  502. $sums = [
  503. "salary_map" => $month_device_salary
  504. ];
  505. $word_keys = [
  506. "salary_map" => [
  507. "key" => "allocated_depreciation",
  508. "value" => "allocated_depreciation",
  509. "type" => "money",
  510. ]
  511. ];
  512. $device_counts = [
  513. "salary_map" => $device_count
  514. ];
  515. $month_employee_list = $collect->transform(function ($item) use (&$device_counts,&$sums,$word_keys) {
  516. // 如果不是最后一条
  517. $key = $item['device_id'] . '_' . $item['month'];
  518. $this->calculateClosure($key,$item,$device_counts,$sums,$word_keys);
  519. return $item;
  520. })->all();
  521. $return_item_list = [];
  522. foreach ($month_employee_list as $v){
  523. $key = $v['item_id'];
  524. if(!isset($return_item_list[$key])) $return_item_list[$key]['allocated_depreciation'] = 0;
  525. $return_item_list[$key]['allocated_depreciation'] += $v['allocated_depreciation'];
  526. }
  527. return $return_item_list;
  528. }
  529. private function getFeeItemSalary($month_start, $month_end, $data, $user)
  530. {
  531. //确认所有项目、费用
  532. $expense = ExpenseClaimsDetails::Clear($user, $data);
  533. $expense_list = $expense->where("claim_date", ">=", $month_start)->where("claim_date", "<", $month_end)
  534. ->where('del_time', 0)
  535. ->select(
  536. "fee_id",
  537. "amount",
  538. "item_id",
  539. "entrust_type"
  540. )->get()->toArray();
  541. //需要根据分类去汇总
  542. $fee = Fee::TopClear($user, $data);
  543. $fee = $fee->where('del_time', 0)->orderBy("sort", 'desc')->get()->toArray();
  544. return $this->groupListByRoot($expense_list, $fee);
  545. }
  546. /**
  547. * 将报销明细按照一级费用和项目分类进行分组
  548. * * @param array $list 报销明细列表 (含 fee_id, amount 等)
  549. * @param array $fee_type_list 费用类型树 (含 id, parent_id, title)
  550. * @return array
  551. */
  552. public function groupListByRoot(array $list, array $fee_type_list)
  553. {
  554. // 1. 建立 ID 索引,方便快速查找
  555. $idMap = array_column($fee_type_list, null, 'id');
  556. // 2. 预处理映射表:让所有子 ID 直接指向它的最顶层“祖宗” ID
  557. $childToRoot = [];
  558. foreach ($fee_type_list as $type) {
  559. $current = $type;
  560. // 向上追溯直到 parent_id 为 0,即找到一级分类
  561. while ($current['parent_id'] != 0) {
  562. $current = $idMap[$current['parent_id']];
  563. }
  564. $childToRoot[$type['id']] = [
  565. 'id' => $current['id'],
  566. 'title' => $current['title'],
  567. 'sort' => $current['sort'],
  568. 'is_other' => $current['is_other'],
  569. ];
  570. }
  571. // 3. 遍历明细数据进行分组
  572. $item_key_list = [];
  573. $type_list = [];
  574. foreach ($list as $item) {
  575. $feeId = $item['fee_id'];
  576. // 获取该费用对应的一级分类信息
  577. if (!isset($childToRoot[$feeId])) continue;
  578. $rootId = $childToRoot[$feeId]['id'];
  579. $title = $childToRoot[$feeId]['title'];
  580. $sort = $childToRoot[$feeId]['sort'];
  581. $other = $childToRoot[$feeId]['is_other'];
  582. $key = $item['item_id'];
  583. if (!isset($item_key_list[$key][$rootId])) {
  584. $item_key_list[$key][$rootId] = [
  585. 'id' => $rootId,
  586. 'total_amount' => 0,
  587. 'entrust1_amount' => 0, //委内
  588. 'entrust2_amount' => 0, //委外
  589. 'is_other' => $other,
  590. ];
  591. }
  592. if ($item['entrust_type'] == 1) {
  593. $item_key_list[$key][$rootId]['entrust1_amount'] += $item['amount']*100;
  594. } elseif ($item['entrust_type'] == 2) {
  595. $item_key_list[$key][$rootId]['entrust2_amount'] += $item['amount']*100;
  596. }else{
  597. $item_key_list[$key][$rootId]['total_amount'] += $item['amount']*100;
  598. }
  599. //这边需要拿到头部所有的一级费用类型
  600. if (!isset($type_list[$rootId])) {
  601. $type_list[$rootId] = [
  602. 'sort' => $sort,
  603. 'id' => $rootId,
  604. 'title' => $title,
  605. 'is_after' => $other,
  606. ];
  607. }
  608. }
  609. // var_dump($item_key_list);die;
  610. foreach ($item_key_list as $k=>$v){
  611. foreach ($v as $kk=>$vv){
  612. $item_key_list[$k][$kk]['entrust1_amount'] = round( $vv['entrust1_amount']/100,2);
  613. $item_key_list[$k][$kk]['entrust2_amount'] = round( $vv['entrust2_amount']/100,2);
  614. $item_key_list[$k][$kk]['total_amount'] = round( $vv['total_amount']/100,2);
  615. }
  616. }
  617. // $item_key_list = collect($item_key_list)->transform(function ($item) {
  618. // $item['entrust1_amount'] = round( $item['entrust1_amount']/100,2);
  619. // $item['entrust2_amount'] = round( $item['entrust2_amount']/100,2);
  620. // $item['total_amount'] = round( $item['total_amount']/100,2);
  621. // return $item;
  622. // })->all();
  623. // 使用 values() 丢弃原始键名,重新从 0 开始建立索引
  624. $type_list = collect($type_list)->sortBy('sort')->values()->all();
  625. // 4. 重置数组索引并返回
  626. return [$item_key_list, $type_list];
  627. }
  628. public function auxiliaryStatistic($data, $user)
  629. {
  630. list($status, $month_start, $month_end) = $this->commonRule($data);
  631. if (!$status) return [false, $month_start];
  632. //项目编码、项目名称、项目状态、凭证日期、凭证种类、凭证号数、凭证摘要、会计凭证归集金额、N个一级费用类型、委内、委外
  633. //确认所有项目
  634. $item = Item::TopClear($user, $data);
  635. $item_list = $item->where('del_time', 0)
  636. /*->where(function ($query) use ($month_start, $month_end) {
  637. $query->where('start_time', '>=', $month_start)
  638. ->orWhere('end_time', '<', $month_end);
  639. })*/->where('end_time', '<', $month_end)->where('end_time', '>=', $month_start)->select("code", "title", "start_time", "end_time", "id", "state")->orderby("start_time", "asc")->get()->toArray();
  640. $item_key_list = [];
  641. foreach ($item_list as $v) {
  642. $item_key_list[$v['id']] = $v;
  643. }
  644. //获取该区间内所有项目人工费、折旧费
  645. $item_salary = $this->auxiliaryEmployee($user, $data, $month_start, $month_end);
  646. $device_depreciation = $this->auxiliaryDevice($user, $data, $month_start, $month_end);
  647. $fee = Fee::TopClear($user, $data);
  648. $fee = $fee->where('del_time', 0)->orderBy("sort", 'desc')->get()->toArray();
  649. $auxiliary = AuxiliaryAccountDetails::Clear($user, $data);
  650. $auxiliary_list = $auxiliary->where("voucher_date", ">=", $month_start)->where("voucher_date", "<", $month_end)
  651. ->where('del_time', 0)
  652. ->select(
  653. "item_id",
  654. "voucher_date",
  655. "voucher_type",
  656. "voucher_no",
  657. "voucher_remark",
  658. "voucher_amount",
  659. "aggregation_amount",
  660. "entrust_type",
  661. "entrust1_amount",
  662. "entrust2_amount",
  663. "entrust2_amount",
  664. "total_amount",
  665. "fee_id",
  666. "type"
  667. )->get()->toArray();
  668. list($fee_amount, $fee_type_list) = $this->auxiliaryGroupListByRoot($auxiliary_list, $fee);
  669. // dd($item_key_list);
  670. //找到项目和设备的费用然后进行比例计算
  671. $return = [];
  672. foreach ($fee_amount as $v) {
  673. //人工费用
  674. if ($v['type'] == 1 || $v['type'] == 2) {
  675. // var_dump();
  676. foreach ($item_key_list as $vv) {
  677. if(!isset($item_salary[$vv['id'] . "_" . date("Y-m", $v['voucher_date'])]['allocated_salary'])) continue;
  678. $detail = [
  679. "code" => $vv['code'],
  680. "title" => $vv['title'],
  681. "state" => $vv['state'] == 3 ? "进行中" : "已完成",
  682. "voucher_date" => date("Y-m-d", $v['voucher_date']),
  683. "voucher_type" => $v['voucher_type'],
  684. "voucher_no" => $v['voucher_no'],
  685. "voucher_remark" => $v['voucher_remark'],
  686. "voucher_amount" => $v['voucher_amount'],
  687. "aggregation_amount" => $v['aggregation_amount'],
  688. "total_amount" => $v['type'] == 1 ?round( $item_salary[$vv['id'] . "_" . date("Y-m", $v['voucher_date'])]['allocated_salary'],2) : (isset($device_depreciation[$vv['id'] . "_" . date("Y-m", $v['voucher_date'])]['depreciation']) ?round($device_depreciation[$vv['id'] . "_" . date("Y-m", $v['voucher_date'])]['depreciation'],2) : 0),
  689. "fee_id" => $v['fee_id'],
  690. "entrust1_amount" => $v['entrust1_amount'],
  691. "entrust2_amount" => $v['entrust2_amount'],
  692. "type" => $v['type'],
  693. "start_time" => date('Y-m-d', $vv['start_time']),
  694. "end_time" => date('Y-m-d', $vv['end_time']),
  695. ];
  696. $return[] = $detail;
  697. }
  698. } else {
  699. if (!isset($item_key_list[$v['item_id']])) continue;
  700. $item_value = $item_key_list[$v['item_id']];
  701. $detail = [
  702. "code" => $item_value['code'],
  703. "title" => $item_value['title'],
  704. "state" => $item_value['state'] == 3 ? "进行中" : "已完成",
  705. "voucher_date" => date("Y-m-d", $v['voucher_date']),
  706. "voucher_type" => $v['voucher_type'],
  707. "voucher_no" => $v['voucher_no'],
  708. "voucher_remark" => $v['voucher_remark'],
  709. "voucher_amount" => $v['voucher_amount'],
  710. "aggregation_amount" => $v['aggregation_amount'],
  711. "total_amount" => $v['total_amount'],
  712. "fee_id" => $v['fee_id'],
  713. "entrust1_amount" => $v['entrust1_amount'],
  714. "entrust2_amount" => $v['entrust2_amount'],
  715. "type" => $v['type'],
  716. "start_time" => date('Y-m-d', $item_value['start_time']),
  717. "end_time" => date('Y-m-d', $item_value['end_time']),
  718. ];
  719. $return[] = $detail;
  720. }
  721. }
  722. return [true, [
  723. 'fee_type_list' => $fee_type_list,
  724. 'list' => $return,
  725. ]];
  726. }
  727. /**
  728. * 将报销明细按照一级费用和项目分类进行分组
  729. * * @param array $list 报销明细列表 (含 fee_id, amount 等)
  730. * @param array $fee_type_list 费用类型树 (含 id, parent_id, title)
  731. * @return array
  732. */
  733. public function auxiliaryGroupListByRoot(array $list, array $fee_type_list)
  734. {
  735. // 1. 建立 ID 索引,方便快速查找
  736. $idMap = array_column($fee_type_list, null, 'id');
  737. // 2. 预处理映射表:让所有子 ID 直接指向它的最顶层“祖宗” ID
  738. $childToRoot = [];
  739. foreach ($fee_type_list as $type) {
  740. $current = $type;
  741. // 向上追溯直到 parent_id 为 0,即找到一级分类
  742. while ($current['parent_id'] != 0) {
  743. $current = $idMap[$current['parent_id']];
  744. }
  745. $childToRoot[$type['id']] = [
  746. 'id' => $current['id'],
  747. 'title' => $current['title'],
  748. 'sort' => $current['sort']
  749. ];
  750. }
  751. // 3. 遍历明细数据进行分组
  752. $type_list = [];
  753. foreach ($list as $k => $item) {
  754. if ($item['item_id'] == 0 || $item['fee_id'] == 0) {
  755. continue;
  756. }
  757. $feeId = $item['fee_id'];
  758. // 获取该费用对应的一级分类信息
  759. if (!isset($childToRoot[$feeId])) continue;
  760. $rootId = $childToRoot[$feeId]['id'];
  761. $title = $childToRoot[$feeId]['title'];
  762. $sort = $childToRoot[$feeId]['sort'];
  763. $item['fee_id'] = $rootId;
  764. $list[$k] = $item;
  765. //这边需要拿到头部所有的一级费用类型
  766. if (!isset($type_list[$rootId])) {
  767. $type_list[$rootId] = [
  768. 'sort' => $sort,
  769. 'id' => $rootId,
  770. 'title' => $title,
  771. ];
  772. }
  773. }
  774. // 使用 values() 丢弃原始键名,重新从 0 开始建立索引
  775. $type_list = collect($type_list)->sortBy('sort')->values()->all();
  776. // 4. 重置数组索引并返回
  777. return [$list, $type_list];
  778. }
  779. public function auxiliaryEmployee($user, $data, $month_start, $month_end)
  780. {
  781. //确认所有项目、人员、人员工时
  782. $month_employee_list = $this->getItemEmployeeMonthWorkList($user, $data, $month_start, $month_end);
  783. //查询所有人员工资
  784. $salary_map = $this->getEmployeeSalary($user, $data, $month_start, $month_end);
  785. // 2. 计算每个员工在每个月的全月总工时
  786. $key = ["employee_id","order_month"];
  787. $employee_monthly_total_min = $this->calculateSum($month_employee_list,$key,"total_work");
  788. // 3. 计算分摊天数与工资
  789. list($item_list,) = $this->calculateRatioForMonth($month_employee_list,$employee_monthly_total_min,$salary_map,$key,["employee_id","month","item_id"]);
  790. $collect = collect($item_list);
  791. $employee_count = $collect->groupBy(function ($item) {
  792. // 这里的 $item 是集合中的每一行数据
  793. return $item['employee_id'] . '_' . $item['month'];
  794. })->map(function ($group) {
  795. return $group->count();
  796. })->toArray();
  797. $sums = [
  798. "salary_map" => $salary_map
  799. ];
  800. $word_keys = [
  801. "salary_map" => [
  802. "key" => "allocated_salary",
  803. "value" => "allocated_salary",
  804. "type" => "money",
  805. ]
  806. ];
  807. $employee_count = [
  808. 'salary_map' => $employee_count
  809. ];
  810. $month_employee_list = $collect->transform(function ($item) use (&$employee_count,&$sums,$word_keys) {
  811. // 如果不是最后一条
  812. $key = $item['employee_id'] . '_' . $item['month'];
  813. $this->calculateClosure($key,$item,$employee_count,$sums,$word_keys);
  814. return $item;
  815. })->all();
  816. $return_item_list = [];
  817. foreach ($month_employee_list as $v){
  818. $key = $v['item_id'] . '_' . $v['month'];
  819. if(!isset($return_item_list[$key])) $return_item_list[$key]['allocated_salary'] = 0;
  820. $return_item_list[$key]['allocated_salary'] += $v['allocated_salary'];
  821. }
  822. return $return_item_list;
  823. }
  824. public function auxiliaryDevice($user, $data, $month_start, $month_end)
  825. {
  826. $month_device_list = $this->getItemDeviceMonthWorkList($user, $data, $month_start, $month_end);
  827. //查询所有设备工资
  828. //查询所有项目人员的工时比例
  829. //汇总每个人每个月工资
  830. $depreciation_map = $this->getDeviceAmount($user, $data, $month_start, $month_end);
  831. // 2. 计算每个员工在每个月的全月总工时
  832. $key = ["device_id","order_month"];
  833. $device_monthly_total_min = $this->calculateSum($month_device_list,$key,"total_work");
  834. // 3. 计算分摊天数与工资
  835. list($item_list,) = $this->calculateDeviceRatioForMonth($month_device_list,$device_monthly_total_min,$depreciation_map,$key,["device_id","month","item_id"]);
  836. $collect = collect($item_list);
  837. $device_count = $collect->groupBy(function ($item) {
  838. // 这里的 $item 是集合中的每一行数据
  839. return $item['device_id'] . '_' . $item['month'];
  840. })->map(function ($group) {
  841. return $group->count();
  842. })->toArray();
  843. $sums = [
  844. "salary_map" => $depreciation_map
  845. ];
  846. $word_keys = [
  847. "salary_map" => [
  848. "key" => "allocated_depreciation",
  849. "value" => "depreciation",
  850. "type" => "money",
  851. ]
  852. ];
  853. $device_count = [
  854. 'salary_map' => $device_count
  855. ];
  856. $month_employee_list = $collect->transform(function ($item) use (&$device_count,&$sums,$word_keys) {
  857. $key = $item['device_id'] . '_' . $item['month'];
  858. $this->calculateClosure($key,$item,$device_count,$sums,$word_keys);
  859. return $item;
  860. })->all();
  861. $return_item_list = [];
  862. foreach ($month_employee_list as $v){
  863. $key = $v['item_id']. '_' . $v['month'];
  864. if(!isset($return_item_list[$key])) $return_item_list[$key]['depreciation'] = 0;
  865. $return_item_list[$key]['depreciation'] += $v['depreciation'];
  866. }
  867. // dd($return_item_list);
  868. return $return_item_list;
  869. }
  870. public function itemEmployeeSalaryStatisticold($data, $user)
  871. {
  872. list($status, $month_start, $month_end) = $this->commonRule($data);
  873. if (!$status) return [false, $month_start];
  874. // 获取人员工资项目相关分组数据
  875. $month_employee_list = $this->getItemEmployeeMonthWorkList($user, $data, $month_start, $month_end);
  876. // 查询所有人员工资
  877. $monthly_ps_order_ids = MonthlyPsOrder::Clear($user, $data)
  878. ->where('del_time', 0)
  879. ->where("month", ">=", $month_start)
  880. ->where("month", "<", $month_end)
  881. ->pluck('id')->toArray();
  882. $monthly_ps_order_key_list = MonthlyPsOrder::Clear($user, $data)
  883. ->where('del_time', 0)
  884. ->where("month", ">=", $month_start)
  885. ->where("month", "<", $month_end)
  886. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  887. ->pluck('month_str', 'id')
  888. ->toArray();
  889. $month_employee_salary = MonthlyPsOrderDetails::wherein('main_id', $monthly_ps_order_ids)
  890. ->select("employee_id", DB::raw("(base_salary + performance_salary + bonus + other) as salary"), "main_id", "social_insurance", "public_housing_fund")
  891. ->get()->toArray();
  892. // 1. 汇总每个人每个月工资
  893. $salary_map = [];
  894. $all_salary = [];
  895. foreach ($month_employee_salary as $val) {
  896. $month = $monthly_ps_order_key_list[$val['main_id']] ?? '';
  897. if ($month) {
  898. $key = $val['employee_id'] . '_' . $month;
  899. $salary_map[$key] = $val;
  900. $all_salary[$key] = [
  901. "salary" => (float)$val['salary'] * 100,
  902. "social_insurance" => (float)$val['social_insurance'] * 100,
  903. "public_housing_fund" => (float)$val['public_housing_fund'] * 100,
  904. ];
  905. }
  906. }
  907. // 2. 计算每个员工在每个月的全月总工时
  908. $employee_monthly_total_min = [];
  909. $all_min = [];
  910. foreach ($month_employee_list as $row) {
  911. $key = $row['employee_id'] . '_' . $row['order_month'];
  912. if (!isset($employee_monthly_total_min[$key])) {
  913. $employee_monthly_total_min[$key] = 0;
  914. $all_min[$key] = 0;
  915. }
  916. // 如果此员工该月无工资记录,初始化默认全 0 结构,防止报错
  917. if (!isset($all_salary[$key])) {
  918. $all_salary[$key] = [
  919. "salary" => 0,
  920. "social_insurance" => 0,
  921. "public_housing_fund" => 0,
  922. ];
  923. }
  924. $employee_monthly_total_min[$key] += $row['total_work'];
  925. $all_min[$key] += round($row['total_work'] / 60, 2) * 100;
  926. }
  927. // 3. 计算分摊天数与工资
  928. $item_month_list = [];
  929. foreach ($month_employee_list as $item) {
  930. $key = $item['employee_id'] . '_' . $item['order_month'];
  931. $item_key = $item['order_month'] . '_' . $item['item_id'] . '_' . $item['employee_id'];
  932. if (!isset($item_month_list[$item_key])) {
  933. $item_month_list[$item_key] = [
  934. "month" => $item['order_month'],
  935. "allocated_salary" => 0,
  936. "employee_id" => $item['employee_id'],
  937. "work_minutes" => 0,
  938. "salary" => ($salary_map[$key]['salary'] ?? 0),
  939. "social_insurance" => ($salary_map[$key]['social_insurance'] ?? 0),
  940. "public_housing_fund" => ($salary_map[$key]['public_housing_fund'] ?? 0),
  941. "item_id" => $item['item_id'],
  942. ];
  943. }
  944. $total_min = $employee_monthly_total_min[$key] ?? 0;
  945. // 计算工资分摊比例
  946. if ($total_min > 0) {
  947. // $ratio = round((round($item['total_work'] / 60, 2) / round($total_min / 60, 2)), 4);
  948. $ratio = round($item['total_work'] / $total_min, 4);
  949. } else {
  950. $ratio = 0;
  951. }
  952. $item_month_list[$item_key]['radio'] = $ratio;
  953. $item_month_list[$item_key]['total_min'] = $total_min;
  954. $item_month_list[$item_key]['work_minutes'] += $item['total_work'];
  955. }
  956. $item_month_list = collect($item_month_list)->sortBy('month')->values()->all();
  957. $items = collect($item_month_list)->pluck('item_id')->unique()->values()->all();
  958. $employee_ids = collect($item_month_list)->pluck('employee_id')->unique()->values()->all();
  959. $employee_list = Employee::TopClear($user, $data)
  960. ->wherein('id', $employee_ids)
  961. ->select("major", "title", "id")
  962. ->get()
  963. ->keyBy('id')
  964. ->toArray();
  965. $item_query = Item::TopClear($user, $data)->wherein('id', $items);
  966. $item_title_key_list = (clone $item_query)->pluck("title", "id")->toArray();
  967. $item_code_key_list = (clone $item_query)->pluck("code", "id")->toArray();
  968. $collect = collect($item_month_list);
  969. $employee_count = $collect->groupBy(function ($item) {
  970. return $item['employee_id'] . '_' . $item['month'];
  971. })->map(function ($group) {
  972. return $group->count();
  973. })->toArray();
  974. // 组装最终结果
  975. $item_month_list = collect($item_month_list)->transform(function ($item) use ($item_title_key_list, $item_code_key_list, $employee_list, &$employee_count, &$all_salary, &$all_min) {
  976. $item['item_title'] = $item_title_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  977. $item['item_code'] = $item_code_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  978. $item['employee_title'] = $employee_list[$item['employee_id']]['title'] ?? "未知人员({$item['employee_id']})";
  979. $item['major'] = $employee_list[$item['employee_id']]['major'] ?? "未知人员({$item['employee_id']})";
  980. $item['total_min'] = round($item['total_min'] / 60, 2);
  981. $key = $item['employee_id'] . '_' . $item['month'];
  982. // 容错处理:确保 $all_salary[$key] 和 $all_min[$key] 一定存在
  983. if (!isset($all_salary[$key])) {
  984. $all_salary[$key] = ['salary' => 0, 'social_insurance' => 0, 'public_housing_fund' => 0];
  985. }
  986. if (!isset($all_min[$key])) {
  987. $all_min[$key] = 0;
  988. }
  989. if (--$employee_count[$key] > 0) {
  990. $work_minutes = round($item['work_minutes'] / 60, 2);
  991. $item['work_minutes'] = $work_minutes;
  992. $all_min[$key] -= ($work_minutes * 100);
  993. $work_salary = round($item['salary'] * $item['radio'], 2);
  994. $all_salary[$key]['salary'] -= ($work_salary * 100);
  995. $item['work_salary'] = $work_salary;
  996. $social_insurance = round($item['social_insurance'] * $item['radio'], 2);
  997. $all_salary[$key]['social_insurance'] -= ($social_insurance * 100);
  998. $item['work_social_insurance'] = $social_insurance;
  999. $work_public_housing_fund = round($item['public_housing_fund'] * $item['radio'], 2);
  1000. $all_salary[$key]['public_housing_fund'] -= ($work_public_housing_fund * 100);
  1001. $item['work_public_housing_fund'] = $work_public_housing_fund;
  1002. } else {
  1003. // 最后一笔记录通过反扣差额尾差,保证总和 100% 精确对齐
  1004. $item['work_salary'] = round($all_salary[$key]['salary'] / 100, 2);
  1005. $item['work_social_insurance'] = round($all_salary[$key]['social_insurance'] / 100, 2);
  1006. $item['work_public_housing_fund'] = round($all_salary[$key]['public_housing_fund'] / 100, 2);
  1007. $item['work_minutes'] = round($all_min[$key] / 100, 2);
  1008. }
  1009. return $item;
  1010. })->all();
  1011. return [true, $item_month_list];
  1012. }
  1013. public function itemEmployeeSalaryStatistic($data, $user)
  1014. {
  1015. list($status, $month_start, $month_end) = $this->commonRule($data);
  1016. if (!$status) return [false, $month_start];
  1017. // 获取人员工资项目相关分组数据
  1018. $month_employee_list = $this->getItemEmployeeMonthWorkList($user, $data, $month_start, $month_end);
  1019. // 1. 查询所有人员工资单
  1020. $monthly_ps_order_ids = MonthlyPsOrder::Clear($user, $data)
  1021. ->where('del_time', 0)
  1022. ->where("month", ">=", $month_start)
  1023. ->where("month", "<", $month_end)
  1024. ->pluck('id')->toArray();
  1025. $monthly_ps_order_key_list = MonthlyPsOrder::Clear($user, $data)
  1026. ->where('del_time', 0)
  1027. ->where("month", ">=", $month_start)
  1028. ->where("month", "<", $month_end)
  1029. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  1030. ->pluck('month_str', 'id')
  1031. ->toArray();
  1032. $month_employee_salary = MonthlyPsOrderDetails::wherein('main_id', $monthly_ps_order_ids)
  1033. ->select("employee_id", DB::raw("(base_salary + performance_salary + bonus + other) as salary"), "main_id", "social_insurance", "public_housing_fund")
  1034. ->get()->toArray();
  1035. // 2. 查询所有人员月度工时单 (新增逻辑)
  1036. $monthly_pw_order_key_list = MonthlyPwOrder::Clear($user, $data)
  1037. ->where('del_time', 0)
  1038. ->where("month", ">=", $month_start)
  1039. ->where("month", "<", $month_end)
  1040. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  1041. ->pluck('month_str', 'id')
  1042. ->toArray();
  1043. $monthly_pw_order_ids = array_keys($monthly_pw_order_key_list);
  1044. $month_employee_pw = MonthlyPwOrderDetails::whereIn('main_id', $monthly_pw_order_ids)
  1045. ->where('del_time', 0)
  1046. ->select('employee_id', 'main_id', 'total_hours')
  1047. ->get()->toArray();
  1048. $pw_hours_map = [];
  1049. foreach ($month_employee_pw as $pw_val) {
  1050. $pw_month = $monthly_pw_order_key_list[$pw_val['main_id']] ?? '';
  1051. if ($pw_month) {
  1052. $pw_key = $pw_val['employee_id'] . '_' . $pw_month;
  1053. $pw_hours_map[$pw_key] = (float)$pw_val['total_hours'];
  1054. }
  1055. }
  1056. // 3. 汇总每个人每个月工资
  1057. $salary_map = [];
  1058. $all_salary = [];
  1059. foreach ($month_employee_salary as $val) {
  1060. $month = $monthly_ps_order_key_list[$val['main_id']] ?? '';
  1061. if ($month) {
  1062. $key = $val['employee_id'] . '_' . $month;
  1063. $salary_map[$key] = $val;
  1064. $all_salary[$key] = [
  1065. "salary" => (float)$val['salary'] * 100,
  1066. "social_insurance" => (float)$val['social_insurance'] * 100,
  1067. "public_housing_fund" => (float)$val['public_housing_fund'] * 100,
  1068. ];
  1069. }
  1070. }
  1071. // 4. 获取每个员工在每个月的全月总工时(改自月度工时单)
  1072. $employee_monthly_total_min = [];
  1073. $all_min = [];
  1074. foreach ($month_employee_list as $row) {
  1075. $key = $row['employee_id'] . '_' . $row['order_month'];
  1076. if (!isset($employee_monthly_total_min[$key])) {
  1077. // 直接从工时单映射中获取小时数,乘以 60 转为分钟供后续比例计算
  1078. $total_hours = $pw_hours_map[$key] ?? 0;
  1079. $employee_monthly_total_min[$key] = $total_hours * 60;
  1080. $all_min[$key] = round($total_hours * 100, 2); // 放大100倍用于尾差倒扣
  1081. }
  1082. // 如果此员工该月无工资记录,初始化默认全 0 结构,防止报错
  1083. if (!isset($all_salary[$key])) {
  1084. $all_salary[$key] = [
  1085. "salary" => 0,
  1086. "social_insurance" => 0,
  1087. "public_housing_fund" => 0,
  1088. ];
  1089. }
  1090. }
  1091. // 5. 计算分摊天数与工资
  1092. $item_month_list = [];
  1093. foreach ($month_employee_list as $item) {
  1094. $key = $item['employee_id'] . '_' . $item['order_month'];
  1095. $item_key = $item['order_month'] . '_' . $item['item_id'] . '_' . $item['employee_id'];
  1096. if (!isset($item_month_list[$item_key])) {
  1097. $item_month_list[$item_key] = [
  1098. "month" => $item['order_month'],
  1099. "allocated_salary" => 0,
  1100. "employee_id" => $item['employee_id'],
  1101. "work_minutes" => 0,
  1102. "salary" => ($salary_map[$key]['salary'] ?? 0),
  1103. "social_insurance" => ($salary_map[$key]['social_insurance'] ?? 0),
  1104. "public_housing_fund" => ($salary_map[$key]['public_housing_fund'] ?? 0),
  1105. "item_id" => $item['item_id'],
  1106. ];
  1107. }
  1108. $total_min = $employee_monthly_total_min[$key] ?? 0;
  1109. // 计算工资分摊比例(项目实际工作分钟数 / 工时单月度总分钟数)
  1110. if ($total_min > 0) {
  1111. $ratio = round($item['total_work'] / $total_min, 4);
  1112. } else {
  1113. $ratio = 0;
  1114. }
  1115. $item_month_list[$item_key]['radio'] = $ratio;
  1116. $item_month_list[$item_key]['total_min'] = $total_min;
  1117. $item_month_list[$item_key]['work_minutes'] += $item['total_work'];
  1118. }
  1119. $item_month_list = collect($item_month_list)->sortBy('month')->values()->all();
  1120. $items = collect($item_month_list)->pluck('item_id')->unique()->values()->all();
  1121. $employee_ids = collect($item_month_list)->pluck('employee_id')->unique()->values()->all();
  1122. $employee_list = Employee::TopClear($user, $data)
  1123. ->wherein('id', $employee_ids)
  1124. ->select("major", "title", "id")
  1125. ->get()
  1126. ->keyBy('id')
  1127. ->toArray();
  1128. $item_query = Item::TopClear($user, $data)->wherein('id', $items);
  1129. $item_title_key_list = (clone $item_query)->pluck("title", "id")->toArray();
  1130. $item_code_key_list = (clone $item_query)->pluck("code", "id")->toArray();
  1131. $collect = collect($item_month_list);
  1132. $employee_count = $collect->groupBy(function ($item) {
  1133. return $item['employee_id'] . '_' . $item['month'];
  1134. })->map(function ($group) {
  1135. return $group->count();
  1136. })->toArray();
  1137. // 6. 组装最终结果
  1138. $item_month_list = collect($item_month_list)->transform(function ($item) use ($item_title_key_list, $item_code_key_list, $employee_list, &$employee_count, &$all_salary, &$all_min) {
  1139. $item['item_title'] = $item_title_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  1140. $item['item_code'] = $item_code_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  1141. $item['employee_title'] = $employee_list[$item['employee_id']]['title'] ?? "未知人员({$item['employee_id']})";
  1142. $item['major'] = $employee_list[$item['employee_id']]['major'] ?? "未知人员({$item['employee_id']})";
  1143. $item['total_min'] = round($item['total_min'] / 60, 2);
  1144. $key = $item['employee_id'] . '_' . $item['month'];
  1145. // 容错处理:确保 $all_salary[$key] 和 $all_min[$key] 一定存在
  1146. if (!isset($all_salary[$key])) {
  1147. $all_salary[$key] = ['salary' => 0, 'social_insurance' => 0, 'public_housing_fund' => 0];
  1148. }
  1149. if (!isset($all_min[$key])) {
  1150. $all_min[$key] = 0;
  1151. }
  1152. if (--$employee_count[$key] > 0) {
  1153. $work_minutes = round($item['work_minutes'] / 60, 2);
  1154. $item['work_minutes'] = $work_minutes;
  1155. $all_min[$key] -= ($work_minutes * 100);
  1156. $work_salary = round($item['salary'] * $item['radio'], 2);
  1157. $all_salary[$key]['salary'] -= ($work_salary * 100);
  1158. $item['work_salary'] = $work_salary;
  1159. $social_insurance = round($item['social_insurance'] * $item['radio'], 2);
  1160. $all_salary[$key]['social_insurance'] -= ($social_insurance * 100);
  1161. $item['work_social_insurance'] = $social_insurance;
  1162. $work_public_housing_fund = round($item['public_housing_fund'] * $item['radio'], 2);
  1163. $all_salary[$key]['public_housing_fund'] -= ($work_public_housing_fund * 100);
  1164. $item['work_public_housing_fund'] = $work_public_housing_fund;
  1165. } else {
  1166. // 最后一笔记录通过反扣差额尾差,保证总和 100% 精确对齐
  1167. $item['work_salary'] = round($all_salary[$key]['salary'] / 100, 2);
  1168. $item['work_social_insurance'] = round($all_salary[$key]['social_insurance'] / 100, 2);
  1169. $item['work_public_housing_fund'] = round($all_salary[$key]['public_housing_fund'] / 100, 2);
  1170. $item['work_minutes'] = round($all_min[$key] / 100, 2);
  1171. }
  1172. return $item;
  1173. })->all();
  1174. return [true, $item_month_list];
  1175. }
  1176. public function enterpriseRdStatistic($data, $user){
  1177. $model = Item::TopClear($user,$data);
  1178. $model = $model->where('del_time',0)
  1179. ->select(Item::$report_field_1)
  1180. ->orderby('id', 'desc');
  1181. if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
  1182. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  1183. if(! empty($data['state'])) $model->where('state', $data['state']);
  1184. if(! empty($data['year'])) {
  1185. $return = $this->getYearRangeInfo($data['year']);
  1186. if (is_null($return)) return [false, '年度格式错误'];
  1187. list($month_start, $month_end) = $return;
  1188. $model->where("start_time", "<", strtotime($month_end)) // 项目开始得比月份结束早
  1189. ->where("end_time", ">", strtotime($month_start)); // 项目结束得比月份开始晚
  1190. }
  1191. $list = $model->get()->toArray();
  1192. if(empty($list)) return [true,[]];
  1193. $datetime = $list[0]['start_time'];
  1194. $list = $this->fillEnterpriseRdStatistic($list, $data, $user,$datetime);
  1195. return [true, $list];
  1196. }
  1197. private function fillEnterpriseRdStatistic($list, $data, $user,$time){
  1198. //项目实际支出 项目费用单
  1199. // $expense = ExpenseClaimsDetails::Clear($user, $data);
  1200. // $expense_map = $expense->where('del_time', 0)
  1201. // ->whereIn('item_id', array_unique(array_column($list,'id')))
  1202. // ->selectRaw('item_id, SUM(amount) as total_amount')
  1203. // ->groupBy('item_id')
  1204. // ->pluck('total_amount', 'item_id') // 这一步直接生成 item_id => total_amount 结构
  1205. // ->toArray();
  1206. $attendance = $this->employeeAttendanceMonthStatistic(["year"=>date("Y-m-d",$time), "s" => "/api/employeeAttendanceMonthStatistic"],$user);
  1207. $attendance_key_list = [];
  1208. foreach ($attendance[1]['list'] as $v){
  1209. $attendance_key_list[$v['code']] = $v['employee_salary']*100+$v['device_depreciation']*100;
  1210. foreach ($v['fee_list'] as $vv){
  1211. $attendance_key_list[$v['code']] += $vv['total_amount']*100;
  1212. $attendance_key_list[$v['code']] += $vv['entrust1_amount']*100;
  1213. $attendance_key_list[$v['code']] += $vv['entrust2_amount']*100;
  1214. }
  1215. }
  1216. // dd($attendance_key_list);
  1217. foreach ($list as $key => $value){
  1218. $list[$key]['actual_expenditure'] = isset($attendance_key_list[$value['code']]) ? round($attendance_key_list[$value['code']]/100,2) : 0;
  1219. $start_time = $value['start_time'] ? date('Y-m-d', $value['start_time']) : '';
  1220. $end_time = $value['end_time'] ? date('Y-m-d', $value['end_time']) : '';
  1221. $list[$key]['time_range'] = $start_time . ' ' . $end_time;
  1222. }
  1223. return $list;
  1224. }
  1225. public function enterpriseRdManStatistic($data, $user){
  1226. $model = Employee::TopClear($user,$data);
  1227. $model = $model->where('del_time',0)
  1228. ->where('is_admin', '<=', Employee::IS_ADMIN_ONE)
  1229. ->select(Employee::$report_field)
  1230. ->orderBy('id','desc');
  1231. if(! empty($data['id_card'])) $model->where('id_card', 'LIKE', '%'.$data['id_card'].'%');
  1232. if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
  1233. if(! empty($data['employee_type'])) $model->where('employee_type', $data['employee_type']);
  1234. if(isset($data['education'])) $model->where('education', $data['education']);
  1235. $list = $model->get()->toArray();
  1236. $list = $this->fillEnterpriseRdManStatistic($list, $data, $user);
  1237. return [true, $list];
  1238. }
  1239. private function fillEnterpriseRdManStatistic($list, $data, $user){
  1240. $man = EmployeeDepartPermission::from('employee_depart_permission as a')
  1241. ->join('depart as b', 'b.id', '=', 'a.depart_id')
  1242. ->whereIn('a.employee_id', array_unique(array_column($list,'id')))
  1243. ->select('a.employee_id', 'b.title')
  1244. ->get()->toArray();
  1245. $man_map = [];
  1246. foreach ($man as $value){
  1247. if(isset($man_map[$value['employee_id']])){
  1248. $man_map[$value['employee_id']] .= ',' . $value['title'];
  1249. }else{
  1250. $man_map[$value['employee_id']] = $value['title'];
  1251. }
  1252. }
  1253. foreach ($list as $key => $value){
  1254. $depart_title = $man_map[$value['id']] ?? "";
  1255. $list[$key]['position_new'] = $depart_title . '/' . $value['position'];
  1256. $list[$key]['employee_type_title'] = Employee::E_State_Type[$value['employee_type']] ?? '';
  1257. $list[$key]['education'] = Employee::Education[$value['education']] ?? '';
  1258. }
  1259. return $list;
  1260. }
  1261. // 取别名
  1262. public function enterpriseRdItemStatistic($data, $user){
  1263. // 1. 先声明表名和别名
  1264. $model = ItemDetails::from('item_details as i');
  1265. // 2. 再调用 TopClear
  1266. $model = $model->TopClear($user, $data);
  1267. $model = $model->where('i.del_time', 0)
  1268. ->where('i.type', ItemDetails::type_one);
  1269. $model = $model->leftJoin('employee as e', 'i.data_id', '=', 'e.id');
  1270. $model = $model->leftJoin('item as it', 'it.id', '=', 'i.item_id');
  1271. if(! empty($data['title'])) $model->where('e.title', 'LIKE', '%'.$data['title'].'%');
  1272. if(! empty($data['item_title'])) $model->where('it.title', 'LIKE', '%'.$data['item_title'].'%');
  1273. $fields = ['e.id', 'e.title', 'e.education', 'e.major','e.p_title','i.item_id','it.title as item_title'];
  1274. $list = $model->select($fields)
  1275. ->orderBy('i.id', 'desc')
  1276. ->get()
  1277. ->toArray();
  1278. $list = $this->fillEnterpriseRdItemStatistic($list, $data, $user);
  1279. return [true, $list];
  1280. }
  1281. private function fillEnterpriseRdItemStatistic($list, $data, $user){
  1282. $man = EmployeeDepartPermission::from('employee_depart_permission as a')
  1283. ->join('depart as b', 'b.id', '=', 'a.depart_id')
  1284. ->whereIn('a.employee_id', array_unique(array_column($list,'id')))
  1285. ->select('a.employee_id', 'b.title')
  1286. ->get()->toArray();
  1287. $man_map = [];
  1288. foreach ($man as $value){
  1289. if(isset($man_map[$value['employee_id']])){
  1290. $man_map[$value['employee_id']] .= ',' . $value['title'];
  1291. }else{
  1292. $man_map[$value['employee_id']] = $value['title'];
  1293. }
  1294. }
  1295. foreach ($list as $key => $value){
  1296. $depart_title = $man_map[$value['id']] ?? "";
  1297. $list[$key]['depart_title'] = $depart_title;
  1298. $list[$key]['education'] = Employee::Education[$value['education']] ?? '';
  1299. }
  1300. return $list;
  1301. }
  1302. public function employeeMonthSalaryStatisticCountCommon($data,$user){
  1303. $model = MonthlyPsOrder::Clear($user,$data);
  1304. $model->leftJoin('monthly_ps_order_details as b', 'b.main_id', 'monthly_ps_order.id')
  1305. ->where('monthly_ps_order.del_time',0)
  1306. ->where('b.del_time',0)
  1307. ->select('monthly_ps_order.month', 'b.employee_id', 'b.base_salary','b.performance_salary','b.bonus','b.other')
  1308. ->orderby('monthly_ps_order.month','desc');
  1309. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  1310. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  1311. $model->where('monthly_ps_order.month','>=',$return[0]);
  1312. $model->where('monthly_ps_order.month','<=',$return[1]);
  1313. }
  1314. if(! empty($data['employee_title'])){
  1315. $model_2 = Employee::TopClear($user,$data);
  1316. $id = $model_2->where('del_time',0)
  1317. ->where('title', 'LIKE', '%'.$data['employee_title'].'%')
  1318. ->pluck('id')
  1319. ->toArray();
  1320. $model->whereIn('b.employee_id', $id);
  1321. }
  1322. return $model;
  1323. }
  1324. public function employeeMonthSalaryStatisticCount($data, $user){
  1325. $model = $this->employeeMonthSalaryStatisticCountCommon($data, $user);
  1326. $list = $this->limit($model,'',$data);
  1327. $list = $this->fillEmployeeMonthSalaryStatisticCount($list, $data, $user);
  1328. return [true, $list];
  1329. }
  1330. public function fillEmployeeMonthSalaryStatisticCount($data, $ergs, $user){
  1331. if(empty($data['data'])) return $data;
  1332. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'employee_id')));
  1333. foreach ($data['data'] as $key => $value){
  1334. $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
  1335. $data['data'][$key]['employee_title'] = $emp[$value['employee_id']] ?? '';
  1336. $totalSalary = (float)($value['base_salary'] ?? 0)
  1337. + (float)($value['performance_salary'] ?? 0)
  1338. + (float)($value['bonus'] ?? 0)
  1339. + (float)($value['other'] ?? 0);
  1340. $data['data'][$key]['total_salary'] = number_format($totalSalary, 2, '.', '');
  1341. }
  1342. return $data;
  1343. }
  1344. /**
  1345. * 获取人员维度的研发工资及工时汇总报表
  1346. * * @param array $data 包含时间范围或年份的请求数据
  1347. * @param object $user 当前用户上下文
  1348. * @return array
  1349. */
  1350. public function employeeSalarySummary($data, $user)
  1351. {
  1352. // 1. 复用时间解析和校验规则
  1353. list($status, $month_start, $month_end) = $this->commonRule($data);
  1354. if (!$status) return [false, $month_start];
  1355. // 2. 复用原始数据拉取:项目人员工时、人员全额原始工资
  1356. $month_employee_list = $this->getItemEmployeeMonthWorkList($user, $data, $month_start, $month_end);
  1357. $salary_map = $this->getEmployeeSalary($user, $data, $month_start, $month_end);
  1358. // 3. 计算每个员工的月总工时(作为分母)
  1359. $keys = ["employee_id", "order_month"];
  1360. $employee_monthly_total_min = $this->calculateSum($month_employee_list, $keys, "total_work");
  1361. // 4. 调用核心分摊算法(拿到每一项明细的 allocated_salary)
  1362. list($item_month_list, ) = $this->calculateRatioForMonth(
  1363. $month_employee_list,
  1364. $employee_monthly_total_min,
  1365. $salary_map,
  1366. ["employee_id", "order_month"],
  1367. ["order_month", "item_id", "employee_id"]
  1368. );
  1369. // 5. 将分摊数据转化为集合,纯粹根据【员工ID + 月份】进行分组汇总
  1370. $collect = collect($item_month_list);
  1371. $employee_ids = $collect->pluck('employee_id')->unique()->values()->all();
  1372. // 6. 仅拉取人员档案名称,不再拉取项目档案(省去不必要的查询,提升性能)
  1373. $employeeModel = Employee::TopClear($user, $data);
  1374. $employee_title_map = $employeeModel->wherein('id', $employee_ids)->pluck("title", "id")->toArray();
  1375. // 7. 开始聚合
  1376. $result = $collect->groupBy(function ($item) {
  1377. // 根据 员工ID_月份 分组,支持跨月查询时的正确归类
  1378. return $item['employee_id'] . '_' . $item['month'];
  1379. })->map(function ($group) use ($employee_title_map) {
  1380. $first = $group->first();
  1381. // 汇总这个人当月在所有项目里的研发工资(分),然后除以 100 变成元
  1382. $total_allocated_salary = round($group->sum('allocated_salary') / 100, 2);
  1383. // 汇总这个人当月的研发总工时(分钟转小时)
  1384. $total_work_hours = round($group->sum('work_minutes') / 60, 2);
  1385. return [
  1386. 'month' => $first['month'],
  1387. 'employee_id' => $first['employee_id'],
  1388. 'employee_title' => $employee_title_map[$first['employee_id']] ?? "未知人员({$first['employee_id']})",
  1389. // '研发总工时(小时)' => $total_work_hours,
  1390. 'money' => $total_allocated_salary // 这里就是您要的纯人员维度的研发工资总额
  1391. ];
  1392. })->values()->all();
  1393. return [true, $result];
  1394. }
  1395. }