StatisticService.php 78 KB

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