StatisticService.php 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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. $ratio = round($item['total_work'] / $total_min, 4);
  947. } else {
  948. $ratio = 0;
  949. }
  950. $item_month_list[$item_key]['radio'] = $ratio;
  951. $item_month_list[$item_key]['total_min'] = $total_min;
  952. $item_month_list[$item_key]['work_minutes'] += $item['total_work'];
  953. }
  954. $item_month_list = collect($item_month_list)->sortBy('month')->values()->all();
  955. $items = collect($item_month_list)->pluck('item_id')->unique()->values()->all();
  956. $employee_ids = collect($item_month_list)->pluck('employee_id')->unique()->values()->all();
  957. $employee_list = Employee::TopClear($user, $data)
  958. ->wherein('id', $employee_ids)
  959. ->select("major", "title", "id")
  960. ->get()
  961. ->keyBy('id')
  962. ->toArray();
  963. $item_query = Item::TopClear($user, $data)->wherein('id', $items);
  964. $item_title_key_list = (clone $item_query)->pluck("title", "id")->toArray();
  965. $item_code_key_list = (clone $item_query)->pluck("code", "id")->toArray();
  966. $collect = collect($item_month_list);
  967. $employee_count = $collect->groupBy(function ($item) {
  968. return $item['employee_id'] . '_' . $item['month'];
  969. })->map(function ($group) {
  970. return $group->count();
  971. })->toArray();
  972. // 组装最终结果
  973. $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) {
  974. $item['item_title'] = $item_title_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  975. $item['item_code'] = $item_code_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  976. $item['employee_title'] = $employee_list[$item['employee_id']]['title'] ?? "未知人员({$item['employee_id']})";
  977. $item['major'] = $employee_list[$item['employee_id']]['major'] ?? "未知人员({$item['employee_id']})";
  978. $item['total_min'] = round($item['total_min'] / 60, 2);
  979. $key = $item['employee_id'] . '_' . $item['month'];
  980. // 容错处理:确保 $all_salary[$key] 和 $all_min[$key] 一定存在
  981. if (!isset($all_salary[$key])) {
  982. $all_salary[$key] = ['salary' => 0, 'social_insurance' => 0, 'public_housing_fund' => 0];
  983. }
  984. if (!isset($all_min[$key])) {
  985. $all_min[$key] = 0;
  986. }
  987. if (--$employee_count[$key] > 0) {
  988. $work_minutes = round($item['work_minutes'] / 60, 2);
  989. $item['work_minutes'] = $work_minutes;
  990. $all_min[$key] -= ($work_minutes * 100);
  991. $work_salary = round($item['salary'] * $item['radio'], 2);
  992. $all_salary[$key]['salary'] -= ($work_salary * 100);
  993. $item['work_salary'] = $work_salary;
  994. $social_insurance = round($item['social_insurance'] * $item['radio'], 2);
  995. $all_salary[$key]['social_insurance'] -= ($social_insurance * 100);
  996. $item['work_social_insurance'] = $social_insurance;
  997. $work_public_housing_fund = round($item['public_housing_fund'] * $item['radio'], 2);
  998. $all_salary[$key]['public_housing_fund'] -= ($work_public_housing_fund * 100);
  999. $item['work_public_housing_fund'] = $work_public_housing_fund;
  1000. } else {
  1001. // 最后一笔记录通过反扣差额尾差,保证总和 100% 精确对齐
  1002. $item['work_salary'] = round($all_salary[$key]['salary'] / 100, 2);
  1003. $item['work_social_insurance'] = round($all_salary[$key]['social_insurance'] / 100, 2);
  1004. $item['work_public_housing_fund'] = round($all_salary[$key]['public_housing_fund'] / 100, 2);
  1005. $item['work_minutes'] = round($all_min[$key] / 100, 2);
  1006. }
  1007. return $item;
  1008. })->all();
  1009. return [true, $item_month_list];
  1010. }
  1011. public function enterpriseRdStatistic($data, $user){
  1012. $model = Item::TopClear($user,$data);
  1013. $model = $model->where('del_time',0)
  1014. ->select(Item::$report_field_1)
  1015. ->orderby('id', 'desc');
  1016. if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
  1017. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  1018. if(! empty($data['state'])) $model->where('state', $data['state']);
  1019. if(! empty($data['year'])) {
  1020. $return = $this->getYearRangeInfo($data['year']);
  1021. if (is_null($return)) return [false, '年度格式错误'];
  1022. list($month_start, $month_end) = $return;
  1023. $model->where("start_time", "<", strtotime($month_end)) // 项目开始得比月份结束早
  1024. ->where("end_time", ">", strtotime($month_start)); // 项目结束得比月份开始晚
  1025. }
  1026. $list = $model->get()->toArray();
  1027. if(empty($list)) return [true,[]];
  1028. $datetime = $list[0]['start_time'];
  1029. $list = $this->fillEnterpriseRdStatistic($list, $data, $user,$datetime);
  1030. return [true, $list];
  1031. }
  1032. private function fillEnterpriseRdStatistic($list, $data, $user,$time){
  1033. //项目实际支出 项目费用单
  1034. // $expense = ExpenseClaimsDetails::Clear($user, $data);
  1035. // $expense_map = $expense->where('del_time', 0)
  1036. // ->whereIn('item_id', array_unique(array_column($list,'id')))
  1037. // ->selectRaw('item_id, SUM(amount) as total_amount')
  1038. // ->groupBy('item_id')
  1039. // ->pluck('total_amount', 'item_id') // 这一步直接生成 item_id => total_amount 结构
  1040. // ->toArray();
  1041. $attendance = $this->employeeAttendanceMonthStatistic(["year"=>date("Y-m-d",$time), "s" => "/api/employeeAttendanceMonthStatistic"],$user);
  1042. $attendance_key_list = [];
  1043. foreach ($attendance[1]['list'] as $v){
  1044. $attendance_key_list[$v['code']] = $v['employee_salary']*100+$v['device_depreciation']*100;
  1045. foreach ($v['fee_list'] as $vv){
  1046. $attendance_key_list[$v['code']] += $vv['total_amount']*100;
  1047. $attendance_key_list[$v['code']] += $vv['entrust1_amount']*100;
  1048. $attendance_key_list[$v['code']] += $vv['entrust2_amount']*100;
  1049. }
  1050. }
  1051. // dd($attendance_key_list);
  1052. foreach ($list as $key => $value){
  1053. $list[$key]['actual_expenditure'] = isset($attendance_key_list[$value['code']]) ? round($attendance_key_list[$value['code']]/100,2) : 0;
  1054. $start_time = $value['start_time'] ? date('Y-m-d', $value['start_time']) : '';
  1055. $end_time = $value['end_time'] ? date('Y-m-d', $value['end_time']) : '';
  1056. $list[$key]['time_range'] = $start_time . ' ' . $end_time;
  1057. }
  1058. return $list;
  1059. }
  1060. public function enterpriseRdManStatistic($data, $user){
  1061. $model = Employee::TopClear($user,$data);
  1062. $model = $model->where('del_time',0)
  1063. ->where('is_admin', '<=', Employee::IS_ADMIN_ONE)
  1064. ->select(Employee::$report_field)
  1065. ->orderBy('id','desc');
  1066. if(! empty($data['id_card'])) $model->where('id_card', 'LIKE', '%'.$data['id_card'].'%');
  1067. if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
  1068. if(! empty($data['employee_type'])) $model->where('employee_type', $data['employee_type']);
  1069. if(isset($data['education'])) $model->where('education', $data['education']);
  1070. $list = $model->get()->toArray();
  1071. $list = $this->fillEnterpriseRdManStatistic($list, $data, $user);
  1072. return [true, $list];
  1073. }
  1074. private function fillEnterpriseRdManStatistic($list, $data, $user){
  1075. $man = EmployeeDepartPermission::from('employee_depart_permission as a')
  1076. ->join('depart as b', 'b.id', '=', 'a.depart_id')
  1077. ->whereIn('a.employee_id', array_unique(array_column($list,'id')))
  1078. ->select('a.employee_id', 'b.title')
  1079. ->get()->toArray();
  1080. $man_map = [];
  1081. foreach ($man as $value){
  1082. if(isset($man_map[$value['employee_id']])){
  1083. $man_map[$value['employee_id']] .= ',' . $value['title'];
  1084. }else{
  1085. $man_map[$value['employee_id']] = $value['title'];
  1086. }
  1087. }
  1088. foreach ($list as $key => $value){
  1089. $depart_title = $man_map[$value['id']] ?? "";
  1090. $list[$key]['position_new'] = $depart_title . '/' . $value['position'];
  1091. $list[$key]['employee_type_title'] = Employee::E_State_Type[$value['employee_type']] ?? '';
  1092. $list[$key]['education'] = Employee::Education[$value['education']] ?? '';
  1093. }
  1094. return $list;
  1095. }
  1096. // 取别名
  1097. public function enterpriseRdItemStatistic($data, $user){
  1098. // 1. 先声明表名和别名
  1099. $model = ItemDetails::from('item_details as i');
  1100. // 2. 再调用 TopClear
  1101. $model = $model->TopClear($user, $data);
  1102. $model = $model->where('i.del_time', 0)
  1103. ->where('i.type', ItemDetails::type_one);
  1104. $model = $model->leftJoin('employee as e', 'i.data_id', '=', 'e.id');
  1105. $model = $model->leftJoin('item as it', 'it.id', '=', 'i.item_id');
  1106. if(! empty($data['title'])) $model->where('e.title', 'LIKE', '%'.$data['title'].'%');
  1107. if(! empty($data['item_title'])) $model->where('it.title', 'LIKE', '%'.$data['item_title'].'%');
  1108. $fields = ['e.id', 'e.title', 'e.education', 'e.major','e.p_title','i.item_id','it.title as item_title'];
  1109. $list = $model->select($fields)
  1110. ->orderBy('i.id', 'desc')
  1111. ->get()
  1112. ->toArray();
  1113. $list = $this->fillEnterpriseRdItemStatistic($list, $data, $user);
  1114. return [true, $list];
  1115. }
  1116. private function fillEnterpriseRdItemStatistic($list, $data, $user){
  1117. $man = EmployeeDepartPermission::from('employee_depart_permission as a')
  1118. ->join('depart as b', 'b.id', '=', 'a.depart_id')
  1119. ->whereIn('a.employee_id', array_unique(array_column($list,'id')))
  1120. ->select('a.employee_id', 'b.title')
  1121. ->get()->toArray();
  1122. $man_map = [];
  1123. foreach ($man as $value){
  1124. if(isset($man_map[$value['employee_id']])){
  1125. $man_map[$value['employee_id']] .= ',' . $value['title'];
  1126. }else{
  1127. $man_map[$value['employee_id']] = $value['title'];
  1128. }
  1129. }
  1130. foreach ($list as $key => $value){
  1131. $depart_title = $man_map[$value['id']] ?? "";
  1132. $list[$key]['depart_title'] = $depart_title;
  1133. $list[$key]['education'] = Employee::Education[$value['education']] ?? '';
  1134. }
  1135. return $list;
  1136. }
  1137. public function employeeMonthSalaryStatisticCountCommon($data,$user){
  1138. $model = MonthlyPsOrder::Clear($user,$data);
  1139. $model->leftJoin('monthly_ps_order_details as b', 'b.main_id', 'monthly_ps_order.id')
  1140. ->where('monthly_ps_order.del_time',0)
  1141. ->where('b.del_time',0)
  1142. ->select('monthly_ps_order.month', 'b.employee_id', 'b.base_salary','b.performance_salary','b.bonus','b.other')
  1143. ->orderby('monthly_ps_order.month','desc');
  1144. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  1145. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  1146. $model->where('monthly_ps_order.month','>=',$return[0]);
  1147. $model->where('monthly_ps_order.month','<=',$return[1]);
  1148. }
  1149. if(! empty($data['employee_title'])){
  1150. $model_2 = Employee::TopClear($user,$data);
  1151. $id = $model_2->where('del_time',0)
  1152. ->where('title', 'LIKE', '%'.$data['employee_title'].'%')
  1153. ->pluck('id')
  1154. ->toArray();
  1155. $model->whereIn('b.employee_id', $id);
  1156. }
  1157. return $model;
  1158. }
  1159. public function employeeMonthSalaryStatisticCount($data, $user){
  1160. $model = $this->employeeMonthSalaryStatisticCountCommon($data, $user);
  1161. $list = $this->limit($model,'',$data);
  1162. $list = $this->fillEmployeeMonthSalaryStatisticCount($list, $data, $user);
  1163. return [true, $list];
  1164. }
  1165. public function fillEmployeeMonthSalaryStatisticCount($data, $ergs, $user){
  1166. if(empty($data['data'])) return $data;
  1167. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'employee_id')));
  1168. foreach ($data['data'] as $key => $value){
  1169. $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
  1170. $data['data'][$key]['employee_title'] = $emp[$value['employee_id']] ?? '';
  1171. $totalSalary = (float)($value['base_salary'] ?? 0)
  1172. + (float)($value['performance_salary'] ?? 0)
  1173. + (float)($value['bonus'] ?? 0)
  1174. + (float)($value['other'] ?? 0);
  1175. $data['data'][$key]['total_salary'] = number_format($totalSalary, 2, '.', '');
  1176. }
  1177. return $data;
  1178. }
  1179. /**
  1180. * 获取人员维度的研发工资及工时汇总报表
  1181. * * @param array $data 包含时间范围或年份的请求数据
  1182. * @param object $user 当前用户上下文
  1183. * @return array
  1184. */
  1185. public function employeeSalarySummary($data, $user)
  1186. {
  1187. // 1. 复用时间解析和校验规则
  1188. list($status, $month_start, $month_end) = $this->commonRule($data);
  1189. if (!$status) return [false, $month_start];
  1190. // 2. 复用原始数据拉取:项目人员工时、人员全额原始工资
  1191. $month_employee_list = $this->getItemEmployeeMonthWorkList($user, $data, $month_start, $month_end);
  1192. $salary_map = $this->getEmployeeSalary($user, $data, $month_start, $month_end);
  1193. // 3. 计算每个员工的月总工时(作为分母)
  1194. $keys = ["employee_id", "order_month"];
  1195. $employee_monthly_total_min = $this->calculateSum($month_employee_list, $keys, "total_work");
  1196. // 4. 调用核心分摊算法(拿到每一项明细的 allocated_salary)
  1197. list($item_month_list, ) = $this->calculateRatioForMonth(
  1198. $month_employee_list,
  1199. $employee_monthly_total_min,
  1200. $salary_map,
  1201. ["employee_id", "order_month"],
  1202. ["order_month", "item_id", "employee_id"]
  1203. );
  1204. // 5. 将分摊数据转化为集合,纯粹根据【员工ID + 月份】进行分组汇总
  1205. $collect = collect($item_month_list);
  1206. $employee_ids = $collect->pluck('employee_id')->unique()->values()->all();
  1207. // 6. 仅拉取人员档案名称,不再拉取项目档案(省去不必要的查询,提升性能)
  1208. $employeeModel = Employee::TopClear($user, $data);
  1209. $employee_title_map = $employeeModel->wherein('id', $employee_ids)->pluck("title", "id")->toArray();
  1210. // 7. 开始聚合
  1211. $result = $collect->groupBy(function ($item) {
  1212. // 根据 员工ID_月份 分组,支持跨月查询时的正确归类
  1213. return $item['employee_id'] . '_' . $item['month'];
  1214. })->map(function ($group) use ($employee_title_map) {
  1215. $first = $group->first();
  1216. // 汇总这个人当月在所有项目里的研发工资(分),然后除以 100 变成元
  1217. $total_allocated_salary = round($group->sum('allocated_salary') / 100, 2);
  1218. // 汇总这个人当月的研发总工时(分钟转小时)
  1219. $total_work_hours = round($group->sum('work_minutes') / 60, 2);
  1220. return [
  1221. 'month' => $first['month'],
  1222. 'employee_id' => $first['employee_id'],
  1223. 'employee_title' => $employee_title_map[$first['employee_id']] ?? "未知人员({$first['employee_id']})",
  1224. // '研发总工时(小时)' => $total_work_hours,
  1225. 'money' => $total_allocated_salary // 这里就是您要的纯人员维度的研发工资总额
  1226. ];
  1227. })->values()->all();
  1228. return [true, $result];
  1229. }
  1230. }