ExportFileService.php 44 KB

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