ExportFileService.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  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. //获取公司基本信息
  408. $company = EmployeeService::getCompanyDetail($user);
  409. foreach ($groupedByMonth as $monthName => $monthItems) {
  410. // A. 计算该月总天数
  411. // 转换 '2024年04月' 为 '2024-04' 获取天数
  412. $formatMonth = str_replace(['年', '月'], ['-', ''], $monthName);
  413. $daysInMonth = date('t', strtotime($formatMonth . '-01'));
  414. // B. 进一步按 项目+人员 分组,因为一行显示一个项目一个人的全月工时
  415. $groupedByUserItem = $monthItems->groupBy(function ($item) {
  416. return $item['item_code'] . '_' . $item['employee_id'];
  417. });
  418. $sheetRows = [];
  419. foreach ($groupedByUserItem as $key => $records) {
  420. $first = $records->first();
  421. // 初始化行:前两列是 项目名称 和 姓名
  422. $row = [
  423. $first['item_title'],
  424. $first['employee_name']
  425. ];
  426. // C. 循环 1 号到该月最后一天,填充工时
  427. // 将该员工该项目在这个月的记录转为 日期 => 工时 的映射
  428. $dayMap = $records->keyBy(function($r){
  429. return (int)date('d', strtotime($r['order_date']));
  430. });
  431. for ($d = 1; $d <= $daysInMonth; $d++) {
  432. $workHour = $dayMap->get($d)['total_work_hours'] ?? '';
  433. // 如果工时为 0 或空,按你要求的格式传空字符串
  434. $row[] = ($workHour > 0) ?(float) $workHour : '';
  435. }
  436. $sheetRows[] = $row;
  437. }
  438. $monthsData[$monthName] = [
  439. 'days' => (int)$daysInMonth,
  440. 'data' => $sheetRows,
  441. 'company_name' => $company['title'] ?? '',
  442. ];
  443. }
  444. $file_name = "人员月工时统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  445. $filename = $file_name . '.' . 'xlsx';
  446. $bool = Excel::store(new ManMonthlyWorkHourMultipleSheetExport($monthsData), "/public/export/{$filename}", null, 'Xlsx', []);
  447. return [true, $filename];
  448. }
  449. // 项目设备折旧
  450. public function exportDeviceZj(array $data, $user)
  451. {
  452. $service = new StatisticService();
  453. list($status, $result) = $service->itemDeviceMonthStatistic($data, $user);
  454. if (!$status) return $result;
  455. // 2. 将数据按 [项目编号][月份] 进行分组
  456. // 预期结构:$monthsData['RD01']['months']['2025-01'] = [设备1, 设备2...]
  457. $groupedData = collect($result)->groupBy('item_code');
  458. $finalExportData = [];
  459. foreach ($groupedData as $itemCode => $itemRecords) {
  460. $firstRecord = $itemRecords->first();
  461. $projectName = $firstRecord['item_title'];
  462. $firstMonth = $firstRecord['month'];
  463. $year = substr($firstMonth, 0, 4);
  464. // 3. 构造新的 Key:年-项目 (例如: 2026-53code)
  465. $newSheetKey = $year . '年度项目' . $itemCode;
  466. // 按月份进一步分组
  467. $monthGroups = $itemRecords->groupBy('month');
  468. $monthsPayload = [];
  469. foreach ($monthGroups as $month => $devices) {
  470. $monthData = [];
  471. foreach ($devices as $dev) {
  472. $monthData[] = [
  473. 'device_name' => $dev['device_title'],
  474. 'original_value' => $dev['device_original'], // 设备原值
  475. 'total_depreciation' => $dev['total_depreciatio'], // 当月总折旧
  476. 'project_hours' => $dev['hours'], // 本项目工时
  477. 'total_hours' => $dev['total_hours'], // 当月总工时
  478. 'ratio' => bcmul($dev['ratio'], 100,2), // 研发工时占比
  479. 'allocated_depreciation' => $dev['allocated_depreciatio'], // 本项目分摊折旧
  480. ];
  481. }
  482. $monthsPayload[$month] = $monthData;
  483. }
  484. // 构造 Sheet 所需结构
  485. $finalExportData[$newSheetKey] = [
  486. 'project_name' => $projectName,
  487. 'months' => $monthsPayload
  488. ];
  489. }
  490. $file_name = "项目设备折旧费用统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  491. $filename = $file_name . '.' . 'xlsx';
  492. $bool = Excel::store(new ProjectDepreciationMultipleSheetExport($finalExportData), "/public/export/{$filename}", null, 'Xlsx', []);
  493. return [true, $filename];
  494. }
  495. // 项目工资分摊
  496. public function exportItemSalaryFT(array $data, $user)
  497. {
  498. $service = new StatisticService();
  499. list($status, $result) = $service->itemDaySalaryStatistic($data, $user);
  500. if (!$status) return $result;
  501. $sourceData = collect($result);
  502. $groupedByMonth = $sourceData->groupBy('month');
  503. $monthsData = [];
  504. foreach ($groupedByMonth as $month => $monthRecords) {
  505. // A. 获取本月参与的所有唯一项目编码
  506. $monthProjects = $monthRecords->pluck('item_code')->unique()->sort()->values()->all();
  507. // B. 按人员分组组织数据
  508. $groupedByEmployee = $monthRecords->groupBy('employee_id');
  509. $sheetRows = [];
  510. $index = 1;
  511. // 初始化列合计
  512. $colTotals = [
  513. 'total_salary' => 0,
  514. 'total_min_hours' => 0, // 月总工时合计
  515. 'project_days' => array_fill_keys($monthProjects, 0),
  516. 'project_salary' => array_fill_keys($monthProjects, 0),
  517. 'total_attendance_days' => 0, // 合计工时列的合计
  518. ];
  519. foreach ($groupedByEmployee as $employeeId => $records) {
  520. $first = $records->first();
  521. $empMonthSalary = (float)$first['total_salary'];
  522. $empTotalHours = $first['total_hours'];
  523. // 1-4列:序号、姓名、工资、月总工时
  524. $row = [$index++, $first['employee_title'], $empMonthSalary, $empTotalHours];
  525. // 5. 动态项目工时列
  526. $empMap = $records->keyBy('item_code');
  527. $rowProjectDaysSum = 0;
  528. foreach ($monthProjects as $code) {
  529. if ($empMap->has($code)) {
  530. $record = $empMap->get($code);
  531. $days = (float)($record['work_hours'] ?? 0);
  532. } else {
  533. $days = 0;
  534. }
  535. $row[] = $days > 0 ? $days : '';
  536. $rowProjectDaysSum += $days;
  537. $colTotals['project_days'][$code] += $days;
  538. }
  539. // 6. 合计工时列
  540. $row[] = $rowProjectDaysSum;
  541. $colTotals['total_attendance_days'] += $rowProjectDaysSum;
  542. // 7. 动态项目金额列
  543. foreach ($monthProjects as $code) {
  544. $salary = $empMap->has($code) ? (float)$empMap->get($code)['allocated_salary'] : 0;
  545. $row[] = $salary > 0 ? $salary : '';
  546. $colTotals['project_salary'][$code] += $salary;
  547. }
  548. // 8. 总计工资列
  549. $row[] = $empMonthSalary;
  550. // 累加合计
  551. $colTotals['total_salary'] += $empMonthSalary;
  552. $colTotals['total_min_hours'] += $empTotalHours;
  553. $sheetRows[] = $row;
  554. }
  555. // C. 构造合计行
  556. $totalRow = ['合计', '', $colTotals['total_salary'], $colTotals['total_min_hours']];
  557. foreach ($monthProjects as $code) { $totalRow[] = $colTotals['project_days'][$code]; }
  558. $totalRow[] = $colTotals['total_attendance_days'];
  559. foreach ($monthProjects as $code) { $totalRow[] = $colTotals['project_salary'][$code]; }
  560. $totalRow[] = $colTotals['total_salary'];
  561. $sheetRows[] = $totalRow;
  562. $monthsData[$month] = [
  563. 'projects' => $monthProjects,
  564. 'data' => $sheetRows
  565. ];
  566. }
  567. //获取公司基本信息
  568. $company = EmployeeService::getCompanyDetail($user);
  569. $file_name = "项目工资分摊统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  570. $filename = $file_name . '.xlsx';
  571. Excel::store(
  572. new ItemSalaryFTMultipleSheetExport($monthsData, $company['title'] ?? ''),
  573. "/public/export/{$filename}"
  574. );
  575. return [true, $filename];
  576. }
  577. // 年度研发支出辅助账汇总表
  578. public function exportResearchExpense(array $data, $user)
  579. {
  580. $service = new StatisticService();
  581. list($status, $result) = $service->auxiliaryStatistic($data, $user);
  582. if (!$status) return [false, $result];
  583. $fee_type_list = $result['fee_type_list'];
  584. $raw_list = $result['list'];
  585. if(empty($raw_list)) return [false, '暂无导出数据'];
  586. // 预读年份和动态表头长度
  587. $year = date("Y", strtotime($raw_list[0]['voucher_date']));
  588. $company = Depart::where('id', $user['top_depart_id'])->value('title');
  589. $dynamicHeaderTitles = array_column($fee_type_list, 'title');
  590. $dynamicCount = count($dynamicHeaderTitles);
  591. $totalColCount = 8 + $dynamicCount + 2; // 基础6 + 固定2 + 动态N + 委托2
  592. $groupedData = [];
  593. foreach ($raw_list as $row) {
  594. $sheetKey = $year . $row['code'];
  595. if (!isset($groupedData[$sheetKey])) {
  596. $groupedData[$sheetKey] = [
  597. 'project' => [
  598. 'code' => $row['code'],
  599. 'name' => $row['title'],
  600. ],
  601. 'dynamic_headers' => $dynamicHeaderTitles,
  602. 'data' => [],
  603. 'year' => $company . $year,
  604. 'totals' => array_fill(0, $totalColCount, 0)
  605. ];
  606. $groupedData[$sheetKey]['totals'][0] = '合计'; // 第一列标识
  607. }
  608. // 组织明细行数据 (逻辑不变)
  609. $excelRow = [
  610. $row['voucher_date'], $row['voucher_type'], $row['voucher_no'], $row['voucher_remark'],
  611. (float)$row['voucher_amount'],
  612. (float)$row['aggregation_amount'],
  613. ($row['type'] == 1 ? (float)$row['total_amount'] : 0), // 人员
  614. ($row['type'] == 2 ? (float)$row['total_amount'] : 0) // 折旧
  615. ];
  616. // 动态列填充
  617. foreach ($fee_type_list as $feeId => $feeItem) {
  618. $excelRow[] = ($row['type'] == 3 && $row['fee_id'] == $feeId) ? (float)$row['total_amount'] : 0;
  619. }
  620. // 委托列
  621. $excelRow[] = (float)($row['entrust1_amount'] ?? 0);
  622. $excelRow[] = (float)($row['entrust2_amount'] ?? 0);
  623. // 【性能优化】:同步累加金额 (从索引 4 开始是金额列)
  624. for ($i = 4; $i < $totalColCount; $i++) {
  625. $groupedData[$sheetKey]['totals'][$i] += $excelRow[$i];
  626. }
  627. $groupedData[$sheetKey]['data'][] = $excelRow;
  628. }
  629. foreach ($groupedData as &$group) {
  630. $group['data'][] = $group['totals'];
  631. unset($group['totals']); // 释放内存
  632. }
  633. // 8. 导出逻辑保持不变
  634. $file_name = "年度研发支出辅助账汇总统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  635. $filename = $file_name . '.xlsx';
  636. Excel::store(
  637. new ResearchExpenseMultipleSheetExport($groupedData),
  638. "public/export/{$filename}"
  639. );
  640. return [true, $filename];
  641. }
  642. // 研发支出辅助帐汇总表
  643. public function exportFormalSummary(array $data, $user)
  644. {
  645. $service = new StatisticService();
  646. // 1. 调用业务逻辑获取原始数据
  647. list($status, $result) = $service->employeeAttendanceMonthStatistic($data, $user);
  648. if (!$status) return [false, $result];
  649. $rawList = $result['list'] ?? [];
  650. $feeTypes = $result['fee_type_list'] ?? [];
  651. // 2. 构造动态表头名称
  652. $dynamicHeaderTitles = array_column($feeTypes, 'title');
  653. $dynamicHeaders = array_merge(['人员人工费用', '折旧费用'], $dynamicHeaderTitles);
  654. $items = [];
  655. foreach ($rawList as $v) {
  656. $rowValues = [];
  657. // A. 填充基础固定两项:人工和折旧
  658. $rowValues[] = (float)($v['employee_salary'] ?? 0);
  659. $rowValues[] = (float)($v['device_depreciation'] ?? 0);
  660. // B. 初始化累加变量
  661. $val7_1 = 0; // 其他相关费用合计 (所有 total_amount 之和)
  662. $val8_1 = 0; // 委托境内合计 (所有 entrust1_amount 之和)
  663. $val8_3 = 0; // 委托境外合计 (所有 entrust2_amount 之和)
  664. // 将当前项目的 fee_list 转为集合以便按 ID 快速查找
  665. $currentProjectFees = collect($v['fee_list'] ?? [])->keyBy('id');
  666. // 遍历所有可能的费用类型,确保 values 数组长度与表头一致
  667. foreach ($feeTypes as $type) {
  668. $feeData = $currentProjectFees->get($type['id']);
  669. $amount = (float)($feeData['total_amount'] ?? 0);
  670. // 填充到动态科目列
  671. $rowValues[] = $amount;
  672. // 1. 累加其他相关费用合计 (7.1)
  673. if(! empty($feeData['is_other']) && $feeData['is_other'] == Fee::IS_OTHER_ONE) $val7_1 += $amount;
  674. // 2. 累加委托费用 (8.1 和 8.3)
  675. $val8_1 += (float)($feeData['entrust1_amount'] ?? 0);
  676. $val8_3 += (float)($feeData['entrust2_amount'] ?? 0);
  677. }
  678. $items[] = [
  679. 'no' => $v['code'] ?? '',
  680. 'name' => $v['title'] ?? '',
  681. 'status' => (($v['state'] ?? '') == "完结" ? 3 : 2),
  682. 'type' => $v['expense_type'] ?? '费用化支出',
  683. 'values' => $rowValues,
  684. 'val7_1' => $val7_1,
  685. 'val8_1' => $val8_1,
  686. 'val8_3' => $val8_3,
  687. ];
  688. }
  689. // 年份获取逻辑
  690. $year = Carbon::parse($data['year'])
  691. ->setTimezone(config('app.timezone')) // 转换为 Laravel 配置的时区
  692. ->format('Y');
  693. //获取公司基本信息
  694. $company = EmployeeService::getCompanyDetail($user);
  695. // 3. 组织多 Sheet 格式数据
  696. $monthsData = [
  697. $year => [
  698. 'tax_id' => $company['code'] ?? '',
  699. 'company_name' => $company['title'] ?? '',
  700. 'items' => $items,
  701. 'dynamic_headers' => $dynamicHeaders
  702. ]
  703. ];
  704. // 4. 执行 Excel 存储
  705. $file_name = "研发支出辅助账汇总表_" . date("YmdHis") . "_" . rand(1000, 9999);
  706. $filename = $file_name . '.xlsx';
  707. Excel::store(
  708. new \App\Exports\ResearchExpenseSummaryMultipleSheetExport($monthsData),
  709. "public/export/{$filename}"
  710. );
  711. return [true, $filename];
  712. }
  713. // 人员活动考勤占比
  714. public function exportActivityTimeCard(array $data, $user)
  715. {
  716. $service = new StatisticService();
  717. // 1. 获取统计数据
  718. list($status, $result) = $service->itemEmployeeSalaryStatistic($data, $user);
  719. if (!$status) return [false, $result];
  720. $rawList = collect($result ?? []);
  721. // 2. 按 项目名称 和 年度 联合分组
  722. $groupedData = $rawList->groupBy(function ($item) {
  723. $year = substr($item['month'] ?? date('Y'), 0, 4);
  724. return $year . "-" . $item['item_title'];
  725. });
  726. $allProjectsData = [];
  727. foreach ($groupedData as $groupKey => $records) {
  728. list($year, $projectTitle) = explode('-', $groupKey);
  729. $projectRows = [];
  730. $groupedByMonth = $records->groupBy('month');
  731. foreach ($groupedByMonth as $monthStr => $monthRecords) {
  732. $monthNum = substr($monthStr, 5, 2);
  733. $monthSubTotal = array_fill(3, 15, 0); // 索引3-17的累加器
  734. foreach ($monthRecords as $v) {
  735. $radioVal = (float)($v['radio'] ?? 0);
  736. $row = [
  737. (int)$monthNum . '月', // 0. 月份
  738. '技术人员', // 1. 类别
  739. $v['employee_title'] ?? '', // 2. 姓名
  740. (float)$v['total_min'], // 3. 应出勤
  741. (float)$v['work_minutes'], // 4. 研发出勤
  742. ($radioVal * 100) . '%', // 5. 占比 (字符串)
  743. (float)$v['salary'], // 6. 归集工资
  744. (float)$v['social_insurance'],// 7. 归集社保
  745. (float)$v['public_housing_fund'], // 8. 归集公积金
  746. (float)$v['work_salary'], // 9. 确定工资
  747. (float)$v['work_social_insurance'], // 10. 确定社保
  748. (float)$v['work_public_housing_fund'], // 11. 确定公积金
  749. (float)$v['work_salary'], // 12. 研发确定总工资
  750. (float)$v['work_social_insurance'], // 13. 研发确定总社保
  751. (float)$v['work_public_housing_fund'], // 14. 研发确定总公积金
  752. 0, 0, 0 // 15, 16, 17. 调整金额
  753. ];
  754. $projectRows[] = $row;
  755. // 累加月份小计 (跳过索引5的百分比字符串)
  756. for ($i = 3; $i <= 14; $i++) {
  757. if ($i == 5) continue;
  758. $monthSubTotal[$i] += (float)$row[$i];
  759. }
  760. }
  761. // 构造月份小计行 (重新计算占比)
  762. $mRadio = $monthSubTotal[3] > 0 ? round($monthSubTotal[4] / $monthSubTotal[3] * 100, 2) . '%' : '0%';
  763. $projectRows[] = [
  764. '小计:', '', '', $monthSubTotal[3], $monthSubTotal[4], $mRadio,
  765. $monthSubTotal[6], $monthSubTotal[7], $monthSubTotal[8],
  766. $monthSubTotal[9], $monthSubTotal[10], $monthSubTotal[11],
  767. $monthSubTotal[12], $monthSubTotal[13], $monthSubTotal[14],
  768. 0, 0, 0
  769. ];
  770. }
  771. // 计算整年合计 (避开小计行,避开非数字)
  772. $yearTotal = array_fill(3, 15, 0);
  773. foreach ($projectRows as $row) {
  774. if ($row[0] !== '小计:' && $row[0] !== '合计') {
  775. for ($i = 3; $i <= 14; $i++) {
  776. if ($i == 5) continue;
  777. $yearTotal[$i] += (float)$row[$i];
  778. }
  779. }
  780. }
  781. $yRadio = $yearTotal[3] > 0 ? round($yearTotal[4] / $yearTotal[3] * 100, 2) . '%' : '0%';
  782. $projectRows[] = [
  783. '合计', '', '', $yearTotal[3], $yearTotal[4], $yRadio,
  784. $yearTotal[6], $yearTotal[7], $yearTotal[8],
  785. $yearTotal[9], $yearTotal[10], $yearTotal[11],
  786. $yearTotal[12], $yearTotal[13], $yearTotal[14],
  787. 0, 0, 0
  788. ];
  789. $allProjectsData[$groupKey] = [
  790. 'project' => $projectTitle,
  791. 'year' => $year,
  792. 'data' => $projectRows
  793. ];
  794. }
  795. $filename = "人员活动考勤占比统计表_" . date("YmdHis") . '.xlsx';
  796. \Maatwebsite\Excel\Facades\Excel::store(
  797. new \App\Exports\ManActivityTimeCardMultipleSheetExport($allProjectsData),
  798. "public/export/{$filename}"
  799. );
  800. return [true, $filename];
  801. }
  802. //业研究开发活动汇总表
  803. public function exportEnterpriseRdStatistic(array $data, $user)
  804. {
  805. $service = new StatisticService();
  806. list($status, $result) = $service->enterpriseRdStatistic($data, $user);
  807. if (!$status) return [false, '获取统计数据失败'];
  808. $exportData = [];
  809. $totalBudget = 0; // 预算总计累加器
  810. $totalActual = 0; // 支出总计累加器
  811. foreach ($result as $row) {
  812. $budget = (float)($row['budget'] ?? 0);
  813. $actual = (float)($row['actual_expenditure'] ?? 0);
  814. $totalBudget = bcadd($totalBudget, $budget, 2);
  815. $totalActual = bcadd($totalActual, $actual, 2);
  816. $exportData[] = [
  817. 'activity_name' => $row['title'] ?? '', // 研发活动名称
  818. 'time_range' => $row['time_range'] ?? '', // 起止时间
  819. 'from' => $row['from'] ?? '自有技术', // 起止时间
  820. 'budget' => $budget, // 研发预算
  821. 'actual_spending' => $actual, // 实际支出
  822. 'tech_area' => $row['field'] ?? '', // 技术领域
  823. 'remark' => $row['mark'] ?? '', // 备注
  824. ];
  825. }
  826. $exportData[] = [
  827. 'activity_name' => '',
  828. 'time_range' => '',
  829. 'from' => '',
  830. 'budget' => $totalBudget,
  831. 'actual_spending' => $totalActual,
  832. 'tech_area' => '',
  833. 'remark' => '',
  834. ];
  835. $file_name = "企业研究开发活动汇总表_" . date("YmdHis");
  836. $filename = $file_name . '.xlsx';
  837. $relative_path = "public/export/{$filename}";
  838. \Maatwebsite\Excel\Facades\Excel::store(
  839. new \App\Exports\CompanyRdActivityExport($exportData),
  840. $relative_path
  841. );
  842. return [true, $filename];
  843. }
  844. //企业研究开发科技人员情况表
  845. public function exportEnterpriseRdManStatistic(array $data, $user)
  846. {
  847. $service = new StatisticService();
  848. list($status, $result) = $service->enterpriseRdManStatistic($data, $user);
  849. if (!$status) return [false, '获取人员统计数据失败'];
  850. // 2. 映射数据到导出类需要的字段格式
  851. $exportData = [];
  852. foreach ($result as $row) {
  853. $exportData[] = [
  854. 'name' => $row['title'] ?? '', // 姓名 (对应模型里的 title 字段)
  855. 'id_card' => $row['id_card'] ?? '', // 身份证号码
  856. 'education' => Employee::Education[$row['education']] ?? "", // 学历
  857. 'major' => $row['major'] ?? '', // 专业
  858. 'title_level' => $row['p_title'] ?? '', // 职称/职业资格
  859. 'department_job' => $row['position_new'] ?? '', // 部门/岗位
  860. 'employment_type' => $row['employee_type_title'] ?? "", // 聘用类型
  861. ];
  862. }
  863. // 3. 定义文件名和路径
  864. $file_name = "企业研究开发科技人员情况表_" . date("YmdHis");
  865. $filename = $file_name . '.xlsx';
  866. $relative_path = "public/export/{$filename}";
  867. \Maatwebsite\Excel\Facades\Excel::store(
  868. new \App\Exports\TechnicalStaffExport($exportData),
  869. $relative_path
  870. );
  871. return [true, $filename];
  872. }
  873. //项目研发活动人员情况表
  874. public function exportEnterpriseRdItemStatistic(array $data, $user)
  875. {
  876. $service = new StatisticService();
  877. list($status, $result) = $service->enterpriseRdItemStatistic($data, $user);
  878. if (!$status) return [false, '获取统计数据失败'];
  879. // 2. 映射数据到导出类需要的字段格式
  880. $exportData = [];
  881. foreach ($result as $row) {
  882. $exportData[] = [
  883. 'title' => $row['title'] ?? '', // 姓名 (对应模型里的 title 字段)
  884. 'education' => Employee::Education[$row['education']] ?? "", // 学历
  885. 'major' => $row['major'] ?? '', // 专业
  886. 'p_title' => $row['p_title'] ?? '', // 职称/职业资格
  887. 'item_title' => $row['item_title'] ?? '', // 项目
  888. 'item_role' => $row['item_role'] ?? '', // 项目角色
  889. 'depart_title' => $row['depart_title'] ?? '', // 部门
  890. 'duty' => $row['duty'] ?? "", // 职责
  891. ];
  892. }
  893. // 3. 定义文件名和路径
  894. $file_name = "项目研发活动人员情况表_" . date("YmdHis");
  895. $filename = $file_name . '.xlsx';
  896. $relative_path = "public/export/{$filename}";
  897. \Maatwebsite\Excel\Facades\Excel::store(
  898. new \App\Exports\ProjectStaffExport($exportData),
  899. $relative_path
  900. );
  901. return [true, $filename];
  902. }
  903. public function saveExportData($data, $headers, $type = 'default',$file_name = ''){
  904. if(empty($file_name)) $file_name = self::$filename . "_". date("Y-m-d") . "_". rand(1000,9999);
  905. $filename = $file_name . '.' . 'xlsx';
  906. $bool = Excel::store(new ExportOrder($data,$type,$headers),"/public/export/{$filename}", null, 'Xlsx', []);
  907. return $filename;
  908. }
  909. public function saveExportData2($data,$type = 1,$column,$timeRow, $file_name = ''){
  910. if(empty($file_name)) $file_name = self::$filename . "_". date("Y-m-d") . "_". rand(1000,9999);
  911. $filename = $file_name . '.' . 'xlsx';
  912. \Maatwebsite\Excel\Facades\Excel::store(new MultiSheetExport($data, $type,$column,$timeRow),"/public/export/{$filename}", null, 'Xlsx', []);
  913. return $filename;
  914. }
  915. }