StatisticService.php 85 KB

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