ExportFileService.php 43 KB

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