StatisticService.php 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088
  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 employeeMonthSalaryStatistic2($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 employeeMonthSalaryStatistic($data, $user)
  221. {
  222. // 1. 基础规则验证与时间范围获取
  223. list($status, $month_start, $month_end) = $this->commonRule($data);
  224. if (!$status) return [false, $month_start];
  225. // 2. 查询员工工时明细 (按月、项目、员工聚合)
  226. $month_employee_list = DailyPwOrderDetails::Clear($user, $data)
  227. ->where("order_time", ">=", $month_start)
  228. ->where("order_time", "<", $month_end)
  229. ->where('del_time', 0)
  230. ->select(
  231. "item_id",
  232. "employee_id",
  233. DB::raw("FROM_UNIXTIME(order_time, '%Y-%m') as order_month"),
  234. DB::raw("SUM(total_work_min) as total_work")
  235. )
  236. ->groupBy("order_month", "item_id", "employee_id")
  237. ->get()->toArray();
  238. // 3. 查询工资主表 (为了获取月份字符串映射)
  239. $monthly_ps_order_query = MonthlyPsOrder::Clear($user, $data)
  240. ->where('del_time', 0)
  241. ->where("month", ">=", $month_start)
  242. ->where("month", "<", $month_end);
  243. $monthly_ps_order_ids = $monthly_ps_order_query->pluck('id')->toArray();
  244. $monthly_ps_order_key_list = $monthly_ps_order_query
  245. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  246. ->pluck('month_str', 'id')
  247. ->toArray();
  248. // 4. 查询工资详情 (计算每人在每个月的分摊基数)
  249. $month_employee_salary = MonthlyPsOrderDetails::whereIn('main_id', $monthly_ps_order_ids)
  250. ->select("employee_id", DB::raw("(base_salary + performance_salary + bonus + other) as salary"), "main_id")
  251. ->get()->toArray();
  252. // 汇总:员工工资映射表 及 每月总工资池
  253. $salary_map = []; // [employee_id_month => salary]
  254. $all_salary_pool = []; // [month => total_salary_of_month]
  255. foreach ($month_employee_salary as $val) {
  256. $month_str = $monthly_ps_order_key_list[$val['main_id']] ?? '';
  257. if ($month_str) {
  258. $s_key = $val['employee_id'] . '_' . $month_str;
  259. $salary_map[$s_key] = $val['salary'];
  260. if (!isset($all_salary_pool[$month_str])) $all_salary_pool[$month_str] = 0;
  261. $all_salary_pool[$month_str] = round($all_salary_pool[$month_str] + $val['salary'], 2);
  262. }
  263. }
  264. // 5. 计算员工全月总工时 (用于算比例)
  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])) $employee_monthly_total_min[$key] = 0;
  269. $employee_monthly_total_min[$key] += $row['total_work'];
  270. }
  271. // 6. 按项目分摊 (初步计算,不四舍五入)
  272. $item_month_list = [];
  273. foreach ($month_employee_list as $item) {
  274. $e_key = $item['employee_id'] . '_' . $item['order_month'];
  275. $item_key = $item['order_month'] . '_' . $item['item_id'];
  276. if (!isset($item_month_list[$item_key])) {
  277. $item_month_list[$item_key] = [
  278. "month" => $item['order_month'],
  279. "item_id" => $item['item_id'],
  280. "allocated_salary" => 0,
  281. "work_minutes" => 0,
  282. ];
  283. }
  284. $total_salary = $salary_map[$e_key] ?? 0;
  285. $total_min = $employee_monthly_total_min[$e_key] ?? 0;
  286. if ($total_min > 0) {
  287. // 这里是关键:(项目工时 / 员工月总工时) * 员工月工资
  288. // 累加时保持高精度
  289. $ratio = $item['total_work'] / $total_min;
  290. $item_month_list[$item_key]['allocated_salary'] += ($ratio * $total_salary);
  291. }
  292. $item_month_list[$item_key]['work_minutes'] += $item['total_work'];
  293. }
  294. // 7. 准备项目基础信息
  295. $item_month_list = collect($item_month_list)->sortBy('month')->values();
  296. $item_ids = $item_month_list->pluck('item_id')->unique()->toArray();
  297. $item_info = Item::TopClear($user, $data)->whereIn('id', $item_ids)->get()->keyBy('id');
  298. // 8. 最终格式化与尾差修正
  299. $month_group_count = $item_month_list->groupBy('month')->map->count()->toArray();
  300. $month_day_pool = $item_month_list->groupBy('month')->map(fn($g) => round($g->sum('work_minutes') / 480))->toArray();
  301. $final_list = $item_month_list->transform(function ($item) use (
  302. $item_info,
  303. &$all_salary_pool,
  304. &$month_day_pool,
  305. &$month_group_count
  306. ) {
  307. $month = $item['month'];
  308. $item['item_title'] = $item_info[$item['item_id']]->title ?? "未知项目";
  309. $item['item_code'] = $item_info[$item['item_id']]->code ?? "N/A";
  310. if ($month_group_count[$month] > 1) {
  311. // 非本月最后一个项目:四舍五入并扣除余额
  312. $item['days'] = round($item['work_minutes'] / 480);
  313. $item['allocated_salary'] = round($item['allocated_salary'], 2);
  314. $month_day_pool[$month] -= $item['days'];
  315. $all_salary_pool[$month] = round($all_salary_pool[$month] - $item['allocated_salary'], 2);
  316. $month_group_count[$month]--;
  317. } else {
  318. // 本月最后一个项目:直接拿走剩下的所有钱和天数,解决精度问题
  319. $item['days'] = $month_day_pool[$month];
  320. $item['allocated_salary'] = $all_salary_pool[$month];
  321. }
  322. return $item;
  323. });
  324. return [true, $final_list->all()];
  325. }
  326. public function employeeMonthSalaryStatistic1($data, $user)
  327. {
  328. //项目编码、项目名称、天数、工资、日期
  329. list($status, $month_start, $month_end) = $this->commonRule($data);
  330. if (!$status) return [false, $month_start];
  331. //确认所有项目、人员、人员工时
  332. $month_employee = DailyPwOrderDetails::Clear($user, $data);
  333. $month_employee_list = $month_employee->where("order_time", ">=", $month_start)->where("order_time", "<", $month_end)
  334. ->where('del_time', 0)
  335. ->select(
  336. "item_id",
  337. "employee_id",
  338. // 将时间戳转为 Y-m-d 格式并起别名
  339. DB::raw("FROM_UNIXTIME(order_time, '%Y-%m') as order_month"),
  340. // 聚合求和
  341. DB::raw("SUM(total_work_min) as total_work")
  342. )
  343. ->groupBy("order_month", "item_id", "employee_id")->get()->toArray();
  344. //查询所有人员工资
  345. $monthly_ps_order_ids = MonthlyPsOrder::Clear($user, $data)->where('del_time', 0)->where("month", ">=", $month_start)->where("month", "<", $month_end)
  346. ->pluck('id')->toArray();
  347. $monthly_ps_order_key_list = MonthlyPsOrder::Clear($user, $data)
  348. ->where('del_time', 0)
  349. ->where("month", ">=", $month_start)
  350. ->where("month", "<", $month_end)
  351. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  352. ->pluck('month_str', 'id')
  353. ->toArray();
  354. $month_employee_salary = MonthlyPsOrderDetails::wherein('main_id', $monthly_ps_order_ids)
  355. ->select("employee_id",DB::raw("(base_salary + performance_salary + bonus + other) as salary"), "main_id")
  356. ->get()->toArray();
  357. //查询所有项目人员的工时比例
  358. //汇总每个人每个月工资
  359. $salary_map = [];
  360. $all_salary = [];
  361. foreach ($month_employee_salary as $val) {
  362. $month = $monthly_ps_order_key_list[$val['main_id']] ?? '';
  363. if ($month) {
  364. $salary_map[$val['employee_id'] . '_' . $month] = $val['salary'];
  365. }
  366. if (!isset($all_salary[$month])) $all_salary[$month] = 0;
  367. $all_salary[$month] += $val['salary'] * 100;
  368. }
  369. // var_dump($salary_map);die;
  370. // 2. 计算每个员工在每个月的全月总工时
  371. $employee_monthly_total_min = [];
  372. foreach ($month_employee_list as $row) {
  373. $key = $row['employee_id'] . '_' . $row['order_month'];
  374. if (!isset($employee_monthly_total_min[$key])) {
  375. $employee_monthly_total_min[$key] = 0;
  376. }
  377. $employee_monthly_total_min[$key] += $row['total_work'];
  378. }
  379. // 3. 计算分摊天数与工资
  380. $item_month_list = [];
  381. foreach ($month_employee_list as $item) {
  382. $key = $item['employee_id'] . '_' . $item['order_month'];
  383. $item_key = $item['order_month'] . '_' . $item['item_id'];
  384. if (!isset($item_month_list[$item_key])) {
  385. $item_month_list[$item_key] = [
  386. "month" => $item['order_month'],
  387. "allocated_salary" => 0,
  388. "work_minutes" => 0,
  389. "item_id" => $item['item_id'],
  390. ];
  391. }
  392. $total_salary = $salary_map[$key] ?? 0;
  393. $total_min = $employee_monthly_total_min[$key] ?? 0;
  394. // B. 计算工资分摊:(项目工时 / 月总工时) * 月工资
  395. if ($total_min > 0) {
  396. $ratio = $item['total_work'] / $total_min;
  397. $allocated_salary = round($ratio * $total_salary, 2);
  398. } else {
  399. $allocated_salary = 0;
  400. }
  401. $item_month_list[$item_key]['allocated_salary'] += $allocated_salary;
  402. $item_month_list[$item_key]['work_minutes'] += $item['total_work'];
  403. }
  404. foreach ($item_month_list as $k => $v) {
  405. $item_month_list[$k]['days'] = round($v['work_minutes'] / 8 / 60);
  406. }
  407. $collect = collect($item_month_list);
  408. $item_month_list = collect($item_month_list)->sortBy('month')->values()->all();
  409. $items = collect($item_month_list)->pluck('item_id')->unique()->values()->all();
  410. $item = Item::TopClear($user, $data);
  411. $item_title_key_list = $item->wherein('id', $items)->pluck("title", "id")->toArray();
  412. $item_code_key_list = $item->wherein('id', $items)->pluck("code", "id")->toArray();
  413. $collect = collect($item_month_list);
  414. $item_count = $collect->groupBy(function ($item) {
  415. // 这里的 $item 是集合中的每一行数据
  416. return $item['month'];
  417. })->map(function ($group) {
  418. return $group->count();
  419. })->toArray();
  420. $item_day_count = $collect->groupBy(fn($item) => $item['month'])
  421. ->map(fn($group) => round($group->sum('work_minutes') / 8 / 60))
  422. ->toArray();
  423. $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) {
  424. $item['item_title'] = $item_title_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  425. $item['item_code'] = $item_code_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  426. $item['allocated_salary'] = round($item['allocated_salary'], 2);
  427. // 如果不是最后一条
  428. $key = $item['month'];
  429. if (--$item_count[$key] > 0) {
  430. // 关键:递减外部的 $absolute_total_hours
  431. $item_day_count[$key] -= $item['days'];
  432. $all_salary[$key] -= $item['allocated_salary'] * 100;
  433. } else {
  434. $item['days'] = $item_day_count[$key];
  435. $item['allocated_salary'] = round($all_salary[$key] / 100, 2);
  436. }
  437. // if ($index < $count - 1) {
  438. // $total_day -= $item['days'];
  439. // // 关键:递减外部的 $absolute_total_hours
  440. // $all_salary -= $item['allocated_salary'];
  441. // } else {
  442. // // 最后一条:直接拿剩下的“余额”
  443. // $item['days'] = $total_day;
  444. // $item['allocated_salary'] = $all_salary;
  445. // }
  446. return $item;
  447. })->all();
  448. return [true, $item_month_list];
  449. }
  450. public function itemDaySalaryStatistic1($data, $user)
  451. {
  452. //项目编码、项目名称、人员名称、研发工时、研发工资、当月总工时、总计工资、年月
  453. list($status, $month_start, $month_end) = $this->commonRule($data);
  454. if (!$status) return [false, $month_start];
  455. //确认所有项目、人员、人员工时
  456. $month_employee = DailyPwOrderDetails::Clear($user, $data);
  457. $month_employee_list = $month_employee->where("order_time", ">=", $month_start)->where("order_time", "<", $month_end)
  458. ->where('del_time', 0)
  459. ->select(
  460. "item_id",
  461. "employee_id",
  462. // 将时间戳转为 Y-m-d 格式并起别名
  463. DB::raw("FROM_UNIXTIME(order_time, '%Y-%m') as order_month"),
  464. // 聚合求和
  465. DB::raw("SUM(total_work_min) as total_work")
  466. )
  467. ->groupBy(DB::raw("FROM_UNIXTIME(order_time, '%Y-%m')"), "item_id", "employee_id")->get()->toArray();
  468. //查询所有人员工资
  469. $monthly_ps_order_ids = MonthlyPsOrder::Clear($user, $data)->where('del_time', 0)->where("month", ">=", $month_start)->where("month", "<", $month_end)->pluck('id')->toArray();
  470. $monthly_ps_order_key_list = MonthlyPsOrder::Clear($user, $data)->where('del_time', 0)->where("month", ">=", $month_start)->where("month", "<", $month_end)
  471. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  472. ->pluck('month_str', 'id')->toArray();
  473. $month_employee_salary = MonthlyPsOrderDetails::wherein('main_id', $monthly_ps_order_ids)
  474. ->select("employee_id",DB::raw("(base_salary + performance_salary + bonus + other) as salary"), "main_id")
  475. ->get()->toArray();
  476. //查询所有项目人员的工时比例
  477. //汇总每个人每个月工资
  478. $salary_map = [];
  479. $all_salary = [];
  480. foreach ($month_employee_salary as $val) {
  481. $month = $monthly_ps_order_key_list[$val['main_id']] ?? '';
  482. if ($month) {
  483. $salary_map[$val['employee_id'] . '_' . $month] = $val['salary'];
  484. }
  485. $key = $val['employee_id'] . '_' . $month;
  486. if (!isset($all_salary[$key])) {
  487. $all_salary[$key] = 0;
  488. }
  489. $all_salary[$key] += $val['salary'] * 100;
  490. }
  491. // 2. 计算每个员工在每个月的全月总工时
  492. $employee_monthly_total_min = [];
  493. foreach ($month_employee_list as $row) {
  494. $key = $row['employee_id'] . '_' . $row['order_month'];
  495. if (!isset($employee_monthly_total_min[$key])) {
  496. $employee_monthly_total_min[$key] = 0;
  497. }
  498. $employee_monthly_total_min[$key] += $row['total_work'];
  499. }
  500. // 3. 计算分摊天数与工资
  501. $item_month_list = [];
  502. $total_work_min = [];
  503. foreach ($month_employee_list as $item) {
  504. $key = $item['employee_id'] . '_' . $item['order_month'];
  505. $employee_key = $item['order_month'] . '_' . $item['item_id'] . '_' . $item['employee_id'];
  506. $total_salary = $salary_map[$key] ?? 0;
  507. $total_min = $employee_monthly_total_min[$key] ?? 0;
  508. if (!isset($item_month_list[$employee_key])) {
  509. $item_month_list[$employee_key] = [
  510. "month" => $item['order_month'],
  511. "allocated_salary" => 0,
  512. "work_minutes" => 0,
  513. "total_min" => $total_min,
  514. "total_salary" => $total_salary,
  515. "item_id" => $item['item_id'],
  516. "employee_id" => $item['employee_id'],
  517. ];
  518. }
  519. // B. 计算工资分摊:(项目工时 / 月总工时) * 月工资
  520. if ($total_min > 0) {
  521. $ratio = $item['total_work'] / $total_min;
  522. $allocated_salary = round($ratio * $total_salary, 2);
  523. } else {
  524. $allocated_salary = 0;
  525. }
  526. $item_month_list[$employee_key]['allocated_salary'] += $allocated_salary;
  527. $item_month_list[$employee_key]['work_minutes'] += $item['total_work'];
  528. $key = $item['employee_id'] . '_' . $item['order_month'];
  529. if (!isset($total_work_min[$key])) $total_work_min[$key] = 0;
  530. $total_work_min[$key] += $item['total_work'];
  531. }
  532. foreach ($total_work_min as $k => $v) {
  533. $total_work_min[$k] = round($v / 60, 2) * 100;
  534. }
  535. $collect = collect($item_month_list);
  536. $employee_count = $collect->groupBy(function ($item) {
  537. // 这里的 $item 是集合中的每一行数据
  538. return $item['employee_id'] . '_' . $item['month'];
  539. })->map(function ($group) {
  540. return $group->count();
  541. })->toArray();
  542. // $collect = collect($item_month_list);
  543. // $employee_count = $collect->groupBy('employee_id')
  544. // ->map(function ($group) {
  545. // return $group->count(); // 统计每个分组里的数量
  546. // })
  547. // ->toArray();
  548. $item_month_list = collect($item_month_list)->sortBy('month')->values()->all();
  549. $items = collect($item_month_list)->pluck('item_id')->unique()->values()->all();
  550. $item = Item::TopClear($user, $data);
  551. $item_title_key_list = $item->wherein('id', $items)->pluck("title", "id")->toArray();
  552. $item_code_key_list = $item->wherein('id', $items)->pluck("code", "id")->toArray();
  553. $employee_ids = collect($item_month_list)->pluck('employee_id')->unique()->values()->all();
  554. $employee = Employee::TopClear($user, $data);
  555. $employee_key_list = $employee->wherein('id', $employee_ids)->pluck("title", "id")->toArray();
  556. $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) {
  557. $item['item_title'] = $item_title_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  558. $item['item_code'] = $item_code_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  559. $item['employee_title'] = $employee_key_list[$item['employee_id']] ?? "未知人员({$item['employee_id']})";
  560. $item['work_hours'] = round($item['work_minutes'] / 60, 2);
  561. $item['total_hours'] = round($item['total_min'] / 60);
  562. $key = $item['employee_id'] . '_' . $item['month'];
  563. if (--$employee_count[$key] > 0) {
  564. $all_salary[$key] -= $item['allocated_salary'] * 100;
  565. $total_work_min[$key] -= $item['work_hours'] * 100;
  566. } else {
  567. $item['allocated_salary'] = round($all_salary[$key] / 100, 2);
  568. $item['work_hours'] = round($total_work_min[$key] / 100, 2);
  569. }
  570. return $item;
  571. })->all();
  572. return [true, $item_month_list];
  573. }
  574. public function itemDeviceMonthStatistic($data, $user)
  575. {
  576. // 1. 基础校验与时间初始化
  577. list($status, $month_start, $month_end) = $this->commonRule($data);
  578. if (!$status) return [false, $month_start];
  579. // 2. 获取设备工时数据 (项目+设备+月)
  580. $month_device_list = DailyDwOrderDetails::Clear($user, $data)
  581. ->where("order_time", ">=", $month_start)
  582. ->where("order_time", "<", $month_end)
  583. ->where('del_time', 0)
  584. ->select(
  585. "item_id",
  586. "device_id",
  587. DB::raw("FROM_UNIXTIME(order_time, '%Y-%m') as order_month"),
  588. DB::raw("SUM(total_work_min) as total_work")
  589. )
  590. ->groupBy(DB::raw("FROM_UNIXTIME(order_time, '%Y-%m')"), "item_id", "device_id")->get()->toArray();
  591. // 3. 获取折旧费主表及详情
  592. $monthly_dd_query = MonthlyDdOrder::Clear($user, $data)->where('del_time', 0)
  593. ->where("month", ">=", $month_start)->where("month", "<", $month_end);
  594. $monthly_dd_ids = $monthly_dd_query->pluck('id')->toArray();
  595. $monthly_dd_months = $monthly_dd_query->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  596. ->pluck("month_str", 'id')->toArray();
  597. $device_salary_details = MonthlyDdOrderDetails::wherein('main_id', $monthly_dd_ids)
  598. ->select("device_id", "depreciation_amount", "main_id")->get()->toArray();
  599. // 4. 构建高精度折旧池 (单位:分)
  600. $depreciation_pool = [];
  601. foreach ($device_salary_details as $val) {
  602. $m = $monthly_dd_months[$val['main_id']] ?? '';
  603. if ($m) {
  604. $key = $val['device_id'] . '_' . $m;
  605. // 同一个设备在同一个月可能存在多条折旧记录,需累加
  606. $depreciation_pool[$key] = ($depreciation_pool[$key] ?? 0) + (int)round($val['depreciation_amount'] * 100);
  607. }
  608. }
  609. // 5. 计算全月总工时及初始化余额池
  610. $device_monthly_total_min = [];
  611. foreach ($month_device_list as $row) {
  612. $key = $row['device_id'] . '_' . $row['order_month'];
  613. $device_monthly_total_min[$key] = ($device_monthly_total_min[$key] ?? 0) + $row['total_work'];
  614. }
  615. $rem_depreciation_cents = $depreciation_pool; // 折旧余额池
  616. $rem_hours_cents = []; // 工时余额池 (小时*100)
  617. foreach ($device_monthly_total_min as $key => $min) {
  618. $rem_hours_cents[$key] = (int)round(($min / 60), 2) * 100;
  619. }
  620. // 6. 统计项目数用于判断“最后一条”
  621. $device_count = collect($month_device_list)->groupBy(fn($i) => $i['device_id'].'_'.$i['order_month'])
  622. ->map(fn($g) => $g->count())->toArray();
  623. // 7. 预加载设备与项目基础信息
  624. $items_ids = collect($month_device_list)->pluck('item_id')->unique()->all();
  625. $device_ids = collect($month_device_list)->pluck('device_id')->unique()->all();
  626. $item_info = Item::TopClear($user, $data)->whereIn('id', $items_ids)->get()->keyBy('id');
  627. $device_info = Device::TopClear($user, $data)->whereIn('id', $device_ids)->get()->keyBy('id');
  628. // 8. 核心转换逻辑
  629. $item_month_list = collect($month_device_list)->sortBy('order_month')->values()->transform(function ($item) use (
  630. $item_info, $device_info, $depreciation_pool, $device_monthly_total_min,
  631. &$device_count, &$rem_depreciation_cents, &$rem_hours_cents
  632. ) {
  633. $key = $item['device_id'] . '_' . $item['order_month'];
  634. $total_min = $device_monthly_total_min[$key] ?? 0;
  635. $item['item_title'] = $item_info[$item['item_id']]->title ?? "未知项目";
  636. $item['item_code'] = $item_info[$item['item_id']]->code ?? "-";
  637. $item['device_title'] = $device_info[$item['device_id']]->title ?? "未知设备";
  638. $item['device_original'] = $device_info[$item['device_id']]->original_value ?? 0;
  639. $item['month'] = $item['order_month'];
  640. $item['total_depreciatio'] = ($depreciation_pool[$key] ?? 0) / 100;
  641. $item['total_hours'] = round($total_min / 60, 2);
  642. // 分摊比例计算
  643. $ratio = $total_min > 0 ? ($item['total_work'] / $total_min) : 0;
  644. $item['ratio'] = round($ratio, 4);
  645. if (--$device_count[$key] > 0) {
  646. // 非最后一条项目
  647. $cur_hours = round($item['total_work'] / 60, 2);
  648. $item['hours'] = $cur_hours;
  649. $rem_hours_cents[$key] -= (int)round($cur_hours * 100);
  650. $cur_depre = round($item['total_depreciatio'] * $ratio, 2);
  651. $item['allocated_depreciatio'] = $cur_depre;
  652. $rem_depreciation_cents[$key] -= (int)round($cur_depre * 100);
  653. } else {
  654. // 最后一条项目,余额补平
  655. $item['hours'] = round(($rem_hours_cents[$key] ?? 0) / 100, 2);
  656. $item['allocated_depreciatio'] = round(($rem_depreciation_cents[$key] ?? 0) / 100, 2);
  657. // 比例也做个平账展示
  658. $item['ratio'] = round($item['hours'] / ($item['total_hours'] ?: 1), 4);
  659. }
  660. return $item;
  661. })->all();
  662. return [true, $item_month_list];
  663. }
  664. public function itemDeviceMonthStatistic1($data, $user)
  665. {
  666. //项目编码、项目名称、设备名称、项目工时、研发工时占比、设备原值、设备折旧额、本项目帐面归集的折旧额、确定的本项目折旧额、加计调整金额、当月工时、日期
  667. list($status, $month_start, $month_end) = $this->commonRule($data);
  668. if (!$status) return [false, $month_start];
  669. //确认所有项目、设备、设备工时
  670. $month_device = DailyDwOrderDetails::Clear($user, $data);
  671. $month_device_list = $month_device->where("order_time", ">=", $month_start)->where("order_time", "<", $month_end)
  672. ->where('del_time', 0)
  673. ->select(
  674. "item_id",
  675. "device_id",
  676. // 将时间戳转为 Y-m-d 格式并起别名
  677. DB::raw("FROM_UNIXTIME(order_time, '%Y-%m') as order_month"),
  678. // 聚合求和
  679. DB::raw("SUM(total_work_min) as total_work")
  680. )
  681. ->groupBy(DB::raw("FROM_UNIXTIME(order_time, '%Y-%m')"), "item_id", "device_id")->get()->toArray();
  682. //查询所有人员工资
  683. $monthly_dd_order_ids = MonthlyDdOrder::Clear($user, $data)->where('del_time', 0)->where("month", ">=", $month_start)->where("month", "<", $month_end)
  684. ->pluck('id')->toArray();
  685. $monthly_dd_order_key_list = MonthlyDdOrder::Clear($user, $data)->where('del_time', 0)->where("month", ">=", $month_start)->where("month", "<", $month_end)
  686. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  687. ->pluck("month_str", 'id')->toArray();
  688. $month_device_salary = MonthlyDdOrderDetails::wherein('main_id', $monthly_dd_order_ids)
  689. ->select("device_id", "depreciation_amount", "main_id")
  690. ->get()->toArray();
  691. //查询所有项目人员的工时比例
  692. //汇总每个人每个月工资
  693. $depreciatio_map = [];
  694. foreach ($month_device_salary as $val) {
  695. $month = $monthly_dd_order_key_list[$val['main_id']] ?? '';
  696. if ($month) {
  697. $depreciatio_map[$val['device_id'] . '_' . $month] = $val['depreciation_amount'];
  698. }
  699. }
  700. // 2. 计算每个员工在每个月的全月总工时
  701. $device_monthly_total_min = [];
  702. foreach ($month_device_list as $row) {
  703. $key = $row['device_id'] . '_' . $row['order_month'];
  704. if (!isset($device_monthly_total_min[$key])) {
  705. $device_monthly_total_min[$key] = 0;
  706. }
  707. $device_monthly_total_min[$key] += $row['total_work'];
  708. }
  709. // 3. 计算分摊天数与工资
  710. $item_month_list = [];
  711. $device_total_depreciatio = [];
  712. foreach ($month_device_list as $item) {
  713. $key = $item['device_id'] . '_' . $item['order_month'];
  714. $device_key = $item['order_month'] . '_' . $item['item_id'] . '_' . $item['device_id'];
  715. $total_depreciatio = $depreciatio_map[$key] ?? 0;
  716. $total_min = $device_monthly_total_min[$key] ?? 0;
  717. if (!isset($item_month_list[$device_key])) {
  718. $item_month_list[$device_key] = [
  719. "month" => $item['order_month'],
  720. "allocated_depreciatio" => 0,
  721. "work_minutes" => 0,
  722. "total_min" => $total_min,
  723. "item_id" => $item['item_id'],
  724. "device_id" => $item['device_id'],
  725. "total_depreciatio" => $total_depreciatio,
  726. ];
  727. $key = $item['device_id'] . '_' . $item['order_month'];
  728. $device_total_depreciatio[$key] = [
  729. 'total_hours' => round($total_min/60,2)*100,
  730. 'total_depreciatio' => $total_depreciatio*100
  731. ];
  732. }
  733. // B. 计算工资分摊:(项目工时 / 月总工时) * 月工资
  734. if ($total_min > 0) {
  735. $ratio = round($item['total_work'] / $total_min, 3);
  736. $allocated_salary = round($ratio * $total_depreciatio, 2);
  737. } else {
  738. $ratio = 0;
  739. $allocated_salary = 0;
  740. }
  741. $item_month_list[$device_key]['allocated_depreciatio'] += $allocated_salary;
  742. $item_month_list[$device_key]['work_minutes'] += $item['total_work'];
  743. $item_month_list[$device_key]['ratio'] = $ratio;
  744. }
  745. foreach ($item_month_list as $k => $v) {
  746. $item_month_list[$k]['total_hours'] = round($v['total_min'] / 60, 1);
  747. $item_month_list[$k]['hours'] = round($v['work_minutes'] / 60, 1);
  748. unset($item_month_list[$k]['work_minutes']);
  749. }
  750. $item_month_list = collect($item_month_list)->sortBy('month')->values()->all();
  751. $items = collect($item_month_list)->pluck('item_id')->unique()->values()->all();
  752. $item = Item::TopClear($user, $data);
  753. $item_title_key_list = $item->wherein('id', $items)->pluck("title", "id")->toArray();
  754. $item_code_key_list = $item->wherein('id', $items)->pluck("code", "id")->toArray();
  755. $device_ids = collect($item_month_list)->pluck('device_id')->unique()->values()->all();
  756. $device = Device::TopClear($user, $data);
  757. $device_key_list = $device->wherein('id', $device_ids)->pluck("title", "id")->toArray();
  758. $device_original_value_key_list = $device->wherein('id', $device_ids)->pluck("original_value", "id")->toArray();
  759. $collect = collect($item_month_list);
  760. $device_count = $collect->groupBy(function ($item) {
  761. // 这里的 $item 是集合中的每一行数据
  762. return $item['device_id'] . '_' . $item['month'];
  763. })->map(function ($group) {
  764. return $group->count();
  765. })->toArray();
  766. $rate_list = [];
  767. $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) {
  768. $item['item_title'] = $item_title_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  769. $item['item_code'] = $item_code_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  770. $item['device_title'] = $device_key_list[$item['device_id']] ?? "未知人员({$item['device_id']})";
  771. $item['device_original'] = $device_original_value_key_list[$item['device_id']] ?? "未知人员({$item['device_id']})";
  772. $key = $item['device_id'] . '_' . $item['month'];
  773. if(!isset($rate_list[$key])) $rate_list[$key] = 100;
  774. if (--$device_count[$key] > 0) {
  775. $rate_list[$key] -= $item['ratio'] * 100;
  776. $device_total_depreciatio[$key]['total_hours'] -= $item['hours'] * 100;
  777. $device_total_depreciatio[$key]['total_depreciatio'] -= $item['allocated_depreciatio'] * 100;
  778. } else {
  779. $item['ratio'] = round($rate_list[$key] / 100, 2);
  780. $item['hours'] = round( $device_total_depreciatio[$key]['total_hours']/ 100, 2);
  781. $item['allocated_depreciatio'] = round( $device_total_depreciatio[$key]['total_depreciatio']/ 100, 2);
  782. }
  783. return $item;
  784. })->all();
  785. return [true, $item_month_list];
  786. }
  787. /**
  788. * 根据前端 ISO 时间字符串获取该年份的起止日期和时间戳
  789. * 适配:2019-12-31T16:00:00.000Z 这种带时区的数据
  790. *
  791. * @param string $isoStr 前端传来的时间字符串
  792. * @return array|null
  793. */
  794. public function getYearRangeInfo($isoStr)
  795. {
  796. if (empty($isoStr)) return null;
  797. try {
  798. // 1. 解析 ISO 8601 字符串
  799. $date = new \DateTime($isoStr);
  800. // 2. 强制转为中国时区(PRC),处理 16:00:00Z 这种 UTC 偏移
  801. $date->setTimezone(new \DateTimeZone('PRC'));
  802. // 3. 提取年份
  803. $year = $date->format('Y');
  804. // 4. 构造日期字符串
  805. $startDate = $year . "-01-01";
  806. $endDate = $year . "-12-31";
  807. return [
  808. $startDate,
  809. $endDate,
  810. ];
  811. } catch (\Exception $e) {
  812. // var_dump($e->getMessage());die;
  813. return null;
  814. }
  815. }
  816. public function employeeAttendanceMonthStatistic($data, $user)
  817. {
  818. //项目编码、项目名称、项目状态、支出类型、允许加计扣除金额合计、人员人工费用、折旧费用、其他费用、前N项小计、其他相关费用合计、委内费用、委外费用、
  819. list($status, $month_start, $month_end) = $this->commonRule($data);
  820. if (!$status) {
  821. return [false, $month_start];
  822. }
  823. //第一步确定项目
  824. $item = Item::TopClear($user, $data);
  825. $item_list = $item->where('del_time', 0)
  826. ->where(function ($query) use ($month_start, $month_end) {
  827. $query->where('start_time', '>=', $month_start)
  828. ->where('end_time', '<', $month_end);
  829. })->select("code", "title", "start_time", "end_time", "id", "state")->orderby("start_time", "asc")->get()->toArray();
  830. $item_key_list = [];
  831. foreach ($item_list as $v) {
  832. $item_key_list[$v['id']] = $v;
  833. }
  834. //第二步确定人员费用
  835. $item_employee_list = $this->getEmployeeItemSalary($month_start, $month_end, $data, $user);
  836. //第三步确定折旧费用
  837. $item_device_list = $this->getDeviceItemSalary($month_start, $month_end, $data, $user);
  838. //第四步其他费用
  839. list($item_fee_list, $fee_type_list) = $this->getFeeItemSalary($month_start, $month_end, $data, $user);
  840. //组合所有数据
  841. $return = [];
  842. foreach ($item_key_list as $v) {
  843. //其他费用是个数组
  844. $item_value = [
  845. "code" => $v['code'],
  846. "title" => $v['title'],
  847. "state" => $v['state'] == 3 ? "完结" : "进行中",
  848. "employee_salary" => isset($item_employee_list[$v['id']]['salary']) ? round($item_employee_list[$v['id']]['salary']/100,2) : 0,
  849. "device_depreciation" => isset($item_device_list[$v['id']]['depreciation']) ? round($item_device_list[$v['id']]['depreciation']/100,2): 0,
  850. "expense_type" => "费用化支出",
  851. "fee_list" => collect($item_fee_list[$v['id']] ?? [])->values()->all(),
  852. ];
  853. $return[] = $item_value;
  854. }
  855. return [true, ["list" => $return, "fee_type_list" => $fee_type_list]];
  856. }
  857. private function getEmployeeItemSalary($month_start, $month_end, $data, $user)
  858. {
  859. $month_employee = DailyPwOrderDetails::Clear($user, $data);
  860. $month_employee_list = $month_employee->where("order_time", ">=", $month_start)->where("order_time", "<", $month_end)
  861. ->where('del_time', 0)
  862. ->select(
  863. "item_id",
  864. "employee_id",
  865. // 将时间戳转为 Y-m-d 格式并起别名
  866. DB::raw("FROM_UNIXTIME(order_time, '%Y-%m') as order_month"),
  867. // 聚合求和
  868. DB::raw("SUM(total_work_min) as total_work")
  869. )
  870. ->groupBy("order_month", "item_id", "employee_id")->get()->toArray();
  871. //查询所有人员工资
  872. $monthly_ps_order_ids = MonthlyPsOrder::Clear($user, $data)->where('del_time', 0)->where("month", ">=", $month_start)->where("month", "<", $month_end)
  873. ->pluck('id')->toArray();
  874. $monthly_ps_order_key_list = MonthlyPsOrder::Clear($user, $data)
  875. ->where('del_time', 0)
  876. ->where("month", ">=", $month_start)
  877. ->where("month", "<", $month_end)
  878. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  879. ->pluck('month_str', 'id')
  880. ->toArray();
  881. $month_employee_salary = MonthlyPsOrderDetails::wherein('main_id', $monthly_ps_order_ids)
  882. ->select("employee_id", DB::raw("(base_salary + performance_salary + bonus + other) as salary"), "main_id")
  883. ->get()->toArray();
  884. //查询所有项目人员的工时比例
  885. //汇总每个人每个月工资
  886. $salary_map = [];
  887. $all_salary = [];
  888. foreach ($month_employee_salary as $val) {
  889. $month = $monthly_ps_order_key_list[$val['main_id']] ?? '';
  890. if ($month) {
  891. $salary_map[$val['employee_id'] . '_' . $month] = $val['salary'];
  892. $all_salary[$val['employee_id'] . '_' . $month] = $val['salary']*100;
  893. }
  894. }
  895. // 2. 计算每个员工在每个月的全月总工时
  896. $employee_monthly_total_min = [];
  897. foreach ($month_employee_list as $row) {
  898. $key = $row['employee_id'] . '_' . $row['order_month'];
  899. if (!isset($employee_monthly_total_min[$key])) {
  900. $employee_monthly_total_min[$key] = 0;
  901. }
  902. $employee_monthly_total_min[$key] += $row['total_work'];
  903. }
  904. // 2. 计算分摊天数与工资
  905. $item_list = [];
  906. foreach ($month_employee_list as $item) {
  907. $key = $item['employee_id'] . '_' . $item['order_month'];
  908. // $item_key = $item['item_id'].'_'.$item['order_month'];
  909. // if (!isset($item_list[$item_key])) {
  910. // $item_list[$item_key] = [
  911. // "salary" => 0,
  912. // ];
  913. // }
  914. $total_salary = $salary_map[$key] ?? 0;
  915. $total_min = $employee_monthly_total_min[$key] ?? 0;
  916. // B. 计算工资分摊:(项目工时 / 月总工时) * 月工资
  917. if ($total_min > 0) {
  918. $ratio = $item['total_work'] / $total_min;
  919. $allocated_salary = round($ratio * $total_salary, 2)*100;
  920. } else {
  921. $allocated_salary = 0;
  922. }
  923. $item_list[] = [
  924. 'employee_id' => $item['employee_id'],
  925. 'allocated_salary' => $allocated_salary,
  926. 'month' => $item['order_month'],
  927. 'item_id' => $item['item_id'],
  928. ];
  929. }
  930. $collect = collect($item_list);
  931. $employee_count = $collect->groupBy(function ($item) {
  932. // 这里的 $item 是集合中的每一行数据
  933. return $item['employee_id'] . '_' . $item['month'];
  934. })->map(function ($group) {
  935. return $group->count();
  936. })->toArray();
  937. $month_employee_list = $collect->transform(function ($item, $index) use (&$employee_count,&$all_salary) {
  938. // 如果不是最后一条
  939. $key = $item['employee_id'] . '_' . $item['month'];
  940. if(!isset($all_salary[$key])) $item['allocated_salary'] = 0;
  941. else{
  942. if (--$employee_count[$key] > 0) {
  943. $all_salary[$key] -= $item['allocated_salary'];
  944. } else {
  945. $item['allocated_salary'] = $all_salary[$key];
  946. }
  947. }
  948. return $item;
  949. })->all();
  950. $return_item_list = [];
  951. foreach ($month_employee_list as $v){
  952. $key = $v['item_id'];
  953. if(!isset($return_item_list[$key])) $return_item_list[$key]['salary'] = 0;
  954. $return_item_list[$key]['salary'] += $v['allocated_salary'];
  955. }
  956. return $return_item_list;
  957. }
  958. private function getDeviceItemSalary($month_start, $month_end, $data, $user)
  959. {
  960. //确认所有项目、设备、设备工时
  961. $month_device = DailyDwOrderDetails::Clear($user, $data);
  962. $month_device_list = $month_device->where("order_time", ">=", $month_start)->where("order_time", "<", $month_end)
  963. ->where('del_time', 0)
  964. ->select(
  965. "item_id",
  966. "device_id",
  967. // 将时间戳转为 Y-m-d 格式并起别名
  968. DB::raw("FROM_UNIXTIME(order_time, '%Y-%m') as order_month"),
  969. // 聚合求和
  970. DB::raw("SUM(total_work_min) as total_work")
  971. )
  972. ->groupBy(DB::raw("FROM_UNIXTIME(order_time, '%Y-%m')"), "item_id", "device_id")->get()->toArray();
  973. //查询所有人员工资
  974. $monthly_dd_order_ids = MonthlyDdOrder::Clear($user, $data)->where('del_time', 0)->where("month", ">=", $month_start)->where("month", "<", $month_end)
  975. ->pluck('id')->toArray();
  976. $monthly_dd_order_key_list = MonthlyDdOrder::Clear($user, $data)->where('del_time', 0)->where("month", ">=", $month_start)->where("month", "<", $month_end)
  977. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  978. ->pluck("month_str", 'id')->toArray();
  979. $month_device_salary = MonthlyDdOrderDetails::wherein('main_id', $monthly_dd_order_ids)
  980. ->select("device_id", "depreciation_amount", "main_id")
  981. ->get()->toArray();
  982. //查询所有项目人员的工时比例
  983. //汇总每个人每个月工资
  984. $depreciatio_map = [];
  985. $all_depreciatio = [];
  986. foreach ($month_device_salary as $val) {
  987. $month = $monthly_dd_order_key_list[$val['main_id']] ?? '';
  988. if ($month) {
  989. $depreciatio_map[$val['device_id'] . '_' . $month] = $val['depreciation_amount'];
  990. $all_depreciatio[$val['device_id'] . '_' . $month] = $val['depreciation_amount']*100;
  991. }
  992. }
  993. // 2. 计算每个员工在每个月的全月总工时
  994. $device_monthly_total_min = [];
  995. foreach ($month_device_list as $row) {
  996. $key = $row['device_id'] . '_' . $row['order_month'];
  997. if (!isset($device_monthly_total_min[$key])) {
  998. $device_monthly_total_min[$key] = 0;
  999. }
  1000. $device_monthly_total_min[$key] += $row['total_work'];
  1001. }
  1002. // 3. 计算分摊天数与工资
  1003. $item_list = [];
  1004. foreach ($month_device_list as $item) {
  1005. $key = $item['device_id'] . '_' . $item['order_month'];
  1006. // $device_key = $item['item_id'];
  1007. $total_depreciatio = $depreciatio_map[$key] ?? 0;
  1008. $total_min = $device_monthly_total_min[$key] ?? 0;
  1009. // if (!isset($item_list[$device_key])) {
  1010. // $item_list[$device_key] = [
  1011. // "depreciation" => 0,
  1012. // ];
  1013. // }
  1014. // B. 计算工资分摊:(项目工时 / 月总工时) * 月工资
  1015. if ($total_min > 0) {
  1016. $ratio = round($item['total_work'] / $total_min, 3);
  1017. $allocated_salary = round($ratio * $total_depreciatio, 2)*100;
  1018. } else {
  1019. $allocated_salary = 0;
  1020. }
  1021. $item_list[] = [
  1022. 'device_id' => $item['device_id'],
  1023. 'depreciation' => $allocated_salary,
  1024. 'month' => $item['order_month'],
  1025. 'item_id' => $item['item_id'],
  1026. ];
  1027. }
  1028. $collect = collect($item_list);
  1029. $device_count = $collect->groupBy(function ($item) {
  1030. // 这里的 $item 是集合中的每一行数据
  1031. return $item['device_id'] . '_' . $item['month'];
  1032. })->map(function ($group) {
  1033. return $group->count();
  1034. })->toArray();
  1035. $month_employee_list = $collect->transform(function ($item) use (&$device_count,&$all_depreciatio) {
  1036. // 如果不是最后一条
  1037. $key = $item['device_id'] . '_' . $item['month'];
  1038. if (--$device_count[$key] > 0) {
  1039. $all_depreciatio[$key] -= $item['depreciation'];
  1040. } else {
  1041. $item['depreciation'] = $all_depreciatio[$key];
  1042. }
  1043. return $item;
  1044. })->all();
  1045. $return_item_list = [];
  1046. foreach ($month_employee_list as $v){
  1047. $key = $v['item_id'];
  1048. if(!isset($return_item_list[$key])) $return_item_list[$key]['depreciation'] = 0;
  1049. $return_item_list[$key]['depreciation'] += $v['depreciation'];
  1050. }
  1051. // var_dump($return_item_list);die;
  1052. return $return_item_list;
  1053. }
  1054. private function getFeeItemSalary($month_start, $month_end, $data, $user)
  1055. {
  1056. //确认所有项目、费用
  1057. $expense = ExpenseClaimsDetails::Clear($user, $data);
  1058. $expense_list = $expense->where("claim_date", ">=", $month_start)->where("claim_date", "<", $month_end)
  1059. ->where('del_time', 0)
  1060. ->select(
  1061. "fee_id",
  1062. "amount",
  1063. "item_id",
  1064. "entrust_type"
  1065. )->get()->toArray();
  1066. //需要根据分类去汇总
  1067. $fee = Fee::TopClear($user, $data);
  1068. $fee = $fee->where('del_time', 0)->orderBy("sort", 'desc')->get()->toArray();
  1069. return $this->groupListByRoot($expense_list, $fee);
  1070. }
  1071. /**
  1072. * 将报销明细按照一级费用和项目分类进行分组
  1073. * * @param array $list 报销明细列表 (含 fee_id, amount 等)
  1074. * @param array $fee_type_list 费用类型树 (含 id, parent_id, title)
  1075. * @return array
  1076. */
  1077. public function groupListByRoot(array $list, array $fee_type_list)
  1078. {
  1079. // 1. 建立 ID 索引,方便快速查找
  1080. $idMap = array_column($fee_type_list, null, 'id');
  1081. // 2. 预处理映射表:让所有子 ID 直接指向它的最顶层“祖宗” ID
  1082. $childToRoot = [];
  1083. foreach ($fee_type_list as $type) {
  1084. $current = $type;
  1085. // 向上追溯直到 parent_id 为 0,即找到一级分类
  1086. while ($current['parent_id'] != 0) {
  1087. $current = $idMap[$current['parent_id']];
  1088. }
  1089. $childToRoot[$type['id']] = [
  1090. 'id' => $current['id'],
  1091. 'title' => $current['title'],
  1092. 'sort' => $current['sort']
  1093. ];
  1094. }
  1095. // 3. 遍历明细数据进行分组
  1096. $item_key_list = [];
  1097. $type_list = [];
  1098. foreach ($list as $item) {
  1099. $feeId = $item['fee_id'];
  1100. // 获取该费用对应的一级分类信息
  1101. if (!isset($childToRoot[$feeId])) continue;
  1102. $rootId = $childToRoot[$feeId]['id'];
  1103. $title = $childToRoot[$feeId]['title'];
  1104. $sort = $childToRoot[$feeId]['sort'];
  1105. $key = $item['item_id'];
  1106. if (!isset($item_key_list[$key][$rootId])) {
  1107. $item_key_list[$key][$rootId] = [
  1108. 'id' => $rootId,
  1109. 'total_amount' => 0,
  1110. 'entrust1_amount' => 0, //委内
  1111. 'entrust2_amount' => 0, //委外
  1112. ];
  1113. }
  1114. if ($item['entrust_type'] == 1) {
  1115. $item_key_list[$key][$rootId]['entrust1_amount'] += $item['amount']*100;
  1116. } elseif ($item['entrust_type'] == 2) {
  1117. $item_key_list[$key][$rootId]['entrust2_amount'] += $item['amount']*100;
  1118. }
  1119. $item_key_list[$key][$rootId]['total_amount'] += $item['amount']*100;
  1120. //这边需要拿到头部所有的一级费用类型
  1121. if (!isset($type_list[$rootId])) {
  1122. $type_list[$rootId] = [
  1123. 'sort' => $sort,
  1124. 'id' => $rootId,
  1125. 'title' => $title,
  1126. ];
  1127. }
  1128. }
  1129. // var_dump($item_key_list);die;
  1130. foreach ($item_key_list as $k=>$v){
  1131. foreach ($v as $kk=>$vv){
  1132. $item_key_list[$k][$kk]['entrust1_amount'] = round( $vv['entrust1_amount']/100,2);
  1133. $item_key_list[$k][$kk]['entrust2_amount'] = round( $vv['entrust2_amount']/100,2);
  1134. $item_key_list[$k][$kk]['total_amount'] = round( $vv['total_amount']/100,2);
  1135. }
  1136. }
  1137. // $item_key_list = collect($item_key_list)->transform(function ($item) {
  1138. // $item['entrust1_amount'] = round( $item['entrust1_amount']/100,2);
  1139. // $item['entrust2_amount'] = round( $item['entrust2_amount']/100,2);
  1140. // $item['total_amount'] = round( $item['total_amount']/100,2);
  1141. // return $item;
  1142. // })->all();
  1143. // 使用 values() 丢弃原始键名,重新从 0 开始建立索引
  1144. $type_list = collect($type_list)->sortBy('sort')->values()->all();
  1145. // 4. 重置数组索引并返回
  1146. return [$item_key_list, $type_list];
  1147. }
  1148. public function auxiliaryStatistic($data, $user)
  1149. {
  1150. list($status, $month_start, $month_end) = $this->commonRule($data);
  1151. if (!$status) return [false, $month_start];
  1152. //项目编码、项目名称、项目状态、凭证日期、凭证种类、凭证号数、凭证摘要、会计凭证归集金额、N个一级费用类型、委内、委外
  1153. //确认所有项目
  1154. $item = Item::TopClear($user, $data);
  1155. $item_list = $item->where('del_time', 0)
  1156. ->where(function ($query) use ($month_start, $month_end) {
  1157. $query->where('start_time', '>=', $month_start)
  1158. ->where('end_time', '<', $month_end);
  1159. })->select("code", "title", "start_time", "end_time", "id", "state")->orderby("start_time", "asc")->get()->toArray();
  1160. $item_key_list = [];
  1161. foreach ($item_list as $v) {
  1162. $item_key_list[$v['id']] = $v;
  1163. }
  1164. //获取该区间内所有项目人工费、折旧费
  1165. $item_salary = $this->auxiliaryEmployee($user, $data, $month_start, $month_end);
  1166. $device_depreciation = $this->auxiliaryDevice($user, $data, $month_start, $month_end);
  1167. $fee = Fee::TopClear($user, $data);
  1168. $fee = $fee->where('del_time', 0)->orderBy("sort", 'desc')->get()->toArray();
  1169. $auxiliary = AuxiliaryAccountDetails::Clear($user, $data);
  1170. $auxiliary_list = $auxiliary->where("voucher_date", ">=", $month_start)->where("voucher_date", "<", $month_end)
  1171. ->where('del_time', 0)
  1172. ->select(
  1173. "item_id",
  1174. "voucher_date",
  1175. "voucher_type",
  1176. "voucher_no",
  1177. "voucher_remark",
  1178. "voucher_amount",
  1179. "aggregation_amount",
  1180. "entrust_type",
  1181. "entrust1_amount",
  1182. "entrust2_amount",
  1183. "entrust2_amount",
  1184. "total_amount",
  1185. "fee_id",
  1186. "type"
  1187. )->get()->toArray();
  1188. list($fee_amount, $fee_type_list) = $this->auxiliaryGroupListByRoot($auxiliary_list, $fee);
  1189. //找到项目和设备的费用然后进行比例计算
  1190. $return = [];
  1191. foreach ($fee_amount as $v) {
  1192. //人工费用
  1193. if ($v['type'] == 1 || $v['type'] == 2) {
  1194. // var_dump();
  1195. foreach ($item_key_list as $vv) {
  1196. if(!isset($item_salary[$vv['id'] . "_" . date("Y-m", $v['voucher_date'])]['allocated_salary'])) continue;
  1197. $detail = [
  1198. "code" => $vv['code'],
  1199. "title" => $vv['title'],
  1200. "state" => $vv['state'] == 3 ? "进行中" : "已完成",
  1201. "voucher_date" => date("Y-m-d", $v['voucher_date']),
  1202. "voucher_type" => $v['voucher_type'],
  1203. "voucher_no" => $v['voucher_no'],
  1204. "voucher_remark" => $v['voucher_remark'],
  1205. "voucher_amount" => $v['voucher_amount'],
  1206. "aggregation_amount" => $v['aggregation_amount'],
  1207. "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),
  1208. "fee_id" => $v['fee_id'],
  1209. "entrust1_amount" => $v['entrust1_amount'],
  1210. "entrust2_amount" => $v['entrust2_amount'],
  1211. "type" => $v['type'],
  1212. ];
  1213. $return[] = $detail;
  1214. }
  1215. } else {
  1216. if (!isset($item_key_list[$v['item_id']])) continue;
  1217. $item_value = $item_key_list[$v['item_id']];
  1218. $detail = [
  1219. "code" => $item_value['code'],
  1220. "title" => $item_value['title'],
  1221. "state" => $item_value['state'] == 3 ? "进行中" : "已完成",
  1222. "voucher_date" => date("Y-m-d", $v['voucher_date']),
  1223. "voucher_type" => $v['voucher_type'],
  1224. "voucher_no" => $v['voucher_no'],
  1225. "voucher_remark" => $v['voucher_remark'],
  1226. "voucher_amount" => $v['voucher_amount'],
  1227. "aggregation_amount" => $v['aggregation_amount'],
  1228. "total_amount" => $v['total_amount'],
  1229. "fee_id" => $v['fee_id'],
  1230. "entrust1_amount" => $v['entrust1_amount'],
  1231. "entrust2_amount" => $v['entrust2_amount'],
  1232. "type" => $v['type'],
  1233. ];
  1234. $return[] = $detail;
  1235. }
  1236. }
  1237. return [true, [
  1238. 'fee_type_list' => $fee_type_list,
  1239. 'list' => $return,
  1240. ]];
  1241. }
  1242. /**
  1243. * 将报销明细按照一级费用和项目分类进行分组
  1244. * * @param array $list 报销明细列表 (含 fee_id, amount 等)
  1245. * @param array $fee_type_list 费用类型树 (含 id, parent_id, title)
  1246. * @return array
  1247. */
  1248. public function auxiliaryGroupListByRoot(array $list, array $fee_type_list)
  1249. {
  1250. // 1. 建立 ID 索引,方便快速查找
  1251. $idMap = array_column($fee_type_list, null, 'id');
  1252. // 2. 预处理映射表:让所有子 ID 直接指向它的最顶层“祖宗” ID
  1253. $childToRoot = [];
  1254. foreach ($fee_type_list as $type) {
  1255. $current = $type;
  1256. // 向上追溯直到 parent_id 为 0,即找到一级分类
  1257. while ($current['parent_id'] != 0) {
  1258. $current = $idMap[$current['parent_id']];
  1259. }
  1260. $childToRoot[$type['id']] = [
  1261. 'id' => $current['id'],
  1262. 'title' => $current['title'],
  1263. 'sort' => $current['sort']
  1264. ];
  1265. }
  1266. // 3. 遍历明细数据进行分组
  1267. $type_list = [];
  1268. foreach ($list as $k => $item) {
  1269. if ($item['item_id'] == 0 || $item['fee_id'] == 0) {
  1270. continue;
  1271. }
  1272. $feeId = $item['fee_id'];
  1273. // 获取该费用对应的一级分类信息
  1274. if (!isset($childToRoot[$feeId])) continue;
  1275. $rootId = $childToRoot[$feeId]['id'];
  1276. $title = $childToRoot[$feeId]['title'];
  1277. $sort = $childToRoot[$feeId]['sort'];
  1278. $item['fee_id'] = $rootId;
  1279. $list[$k] = $item;
  1280. //这边需要拿到头部所有的一级费用类型
  1281. if (!isset($type_list[$rootId])) {
  1282. $type_list[$rootId] = [
  1283. 'sort' => $sort,
  1284. 'id' => $rootId,
  1285. 'title' => $title,
  1286. ];
  1287. }
  1288. }
  1289. // 使用 values() 丢弃原始键名,重新从 0 开始建立索引
  1290. $type_list = collect($type_list)->sortBy('sort')->values()->all();
  1291. // 4. 重置数组索引并返回
  1292. return [$list, $type_list];
  1293. }
  1294. public function auxiliaryEmployee($user, $data, $month_start, $month_end)
  1295. {
  1296. //确认所有项目、人员、人员工时
  1297. $month_employee = DailyPwOrderDetails::Clear($user, $data);
  1298. $month_employee_list = $month_employee->where("order_time", ">=", $month_start)->where("order_time", "<", $month_end)
  1299. ->where('del_time', 0)
  1300. ->select(
  1301. "item_id",
  1302. "employee_id",
  1303. // 将时间戳转为 Y-m-d 格式并起别名
  1304. DB::raw("FROM_UNIXTIME(order_time, '%Y-%m') as order_month"),
  1305. // 聚合求和
  1306. DB::raw("SUM(total_work_min) as total_work")
  1307. )
  1308. ->groupBy("order_month", "item_id", "employee_id")->get()->toArray();
  1309. //查询所有人员工资
  1310. $monthly_ps_order_ids = MonthlyPsOrder::Clear($user, $data)->where('del_time', 0)->where("month", ">=", $month_start)->where("month", "<", $month_end)
  1311. ->pluck('id')->toArray();
  1312. $monthly_ps_order_key_list = MonthlyPsOrder::Clear($user, $data)
  1313. ->where('del_time', 0)
  1314. ->where("month", ">=", $month_start)
  1315. ->where("month", "<", $month_end)
  1316. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  1317. ->pluck('month_str', 'id')
  1318. ->toArray();
  1319. $month_employee_salary = MonthlyPsOrderDetails::wherein('main_id', $monthly_ps_order_ids)
  1320. ->select("employee_id",DB::raw("(base_salary + performance_salary + bonus + other) as salary"), "main_id")
  1321. ->get()->toArray();
  1322. //查询所有项目人员的工时比例
  1323. //汇总每个人每个月工资
  1324. $salary_map = [];
  1325. $all_salary = [];
  1326. foreach ($month_employee_salary as $val) {
  1327. $month = $monthly_ps_order_key_list[$val['main_id']] ?? '';
  1328. if ($month) {
  1329. $salary_map[$val['employee_id'] . '_' . $month] = $val['salary'];
  1330. $all_salary[$val['employee_id'] . '_' . $month] = $val['salary']*100;
  1331. }
  1332. }
  1333. // var_dump($salary_map);die;
  1334. // 2. 计算每个员工在每个月的全月总工时
  1335. $employee_monthly_total_min = [];
  1336. foreach ($month_employee_list as $row) {
  1337. $key = $row['employee_id'] . '_' . $row['order_month'];
  1338. if (!isset($employee_monthly_total_min[$key])) {
  1339. $employee_monthly_total_min[$key] = 0;
  1340. }
  1341. $employee_monthly_total_min[$key] += $row['total_work'];
  1342. }
  1343. // 3. 计算分摊天数与工资
  1344. // $item_year_list = [];
  1345. $item_list = [];
  1346. foreach ($month_employee_list as $item) {
  1347. $key = $item['employee_id'] . '_' . $item['order_month'];
  1348. // $item_key = $item['item_id'] . '_' . $item['order_month'];
  1349. // if (!isset($item_year_list[$item_key])) {
  1350. // $item_year_list[$item_key] = [
  1351. // "allocated_salary" => 0,
  1352. // "item_id" => $item['item_id'],
  1353. // ];
  1354. // }
  1355. $total_salary = $salary_map[$key] ?? 0;
  1356. $total_min = $employee_monthly_total_min[$key] ?? 0;
  1357. // B. 计算工资分摊:(项目工时 / 月总工时) * 月工资
  1358. if ($total_min > 0) {
  1359. $ratio = $item['total_work'] / $total_min;
  1360. $allocated_salary = round($ratio * $total_salary, 2)*100;
  1361. } else {
  1362. $allocated_salary = 0;
  1363. }
  1364. $item_list[] = [
  1365. 'employee_id' => $item['employee_id'],
  1366. 'allocated_salary' => $allocated_salary,
  1367. 'month' => $item['order_month'],
  1368. 'item_id' => $item['item_id'],
  1369. ];
  1370. }
  1371. $collect = collect($item_list);
  1372. $employee_count = $collect->groupBy(function ($item) {
  1373. // 这里的 $item 是集合中的每一行数据
  1374. return $item['employee_id'] . '_' . $item['month'];
  1375. })->map(function ($group) {
  1376. return $group->count();
  1377. })->toArray();
  1378. $month_employee_list = $collect->transform(function ($item, $index) use (&$employee_count,&$all_salary) {
  1379. // 如果不是最后一条
  1380. $key = $item['employee_id'] . '_' . $item['month'];
  1381. if(!isset($all_salary[$key])) $item['allocated_salary'] = 0;
  1382. else {
  1383. if (--$employee_count[$key] > 0) {
  1384. $all_salary[$key] -= $item['allocated_salary'];
  1385. } else {
  1386. $item['allocated_salary'] = $all_salary[$key];
  1387. }
  1388. }
  1389. return $item;
  1390. })->all();
  1391. $return_item_list = [];
  1392. foreach ($month_employee_list as $v){
  1393. $key = $v['item_id'] . '_' . $v['month'];
  1394. if(!isset($return_item_list[$key])) $return_item_list[$key]['allocated_salary'] = 0;
  1395. $return_item_list[$key]['allocated_salary'] += $v['allocated_salary'];
  1396. }
  1397. return $return_item_list;
  1398. }
  1399. public function auxiliaryDevice($user, $data, $month_start, $month_end)
  1400. {
  1401. $month_device = DailyDwOrderDetails::Clear($user, $data);
  1402. $month_device_list = $month_device->where("order_time", ">=", $month_start)->where("order_time", "<", $month_end)
  1403. ->where('del_time', 0)
  1404. ->select(
  1405. "item_id",
  1406. "device_id",
  1407. // 将时间戳转为 Y-m-d 格式并起别名
  1408. DB::raw("FROM_UNIXTIME(order_time, '%Y-%m') as order_month"),
  1409. // 聚合求和
  1410. DB::raw("SUM(total_work_min) as total_work")
  1411. )
  1412. ->groupBy(DB::raw("FROM_UNIXTIME(order_time, '%Y-%m')"), "item_id", "device_id")->get()->toArray();
  1413. //查询所有人员工资
  1414. $monthly_dd_order_ids = MonthlyDdOrder::Clear($user, $data)->where('del_time', 0)->where("month", ">=", $month_start)->where("month", "<", $month_end)
  1415. ->pluck('id')->toArray();
  1416. $monthly_dd_order_key_list = MonthlyDdOrder::Clear($user, $data)->where('del_time', 0)->where("month", ">=", $month_start)->where("month", "<", $month_end)
  1417. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  1418. ->pluck("month_str", 'id')->toArray();
  1419. $month_device_salary = MonthlyDdOrderDetails::wherein('main_id', $monthly_dd_order_ids)
  1420. ->select("device_id", "depreciation_amount", "main_id")
  1421. ->get()->toArray();
  1422. //查询所有项目人员的工时比例
  1423. //汇总每个人每个月工资
  1424. $depreciatio_map = [];
  1425. $all_depreciatio = [];
  1426. foreach ($month_device_salary as $val) {
  1427. $month = $monthly_dd_order_key_list[$val['main_id']] ?? '';
  1428. if ($month) {
  1429. $depreciatio_map[$val['device_id'] . '_' . $month] = $val['depreciation_amount'];
  1430. $all_depreciatio[$val['device_id'] . '_' . $month] = $val['depreciation_amount']*100;
  1431. }
  1432. }
  1433. // 2. 计算每个员工在每个月的全月总工时
  1434. $device_monthly_total_min = [];
  1435. foreach ($month_device_list as $row) {
  1436. $key = $row['device_id'] . '_' . $row['order_month'];
  1437. if (!isset($device_monthly_total_min[$key])) {
  1438. $device_monthly_total_min[$key] = 0;
  1439. }
  1440. $device_monthly_total_min[$key] += $row['total_work'];
  1441. }
  1442. // 3. 计算分摊天数与工资
  1443. $item_year_list = [];
  1444. $item_list = [];
  1445. foreach ($month_device_list as $item) {
  1446. $key = $item['device_id'] . '_' . $item['order_month'];
  1447. // $device_key = $item['item_id'] . '_' . $item['order_month'];
  1448. $total_depreciatio = $depreciatio_map[$key] ?? 0;
  1449. $total_min = $device_monthly_total_min[$key] ?? 0;
  1450. // if (!isset($item_year_list[$device_key])) {
  1451. // $item_year_list[$device_key] = [
  1452. // "allocated_depreciation" => 0,
  1453. // ];
  1454. // }
  1455. // B. 计算工资分摊:(项目工时 / 月总工时) * 月工资
  1456. if ($total_min > 0) {
  1457. $ratio = round($item['total_work'] / $total_min, 3);
  1458. $allocated_salary = round($ratio * $total_depreciatio, 2)*100;
  1459. } else {
  1460. $allocated_salary = 0;
  1461. }
  1462. // $item_year_list[$device_key]['allocated_depreciation'] += $allocated_salary;
  1463. $item_list[] = [
  1464. 'device_id' => $item['device_id'],
  1465. 'depreciation' => $allocated_salary,
  1466. 'month' => $item['order_month'],
  1467. 'item_id' => $item['item_id'],
  1468. ];
  1469. }
  1470. $collect = collect($item_list);
  1471. $device_count = $collect->groupBy(function ($item) {
  1472. // 这里的 $item 是集合中的每一行数据
  1473. return $item['device_id'] . '_' . $item['month'];
  1474. })->map(function ($group) {
  1475. return $group->count();
  1476. })->toArray();
  1477. $month_employee_list = $collect->transform(function ($item) use (&$device_count,&$all_depreciatio) {
  1478. // 如果不是最后一条
  1479. $key = $item['device_id'] . '_' . $item['month'];
  1480. if (--$device_count[$key] > 0) {
  1481. $all_depreciatio[$key] -= $item['depreciation'];
  1482. } else {
  1483. $item['depreciation'] = $all_depreciatio[$key];
  1484. }
  1485. return $item;
  1486. })->all();
  1487. $return_item_list = [];
  1488. foreach ($month_employee_list as $v){
  1489. $key = $v['item_id']. '_' . $v['month'];
  1490. if(!isset($return_item_list[$key])) $return_item_list[$key]['depreciation'] = 0;
  1491. $return_item_list[$key]['depreciation'] += $v['depreciation'];
  1492. }
  1493. // dd($return_item_list);
  1494. return $return_item_list;
  1495. }
  1496. public function itemEmployeeSalaryStatistic($data, $user)
  1497. {
  1498. list($status, $month_start, $month_end) = $this->commonRule($data);
  1499. if (!$status) return [false, $month_start];
  1500. // 1. 获取人员工时记录
  1501. $month_employee_list = DailyPwOrderDetails::Clear($user, $data)
  1502. ->where("order_time", ">=", $month_start)
  1503. ->where("order_time", "<", $month_end)
  1504. ->where('del_time', 0)
  1505. ->select(
  1506. "item_id",
  1507. "employee_id",
  1508. DB::raw("FROM_UNIXTIME(order_time, '%Y-%m') as order_month"),
  1509. DB::raw("SUM(total_work_min) as total_work")
  1510. )
  1511. ->groupBy("order_month", "item_id", "employee_id")->get()->toArray();
  1512. // 2. 获取工资及配置
  1513. $monthly_ps_order_query = MonthlyPsOrder::Clear($user, $data)
  1514. ->where('del_time', 0)
  1515. ->where("month", ">=", $month_start)
  1516. ->where("month", "<", $month_end);
  1517. $monthly_ps_order_ids = $monthly_ps_order_query->pluck('id')->toArray();
  1518. $monthly_ps_order_key_list = $monthly_ps_order_query
  1519. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  1520. ->pluck('month_str', 'id')->toArray();
  1521. $month_employee_salary = MonthlyPsOrderDetails::wherein('main_id', $monthly_ps_order_ids)
  1522. ->select("employee_id", DB::raw("(base_salary + performance_salary + bonus + other) as salary"), "main_id", "social_insurance", "public_housing_fund")
  1523. ->get()->toArray();
  1524. // 3. 汇总每个人每个月的工资 (单位:分)
  1525. $salary_map = [];
  1526. $all_salary = [];
  1527. foreach ($month_employee_salary as $val) {
  1528. $month = $monthly_ps_order_key_list[$val['main_id']] ?? '';
  1529. if ($month) {
  1530. $key = $val['employee_id'] . '_' . $month;
  1531. $salary_map[$key] = $val;
  1532. $all_salary[$key] = [
  1533. "salary" => (int)round($val['salary'] * 100),
  1534. "social_insurance" => (int)round($val['social_insurance'] * 100),
  1535. "public_housing_fund" => (int)round($val['public_housing_fund'] * 100),
  1536. ];
  1537. }
  1538. }
  1539. // 4. 计算月总工时 (分钟) 及 余额池初始化 (小时*100)
  1540. $employee_monthly_total_min = [];
  1541. foreach ($month_employee_list as $row) {
  1542. $key = $row['employee_id'] . '_' . $row['order_month'];
  1543. $employee_monthly_total_min[$key] = ($employee_monthly_total_min[$key] ?? 0) + $row['total_work'];
  1544. }
  1545. $all_min = [];
  1546. foreach ($employee_monthly_total_min as $key => $min) {
  1547. // 重要修复:以总分钟数计算出全月总小时数,作为余额池的起点
  1548. $all_min[$key] = (int)round($min / 60, 2) * 100;
  1549. }
  1550. // 5. 初步构建待分摊列表
  1551. $item_month_list = [];
  1552. foreach ($month_employee_list as $item) {
  1553. $key = $item['employee_id'] . '_' . $item['order_month'];
  1554. $item_key = $item['order_month'] . '_' . $item['item_id'] . '_' . $item['employee_id'];
  1555. $total_min = $employee_monthly_total_min[$key] ?? 0;
  1556. $ratio = $total_min > 0 ? ($item['total_work'] / $total_min) : 0;
  1557. $item_month_list[$item_key] = [
  1558. "month" => $item['order_month'],
  1559. "employee_id" => $item['employee_id'],
  1560. "item_id" => $item['item_id'],
  1561. "salary" => $salary_map[$key]['salary'] ?? 0,
  1562. "social_insurance" => $salary_map[$key]['social_insurance'] ?? 0,
  1563. "public_housing_fund" => $salary_map[$key]['public_housing_fund'] ?? 0,
  1564. "radio" => round($ratio, 4),
  1565. "total_min_raw" => $total_min, // 保留原始分钟,不在这里修改
  1566. "work_min_raw" => $item['total_work'],
  1567. ];
  1568. }
  1569. // 6. 获取项目和人员信息
  1570. $items = collect($item_month_list)->pluck('item_id')->unique()->all();
  1571. $employee_ids = collect($item_month_list)->pluck('employee_id')->unique()->all();
  1572. $employee_key_list = Employee::TopClear($user, $data)->wherein('id', $employee_ids)
  1573. ->select("major", "title", "id")->get()->keyBy('id')->toArray();
  1574. $item_info = Item::TopClear($user, $data)->wherein('id', $items)
  1575. ->select("title", "code", "id")->get()->keyBy('id')->toArray();
  1576. // 7. 统计每人项目数用于平账
  1577. $employee_count = collect($item_month_list)->groupBy(fn($i) => $i['employee_id'].'_'.$i['month'])
  1578. ->map(fn($g) => $g->count())->toArray();
  1579. // 8. 核心转换
  1580. $result = collect($item_month_list)->sortBy('month')->values()->transform(function ($item) use ($item_info, $employee_key_list, &$employee_count, &$all_salary, &$all_min) {
  1581. $key = $item['employee_id'] . '_' . $item['month'];
  1582. $item['item_title'] = $item_info[$item['item_id']]['title'] ?? "未知项目";
  1583. $item['item_code'] = $item_info[$item['item_id']]['code'] ?? "-";
  1584. $item['employee_title'] = $employee_key_list[$item['employee_id']]['title'] ?? "未知人员";
  1585. $item['major'] = $employee_key_list[$item['employee_id']]['major'] ?? "-";
  1586. // 应出勤工时:固定展示,不参与递减
  1587. $item['total_min'] = round($item['total_min_raw'] / 60, 2);
  1588. if (isset($employee_count[$key]) && --$employee_count[$key] > 0) {
  1589. // 非最后一条项目
  1590. $work_h = round($item['work_min_raw'] / 60, 2);
  1591. $item['work_minutes'] = $work_h;
  1592. $all_min[$key] -= ($work_h * 100);
  1593. // 分摊工资
  1594. $ws = round($item['salary'] * ($item['work_min_raw'] / $item['total_min_raw']), 2);
  1595. $item['work_salary'] = $ws;
  1596. if (isset($all_salary[$key])) $all_salary[$key]['salary'] -= ($ws * 100);
  1597. // 分摊社保
  1598. $wsi = round($item['social_insurance'] * ($item['work_min_raw'] / $item['total_min_raw']), 2);
  1599. $item['work_social_insurance'] = $wsi;
  1600. if (isset($all_salary[$key])) $all_salary[$key]['social_insurance'] -= ($wsi * 100);
  1601. // 分摊公积金
  1602. $wphf = round($item['public_housing_fund'] * ($item['work_min_raw'] / $item['total_min_raw']), 2);
  1603. $item['work_public_housing_fund'] = $wphf;
  1604. if (isset($all_salary[$key])) $all_salary[$key]['public_housing_fund'] -= ($wphf * 100);
  1605. } else {
  1606. // 最后一条,从余额池取值(解决精度)
  1607. $item['work_salary'] = isset($all_salary[$key]) ? round($all_salary[$key]['salary'] / 100, 2) : 0;
  1608. $item['work_social_insurance'] = isset($all_salary[$key]) ? round($all_salary[$key]['social_insurance'] / 100, 2) : 0;
  1609. $item['work_public_housing_fund'] = isset($all_salary[$key]) ? round($all_salary[$key]['public_housing_fund'] / 100, 2) : 0;
  1610. $item['work_minutes'] = isset($all_min[$key]) ? round($all_min[$key] / 100, 2) : 0;
  1611. }
  1612. unset($item['total_min_raw'], $item['work_min_raw']);
  1613. return $item;
  1614. })->all();
  1615. return [true, $result];
  1616. }
  1617. public function itemEmployeeSalaryStatistic1($data, $user)
  1618. {
  1619. list($status, $month_start, $month_end) = $this->commonRule($data);
  1620. if (!$status) return [false, $month_start];
  1621. //项目编码、项目名称、姓名、人员类别、应出勤工时、研发出勤工时、研发工时占比、归集工资总额、归集社保金额、归集公积金、研发工资总额、研发社保金额、研发公积金
  1622. //获取人员工资项目相关分组数据
  1623. $month_employee = DailyPwOrderDetails::Clear($user, $data);
  1624. $month_employee_list = $month_employee->where("order_time", ">=", $month_start)->where("order_time", "<", $month_end)
  1625. ->where('del_time', 0)
  1626. ->select(
  1627. "item_id",
  1628. "employee_id",
  1629. // 将时间戳转为 Y-m-d 格式并起别名
  1630. DB::raw("FROM_UNIXTIME(order_time, '%Y-%m') as order_month"),
  1631. // 聚合求和
  1632. DB::raw("SUM(total_work_min) as total_work")
  1633. )
  1634. ->groupBy("order_month", "item_id", "employee_id")->get()->toArray();
  1635. //查询所有人员工资
  1636. $monthly_ps_order_ids = MonthlyPsOrder::Clear($user, $data)->where('del_time', 0)->where("month", ">=", $month_start)->where("month", "<", $month_end)
  1637. ->pluck('id')->toArray();
  1638. $monthly_ps_order_key_list = MonthlyPsOrder::Clear($user, $data)
  1639. ->where('del_time', 0)
  1640. ->where("month", ">=", $month_start)
  1641. ->where("month", "<", $month_end)
  1642. ->select('id', DB::raw("FROM_UNIXTIME(month, '%Y-%m') as month_str"))
  1643. ->pluck('month_str', 'id')
  1644. ->toArray();
  1645. $month_employee_salary = MonthlyPsOrderDetails::wherein('main_id', $monthly_ps_order_ids)
  1646. ->select("employee_id",DB::raw("(base_salary + performance_salary + bonus + other) as salary"), "main_id", "social_insurance", "public_housing_fund")
  1647. ->get()->toArray();
  1648. //查询所有项目人员的工时比例
  1649. //汇总每个人每个月工资
  1650. $salary_map = [];
  1651. $all_salary = [];
  1652. foreach ($month_employee_salary as $val) {
  1653. $month = $monthly_ps_order_key_list[$val['main_id']] ?? '';
  1654. if ($month) {
  1655. $salary_map[$val['employee_id'] . '_' . $month] = $val;
  1656. $all_salary[$val['employee_id'] . '_' . $month] = [
  1657. "salary" => $val['salary']*100,
  1658. "social_insurance" => $val['social_insurance']*100,
  1659. "public_housing_fund" => $val['public_housing_fund']*100,
  1660. ];
  1661. }
  1662. }
  1663. // var_dump($salary_map);die;
  1664. // 2. 计算每个员工在每个月的全月总工时
  1665. $employee_monthly_total_min = [];
  1666. $all_min = [];
  1667. foreach ($month_employee_list as $row) {
  1668. $key = $row['employee_id'] . '_' . $row['order_month'];
  1669. if (!isset($employee_monthly_total_min[$key])) {
  1670. $employee_monthly_total_min[$key] = 0;
  1671. $all_min[$key] = 0;
  1672. }
  1673. $employee_monthly_total_min[$key] += $row['total_work'];
  1674. $all_min[$key] = round($row['total_work']/60,2)*100;
  1675. }
  1676. // 3. 计算分摊天数与工资
  1677. $item_month_list = [];
  1678. foreach ($month_employee_list as $item) {
  1679. $key = $item['employee_id'] . '_' . $item['order_month'];
  1680. $item_key = $item['order_month'] . '_' . $item['item_id'] . '_' . $item['employee_id'];
  1681. if (!isset($item_month_list[$item_key])) {
  1682. $item_month_list[$item_key] = [
  1683. "month" => $item['order_month'],
  1684. "allocated_salary" => 0,
  1685. "employee_id" => $item['employee_id'],
  1686. "work_minutes" => 0,
  1687. "salary" => ($salary_map[$key]['salary'] ?? 0),
  1688. "social_insurance" => ($salary_map[$key]['social_insurance'] ?? 0),
  1689. "public_housing_fund" => ($salary_map[$key]['public_housing_fund'] ?? 0),
  1690. "item_id" => $item['item_id'],
  1691. ];
  1692. }
  1693. $total_min = $employee_monthly_total_min[$key] ?? 0;
  1694. // B. 计算工资分摊:(项目工时 / 月总工时) * 月工资
  1695. if ($total_min > 0) {
  1696. $ratio = round($item['total_work'] / $total_min, 4);
  1697. } else {
  1698. $ratio = 0;
  1699. }
  1700. $item_month_list[$item_key]['radio'] = $ratio;
  1701. $item_month_list[$item_key]['total_min'] = $total_min;
  1702. $item_month_list[$item_key]['work_minutes'] += $item['total_work'];
  1703. }
  1704. $item_month_list = collect($item_month_list)->sortBy('month')->values()->all();
  1705. $items = collect($item_month_list)->pluck('item_id')->unique()->values()->all();
  1706. $employee_ids = collect($item_month_list)->pluck('employee_id')->unique()->values()->all();
  1707. $employee = Employee::TopClear($user, $data);
  1708. $employee_list = $employee->wherein('id', $employee_ids)->select("major", "title", "id")->get()->toArray();
  1709. $employee_key_list = [];
  1710. foreach ($employee_list as $v) {
  1711. $employee_key_list[$v['id']] = $v;
  1712. }
  1713. $item = Item::TopClear($user, $data);
  1714. $item_title_key_list = $item->wherein('id', $items)->pluck("title", "id")->toArray();
  1715. $item_code_key_list = $item->wherein('id', $items)->pluck("code", "id")->toArray();
  1716. $collect = collect($item_month_list);
  1717. $employee_count = $collect->groupBy(function ($item) {
  1718. // 这里的 $item 是集合中的每一行数据
  1719. return $item['employee_id'] . '_' . $item['month'];
  1720. })->map(function ($group) {
  1721. return $group->count();
  1722. })->toArray();
  1723. //项目编码、项目名称、姓名、人员类别、应出勤工时、研发出勤工时、研发工时占比、归集工资总额、归集社保金额、归集公积金、研发工资总额、研发社保金额、研发公积金
  1724. $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) {
  1725. $item['item_title'] = $item_title_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  1726. $item['item_code'] = $item_code_key_list[$item['item_id']] ?? "未知项目({$item['item_id']})";
  1727. $item['employee_title'] = $employee_key_list[$item['employee_id']]['title'] ?? "未知人员({$item['employee_id']})";
  1728. $item['major'] = $employee_key_list[$item['employee_id']]['major'] ?? "未知人员({$item['employee_id']})";
  1729. $item['total_min'] = round($item['total_min'] / 60, 2);
  1730. $key = $item['employee_id'] . '_' . $item['month'];
  1731. if (--$employee_count[$key] > 0) {
  1732. $work_minutes = round($item['work_minutes'] / 60, 2);
  1733. $item['work_minutes'] = $work_minutes;
  1734. $all_min[$key] -= ($work_minutes*100);
  1735. $work_salary = round($item['salary'] * $item['radio'], 2);
  1736. $all_salary[$key]['salary'] -= ($work_salary*100);
  1737. $item['work_salary'] = $work_salary;
  1738. $social_insurance = round($item['social_insurance'] * $item['radio'], 2);
  1739. $all_salary[$key]['social_insurance'] -= ($social_insurance*100);
  1740. $item['work_social_insurance'] = $social_insurance;
  1741. $work_public_housing_fund = round($item['public_housing_fund'] * $item['radio'], 2);
  1742. $all_salary[$key]['public_housing_fund'] -= ($work_public_housing_fund*100);
  1743. $item['work_public_housing_fund'] = $work_public_housing_fund;
  1744. } else {
  1745. $item['work_salary'] = round($all_salary[$key]['salary']/100,2);
  1746. $item['work_social_insurance'] = round($all_salary[$key]['social_insurance'] /100,2);
  1747. $item['work_public_housing_fund'] = round( $all_salary[$key]['public_housing_fund']/100,2);
  1748. $item['work_minutes'] = round( $all_min[$key]/100,2);
  1749. }
  1750. return $item;
  1751. })->all();
  1752. return [true, $item_month_list];
  1753. }
  1754. public function enterpriseRdStatistic($data, $user){
  1755. $model = Item::TopClear($user,$data);
  1756. $model = $model->where('del_time',0)
  1757. ->select(Item::$report_field_1)
  1758. ->orderby('id', 'desc');
  1759. if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
  1760. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  1761. if(! empty($data['state'])) $model->where('state', $data['state']);
  1762. $list = $model->get()->toArray();
  1763. $list = $this->fillEnterpriseRdStatistic($list, $data, $user);
  1764. return [true, $list];
  1765. }
  1766. private function fillEnterpriseRdStatistic($list, $data, $user){
  1767. //项目实际支出 项目费用单
  1768. $expense = ExpenseClaimsDetails::Clear($user, $data);
  1769. $expense_map = $expense->where('del_time', 0)
  1770. ->whereIn('item_id', array_unique(array_column($list,'id')))
  1771. ->selectRaw('item_id, SUM(amount) as total_amount')
  1772. ->groupBy('item_id')
  1773. ->pluck('total_amount', 'item_id') // 这一步直接生成 item_id => total_amount 结构
  1774. ->toArray();
  1775. foreach ($list as $key => $value){
  1776. $list[$key]['actual_expenditure'] = $expense_map[$value['id']] ?? 0;
  1777. $start_time = $value['start_time'] ? date('Y-m-d', $value['start_time']) : '';
  1778. $end_time = $value['end_time'] ? date('Y-m-d', $value['end_time']) : '';
  1779. $list[$key]['time_range'] = $start_time . ' ' . $end_time;
  1780. }
  1781. return $list;
  1782. }
  1783. public function enterpriseRdManStatistic($data, $user){
  1784. $model = Employee::TopClear($user,$data);
  1785. $model = $model->where('del_time',0)
  1786. ->where('is_admin', '<=', Employee::IS_ADMIN_ONE)
  1787. ->select(Employee::$report_field)
  1788. ->orderBy('id','desc');
  1789. if(! empty($data['id_card'])) $model->where('id_card', 'LIKE', '%'.$data['id_card'].'%');
  1790. if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
  1791. if(! empty($data['employee_type'])) $model->where('employee_type', $data['employee_type']);
  1792. if(isset($data['education'])) $model->where('education', $data['education']);
  1793. $list = $model->get()->toArray();
  1794. $list = $this->fillEnterpriseRdManStatistic($list, $data, $user);
  1795. return [true, $list];
  1796. }
  1797. private function fillEnterpriseRdManStatistic($list, $data, $user){
  1798. $man = EmployeeDepartPermission::from('employee_depart_permission as a')
  1799. ->join('depart as b', 'b.id', '=', 'a.depart_id')
  1800. ->whereIn('a.employee_id', array_unique(array_column($list,'id')))
  1801. ->select('a.employee_id', 'b.title')
  1802. ->get()->toArray();
  1803. $man_map = [];
  1804. foreach ($man as $value){
  1805. if(isset($man_map[$value['employee_id']])){
  1806. $man_map[$value['employee_id']] .= ',' . $value['title'];
  1807. }else{
  1808. $man_map[$value['employee_id']] = $value['title'];
  1809. }
  1810. }
  1811. foreach ($list as $key => $value){
  1812. $depart_title = $man_map[$value['id']] ?? "";
  1813. $list[$key]['position_new'] = $depart_title . '/' . $value['position'];
  1814. $list[$key]['employee_type_title'] = Employee::E_State_Type[$value['employee_type']] ?? '';
  1815. $list[$key]['education'] = Employee::Education[$value['education']] ?? '';
  1816. }
  1817. return $list;
  1818. }
  1819. public function enterpriseRdItemStatistic($data, $user){
  1820. // 1. 先声明表名和别名
  1821. $model = ItemDetails::from('item_details as i');
  1822. // 2. 再调用 TopClear
  1823. $model = $model->TopClear($user, $data);
  1824. $model = $model->from('item_details as i')
  1825. ->where('i.del_time', 0)
  1826. ->where('i.type', ItemDetails::type_one);
  1827. $model = $model->leftJoin('employee as e', 'i.data_id', '=', 'e.id');
  1828. $fields = ['e.id', 'e.title', 'e.education', 'e.major','e.p_title','i.item_id'];
  1829. $list = $model->select($fields)
  1830. ->orderBy('i.id', 'desc')
  1831. ->get()
  1832. ->toArray();
  1833. $list = $this->fillEnterpriseRdItemStatistic($list, $data, $user);
  1834. return [true, $list];
  1835. }
  1836. private function fillEnterpriseRdItemStatistic($list, $data, $user){
  1837. $man = EmployeeDepartPermission::from('employee_depart_permission as a')
  1838. ->join('depart as b', 'b.id', '=', 'a.depart_id')
  1839. ->whereIn('a.employee_id', array_unique(array_column($list,'id')))
  1840. ->select('a.employee_id', 'b.title')
  1841. ->get()->toArray();
  1842. $man_map = [];
  1843. foreach ($man as $value){
  1844. if(isset($man_map[$value['employee_id']])){
  1845. $man_map[$value['employee_id']] .= ',' . $value['title'];
  1846. }else{
  1847. $man_map[$value['employee_id']] = $value['title'];
  1848. }
  1849. }
  1850. $item_map = Item::whereIn('id',array_unique(array_column($list,'item_id')))
  1851. ->pluck('title','id')
  1852. ->toArray();
  1853. foreach ($list as $key => $value){
  1854. $depart_title = $man_map[$value['id']] ?? "";
  1855. $list[$key]['depart_title'] = $depart_title;
  1856. $item_title = $item_map[$value['item_id']] ?? "";
  1857. $list[$key]['item_title'] = $item_title;
  1858. $list[$key]['education'] = Employee::Education[$value['education']] ?? '';
  1859. }
  1860. return $list;
  1861. }
  1862. }