ExportFileService.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. <?php
  2. namespace App\Service;
  3. use App\Exports\ExportOrder;
  4. use App\Exports\ItemSalaryFTMultipleSheetExport;
  5. use App\Exports\ItemSalarySheetExport;
  6. use App\Exports\ManMonthlyWorkHourMultipleSheetExport;
  7. use App\Exports\MultiSheetExport;
  8. use App\Exports\ProjectDepreciationMultipleSheetExport;
  9. use App\Exports\ResearchExpenseMultipleSheetExport;
  10. use App\Model\Depart;
  11. use App\Model\PLeaveOverOrder;
  12. use Maatwebsite\Excel\Facades\Excel;
  13. class ExportFileService extends Service
  14. {
  15. public static $filename = "";
  16. //导出的方式 0 选择导出的数据 1 查询后 导出指定的数据(最多每次一千条)
  17. public static $export_type = [
  18. 0,
  19. 1
  20. ];
  21. public function exportAll($data,$user){
  22. if(empty($data['menu_id'])) return [false, 'menu_id不能为空'];
  23. if(empty($data['type'])) return [false, 'type不能为空'];
  24. $function = $data['type'];
  25. $name = $this->fillE($data['type'], $user);
  26. if (! method_exists(self::class, $function)) return [false, "导出方法不存在,请联系开发"];
  27. self::$filename = $name;
  28. $export_type = $data['export_type'] ?? 0;
  29. if(! isset(self::$export_type[$export_type])) return [false,'导出文件方式错误或者不存在'];
  30. if(empty($export_type)){
  31. if(empty($data['id'])) return [false,'请选择导出数据'];
  32. $search = $data;
  33. }else{
  34. if(empty($data['order_search'])) return [false,'搜索条件不能为空'];
  35. $search = $data['order_search'];
  36. if(empty($search['page_index'])) return [false,'请选择导出数据的开始页码'];
  37. if(empty($search['page_size'])) return [false,'请选择导出数据的条数'];
  38. if($search['page_size'] > 5000) return [false,'请选择导出数据的条数每次最多5000条'];
  39. $data['order_search']['menu_id'] = $data['menu_id'];
  40. $search = $data['order_search'];
  41. }
  42. list($status, $return) = $this->$function($search,$user);
  43. if(! $status) return [false, $return];
  44. return [true, $return];
  45. }
  46. public function fillE($type, &$user){
  47. $header = config("excel." . $type) ?? [];
  48. $funcName = $header['name'] ?? "";
  49. // $header_f = "extra_" . $menu_id;
  50. // $service = new TableHeadService();
  51. // if(method_exists($service,$header_f)) $service->$header_f($header_default);
  52. $user['e_header_default'] = $header['array'] ?? [];
  53. return $funcName;
  54. }
  55. private function fillData($data, $column, &$return)
  56. {
  57. // 预先创建包含默认值的键数组
  58. $default = array_fill_keys($column, '');
  59. foreach ($data as $value) {
  60. // 提取交集,并用默认值补充缺失的键
  61. $return[] = array_merge($default, array_intersect_key($value, $default));
  62. }
  63. }
  64. private function fillTotalData($data, $column, &$return){
  65. $tmp = [];
  66. foreach ($column as $value){
  67. $key = $value['key'];
  68. if(! empty($value['sum']) && isset($data[$value['key']])){
  69. $decimals = $col['decimals'] ?? 2;
  70. // $tmp[$value['key']] = $data[$value['key']];
  71. // 用 number_format 格式化输出(保持字符串形式,避免科学计数)
  72. $tmp[$key] = number_format((float)$data[$key], $decimals, '.', '');
  73. }else{
  74. $tmp[$value['key']] = "";
  75. }
  76. }
  77. $return[] = $tmp;
  78. }
  79. public function employee($ergs,$user){
  80. // 导出数据
  81. $return = [];
  82. $header_default = $user['e_header_default'];
  83. $column = array_column($header_default,'export');
  84. $header = array_column($header_default,'value');
  85. $service = new EmployeeService();
  86. $model = $service->employeeCommon($ergs, $user);
  87. $model->chunk(500,function ($data) use(&$return, $service, $column, $user){
  88. $service->fillDataForExport($data, $column, $user, $return);
  89. });
  90. return [true, $this->saveExportData($return,$header)];
  91. }
  92. public function depart($ergs,$user){
  93. // 导出数据
  94. $return = [];
  95. $header_default = $user['e_header_default'];
  96. $column = array_column($header_default,'export');
  97. $header = array_column($header_default,'value');
  98. $service = new EmployeeService();
  99. $model = $service->departCommon($ergs, $user);
  100. $model->chunk(500,function ($data) use(&$return, $service, $column, $user){
  101. $data = $data->toArray();
  102. $list['data'] = $data;
  103. //订单数据
  104. $list = $service->fillDepartList($list, $user, true);
  105. //返回数据
  106. $this->fillData($list['data'], $column, $return);
  107. });
  108. return [true, $this->saveExportData($return,$header)];
  109. }
  110. public function device($ergs,$user){
  111. // 导出数据
  112. $return = [];
  113. $header_default = $user['e_header_default'];
  114. $column = array_column($header_default,'export');
  115. $header = array_column($header_default,'value');
  116. $service = new DeviceService();
  117. $model = $service->deviceCommon($ergs, $user);
  118. $model->chunk(500,function ($data) use(&$return, $service, $column,$ergs, $user){
  119. $data = $data->toArray();
  120. $list['data'] = $data;
  121. //订单数据
  122. $list = $service->fillData($list, $ergs, $user);
  123. //返回数据
  124. $this->fillData($list['data'], $column, $return);
  125. });
  126. return [true, $this->saveExportData($return,$header)];
  127. }
  128. public function item($ergs,$user){
  129. // 导出数据
  130. $return = [];
  131. $header_default = $user['e_header_default'];
  132. $column = array_column($header_default,'export');
  133. $header = array_column($header_default,'value');
  134. $service = new ItemService();
  135. $model = $service->itemCommon($ergs, $user);
  136. $model->chunk(500,function ($data) use(&$return,$column,$service, $user){
  137. // 调用 Service 层的填充方法
  138. $service->fillDataForExport($data, $column, $user, $return);
  139. });
  140. return [true, $this->saveExportData($return,$header)];
  141. }
  142. public function fee($ergs,$user){
  143. // 导出数据
  144. $return = [];
  145. $header_default = $user['e_header_default'];
  146. $column = array_column($header_default,'export');
  147. $header = array_column($header_default,'value');
  148. $service = new FeeService();
  149. $model = $service->feeCommon($ergs, $user);
  150. $model->chunk(500,function ($data) use(&$return, $service, $column, $user){
  151. $data = $data->toArray();
  152. $list['data'] = $data;
  153. //订单数据
  154. $list = $service->fillFeeList($list, $user, true);
  155. //返回数据
  156. $this->fillData($list['data'], $column, $return);
  157. });
  158. return [true, $this->saveExportData($return,$header)];
  159. }
  160. public function monthPwOrder($ergs,$user){
  161. // 导出数据
  162. $return = [];
  163. $header_default = $user['e_header_default'];
  164. $column = array_column($header_default,'export');
  165. $header = array_column($header_default,'value');
  166. $service = new PersonWorkService();
  167. $model = $service->monthlyPwOrderCommon($ergs, $user);
  168. $model->chunk(500,function ($data) use(&$return, $service, $column){
  169. // 直接处理这一批主表数据,将其与详情合并平铺
  170. $service->fillDataForExport($data->toArray(), $column, $return);
  171. });
  172. return [true, $this->saveExportData($return,$header)];
  173. }
  174. public function monthDwOrder($ergs,$user){
  175. // 导出数据
  176. $return = [];
  177. $header_default = $user['e_header_default'];
  178. $column = array_column($header_default,'export');
  179. $header = array_column($header_default,'value');
  180. $service = new DeviceWorkService();
  181. $model = $service->monthlyDwOrderCommon($ergs, $user);
  182. $model->chunk(500,function ($data) use(&$return, $service, $column){
  183. // 直接处理这一批主表数据,将其与详情合并平铺
  184. $service->fillDataForExport($data->toArray(), $column, $return);
  185. });
  186. return [true, $this->saveExportData($return,$header)];
  187. }
  188. public function monthPsOrder($ergs,$user){
  189. // 导出数据
  190. $return = [];
  191. $header_default = $user['e_header_default'];
  192. $column = array_column($header_default,'export');
  193. $header = array_column($header_default,'value');
  194. $service = new PersonSalaryService();
  195. $model = $service->monthlyPsOrderCommon($ergs, $user);
  196. $model->chunk(500,function ($data) use(&$return, $service, $column){
  197. // 直接处理这一批主表数据,将其与详情合并平铺
  198. $service->fillDataForExport($data->toArray(), $column, $return);
  199. });
  200. return [true, $this->saveExportData($return,$header)];
  201. }
  202. public function monthDdOrder($ergs,$user){
  203. // 导出数据
  204. $return = [];
  205. $header_default = $user['e_header_default'];
  206. $column = array_column($header_default,'export');
  207. $header = array_column($header_default,'value');
  208. $service = new DeviceDepreciationService();
  209. $model = $service->monthlyDdOrderCommon($ergs, $user);
  210. $model->chunk(500,function ($data) use(&$return, $service, $column){
  211. // 直接处理这一批主表数据,将其与详情合并平铺
  212. $service->fillDataForExport($data->toArray(), $column, $return);
  213. });
  214. return [true, $this->saveExportData($return,$header)];
  215. }
  216. public function ruleSet($ergs,$user){
  217. // 导出数据
  218. $return = [];
  219. $header_default = $user['e_header_default'];
  220. $column = array_column($header_default,'export');
  221. $header = array_column($header_default,'value');
  222. $service = new RuleSetService();
  223. $model = $service->ruleSetCommon($ergs, $user);
  224. $model->chunk(500,function ($data) use(&$return, $service, $column){
  225. // 直接处理这一批主表数据,将其与详情合并平铺
  226. $service->fillDataForExport($data->toArray(), $column, $return);
  227. });
  228. return [true, $this->saveExportData($return,$header)];
  229. }
  230. public function dailyPwOrder($ergs,$user){
  231. // 导出数据
  232. $return = [];
  233. $header_default = $user['e_header_default'];
  234. $column = array_column($header_default,'export');
  235. $header = array_column($header_default,'value');
  236. $service = new PersonWorkService();
  237. $model = $service->dailyPwOrderCommon($ergs, $user);
  238. $model->chunk(500,function ($data) use(&$return, $service, $column){
  239. // 直接处理这一批主表数据,将其与详情合并平铺
  240. $service->fillDataForExportDaily($data->toArray(), $column, $return);
  241. });
  242. return [true, $this->saveExportData($return,$header)];
  243. }
  244. public function dailyDwOrder($ergs,$user){
  245. // 导出数据
  246. $return = [];
  247. $header_default = $user['e_header_default'];
  248. $column = array_column($header_default,'export');
  249. $header = array_column($header_default,'value');
  250. $service = new DeviceWorkService();
  251. $model = $service->dailyDwOrderCommon($ergs, $user);
  252. $model->chunk(500,function ($data) use(&$return, $service, $column){
  253. // 直接处理这一批主表数据,将其与详情合并平铺
  254. $service->fillDataForExportDaily($data->toArray(), $column, $return);
  255. });
  256. return [true, $this->saveExportData($return,$header)];
  257. }
  258. public function leaveOrder($ergs,$user){
  259. // 导出数据
  260. $return = [];
  261. $header_default = $user['e_header_default'];
  262. $column = array_column($header_default,'export');
  263. $header = array_column($header_default,'value');
  264. $service = new PLeaveOverService();
  265. $ergs['type'] = PLeaveOverOrder::TYPE_ONE;
  266. $model = $service->pLeaveOverCommon($ergs, $user);
  267. $model->chunk(500,function ($data) use(&$return, $service, $column){
  268. // 直接处理这一批主表数据,将其与详情合并平铺
  269. $service->fillDataForExportDaily($data->toArray(), $column, $return);
  270. });
  271. return [true, $this->saveExportData($return,$header)];
  272. }
  273. public function overtimeOrder($ergs,$user){
  274. // 导出数据
  275. $return = [];
  276. $header_default = $user['e_header_default'];
  277. $column = array_column($header_default,'export');
  278. $header = array_column($header_default,'value');
  279. $service = new PLeaveOverService();
  280. $ergs['type'] = PLeaveOverOrder::TYPE_TWO;
  281. $model = $service->pLeaveOverCommon($ergs, $user);
  282. $model->chunk(500,function ($data) use(&$return, $service, $column){
  283. // 直接处理这一批主表数据,将其与详情合并平铺
  284. $service->fillDataForExportDaily($data->toArray(), $column, $return);
  285. });
  286. return [true, $this->saveExportData($return,$header)];
  287. }
  288. public function feeOrder($ergs, $user)
  289. {
  290. // 导出配置
  291. $return = [];
  292. $header_default = $user['e_header_default']; // 假设前端已下发报销单的模板配置
  293. $column = array_column($header_default, 'export');
  294. $header = array_column($header_default, 'value');
  295. $service = new ExpenseClaimsService();
  296. // 使用你提到的 common 方法获取 Query Builder
  297. $model = $service->expenseClaimsSetCommon($ergs, $user);
  298. $model->chunk(500, function ($data) use (&$return, $service, $column) {
  299. // 直接处理这一批主表数据,将其与详情合并平铺
  300. $service->fillDataForExport($data->toArray(), $column, $return);
  301. });
  302. return [true, $this->saveExportData($return, $header)];
  303. }
  304. public function RDOrder($ergs, $user)
  305. {
  306. // 导出配置
  307. $return = [];
  308. $header_default = $user['e_header_default'];
  309. $column = array_column($header_default, 'export');
  310. $header = array_column($header_default, 'value');
  311. $service = new AuxiliaryAccountService();
  312. $model = $service->setCommon($ergs, $user);
  313. $model->chunk(500, function ($data) use (&$return, $service, $column) {
  314. // 直接处理这一批主表数据,将其与详情合并平铺
  315. $service->fillDataForExport($data->toArray(), $column, $return);
  316. });
  317. return [true, $this->saveExportData($return, $header)];
  318. }
  319. // 项目工资统计表
  320. public function exportEmployeeSalary($data, $user)
  321. {
  322. $service = new StatisticService();
  323. // 1. 调用你现有的查询方法获取基础数据
  324. list($status, $itemMonthList) = $service->employeeMonthSalaryStatistic($data, $user);
  325. if (!$status) return $itemMonthList; // 返回错误信息
  326. // 2. 提取所有涉及到的唯一项目 (按 Code 排序,保证列顺序固定)
  327. $projects = collect($itemMonthList)->pluck('item_code')->unique()->sort()->values()->toArray();
  328. // 3. 按月份对数据进行分组
  329. $groupedByMonth = collect($itemMonthList)->groupBy('month')->sortKeys();
  330. $exportData = [];
  331. $columnTotals = array_fill(0, count($projects) * 2, 0); // 用于存储每列的合计
  332. $grandTotalSalary = 0; // 总计金额
  333. // 4. 循环每个月,构造行数据
  334. foreach ($groupedByMonth as $month => $items) {
  335. $row = [$month]; // A列:月份
  336. $monthTotalSalary = 0;
  337. // 创建该月项目的映射,方便快速查找
  338. $monthItemsMap = $items->keyBy('item_code');
  339. foreach ($projects as $index => $code) {
  340. $itemDetail = $monthItemsMap->get($code);
  341. $days = $itemDetail['days'] ?? 0;
  342. $salary = $itemDetail['allocated_salary'] ?? 0;
  343. $row[] = $days > 0 ? $days : ''; // 天数列
  344. $row[] = $salary > 0 ? $salary : ''; // 工资列
  345. // 累加合计行(列合计)
  346. $columnTotals[$index * 2] += $days;
  347. $columnTotals[$index * 2 + 1] += $salary;
  348. $monthTotalSalary += $salary;
  349. }
  350. $row[] = $monthTotalSalary; // 最后一列:该月合计工资
  351. $grandTotalSalary += $monthTotalSalary;
  352. $exportData[] = $row;
  353. }
  354. // 5. 构造最后的“合计”行
  355. $totalRow = ['合计'];
  356. foreach ($columnTotals as $val) {
  357. $totalRow[] = $val > 0 ? $val : 0;
  358. }
  359. $totalRow[] = $grandTotalSalary;
  360. $exportData[] = $totalRow;
  361. $file_name = "项目工资统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  362. $filename = $file_name . '.' . 'xlsx';
  363. $bool = Excel::store(new ItemSalarySheetExport($projects, $exportData, Depart::where('id', $user['top_depart_id'])->value('title')),"/public/export/{$filename}", null, 'Xlsx', []);
  364. return [true, $filename];
  365. }
  366. // 人员月工时统计表
  367. public function exportManMonthlyWorkHour($data, $user)
  368. {
  369. // 1. 获取报表基础数据
  370. $service = new StatisticService();
  371. list($status, $result) = $service->employeeDayHourStatistic($data, $user);
  372. if (!$status) return $result;
  373. $sourceData = collect($result['data']);
  374. // 2. 按月份分组,准备多 Sheet 数据
  375. // 结构:[ '2024-04' => [ 'days' => 30, 'data' => [...] ], ... ]
  376. $monthsData = [];
  377. // 按月分组数据
  378. $groupedByMonth = $sourceData->groupBy(function ($item) {
  379. return date('Y年m月', strtotime($item['order_date']));
  380. });
  381. foreach ($groupedByMonth as $monthName => $monthItems) {
  382. // A. 计算该月总天数
  383. // 转换 '2024年04月' 为 '2024-04' 获取天数
  384. $formatMonth = str_replace(['年', '月'], ['-', ''], $monthName);
  385. $daysInMonth = date('t', strtotime($formatMonth . '-01'));
  386. // B. 进一步按 项目+人员 分组,因为一行显示一个项目一个人的全月工时
  387. $groupedByUserItem = $monthItems->groupBy(function ($item) {
  388. return $item['item_code'] . '_' . $item['employee_id'];
  389. });
  390. $sheetRows = [];
  391. foreach ($groupedByUserItem as $key => $records) {
  392. $first = $records->first();
  393. // 初始化行:前两列是 项目编号 和 姓名
  394. $row = [
  395. $first['item_code'],
  396. $first['employee_name']
  397. ];
  398. // C. 循环 1 号到该月最后一天,填充工时
  399. // 将该员工该项目在这个月的记录转为 日期 => 工时 的映射
  400. $dayMap = $records->keyBy(function($r){
  401. return (int)date('d', strtotime($r['order_date']));
  402. });
  403. for ($d = 1; $d <= $daysInMonth; $d++) {
  404. $workHour = $dayMap->get($d)['total_work_hours'] ?? '';
  405. // 如果工时为 0 或空,按你要求的格式传空字符串
  406. $row[] = ($workHour > 0) ?(float) $workHour : '';
  407. }
  408. $sheetRows[] = $row;
  409. }
  410. $monthsData[$monthName] = [
  411. 'days' => (int)$daysInMonth,
  412. 'data' => $sheetRows
  413. ];
  414. }
  415. $file_name = "人员月工时统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  416. $filename = $file_name . '.' . 'xlsx';
  417. $bool = Excel::store(new ManMonthlyWorkHourMultipleSheetExport($monthsData), "/public/export/{$filename}", null, 'Xlsx', []);
  418. return [true, $filename];
  419. }
  420. // 项目设备折旧
  421. public function exportDeviceZj(array $data, $user)
  422. {
  423. $service = new StatisticService();
  424. list($status, $result) = $service->itemDeviceMonthStatistic($data, $user);
  425. if (!$status) return $result;
  426. // 2. 将数据按 [项目编号][月份] 进行分组
  427. // 预期结构:$monthsData['RD01']['months']['2025-01'] = [设备1, 设备2...]
  428. $groupedData = collect($result)->groupBy('item_code');
  429. $finalExportData = [];
  430. foreach ($groupedData as $itemCode => $itemRecords) {
  431. $projectName = $itemRecords->first()['item_title'] ?? '';
  432. // 2. 获取年份(从 order_month 字段提取,如 "2026-01" 取前4位)
  433. $firstMonth = $firstRecord['month'] ?? date('Y-m');
  434. $year = substr($firstMonth, 0, 4);
  435. // 3. 构造新的 Key:年-项目 (例如: 2026-53code)
  436. $newSheetKey = $year . '年度项目' . $itemCode;
  437. // 按月份进一步分组
  438. $monthGroups = $itemRecords->groupBy('month');
  439. $monthsPayload = [];
  440. foreach ($monthGroups as $month => $devices) {
  441. $monthData = [];
  442. foreach ($devices as $dev) {
  443. $monthData[] = [
  444. 'device_name' => $dev['device_title'],
  445. 'original_value' => $dev['device_original'], // 设备原值
  446. 'total_depreciation' => $dev['total_depreciatio'], // 当月总折旧
  447. 'project_hours' => $dev['hours'], // 本项目工时
  448. 'total_hours' => $dev['total_hours'], // 当月总工时
  449. 'ratio' => bcmul($dev['ratio'], 100,2), // 研发工时占比
  450. 'allocated_depreciation' => $dev['allocated_depreciatio'], // 本项目分摊折旧
  451. ];
  452. }
  453. $monthsPayload[$month] = $monthData;
  454. }
  455. // 构造 Sheet 所需结构
  456. $finalExportData[$newSheetKey] = [
  457. 'project_name' => $projectName,
  458. 'months' => $monthsPayload
  459. ];
  460. }
  461. $file_name = "项目设备折旧费用统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  462. $filename = $file_name . '.' . 'xlsx';
  463. $bool = Excel::store(new ProjectDepreciationMultipleSheetExport($finalExportData), "/public/export/{$filename}", null, 'Xlsx', []);
  464. return [true, $filename];
  465. }
  466. // 项目工资分摊
  467. public function exportItemSalaryFT(array $data, $user)
  468. {
  469. $service = new StatisticService();
  470. list($status, $result) = $service->itemDaySalaryStatistic($data, $user);
  471. if (!$status) return $result;
  472. $sourceData = collect($result);
  473. $groupedByMonth = $sourceData->groupBy('month');
  474. $monthsData = [];
  475. foreach ($groupedByMonth as $month => $monthRecords) {
  476. // A. 获取本月参与的所有唯一项目编码
  477. $monthProjects = $monthRecords->pluck('item_code')->unique()->sort()->values()->all();
  478. // B. 按人员分组组织数据
  479. $groupedByEmployee = $monthRecords->groupBy('employee_id');
  480. $sheetRows = [];
  481. $index = 1;
  482. // 初始化列合计
  483. $colTotals = [
  484. 'total_salary' => 0,
  485. 'total_min_hours' => 0, // 月总工时合计
  486. 'project_days' => array_fill_keys($monthProjects, 0),
  487. 'project_salary' => array_fill_keys($monthProjects, 0),
  488. 'total_attendance_days' => 0, // 合计工时列的合计
  489. ];
  490. foreach ($groupedByEmployee as $employeeId => $records) {
  491. $first = $records->first();
  492. $empMonthSalary = (float)$first['total_salary'];
  493. $empTotalHours = round((float)$first['total_min'] / 60, 2); // 月总工时(小时)
  494. // 1-4列:序号、姓名、工资、月总工时
  495. $row = [$index++, $first['employee_title'], $empMonthSalary, $empTotalHours];
  496. // 5. 动态项目工时列
  497. $empMap = $records->keyBy('item_code');
  498. $rowProjectDaysSum = 0;
  499. foreach ($monthProjects as $code) {
  500. $days = $empMap->has($code) ? (float)$empMap->get($code)['days'] : 0;
  501. $row[] = $days > 0 ? $days : '';
  502. $rowProjectDaysSum += $days;
  503. $colTotals['project_days'][$code] += $days;
  504. }
  505. // 6. 合计工时列
  506. $row[] = $rowProjectDaysSum;
  507. $colTotals['total_attendance_days'] += $rowProjectDaysSum;
  508. // 7. 动态项目金额列
  509. foreach ($monthProjects as $code) {
  510. $salary = $empMap->has($code) ? (float)$empMap->get($code)['allocated_salary'] : 0;
  511. $row[] = $salary > 0 ? $salary : '';
  512. $colTotals['project_salary'][$code] += $salary;
  513. }
  514. // 8. 总计工资列
  515. $row[] = $empMonthSalary;
  516. // 累加合计
  517. $colTotals['total_salary'] += $empMonthSalary;
  518. $colTotals['total_min_hours'] += $empTotalHours;
  519. $sheetRows[] = $row;
  520. }
  521. // C. 构造合计行
  522. $totalRow = ['合计', '', $colTotals['total_salary'], $colTotals['total_min_hours']];
  523. foreach ($monthProjects as $code) { $totalRow[] = $colTotals['project_days'][$code]; }
  524. $totalRow[] = $colTotals['total_attendance_days'];
  525. foreach ($monthProjects as $code) { $totalRow[] = $colTotals['project_salary'][$code]; }
  526. $totalRow[] = $colTotals['total_salary'];
  527. $sheetRows[] = $totalRow;
  528. $monthsData[$month] = [
  529. 'projects' => $monthProjects,
  530. 'data' => $sheetRows
  531. ];
  532. }
  533. $file_name = "项目工资分摊统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  534. $filename = $file_name . '.xlsx';
  535. Excel::store(
  536. new ItemSalaryFTMultipleSheetExport($monthsData, Depart::where('id', $user['top_depart_id'])->value('title')),
  537. "/public/export/{$filename}"
  538. );
  539. return [true, $filename];
  540. }
  541. // 年度研发支出辅助账汇总表
  542. public function exportResearchExpense(array $data, $user)
  543. {
  544. $service = new StatisticService();
  545. list($status, $result) = $service->auxiliaryStatistic($data, $user);
  546. if (!$status) return [false, $result];
  547. $fee_type_list = $result['fee_type_list'];
  548. $raw_list = $result['list'];
  549. if(empty($raw_list)) return [false, '暂无导出数据'];
  550. // 预读年份和动态表头长度
  551. $year = date("Y", strtotime($raw_list[0]['voucher_date']));
  552. $company = Depart::where('id', $user['top_depart_id'])->value('title');
  553. $dynamicHeaderTitles = array_column($fee_type_list, 'title');
  554. $dynamicCount = count($dynamicHeaderTitles);
  555. $totalColCount = 8 + $dynamicCount + 2; // 基础6 + 固定2 + 动态N + 委托2
  556. $groupedData = [];
  557. foreach ($raw_list as $row) {
  558. $sheetKey = $year . $row['code'];
  559. if (!isset($groupedData[$sheetKey])) {
  560. $groupedData[$sheetKey] = [
  561. 'project' => [
  562. 'code' => $row['code'],
  563. 'name' => $row['title'],
  564. ],
  565. 'dynamic_headers' => $dynamicHeaderTitles,
  566. 'data' => [],
  567. 'year' => $company . $year,
  568. 'totals' => array_fill(0, $totalColCount, 0)
  569. ];
  570. $groupedData[$sheetKey]['totals'][0] = '合计'; // 第一列标识
  571. }
  572. // 组织明细行数据 (逻辑不变)
  573. $excelRow = [
  574. $row['voucher_date'], $row['voucher_type'], $row['voucher_no'], $row['voucher_remark'],
  575. (float)$row['voucher_amount'],
  576. (float)$row['aggregation_amount'],
  577. ($row['type'] == 1 ? (float)$row['total_amount'] : 0), // 人员
  578. ($row['type'] == 2 ? (float)$row['total_amount'] : 0) // 折旧
  579. ];
  580. // 动态列填充
  581. foreach ($fee_type_list as $feeId => $feeItem) {
  582. $excelRow[] = ($row['type'] == 3 && $row['fee_id'] == $feeId) ? (float)$row['total_amount'] : 0;
  583. }
  584. // 委托列
  585. $excelRow[] = (float)($row['entrust1_amount'] ?? 0);
  586. $excelRow[] = (float)($row['entrust2_amount'] ?? 0);
  587. // 【性能优化】:同步累加金额 (从索引 4 开始是金额列)
  588. for ($i = 4; $i < $totalColCount; $i++) {
  589. $groupedData[$sheetKey]['totals'][$i] += $excelRow[$i];
  590. }
  591. $groupedData[$sheetKey]['data'][] = $excelRow;
  592. }
  593. foreach ($groupedData as &$group) {
  594. $group['data'][] = $group['totals'];
  595. unset($group['totals']); // 释放内存
  596. }
  597. // 8. 导出逻辑保持不变
  598. $file_name = "年度研发支出辅助账汇总统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  599. $filename = $file_name . '.xlsx';
  600. Excel::store(
  601. new ResearchExpenseMultipleSheetExport($groupedData),
  602. "public/export/{$filename}"
  603. );
  604. return [true, $filename];
  605. }
  606. // 研发支出辅助帐汇总表
  607. public function exportFormalSummary(array $data, $user)
  608. {
  609. $service = new StatisticService();
  610. // 1. 调用业务逻辑获取原始数据
  611. list($status, $result) = $service->employeeAttendanceMonthStatistic($data, $user);
  612. if (!$status) return [false, $result];
  613. $rawList = $result['list'] ?? [];
  614. $feeTypes = $result['fee_type_list'] ?? [];
  615. // 2. 构造动态表头名称
  616. $dynamicHeaderTitles = array_column($feeTypes, 'title');
  617. $dynamicHeaders = array_merge(['人员人工费用', '折旧费用'], $dynamicHeaderTitles);
  618. $items = [];
  619. foreach ($rawList as $v) {
  620. $rowValues = [];
  621. // A. 填充基础固定两项:人工和折旧
  622. $rowValues[] = (float)($v['employee_salary'] ?? 0);
  623. $rowValues[] = (float)($v['device_depreciation'] ?? 0);
  624. // B. 初始化累加变量
  625. $val7_1 = 0; // 其他相关费用合计 (所有 total_amount 之和)
  626. $val8_1 = 0; // 委托境内合计 (所有 entrust1_amount 之和)
  627. $val8_3 = 0; // 委托境外合计 (所有 entrust2_amount 之和)
  628. // 将当前项目的 fee_list 转为集合以便按 ID 快速查找
  629. $currentProjectFees = collect($v['fee_list'] ?? [])->keyBy('id');
  630. // 遍历所有可能的费用类型,确保 values 数组长度与表头一致
  631. foreach ($feeTypes as $type) {
  632. $feeData = $currentProjectFees->get($type['id']);
  633. $amount = (float)($feeData['total_amount'] ?? 0);
  634. // 填充到动态科目列
  635. $rowValues[] = $amount;
  636. // --- 费用归集逻辑修正 ---
  637. // 1. 累加其他相关费用合计 (7.1)
  638. $val7_1 += $amount;
  639. // 2. 累加委托费用 (8.1 和 8.3)
  640. $val8_1 += (float)($feeData['entrust1_amount'] ?? 0);
  641. $val8_3 += (float)($feeData['entrust2_amount'] ?? 0);
  642. }
  643. $items[] = [
  644. 'no' => $v['code'] ?? '',
  645. 'name' => $v['title'] ?? '',
  646. 'status' => (($v['state'] ?? '') == "完结" ? 3 : 2),
  647. 'type' => $v['expense_type'] ?? '费用化支出',
  648. 'values' => $rowValues,
  649. 'val7_1' => $val7_1, // 修正:此处为 total_amount 累加之和
  650. 'val8_1' => $val8_1, // 修正:此处为 entrust1_amount 累加之和
  651. 'val8_3' => $val8_3, // 修正:此处为 entrust2_amount 累加之和
  652. ];
  653. }
  654. // 年份获取逻辑
  655. $timeSource = $data['month_start'] ?? ($data['month_end'] ?? 'now');
  656. $year = is_numeric($timeSource) ? date('Y', $timeSource) : date('Y', strtotime($timeSource));
  657. // 3. 组织多 Sheet 格式数据
  658. $monthsData = [
  659. $year => [
  660. 'tax_id' => $user->tax_id ?? '***********',
  661. 'company_name' => Depart::where('id', $user['top_depart_id'])->value('title'),
  662. 'items' => $items,
  663. 'dynamic_headers' => $dynamicHeaders
  664. ]
  665. ];
  666. // 4. 执行 Excel 存储
  667. $file_name = "研发支出辅助账汇总表_" . date("YmdHis") . "_" . rand(1000, 9999);
  668. $filename = $file_name . '.xlsx';
  669. Excel::store(
  670. new \App\Exports\ResearchExpenseSummaryMultipleSheetExport($monthsData),
  671. "public/export/{$filename}"
  672. );
  673. return [true, $filename];
  674. }
  675. // 人员活动考勤占比
  676. public function exportActivityTimeCard(array $data, $user)
  677. {
  678. $service = new StatisticService();
  679. // 1. 获取统计数据
  680. list($status, $result) = $service->itemEmployeeSalaryStatistic($data, $user);
  681. if (!$status) return [false, $result];
  682. $rawList = collect($result ?? []);
  683. // 2. 按 项目名称 和 年度 联合分组
  684. $groupedData = $rawList->groupBy(function ($item) {
  685. $year = substr($item['month'] ?? date('Y'), 0, 4);
  686. return $year . "-" . $item['item_title'];
  687. });
  688. $allProjectsData = [];
  689. foreach ($groupedData as $groupKey => $records) {
  690. list($year, $projectTitle) = explode('-', $groupKey);
  691. $projectRows = [];
  692. $groupedByMonth = $records->groupBy('month');
  693. foreach ($groupedByMonth as $monthStr => $monthRecords) {
  694. $monthNum = substr($monthStr, 5, 2);
  695. $monthSubTotal = array_fill(3, 15, 0); // 索引3-17的累加器
  696. foreach ($monthRecords as $v) {
  697. $radioVal = (float)($v['radio'] ?? 0);
  698. $row = [
  699. (int)$monthNum . '月', // 0. 月份
  700. '技术人员', // 1. 类别
  701. $v['employee_title'] ?? '', // 2. 姓名
  702. (float)$v['total_min'], // 3. 应出勤
  703. (float)$v['work_minutes'], // 4. 研发出勤
  704. ($radioVal * 100) . '%', // 5. 占比 (字符串)
  705. (float)$v['salary'], // 6. 归集工资
  706. (float)$v['social_insurance'],// 7. 归集社保
  707. (float)$v['public_housing_fund'], // 8. 归集公积金
  708. (float)$v['work_salary'], // 9. 确定工资
  709. (float)$v['work_social_insurance'], // 10. 确定社保
  710. (float)$v['work_public_housing_fund'], // 11. 确定公积金
  711. (float)$v['work_salary'], // 12. 研发确定总工资
  712. (float)$v['work_social_insurance'], // 13. 研发确定总社保
  713. (float)$v['work_public_housing_fund'], // 14. 研发确定总公积金
  714. 0, 0, 0 // 15, 16, 17. 调整金额
  715. ];
  716. $projectRows[] = $row;
  717. // 累加月份小计 (跳过索引5的百分比字符串)
  718. for ($i = 3; $i <= 14; $i++) {
  719. if ($i == 5) continue;
  720. $monthSubTotal[$i] += (float)$row[$i];
  721. }
  722. }
  723. // 构造月份小计行 (重新计算占比)
  724. $mRadio = $monthSubTotal[3] > 0 ? round($monthSubTotal[4] / $monthSubTotal[3] * 100, 2) . '%' : '0%';
  725. $projectRows[] = [
  726. '小计:', '', '', $monthSubTotal[3], $monthSubTotal[4], $mRadio,
  727. $monthSubTotal[6], $monthSubTotal[7], $monthSubTotal[8],
  728. $monthSubTotal[9], $monthSubTotal[10], $monthSubTotal[11],
  729. $monthSubTotal[12], $monthSubTotal[13], $monthSubTotal[14],
  730. 0, 0, 0
  731. ];
  732. }
  733. // 计算整年合计 (避开小计行,避开非数字)
  734. $yearTotal = array_fill(3, 15, 0);
  735. foreach ($projectRows as $row) {
  736. if ($row[0] !== '小计:' && $row[0] !== '合计') {
  737. for ($i = 3; $i <= 14; $i++) {
  738. if ($i == 5) continue;
  739. $yearTotal[$i] += (float)$row[$i];
  740. }
  741. }
  742. }
  743. $yRadio = $yearTotal[3] > 0 ? round($yearTotal[4] / $yearTotal[3] * 100, 2) . '%' : '0%';
  744. $projectRows[] = [
  745. '合计', '', '', $yearTotal[3], $yearTotal[4], $yRadio,
  746. $yearTotal[6], $yearTotal[7], $yearTotal[8],
  747. $yearTotal[9], $yearTotal[10], $yearTotal[11],
  748. $yearTotal[12], $yearTotal[13], $yearTotal[14],
  749. 0, 0, 0
  750. ];
  751. $allProjectsData[$groupKey] = [
  752. 'project' => $projectTitle,
  753. 'year' => $year,
  754. 'data' => $projectRows
  755. ];
  756. }
  757. $filename = "人员活动考勤占比统计表_" . date("YmdHis") . '.xlsx';
  758. \Maatwebsite\Excel\Facades\Excel::store(
  759. new \App\Exports\ManActivityTimeCardMultipleSheetExport($allProjectsData),
  760. "public/export/{$filename}"
  761. );
  762. return [true, $filename];
  763. }
  764. public function saveExportData($data, $headers, $type = 'default',$file_name = ''){
  765. if(empty($file_name)) $file_name = self::$filename . "_". date("Y-m-d") . "_". rand(1000,9999);
  766. $filename = $file_name . '.' . 'xlsx';
  767. $bool = Excel::store(new ExportOrder($data,$type,$headers),"/public/export/{$filename}", null, 'Xlsx', []);
  768. return $filename;
  769. }
  770. public function saveExportData2($data,$type = 1,$column,$timeRow, $file_name = ''){
  771. if(empty($file_name)) $file_name = self::$filename . "_". date("Y-m-d") . "_". rand(1000,9999);
  772. $filename = $file_name . '.' . 'xlsx';
  773. \Maatwebsite\Excel\Facades\Excel::store(new MultiSheetExport($data, $type,$column,$timeRow),"/public/export/{$filename}", null, 'Xlsx', []);
  774. return $filename;
  775. }
  776. }