ExportFileService.php 44 KB

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