StatisticService.php 64 KB

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