ExportFileService.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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. // 项目工资统计表
  289. public function exportEmployeeSalary($data, $user)
  290. {
  291. $service = new StatisticService();
  292. // 1. 调用你现有的查询方法获取基础数据
  293. list($status, $itemMonthList) = $service->employeeMonthSalaryStatistic($data, $user);
  294. if (!$status) return $itemMonthList; // 返回错误信息
  295. // 2. 提取所有涉及到的唯一项目 (按 Code 排序,保证列顺序固定)
  296. $projects = collect($itemMonthList)->pluck('item_code')->unique()->sort()->values()->toArray();
  297. // 3. 按月份对数据进行分组
  298. $groupedByMonth = collect($itemMonthList)->groupBy('month')->sortKeys();
  299. $exportData = [];
  300. $columnTotals = array_fill(0, count($projects) * 2, 0); // 用于存储每列的合计
  301. $grandTotalSalary = 0; // 总计金额
  302. // 4. 循环每个月,构造行数据
  303. foreach ($groupedByMonth as $month => $items) {
  304. $row = [$month]; // A列:月份
  305. $monthTotalSalary = 0;
  306. // 创建该月项目的映射,方便快速查找
  307. $monthItemsMap = $items->keyBy('item_code');
  308. foreach ($projects as $index => $code) {
  309. $itemDetail = $monthItemsMap->get($code);
  310. $days = $itemDetail['days'] ?? 0;
  311. $salary = $itemDetail['allocated_salary'] ?? 0;
  312. $row[] = $days > 0 ? $days : ''; // 天数列
  313. $row[] = $salary > 0 ? $salary : ''; // 工资列
  314. // 累加合计行(列合计)
  315. $columnTotals[$index * 2] += $days;
  316. $columnTotals[$index * 2 + 1] += $salary;
  317. $monthTotalSalary += $salary;
  318. }
  319. $row[] = $monthTotalSalary; // 最后一列:该月合计工资
  320. $grandTotalSalary += $monthTotalSalary;
  321. $exportData[] = $row;
  322. }
  323. // 5. 构造最后的“合计”行
  324. $totalRow = ['合计'];
  325. foreach ($columnTotals as $val) {
  326. $totalRow[] = $val > 0 ? $val : 0;
  327. }
  328. $totalRow[] = $grandTotalSalary;
  329. $exportData[] = $totalRow;
  330. $file_name = "项目工资统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  331. $filename = $file_name . '.' . 'xlsx';
  332. $bool = Excel::store(new ItemSalarySheetExport($projects, $exportData, Depart::where('id', $user['top_depart_id'])->value('title')),"/public/export/{$filename}", null, 'Xlsx', []);
  333. return [true, $filename];
  334. }
  335. // 人员月工时统计表
  336. public function exportManMonthlyWorkHour($data, $user)
  337. {
  338. // 1. 获取报表基础数据
  339. $service = new StatisticService();
  340. list($status, $result) = $service->employeeDayHourStatistic($data, $user);
  341. if (!$status) return $result;
  342. $sourceData = collect($result['data']);
  343. // 2. 按月份分组,准备多 Sheet 数据
  344. // 结构:[ '2024-04' => [ 'days' => 30, 'data' => [...] ], ... ]
  345. $monthsData = [];
  346. // 按月分组数据
  347. $groupedByMonth = $sourceData->groupBy(function ($item) {
  348. return date('Y年m月', strtotime($item['order_date']));
  349. });
  350. foreach ($groupedByMonth as $monthName => $monthItems) {
  351. // A. 计算该月总天数
  352. // 转换 '2024年04月' 为 '2024-04' 获取天数
  353. $formatMonth = str_replace(['年', '月'], ['-', ''], $monthName);
  354. $daysInMonth = date('t', strtotime($formatMonth . '-01'));
  355. // B. 进一步按 项目+人员 分组,因为一行显示一个项目一个人的全月工时
  356. $groupedByUserItem = $monthItems->groupBy(function ($item) {
  357. return $item['item_code'] . '_' . $item['employee_id'];
  358. });
  359. $sheetRows = [];
  360. foreach ($groupedByUserItem as $key => $records) {
  361. $first = $records->first();
  362. // 初始化行:前两列是 项目编号 和 姓名
  363. $row = [
  364. $first['item_code'],
  365. $first['employee_name']
  366. ];
  367. // C. 循环 1 号到该月最后一天,填充工时
  368. // 将该员工该项目在这个月的记录转为 日期 => 工时 的映射
  369. $dayMap = $records->keyBy(function($r){
  370. return (int)date('d', strtotime($r['order_date']));
  371. });
  372. for ($d = 1; $d <= $daysInMonth; $d++) {
  373. $workHour = $dayMap->get($d)['total_work_hours'] ?? '';
  374. // 如果工时为 0 或空,按你要求的格式传空字符串
  375. $row[] = ($workHour > 0) ?(float) $workHour : '';
  376. }
  377. $sheetRows[] = $row;
  378. }
  379. $monthsData[$monthName] = [
  380. 'days' => (int)$daysInMonth,
  381. 'data' => $sheetRows
  382. ];
  383. }
  384. $file_name = "人员月工时统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  385. $filename = $file_name . '.' . 'xlsx';
  386. $bool = Excel::store(new ManMonthlyWorkHourMultipleSheetExport($monthsData), "/public/export/{$filename}", null, 'Xlsx', []);
  387. return [true, $filename];
  388. }
  389. // 项目设备折旧
  390. public function exportDeviceZj(array $data, $user)
  391. {
  392. $service = new StatisticService();
  393. list($status, $result) = $service->itemDeviceMonthStatistic($data, $user);
  394. if (!$status) return $result;
  395. // 2. 将数据按 [项目编号][月份] 进行分组
  396. // 预期结构:$monthsData['RD01']['months']['2025-01'] = [设备1, 设备2...]
  397. $groupedData = collect($result)->groupBy('item_code');
  398. $finalExportData = [];
  399. foreach ($groupedData as $itemCode => $itemRecords) {
  400. $projectName = $itemRecords->first()['item_title'] ?? '';
  401. // 2. 获取年份(从 order_month 字段提取,如 "2026-01" 取前4位)
  402. $firstMonth = $firstRecord['month'] ?? date('Y-m');
  403. $year = substr($firstMonth, 0, 4);
  404. // 3. 构造新的 Key:年-项目 (例如: 2026-53code)
  405. $newSheetKey = $year . '年度项目' . $itemCode;
  406. // 按月份进一步分组
  407. $monthGroups = $itemRecords->groupBy('month');
  408. $monthsPayload = [];
  409. foreach ($monthGroups as $month => $devices) {
  410. $monthData = [];
  411. foreach ($devices as $dev) {
  412. $monthData[] = [
  413. 'device_name' => $dev['device_title'],
  414. 'original_value' => $dev['device_original'], // 设备原值
  415. 'total_depreciation' => $dev['total_depreciatio'], // 当月总折旧
  416. 'project_hours' => $dev['hours'], // 本项目工时
  417. 'total_hours' => $dev['total_hours'], // 当月总工时
  418. 'ratio' => bcmul($dev['ratio'], 100,2), // 研发工时占比
  419. 'allocated_depreciation' => $dev['allocated_depreciatio'], // 本项目分摊折旧
  420. ];
  421. }
  422. $monthsPayload[$month] = $monthData;
  423. }
  424. // 构造 Sheet 所需结构
  425. $finalExportData[$newSheetKey] = [
  426. 'project_name' => $projectName,
  427. 'months' => $monthsPayload
  428. ];
  429. }
  430. $file_name = "项目设备折旧费用统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  431. $filename = $file_name . '.' . 'xlsx';
  432. $bool = Excel::store(new ProjectDepreciationMultipleSheetExport($finalExportData), "/public/export/{$filename}", null, 'Xlsx', []);
  433. return [true, $filename];
  434. }
  435. // 项目工资分摊
  436. public function exportItemSalaryFT(array $data, $user)
  437. {
  438. $service = new StatisticService();
  439. list($status, $result) = $service->itemDaySalaryStatistic($data, $user);
  440. if (!$status) return $result;
  441. $sourceData = collect($result);
  442. $groupedByMonth = $sourceData->groupBy('month');
  443. $monthsData = [];
  444. foreach ($groupedByMonth as $month => $monthRecords) {
  445. // A. 获取本月参与的所有唯一项目编码
  446. $monthProjects = $monthRecords->pluck('item_code')->unique()->sort()->values()->all();
  447. // B. 按人员分组组织数据
  448. $groupedByEmployee = $monthRecords->groupBy('employee_id');
  449. $sheetRows = [];
  450. $index = 1;
  451. // 初始化列合计
  452. $colTotals = [
  453. 'total_salary' => 0,
  454. 'total_min_hours' => 0, // 月总工时合计
  455. 'project_days' => array_fill_keys($monthProjects, 0),
  456. 'project_salary' => array_fill_keys($monthProjects, 0),
  457. 'total_attendance_days' => 0, // 合计工时列的合计
  458. ];
  459. foreach ($groupedByEmployee as $employeeId => $records) {
  460. $first = $records->first();
  461. $empMonthSalary = (float)$first['total_salary'];
  462. $empTotalHours = round((float)$first['total_min'] / 60, 2); // 月总工时(小时)
  463. // 1-4列:序号、姓名、工资、月总工时
  464. $row = [$index++, $first['employee_title'], $empMonthSalary, $empTotalHours];
  465. // 5. 动态项目工时列
  466. $empMap = $records->keyBy('item_code');
  467. $rowProjectDaysSum = 0;
  468. foreach ($monthProjects as $code) {
  469. $days = $empMap->has($code) ? (float)$empMap->get($code)['days'] : 0;
  470. $row[] = $days > 0 ? $days : '';
  471. $rowProjectDaysSum += $days;
  472. $colTotals['project_days'][$code] += $days;
  473. }
  474. // 6. 合计工时列
  475. $row[] = $rowProjectDaysSum;
  476. $colTotals['total_attendance_days'] += $rowProjectDaysSum;
  477. // 7. 动态项目金额列
  478. foreach ($monthProjects as $code) {
  479. $salary = $empMap->has($code) ? (float)$empMap->get($code)['allocated_salary'] : 0;
  480. $row[] = $salary > 0 ? $salary : '';
  481. $colTotals['project_salary'][$code] += $salary;
  482. }
  483. // 8. 总计工资列
  484. $row[] = $empMonthSalary;
  485. // 累加合计
  486. $colTotals['total_salary'] += $empMonthSalary;
  487. $colTotals['total_min_hours'] += $empTotalHours;
  488. $sheetRows[] = $row;
  489. }
  490. // C. 构造合计行
  491. $totalRow = ['合计', '', $colTotals['total_salary'], $colTotals['total_min_hours']];
  492. foreach ($monthProjects as $code) { $totalRow[] = $colTotals['project_days'][$code]; }
  493. $totalRow[] = $colTotals['total_attendance_days'];
  494. foreach ($monthProjects as $code) { $totalRow[] = $colTotals['project_salary'][$code]; }
  495. $totalRow[] = $colTotals['total_salary'];
  496. $sheetRows[] = $totalRow;
  497. $monthsData[$month] = [
  498. 'projects' => $monthProjects,
  499. 'data' => $sheetRows
  500. ];
  501. }
  502. $file_name = "项目工资分摊统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  503. $filename = $file_name . '.xlsx';
  504. Excel::store(
  505. new ItemSalaryFTMultipleSheetExport($monthsData, Depart::where('id', $user['top_depart_id'])->value('title')),
  506. "/public/export/{$filename}"
  507. );
  508. return [true, $filename];
  509. }
  510. // 年度研发支出辅助账汇总表
  511. public function exportResearchExpense(array $data, $user)
  512. {
  513. $service = new StatisticService();
  514. list($status, $result) = $service->auxiliaryStatistic($data, $user);
  515. if (!$status) return [false, $result];
  516. $fee_type_list = $result['fee_type_list'];
  517. $raw_list = $result['list'];
  518. if(empty($raw_list)) return [false, '暂无导出数据'];
  519. // 预读年份和动态表头长度
  520. $year = date("Y", strtotime($raw_list[0]['voucher_date']));
  521. $company = Depart::where('id', $user['top_depart_id'])->value('title');
  522. $dynamicHeaderTitles = array_column($fee_type_list, 'title');
  523. $dynamicCount = count($dynamicHeaderTitles);
  524. $totalColCount = 8 + $dynamicCount + 2; // 基础6 + 固定2 + 动态N + 委托2
  525. $groupedData = [];
  526. foreach ($raw_list as $row) {
  527. $sheetKey = $year . $row['code'];
  528. if (!isset($groupedData[$sheetKey])) {
  529. $groupedData[$sheetKey] = [
  530. 'project' => [
  531. 'code' => $row['code'],
  532. 'name' => $row['title'],
  533. ],
  534. 'dynamic_headers' => $dynamicHeaderTitles,
  535. 'data' => [],
  536. 'year' => $company . $year,
  537. 'totals' => array_fill(0, $totalColCount, 0)
  538. ];
  539. $groupedData[$sheetKey]['totals'][0] = '合计'; // 第一列标识
  540. }
  541. // 组织明细行数据 (逻辑不变)
  542. $excelRow = [
  543. $row['voucher_date'], $row['voucher_type'], $row['voucher_no'], $row['voucher_remark'],
  544. (float)$row['voucher_amount'],
  545. (float)$row['aggregation_amount'],
  546. ($row['type'] == 1 ? (float)$row['total_amount'] : 0), // 人员
  547. ($row['type'] == 2 ? (float)$row['total_amount'] : 0) // 折旧
  548. ];
  549. // 动态列填充
  550. foreach ($fee_type_list as $feeId => $feeItem) {
  551. $excelRow[] = ($row['type'] == 3 && $row['fee_id'] == $feeId) ? (float)$row['total_amount'] : 0;
  552. }
  553. // 委托列
  554. $excelRow[] = (float)($row['entrust1_amount'] ?? 0);
  555. $excelRow[] = (float)($row['entrust2_amount'] ?? 0);
  556. // 【性能优化】:同步累加金额 (从索引 4 开始是金额列)
  557. for ($i = 4; $i < $totalColCount; $i++) {
  558. $groupedData[$sheetKey]['totals'][$i] += $excelRow[$i];
  559. }
  560. $groupedData[$sheetKey]['data'][] = $excelRow;
  561. }
  562. foreach ($groupedData as &$group) {
  563. $group['data'][] = $group['totals'];
  564. unset($group['totals']); // 释放内存
  565. }
  566. // 8. 导出逻辑保持不变
  567. $file_name = "年度研发支出辅助账汇总统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  568. $filename = $file_name . '.xlsx';
  569. Excel::store(
  570. new ResearchExpenseMultipleSheetExport($groupedData),
  571. "public/export/{$filename}"
  572. );
  573. return [true, $filename];
  574. }
  575. // 研发支出辅助帐汇总表
  576. public function exportFormalSummary(array $data, $user)
  577. {
  578. $service = new StatisticService();
  579. // 1. 调用业务逻辑获取原始数据
  580. list($status, $result) = $service->employeeAttendanceMonthStatistic($data, $user);
  581. if (!$status) return [false, $result];
  582. $rawList = $result['list'] ?? [];
  583. $feeTypes = $result['fee_type_list'] ?? [];
  584. // 2. 构造动态表头名称
  585. $dynamicHeaderTitles = array_column($feeTypes, 'title');
  586. $dynamicHeaders = array_merge(['人员人工费用', '折旧费用'], $dynamicHeaderTitles);
  587. $items = [];
  588. foreach ($rawList as $v) {
  589. $rowValues = [];
  590. // A. 填充基础固定两项:人工和折旧
  591. $rowValues[] = (float)($v['employee_salary'] ?? 0);
  592. $rowValues[] = (float)($v['device_depreciation'] ?? 0);
  593. // B. 初始化累加变量
  594. $val7_1 = 0; // 其他相关费用合计 (所有 total_amount 之和)
  595. $val8_1 = 0; // 委托境内合计 (所有 entrust1_amount 之和)
  596. $val8_3 = 0; // 委托境外合计 (所有 entrust2_amount 之和)
  597. // 将当前项目的 fee_list 转为集合以便按 ID 快速查找
  598. $currentProjectFees = collect($v['fee_list'] ?? [])->keyBy('id');
  599. // 遍历所有可能的费用类型,确保 values 数组长度与表头一致
  600. foreach ($feeTypes as $type) {
  601. $feeData = $currentProjectFees->get($type['id']);
  602. $amount = (float)($feeData['total_amount'] ?? 0);
  603. // 填充到动态科目列
  604. $rowValues[] = $amount;
  605. // --- 费用归集逻辑修正 ---
  606. // 1. 累加其他相关费用合计 (7.1)
  607. $val7_1 += $amount;
  608. // 2. 累加委托费用 (8.1 和 8.3)
  609. $val8_1 += (float)($feeData['entrust1_amount'] ?? 0);
  610. $val8_3 += (float)($feeData['entrust2_amount'] ?? 0);
  611. }
  612. $items[] = [
  613. 'no' => $v['code'] ?? '',
  614. 'name' => $v['title'] ?? '',
  615. 'status' => (($v['state'] ?? '') == "完结" ? 3 : 2),
  616. 'type' => $v['expense_type'] ?? '费用化支出',
  617. 'values' => $rowValues,
  618. 'val7_1' => $val7_1, // 修正:此处为 total_amount 累加之和
  619. 'val8_1' => $val8_1, // 修正:此处为 entrust1_amount 累加之和
  620. 'val8_3' => $val8_3, // 修正:此处为 entrust2_amount 累加之和
  621. ];
  622. }
  623. // 年份获取逻辑
  624. $timeSource = $data['month_start'] ?? ($data['month_end'] ?? 'now');
  625. $year = is_numeric($timeSource) ? date('Y', $timeSource) : date('Y', strtotime($timeSource));
  626. // 3. 组织多 Sheet 格式数据
  627. $monthsData = [
  628. $year => [
  629. 'tax_id' => $user->tax_id ?? '***********',
  630. 'company_name' => Depart::where('id', $user['top_depart_id'])->value('title'),
  631. 'items' => $items,
  632. 'dynamic_headers' => $dynamicHeaders
  633. ]
  634. ];
  635. // 4. 执行 Excel 存储
  636. $file_name = "研发支出辅助账汇总表_" . date("YmdHis") . "_" . rand(1000, 9999);
  637. $filename = $file_name . '.xlsx';
  638. Excel::store(
  639. new \App\Exports\ResearchExpenseSummaryMultipleSheetExport($monthsData),
  640. "public/export/{$filename}"
  641. );
  642. return [true, $filename];
  643. }
  644. public function saveExportData($data, $headers, $type = 'default',$file_name = ''){
  645. if(empty($file_name)) $file_name = self::$filename . "_". date("Y-m-d") . "_". rand(1000,9999);
  646. $filename = $file_name . '.' . 'xlsx';
  647. $bool = Excel::store(new ExportOrder($data,$type,$headers),"/public/export/{$filename}", null, 'Xlsx', []);
  648. return $filename;
  649. }
  650. public function saveExportData2($data,$type = 1,$column,$timeRow, $file_name = ''){
  651. if(empty($file_name)) $file_name = self::$filename . "_". date("Y-m-d") . "_". rand(1000,9999);
  652. $filename = $file_name . '.' . 'xlsx';
  653. \Maatwebsite\Excel\Facades\Excel::store(new MultiSheetExport($data, $type,$column,$timeRow),"/public/export/{$filename}", null, 'Xlsx', []);
  654. return $filename;
  655. }
  656. }