ExportFileService.php 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492
  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\MonthlyPsMatrixExport;
  8. use App\Exports\MultiSheetExport;
  9. use App\Exports\ProjectDepreciationMultipleSheetExport;
  10. use App\Exports\ProjectStaffExport;
  11. use App\Exports\ResearchExpenseMultipleSheetExport;
  12. use App\Model\Depart;
  13. use App\Model\Employee;
  14. use App\Model\Fee;
  15. use App\Model\PLeaveOverOrder;
  16. use Illuminate\Support\Carbon;
  17. use Maatwebsite\Excel\Facades\Excel;
  18. class ExportFileService extends Service
  19. {
  20. public static $filename = "";
  21. //导出的方式 0 选择导出的数据 1 查询后 导出指定的数据(最多每次一千条)
  22. public static $export_type = [
  23. 0,
  24. 1
  25. ];
  26. public function exportAll($data,$user){
  27. if(empty($data['menu_id'])) return [false, 'menu_id不能为空'];
  28. if(empty($data['type'])) return [false, 'type不能为空'];
  29. $function = $data['type'];
  30. $name = $this->fillE($data['type'], $user);
  31. if (! method_exists(self::class, $function)) return [false, "导出方法不存在,请联系开发"];
  32. self::$filename = $name;
  33. $export_type = $data['export_type'] ?? 0;
  34. if(! isset(self::$export_type[$export_type])) return [false,'导出文件方式错误或者不存在'];
  35. if(empty($export_type)){
  36. if(empty($data['id'])) return [false,'请选择导出数据'];
  37. $search = $data;
  38. }else{
  39. if(empty($data['order_search'])) return [false,'搜索条件不能为空'];
  40. $search = $data['order_search'];
  41. if(empty($search['page_index'])) return [false,'请选择导出数据的开始页码'];
  42. if(empty($search['page_size'])) return [false,'请选择导出数据的条数'];
  43. if($search['page_size'] > 5000) return [false,'请选择导出数据的条数每次最多5000条'];
  44. $data['order_search']['menu_id'] = $data['menu_id'];
  45. $search = $data['order_search'];
  46. }
  47. list($status, $return) = $this->$function($search,$user);
  48. if(! $status) return [false, $return];
  49. return [true, $return];
  50. }
  51. public function fillE($type, &$user){
  52. $header = config("excel." . $type) ?? [];
  53. $funcName = $header['name'] ?? "";
  54. // $header_f = "extra_" . $menu_id;
  55. // $service = new TableHeadService();
  56. // if(method_exists($service,$header_f)) $service->$header_f($header_default);
  57. $user['e_header_default'] = $header['array'] ?? [];
  58. return $funcName;
  59. }
  60. private function fillData($data, $column, &$return)
  61. {
  62. // 预先创建包含默认值的键数组
  63. $default = array_fill_keys($column, '');
  64. foreach ($data as $value) {
  65. // 提取交集,并用默认值补充缺失的键
  66. $return[] = array_merge($default, array_intersect_key($value, $default));
  67. }
  68. }
  69. private function fillTotalData($data, $column, &$return){
  70. $tmp = [];
  71. foreach ($column as $value){
  72. $key = $value['key'];
  73. if(! empty($value['sum']) && isset($data[$value['key']])){
  74. $decimals = $col['decimals'] ?? 2;
  75. // $tmp[$value['key']] = $data[$value['key']];
  76. // 用 number_format 格式化输出(保持字符串形式,避免科学计数)
  77. $tmp[$key] = number_format((float)$data[$key], $decimals, '.', '');
  78. }else{
  79. $tmp[$value['key']] = "";
  80. }
  81. }
  82. $return[] = $tmp;
  83. }
  84. public function employee($ergs,$user){
  85. // 导出数据
  86. $return = [];
  87. $header_default = $user['e_header_default'];
  88. $column = array_column($header_default,'export');
  89. $header = array_column($header_default,'value');
  90. $service = new EmployeeService();
  91. $model = $service->employeeCommon($ergs, $user);
  92. $model->chunk(500,function ($data) use(&$return, $service, $column, $user){
  93. $service->fillDataForExport($data, $column, $user, $return);
  94. });
  95. return [true, $this->saveExportData($return,$header)];
  96. }
  97. public function depart($ergs,$user){
  98. // 导出数据
  99. $return = [];
  100. $header_default = $user['e_header_default'];
  101. $column = array_column($header_default,'export');
  102. $header = array_column($header_default,'value');
  103. $service = new EmployeeService();
  104. $model = $service->departCommon($ergs, $user);
  105. $model->chunk(500,function ($data) use(&$return, $service, $column, $user){
  106. $data = $data->toArray();
  107. $list['data'] = $data;
  108. //订单数据
  109. $list = $service->fillDepartList($list, $user, true);
  110. //返回数据
  111. $this->fillData($list, $column, $return);
  112. });
  113. return [true, $this->saveExportData($return,$header)];
  114. }
  115. public function device($ergs,$user){
  116. // 导出数据
  117. $return = [];
  118. $header_default = $user['e_header_default'];
  119. $column = array_column($header_default,'export');
  120. $header = array_column($header_default,'value');
  121. $service = new DeviceService();
  122. $model = $service->deviceCommon($ergs, $user);
  123. $model->chunk(500,function ($data) use(&$return, $service, $column,$ergs, $user){
  124. $data = $data->toArray();
  125. $list['data'] = $data;
  126. //订单数据
  127. $list = $service->fillData($list, $ergs, $user);
  128. //返回数据
  129. $this->fillData($list['data'], $column, $return);
  130. });
  131. return [true, $this->saveExportData($return,$header)];
  132. }
  133. public function item($ergs,$user){
  134. // 导出数据
  135. $return = [];
  136. $header_default = $user['e_header_default'];
  137. $column = array_column($header_default,'export');
  138. $header = array_column($header_default,'value');
  139. $service = new ItemService();
  140. $model = $service->itemCommon($ergs, $user);
  141. $model->chunk(500,function ($data) use(&$return,$column,$service, $user){
  142. // 调用 Service 层的填充方法
  143. $service->fillDataForExport($data, $column, $user, $return);
  144. });
  145. return [true, $this->saveExportData($return,$header)];
  146. }
  147. public function fee($ergs,$user){
  148. // 导出数据
  149. $return = [];
  150. $header_default = $user['e_header_default'];
  151. $column = array_column($header_default,'export');
  152. $header = array_column($header_default,'value');
  153. $service = new FeeService();
  154. $model = $service->feeCommon($ergs, $user);
  155. $model->chunk(500,function ($data) use(&$return, $service, $column, $user){
  156. $data = $data->toArray();
  157. $list['data'] = $data;
  158. //订单数据
  159. $list = $service->fillFeeList($list, $user, true);
  160. //返回数据
  161. $this->fillData($list['data'], $column, $return);
  162. });
  163. return [true, $this->saveExportData($return,$header)];
  164. }
  165. public function monthPwOrder($ergs,$user){
  166. // 导出数据
  167. $return = [];
  168. $header_default = $user['e_header_default'];
  169. $column = array_column($header_default,'export');
  170. $header = array_column($header_default,'value');
  171. $service = new PersonWorkService();
  172. $model = $service->monthlyPwOrderCommon($ergs, $user);
  173. $model->chunk(500,function ($data) use(&$return, $service, $column){
  174. // 直接处理这一批主表数据,将其与详情合并平铺
  175. $service->fillDataForExport($data->toArray(), $column, $return);
  176. });
  177. return [true, $this->saveExportData($return,$header)];
  178. }
  179. public function monthDwOrder($ergs,$user){
  180. // 导出数据
  181. $return = [];
  182. $header_default = $user['e_header_default'];
  183. $column = array_column($header_default,'export');
  184. $header = array_column($header_default,'value');
  185. $service = new DeviceWorkService();
  186. $model = $service->monthlyDwOrderCommon($ergs, $user);
  187. $model->chunk(500,function ($data) use(&$return, $service, $column){
  188. // 直接处理这一批主表数据,将其与详情合并平铺
  189. $service->fillDataForExport($data->toArray(), $column, $return);
  190. });
  191. return [true, $this->saveExportData($return,$header)];
  192. }
  193. public function monthPsOrder($ergs,$user){
  194. // 导出数据
  195. $return = [];
  196. $header_default = $user['e_header_default'];
  197. $column = array_column($header_default,'export');
  198. $header = array_column($header_default,'value');
  199. $service = new PersonSalaryService();
  200. $model = $service->monthlyPsOrderCommon($ergs, $user);
  201. $model->chunk(500,function ($data) use(&$return, $service, $column){
  202. // 直接处理这一批主表数据,将其与详情合并平铺
  203. $service->fillDataForExport($data->toArray(), $column, $return);
  204. });
  205. return [true, $this->saveExportData($return,$header)];
  206. }
  207. public function monthPsOrderCount($ergs, $user)
  208. {
  209. $service = new PersonSalaryService();
  210. // 1. 获取主表查询模型
  211. $model = $service->monthlyPsOrderCommon($ergs, $user);
  212. $yearlyData = []; // 用于存放归类后的数据:[年份][员工Key][月份] = 薪资数据
  213. // 2. 分批捞取主表数据并按年、人、月进行归类
  214. $model->chunk(500, function ($mainOrders) use (&$yearlyData, $service) {
  215. $mainIds = $mainOrders->pluck('id')->toArray();
  216. // 获取详情映射 [main_id => [details...]]
  217. $detailsMap = $service->getDetailsMap($mainIds);
  218. foreach ($mainOrders as $main) {
  219. // 解析年份和月份
  220. if (empty($main['month'])) continue;
  221. $year = date('Y', $main['month']); // 例如: "2025"
  222. $month = (int)date('m', $main['month']); // 例如: 5 (直接转成数字 1-12)
  223. $details = $detailsMap[$main['id']] ?? [];
  224. foreach ($details as $sub) {
  225. // 构造员工在表格左侧的唯一标识(工号 + 姓名)
  226. $empKey = $sub['employee_number'] . '_' . $sub['employee_title'];
  227. // 计算当前月份该员工的总薪资 = 基本 + 绩效 + 奖金 + 其他
  228. $totalSalary = (float)($sub['base_salary'] ?? 0)
  229. + (float)($sub['performance_salary'] ?? 0)
  230. + (float)($sub['bonus'] ?? 0)
  231. + (float)($sub['other'] ?? 0);
  232. // 归入矩阵:如果该年该人该月已经有值,做累加(防止单月重复发薪单)
  233. if (!isset($yearlyData[$year][$empKey][$month])) {
  234. $yearlyData[$year][$empKey][$month] = 0.00;
  235. }
  236. $yearlyData[$year][$empKey][$month] += $totalSalary;
  237. }
  238. }
  239. });
  240. if (empty($yearlyData)) {
  241. return [false, '没有可导出的数据'];
  242. }
  243. // 3. 排序并统一格式化金额为两位小数
  244. ksort($yearlyData);
  245. foreach ($yearlyData as $year => &$emps) {
  246. ksort($emps); // 员工按工号等 Key 排序
  247. // ✨【核心修改】:遍历当前年份下的所有员工和月份,统一将累加完的最终金额保留2位小数
  248. foreach ($emps as $empKey => &$months) {
  249. foreach ($months as $month => $totalSalary) {
  250. $months[$month] = number_format($totalSalary, 2, '.', '');
  251. }
  252. }
  253. }
  254. unset($emps); // 释放引用避免后续潜在干扰
  255. $file_name = "人员月工资单统计表_" . date("Y-m-d") . "_". rand(1000, 9999);
  256. $filename = $file_name . '.' . 'xlsx';
  257. $bool = Excel::store(new MonthlyPsMatrixExport($yearlyData), "/public/export/{$filename}", null, 'Xlsx', []);
  258. return [true, $filename];
  259. }
  260. public function monthDdOrder($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 DeviceDepreciationService();
  267. $model = $service->monthlyDdOrderCommon($ergs, $user);
  268. $model->chunk(500,function ($data) use(&$return, $service, $column){
  269. // 直接处理这一批主表数据,将其与详情合并平铺
  270. $service->fillDataForExport($data->toArray(), $column, $return);
  271. });
  272. return [true, $this->saveExportData($return,$header)];
  273. }
  274. public function ruleSet($ergs,$user){
  275. // 导出数据
  276. $return = [];
  277. $header_default = $user['e_header_default'];
  278. $column = array_column($header_default,'export');
  279. $header = array_column($header_default,'value');
  280. $service = new RuleSetService();
  281. $model = $service->ruleSetCommon($ergs, $user);
  282. $model->chunk(500,function ($data) use(&$return, $service, $column){
  283. // 直接处理这一批主表数据,将其与详情合并平铺
  284. $service->fillDataForExport($data->toArray(), $column, $return);
  285. });
  286. return [true, $this->saveExportData($return,$header)];
  287. }
  288. public function dailyPwOrder($ergs,$user){
  289. // 导出数据
  290. $return = [];
  291. $header_default = $user['e_header_default'];
  292. $column = array_column($header_default,'export');
  293. $header = array_column($header_default,'value');
  294. $service = new PersonWorkService();
  295. $model = $service->dailyPwOrderCommon($ergs, $user);
  296. $model->chunk(500,function ($data) use(&$return, $service, $column){
  297. // 直接处理这一批主表数据,将其与详情合并平铺
  298. $service->fillDataForExportDaily($data->toArray(), $column, $return);
  299. });
  300. return [true, $this->saveExportData($return,$header)];
  301. }
  302. public function dailyDwOrder($ergs,$user){
  303. // 导出数据
  304. $return = [];
  305. $header_default = $user['e_header_default'];
  306. $column = array_column($header_default,'export');
  307. $header = array_column($header_default,'value');
  308. $service = new DeviceWorkService();
  309. $model = $service->dailyDwOrderCommon($ergs, $user);
  310. $model->chunk(500,function ($data) use(&$return, $service, $column){
  311. // 直接处理这一批主表数据,将其与详情合并平铺
  312. $service->fillDataForExportDaily($data->toArray(), $column, $return);
  313. });
  314. return [true, $this->saveExportData($return,$header)];
  315. }
  316. public function leaveOrder($ergs,$user){
  317. // 导出数据
  318. $return = [];
  319. $header_default = $user['e_header_default'];
  320. $column = array_column($header_default,'export');
  321. $header = array_column($header_default,'value');
  322. $service = new PLeaveOverService();
  323. $ergs['type'] = PLeaveOverOrder::TYPE_ONE;
  324. $model = $service->pLeaveOverCommon($ergs, $user);
  325. $model->chunk(500,function ($data) use(&$return, $service, $column){
  326. // 直接处理这一批主表数据,将其与详情合并平铺
  327. $service->fillDataForExportDaily($data->toArray(), $column, $return);
  328. });
  329. return [true, $this->saveExportData($return,$header)];
  330. }
  331. public function overtimeOrder($ergs,$user){
  332. // 导出数据
  333. $return = [];
  334. $header_default = $user['e_header_default'];
  335. $column = array_column($header_default,'export');
  336. $header = array_column($header_default,'value');
  337. $service = new PLeaveOverService();
  338. $ergs['type'] = PLeaveOverOrder::TYPE_TWO;
  339. $model = $service->pLeaveOverCommon($ergs, $user);
  340. $model->chunk(500,function ($data) use(&$return, $service, $column){
  341. // 直接处理这一批主表数据,将其与详情合并平铺
  342. $service->fillDataForExportDaily($data->toArray(), $column, $return);
  343. });
  344. return [true, $this->saveExportData($return,$header)];
  345. }
  346. public function feeOrder($ergs, $user)
  347. {
  348. // 导出配置
  349. $return = [];
  350. $header_default = $user['e_header_default']; // 假设前端已下发报销单的模板配置
  351. $column = array_column($header_default, 'export');
  352. $header = array_column($header_default, 'value');
  353. $service = new ExpenseClaimsService();
  354. // 使用你提到的 common 方法获取 Query Builder
  355. $model = $service->expenseClaimsSetCommon($ergs, $user);
  356. $model->chunk(500, function ($data) use (&$return, $service, $column) {
  357. // 直接处理这一批主表数据,将其与详情合并平铺
  358. $service->fillDataForExport($data->toArray(), $column, $return);
  359. });
  360. return [true, $this->saveExportData($return, $header)];
  361. }
  362. public function RDOrder($ergs, $user)
  363. {
  364. // 导出配置
  365. $return = [];
  366. $header_default = $user['e_header_default'];
  367. $column = array_column($header_default, 'export');
  368. $header = array_column($header_default, 'value');
  369. $service = new AuxiliaryAccountService();
  370. $model = $service->setCommon($ergs, $user);
  371. $model->chunk(500, function ($data) use (&$return, $service, $column) {
  372. // 直接处理这一批主表数据,将其与详情合并平铺
  373. $service->fillDataForExport($data->toArray(), $column, $return);
  374. });
  375. return [true, $this->saveExportData($return, $header)];
  376. }
  377. //标签管理
  378. public function tag($ergs, $user)
  379. {
  380. // 导出配置
  381. $return = [];
  382. $header_default = $user['e_header_default'];
  383. $column = array_column($header_default, 'export');
  384. $header = array_column($header_default, 'value');
  385. $service = new TagService();
  386. $model = $service->tagCommon($ergs, $user);
  387. $model->chunk(500, function ($data) use (&$return, $service, $column, $user) {
  388. $data = $data->toArray();
  389. $list['data'] = $data;
  390. //订单数据
  391. $list = $service->fillPriorityList($list, $user, true);
  392. //返回数据
  393. $this->fillData($list['data'], $column, $return);
  394. });
  395. return [true, $this->saveExportData($return, $header)];
  396. }
  397. // 项目工资统计表
  398. public function exportEmployeeSalary($data, $user)
  399. {
  400. $service = new StatisticService();
  401. // 1. 调用你现有的查询方法获取基础数据
  402. list($status, $itemMonthList) = $service->employeeMonthSalaryStatistic($data, $user);
  403. if (!$status) return $itemMonthList; // 返回错误信息
  404. // 2. 提取所有涉及到的唯一项目 (按 Code 排序,保证列顺序固定)
  405. $projects = collect($itemMonthList)->pluck('item_code')->unique()->sort()->values()->toArray();
  406. // 3. 按月份对数据进行分组
  407. $groupedByMonth = collect($itemMonthList)->groupBy('month')->sortKeys();
  408. $exportData = [];
  409. $columnTotals = array_fill(0, count($projects) * 2, 0); // 用于存储每列的合计
  410. $grandTotalSalary = 0; // 总计金额
  411. // 4. 循环每个月,构造行数据
  412. foreach ($groupedByMonth as $month => $items) {
  413. $row = [$month]; // A列:月份
  414. $monthTotalSalary = 0;
  415. // 创建该月项目的映射,方便快速查找
  416. $monthItemsMap = $items->keyBy('item_code');
  417. foreach ($projects as $index => $code) {
  418. $itemDetail = $monthItemsMap->get($code);
  419. $days = $itemDetail['days'] ?? 0;
  420. $salary = $itemDetail['allocated_salary'] ?? 0;
  421. $row[] = $days > 0 ? $days : ''; // 天数列
  422. $row[] = $salary > 0 ? $salary : ''; // 工资列
  423. // 累加合计行(列合计)
  424. $columnTotals[$index * 2] += $days;
  425. $columnTotals[$index * 2 + 1] += $salary;
  426. $monthTotalSalary += $salary;
  427. }
  428. $row[] = $monthTotalSalary; // 最后一列:该月合计工资
  429. $grandTotalSalary += $monthTotalSalary;
  430. $exportData[] = $row;
  431. }
  432. // 5. 构造最后的“合计”行
  433. $totalRow = ['合计'];
  434. foreach ($columnTotals as $val) {
  435. $totalRow[] = $val > 0 ? $val : 0;
  436. }
  437. $totalRow[] = $grandTotalSalary;
  438. $exportData[] = $totalRow;
  439. //获取公司基本信息
  440. $company = EmployeeService::getCompanyDetail($user);
  441. $file_name = "项目工资统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  442. $filename = $file_name . '.' . 'xlsx';
  443. $bool = Excel::store(new ItemSalarySheetExport($projects, $exportData, $company['title'] ?? ''),"/public/export/{$filename}", null, 'Xlsx', []);
  444. return [true, $filename];
  445. }
  446. // 人员月工时统计表
  447. public function exportManMonthlyWorkHour($data, $user)
  448. {
  449. // 1. 获取报表基础数据
  450. $service = new StatisticService();
  451. list($status, $result) = $service->employeeDayHourStatistic($data, $user);
  452. if (!$status) return $result;
  453. $sourceData = collect($result);
  454. // 2. 按月份分组,准备多 Sheet 数据
  455. $monthsData = [];
  456. // 按月分组数据
  457. $groupedByMonth = $sourceData->groupBy(function ($item) {
  458. return date('Y年m月', strtotime($item['order_date']));
  459. });
  460. // 获取公司基本信息
  461. $company = EmployeeService::getCompanyDetail($user);
  462. foreach ($groupedByMonth as $monthName => $monthItems) {
  463. $formatMonth = str_replace(['年', '月'], ['-', ''], $monthName);
  464. $daysInMonth = date('t', strtotime($formatMonth . '-01'));
  465. // 按 项目+人员 分组
  466. $groupedByUserItem = $monthItems->groupBy(function ($item) {
  467. return $item['item_code'] . '_' . $item['employee_id'];
  468. });
  469. $sheetRows = [];
  470. foreach ($groupedByUserItem as $key => $records) {
  471. $first = $records->first();
  472. // 初始化行:前两列是 项目名称 和 姓名
  473. $row = [
  474. $first['item_title'],
  475. $first['employee_name']
  476. ];
  477. // 映射日期 => 记录
  478. $dayMap = $records->keyBy(function($r){
  479. return (int)date('d', strtotime($r['order_date']));
  480. });
  481. for ($d = 1; $d <= $daysInMonth; $d++) {
  482. $record = $dayMap->get($d);
  483. // ==================== 【核心改动点】 ====================
  484. // 不使用截断后的 $record['total_work_hours']
  485. // 直接使用原始分钟数 $record['total_work'] 除以 60,保留高精度浮点数给 Excel
  486. if ($record && isset($record['total_work']) && $record['total_work'] > 0) {
  487. $row[] = (float)($record['total_work'] / 60);
  488. } else {
  489. $row[] = '';
  490. }
  491. // ========================================================
  492. }
  493. $sheetRows[] = $row;
  494. }
  495. $monthsData[$monthName] = [
  496. 'days' => (int)$daysInMonth,
  497. 'data' => $sheetRows,
  498. 'company_name' => $company['title'] ?? '',
  499. ];
  500. }
  501. $file_name = "人员月工时统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  502. $filename = $file_name . '.' . 'xlsx';
  503. $bool = Excel::store(new ManMonthlyWorkHourMultipleSheetExport($monthsData), "/public/export/{$filename}", null, 'Xlsx', []);
  504. return [true, $filename];
  505. }
  506. // 项目设备折旧
  507. public function exportDeviceZj(array $data, $user)
  508. {
  509. $service = new StatisticService();
  510. list($status, $result) = $service->itemDeviceMonthStatistic($data, $user);
  511. if (!$status) return $result;
  512. // 2. 将数据按 [项目编号][月份] 进行分组
  513. // 预期结构:$monthsData['RD01']['months']['2025-01'] = [设备1, 设备2...]
  514. $groupedData = collect($result)->groupBy('item_code');
  515. $finalExportData = [];
  516. foreach ($groupedData as $itemCode => $itemRecords) {
  517. $firstRecord = $itemRecords->first();
  518. $projectName = $firstRecord['item_title'];
  519. $firstMonth = $firstRecord['month'];
  520. $year = substr($firstMonth, 0, 4);
  521. // 3. 构造新的 Key:年-项目 (例如: 2026-53code)
  522. $newSheetKey = $year . '年度项目' . $itemCode;
  523. // 按月份进一步分组
  524. $monthGroups = $itemRecords->groupBy('month');
  525. $monthsPayload = [];
  526. foreach ($monthGroups as $month => $devices) {
  527. $monthData = [];
  528. foreach ($devices as $dev) {
  529. $monthData[] = [
  530. 'device_name' => $dev['device_title'],
  531. 'original_value' => $dev['device_original'], // 设备原值
  532. 'total_depreciation' => $dev['total_depreciatio'], // 当月总折旧
  533. 'project_hours' => $dev['hours'], // 本项目工时
  534. 'total_hours' => $dev['total_hours'], // 当月总工时
  535. 'ratio' => bcmul($dev['ratio'], 100,2), // 研发工时占比
  536. 'allocated_depreciation' => $dev['allocated_depreciatio'], // 本项目分摊折旧
  537. ];
  538. }
  539. $monthsPayload[$month] = $monthData;
  540. }
  541. // 构造 Sheet 所需结构
  542. $finalExportData[$newSheetKey] = [
  543. 'project_name' => $projectName,
  544. 'months' => $monthsPayload
  545. ];
  546. }
  547. $file_name = "项目设备折旧费用统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  548. $filename = $file_name . '.' . 'xlsx';
  549. $bool = Excel::store(new ProjectDepreciationMultipleSheetExport($finalExportData), "/public/export/{$filename}", null, 'Xlsx', []);
  550. return [true, $filename];
  551. }
  552. // 项目工资分摊
  553. public function exportItemSalaryFT(array $data, $user)
  554. {
  555. $service = new StatisticService();
  556. list($status, $result) = $service->itemDaySalaryStatistic($data, $user);
  557. if (!$status) return $result;
  558. $sourceData = collect($result);
  559. $groupedByMonth = $sourceData->groupBy('month');
  560. $monthsData = [];
  561. foreach ($groupedByMonth as $month => $monthRecords) {
  562. // A. 获取本月参与的所有唯一项目编码
  563. $monthProjects = $monthRecords->pluck('item_code')->unique()->sort()->values()->all();
  564. // B. 按人员分组组织数据
  565. $groupedByEmployee = $monthRecords->groupBy('employee_id');
  566. $sheetRows = [];
  567. $index = 1;
  568. // 初始化列合计
  569. $colTotals = [
  570. 'total_salary' => 0,
  571. 'total_min_hours' => 0, // 月总工时合计
  572. 'project_days' => array_fill_keys($monthProjects, 0),
  573. 'project_salary' => array_fill_keys($monthProjects, 0),
  574. 'total_attendance_days' => 0, // 合计工时列的合计
  575. ];
  576. foreach ($groupedByEmployee as $employeeId => $records) {
  577. $first = $records->first();
  578. $empMonthSalary = (float)$first['total_salary'];
  579. $empTotalHours = $first['total_hours'];
  580. // 1-4列:序号、姓名、工资、月总工时
  581. $row = [$index++, $first['employee_title'], $empMonthSalary, $empTotalHours];
  582. // 5. 动态项目工时列
  583. $empMap = $records->keyBy('item_code');
  584. $rowProjectDaysSum = 0;
  585. foreach ($monthProjects as $code) {
  586. if ($empMap->has($code)) {
  587. $record = $empMap->get($code);
  588. $days = (float)($record['work_hours'] ?? 0);
  589. } else {
  590. $days = 0;
  591. }
  592. $row[] = $days > 0 ? $days : '';
  593. $rowProjectDaysSum += $days;
  594. $colTotals['project_days'][$code] += $days;
  595. }
  596. // 6. 合计工时列
  597. $row[] = $rowProjectDaysSum;
  598. $colTotals['total_attendance_days'] += $rowProjectDaysSum;
  599. // 7. 动态项目金额列
  600. foreach ($monthProjects as $code) {
  601. $salary = $empMap->has($code) ? (float)$empMap->get($code)['allocated_salary'] : 0;
  602. $row[] = $salary > 0 ? $salary : '';
  603. $colTotals['project_salary'][$code] += $salary;
  604. }
  605. // 8. 总计工资列
  606. $row[] = $empMonthSalary;
  607. // 累加合计
  608. $colTotals['total_salary'] += $empMonthSalary;
  609. $colTotals['total_min_hours'] += $empTotalHours;
  610. $sheetRows[] = $row;
  611. }
  612. // C. 构造合计行
  613. $totalRow = ['合计', '', $colTotals['total_salary'], $colTotals['total_min_hours']];
  614. foreach ($monthProjects as $code) { $totalRow[] = $colTotals['project_days'][$code]; }
  615. $totalRow[] = $colTotals['total_attendance_days'];
  616. foreach ($monthProjects as $code) { $totalRow[] = $colTotals['project_salary'][$code]; }
  617. $totalRow[] = $colTotals['total_salary'];
  618. $sheetRows[] = $totalRow;
  619. $monthsData[$month] = [
  620. 'projects' => $monthProjects,
  621. 'data' => $sheetRows
  622. ];
  623. }
  624. //获取公司基本信息
  625. $company = EmployeeService::getCompanyDetail($user);
  626. $file_name = "项目工资分摊统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  627. $filename = $file_name . '.xlsx';
  628. Excel::store(
  629. new ItemSalaryFTMultipleSheetExport($monthsData, $company['title'] ?? ''),
  630. "/public/export/{$filename}"
  631. );
  632. return [true, $filename];
  633. }
  634. // 年度研发支出辅助账汇总表
  635. public function exportResearchExpense1(array $data, $user)
  636. {
  637. $service = new StatisticService();
  638. list($status, $result) = $service->auxiliaryStatistic($data, $user);
  639. if (!$status) return [false, $result];
  640. $fee_type_list = $result['fee_type_list'];
  641. $raw_list = $result['list'];
  642. if(empty($raw_list)) return [false, '暂无导出数据'];
  643. // 预读年份和动态表头长度
  644. $year = date("Y", strtotime($raw_list[0]['voucher_date']));
  645. $company = Depart::where('id', $user['top_depart_id'])->value('title');
  646. $dynamicHeaderTitles = array_column($fee_type_list, 'title');
  647. $dynamicCount = count($dynamicHeaderTitles);
  648. $totalColCount = 8 + $dynamicCount + 2; // 基础6 + 固定2 + 动态N + 委托2
  649. $groupedData = [];
  650. foreach ($raw_list as $row) {
  651. $sheetKey = $year . $row['code'];
  652. if (!isset($groupedData[$sheetKey])) {
  653. $groupedData[$sheetKey] = [
  654. 'project' => [
  655. 'code' => $row['code'],
  656. 'name' => $row['title'],
  657. ],
  658. 'dynamic_headers' => $dynamicHeaderTitles,
  659. 'data' => [],
  660. 'year' => $company . $year,
  661. 'totals' => array_fill(0, $totalColCount, 0)
  662. ];
  663. $groupedData[$sheetKey]['totals'][0] = '合计'; // 第一列标识
  664. }
  665. // 组织明细行数据 (逻辑不变)
  666. $excelRow = [
  667. $row['voucher_date'], $row['voucher_type'], $row['voucher_no'], $row['voucher_remark'],
  668. (float)$row['voucher_amount'],
  669. (float)$row['aggregation_amount'],
  670. ($row['type'] == 1 ? (float)$row['total_amount'] : 0), // 人员
  671. ($row['type'] == 2 ? (float)$row['total_amount'] : 0) // 折旧
  672. ];
  673. // 动态列填充
  674. foreach ($fee_type_list as $feeId => $feeItem) {
  675. $excelRow[] = ($row['type'] == 3 && $row['fee_id'] == $feeId) ? (float)$row['total_amount'] : 0;
  676. }
  677. // 委托列
  678. $excelRow[] = (float)($row['entrust1_amount'] ?? 0);
  679. $excelRow[] = (float)($row['entrust2_amount'] ?? 0);
  680. // 【性能优化】:同步累加金额 (从索引 4 开始是金额列)
  681. for ($i = 4; $i < $totalColCount; $i++) {
  682. $groupedData[$sheetKey]['totals'][$i] += $excelRow[$i];
  683. }
  684. $groupedData[$sheetKey]['data'][] = $excelRow;
  685. }
  686. foreach ($groupedData as &$group) {
  687. $group['data'][] = $group['totals'];
  688. unset($group['totals']); // 释放内存
  689. }
  690. // 8. 导出逻辑保持不变
  691. $file_name = "年度研发支出辅助账汇总统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  692. $filename = $file_name . '.xlsx';
  693. Excel::store(
  694. new ResearchExpenseMultipleSheetExport($groupedData),
  695. "public/export/{$filename}"
  696. );
  697. return [true, $filename];
  698. }
  699. // 年度研发支出辅助账汇总表
  700. public function exportResearchExpense(array $data, $user)
  701. {
  702. $service = new StatisticService();
  703. list($status, $result) = $service->auxiliaryStatistic($data, $user);
  704. if (!$status) return [false, $result];
  705. $fee_type_list = $result['fee_type_list'];
  706. $raw_list = $result['list'];
  707. if(empty($raw_list)) return [false, '暂无导出数据'];
  708. // 预读年份和基本信息
  709. $year = date("Y", strtotime($raw_list[0]['voucher_date']));
  710. $company = Depart::where('id', $user['top_depart_id'])->value('title');
  711. // ================== 【核心修复 1:精准使用 $feeItem['id'] 参与排序与映射】 ==================
  712. // 1. 定义固定的人员和折旧列配置并赋予 sort
  713. $amountColumnsConfig = [
  714. [
  715. 'type_key' => 'type_1', // 对应原逻辑 type == 1 (人员)
  716. 'title' => '人员人工费用',
  717. 'sort' => -1,
  718. ],
  719. [
  720. 'type_key' => 'type_2', // 对应原逻辑 type == 2 (折旧)
  721. 'title' => '折旧费用',
  722. 'sort' => 1,
  723. ]
  724. ];
  725. // 2. 将动态费用类型塞入同一个配置池中(【修复点】:从 $feeItem['id'] 读出真实的 55, 56 等真实ID)
  726. foreach ($fee_type_list as $feeItem) {
  727. $realFeeId = $feeItem['id'] ?? 0;
  728. $amountColumnsConfig[] = [
  729. 'type_key' => 'fee_' . $realFeeId,
  730. 'fee_id' => $realFeeId, // 显式留存住真实的数据库 ID,不再受数组索引干扰
  731. 'title' => $feeItem['title'] ?? '',
  732. 'sort' => (int)($feeItem['sort'] ?? 0),
  733. ];
  734. }
  735. // 3. 按照 sort 正序排序(值越小越靠前)
  736. $sortedAmountColumns = collect($amountColumnsConfig)->sortBy('sort')->values()->all();
  737. // 4. 提取出最终的动态表头名称供 Excel 使用
  738. $dynamicHeaderTitles = array_column($sortedAmountColumns, 'title');
  739. // 5. 计算总列数
  740. $baseColCount = 6;
  741. $sortedColCount = count($sortedAmountColumns);
  742. $totalColCount = $baseColCount + $sortedColCount + 2;
  743. // =========================================================================
  744. $groupedData = [];
  745. foreach ($raw_list as $row) {
  746. $sheetKey = $year . $row['code'];
  747. if (!isset($groupedData[$sheetKey])) {
  748. $groupedData[$sheetKey] = [
  749. 'project' => [
  750. 'code' => $row['code'],
  751. 'name' => $row['title'],
  752. ],
  753. 'dynamic_headers' => $dynamicHeaderTitles,
  754. 'data' => [],
  755. 'year' => $company . $year,
  756. 'totals' => array_fill(0, $totalColCount, 0)
  757. ];
  758. $groupedData[$sheetKey]['totals'][0] = '合计'; // 第一列标识
  759. }
  760. // 1. 初始化明细行的前 6 列(基础信息 + 基础金额)
  761. $excelRow = [
  762. $row['voucher_date'],
  763. $row['voucher_type'],
  764. $row['voucher_no'],
  765. $row['voucher_remark'],
  766. (float)($row['voucher_amount'] ?? 0),
  767. (float)($row['aggregation_amount'] ?? 0),
  768. ];
  769. // ================== 【核心修复 2:依照正确的真实 fee_id 填充科目金额】 ==================
  770. foreach ($sortedAmountColumns as $col) {
  771. $colValue = 0.0;
  772. if ($col['type_key'] === 'type_1') {
  773. // 人员人工
  774. $colValue = ($row['type'] == 1 ? (float)$row['total_amount'] : 0);
  775. } elseif ($col['type_key'] === 'type_2') {
  776. // 折旧费用
  777. $colValue = ($row['type'] == 2 ? (float)$row['total_amount'] : 0);
  778. } else {
  779. // 动态费用科目(【修复点】:此时的 $col['fee_id'] 已经能够完美匹配 $row['fee_id'])
  780. $colValue = ($row['type'] == 3 && $row['fee_id'] == $col['fee_id']) ? (float)$row['total_amount'] : 0;
  781. }
  782. $excelRow[] = $colValue;
  783. }
  784. // =========================================================================
  785. // 3. 追加尾部的委托列
  786. $excelRow[] = (float)($row['entrust1_amount'] ?? 0);
  787. $excelRow[] = (float)($row['entrust2_amount'] ?? 0);
  788. // 同步累加金额 (从索引 4 [记账凭证金额] 开始一直到最后一列)
  789. for ($i = 4; $i < $totalColCount; $i++) {
  790. $groupedData[$sheetKey]['totals'][$i] += $excelRow[$i];
  791. }
  792. $groupedData[$sheetKey]['data'][] = $excelRow;
  793. }
  794. foreach ($groupedData as &$group) {
  795. $group['data'][] = $group['totals'];
  796. unset($group['totals']); // 释放内存
  797. }
  798. // 8. 导出逻辑
  799. $file_name = "年度研发支出辅助账汇总统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  800. $filename = $file_name . '.xlsx';
  801. Excel::store(
  802. new ResearchExpenseMultipleSheetExport($groupedData),
  803. "public/export/{$filename}"
  804. );
  805. return [true, $filename];
  806. }
  807. // 研发支出辅助帐汇总表
  808. public function exportFormalSummary1(array $data, $user)
  809. {
  810. $service = new StatisticService();
  811. // 1. 调用业务逻辑获取原始数据
  812. list($status, $result) = $service->employeeAttendanceMonthStatistic($data, $user);
  813. if (!$status) return [false, $result];
  814. $rawList = $result['list'] ?? [];
  815. $feeTypes = $result['fee_type_list'] ?? [];
  816. // 2. 构造动态表头名称
  817. $dynamicHeaderTitles = [];
  818. foreach ($feeTypes as $value){
  819. if(! $value['is_after']) $dynamicHeaderTitles[] = $value['title'];
  820. }
  821. // $dynamicHeaderTitles = array_column($feeTypes, 'title');
  822. $dynamicHeaders = array_merge(['人员人工费用', '折旧费用'], $dynamicHeaderTitles);
  823. $items = [];
  824. foreach ($rawList as $v) {
  825. $rowValues = [];
  826. // A. 填充基础固定两项:人工和折旧
  827. $rowValues[] = (float)($v['employee_salary'] ?? 0);
  828. $rowValues[] = (float)($v['device_depreciation'] ?? 0);
  829. // B. 初始化累加变量
  830. // $val7_1 = 0; // 其他相关费用合计 (所有 total_amount 之和)
  831. $val8_1 = 0; // 委托境内合计 (所有 entrust1_amount 之和)
  832. $val8_3 = 0; // 委托境外合计 (所有 entrust2_amount 之和)
  833. // 将当前项目的 fee_list 转为集合以便按 ID 快速查找
  834. $currentProjectFees = collect($v['fee_list'] ?? [])->keyBy('id');
  835. // 遍历所有可能的费用类型,确保 values 数组长度与表头一致
  836. foreach ($feeTypes as $type) {
  837. $feeData = $currentProjectFees->get($type['id']);
  838. if($feeData == null) continue;
  839. $amount = (float)($feeData['total_amount'] ?? 0);
  840. // 2. 累加委托费用 (8.1 和 8.3)
  841. $val8_1 += (float)($feeData['entrust1_amount'] ?? 0);
  842. $val8_3 += (float)($feeData['entrust2_amount'] ?? 0);
  843. if($feeData['is_other']) continue;
  844. // 填充到动态科目列
  845. $rowValues[] = $amount;
  846. // 1. 累加其他相关费用合计 (7.1)
  847. // if(! empty($feeData['is_other']) && $feeData['is_other'] == Fee::IS_OTHER_ONE) $val7_1 += $amount;
  848. }
  849. $items[] = [
  850. 'no' => $v['code'] ?? '',
  851. 'name' => $v['title'] ?? '',
  852. 'status' => (($v['state'] ?? '') == "完结" ? 3 : 2),
  853. 'type' => $v['expense_type'] ?? '费用化支出',
  854. 'values' => $rowValues,
  855. 'val7_1' => $v['other_amount'],
  856. 'val7_2' => $v['jj_other_amount'],
  857. 'val8_1' => $val8_1,
  858. 'val8_3' => $val8_3,
  859. ];
  860. }
  861. // 年份获取逻辑
  862. $year = Carbon::parse($data['year'])
  863. ->setTimezone(config('app.timezone')) // 转换为 Laravel 配置的时区
  864. ->format('Y');
  865. //获取公司基本信息
  866. $company = EmployeeService::getCompanyDetail($user);
  867. // 3. 组织多 Sheet 格式数据
  868. $monthsData = [
  869. $year => [
  870. 'tax_id' => $company['code'] ?? '',
  871. 'company_name' => $company['title'] ?? '',
  872. 'items' => $items,
  873. 'dynamic_headers' => $dynamicHeaders
  874. ]
  875. ];
  876. // 4. 执行 Excel 存储
  877. $file_name = "研发支出辅助账汇总表_" . date("YmdHis") . "_" . rand(1000, 9999);
  878. $filename = $file_name . '.xlsx';
  879. Excel::store(
  880. new \App\Exports\ResearchExpenseSummaryMultipleSheetExport($monthsData),
  881. "public/export/{$filename}"
  882. );
  883. return [true, $filename];
  884. }
  885. public function exportFormalSummary(array $data, $user)
  886. {
  887. $service = new StatisticService();
  888. // 1. 调用业务逻辑获取原始数据
  889. list($status, $result) = $service->employeeAttendanceMonthStatistic($data, $user);
  890. if (!$status) return [false, $result];
  891. $rawList = $result['list'] ?? [];
  892. $feeTypes = $result['fee_type_list'] ?? [];
  893. // ================== 1. 统一表头与排序 ==================
  894. // 定义固定表头并赋予默认 sort
  895. $allHeadersTemp = [
  896. [
  897. 'id' => 'employee_salary', // 用特殊标识代表固定列
  898. 'title' => '人员人工费用',
  899. 'sort' => -1,
  900. 'is_fixed' => true
  901. ],
  902. [
  903. 'id' => 'device_depreciation',
  904. 'title' => '折旧费用',
  905. 'sort' => 1,
  906. 'is_fixed' => true
  907. ]
  908. ];
  909. // 将符合条件的动态表头合并进来
  910. foreach ($feeTypes as $value) {
  911. if (!$value['is_after']) {
  912. $allHeadersTemp[] = [
  913. 'id' => $value['id'],
  914. 'title' => $value['title'],
  915. 'sort' => (int)($value['sort'] ?? 0), // 确保是整型
  916. 'is_fixed' => false
  917. ];
  918. }
  919. }
  920. // 使用 collect 按照 sort 正序排序(值越小越靠前)
  921. $sortedHeaders = collect($allHeadersTemp)->sortBy('sort')->values()->all();
  922. // 提取出最终传给 Excel 的纯文本表头数组
  923. $dynamicHeaders = array_column($sortedHeaders, 'title');
  924. // =======================================================
  925. $items = [];
  926. foreach ($rawList as $v) {
  927. $rowValues = [];
  928. $val8_1 = 0; // 委托境内合计
  929. $val8_3 = 0; // 委托境外合计
  930. // 1. 先把当前项目所有的 fee_list 进行全量费用累加(修复漏计 Bug)
  931. $currentFeeList = $v['fee_list'] ?? [];
  932. foreach ($currentFeeList as $feeData) {
  933. $val8_1 += (float)($feeData['entrust1_amount'] ?? 0);
  934. $val8_3 += (float)($feeData['entrust2_amount'] ?? 0);
  935. }
  936. // 2. 将当前项目的 fee_list 转为集合,以便按 ID 快速查找对齐
  937. $currentProjectFees = collect($currentFeeList)->keyBy('id');
  938. // 3. 依照排序后的表头填充 Excel 列数据
  939. foreach ($sortedHeaders as $header) {
  940. if ($header['is_fixed']) {
  941. // 如果是固定的基础两项(人员人工、折旧),直接从主记录 $v 中取值
  942. $rowValues[] = (float)($v[$header['id']] ?? 0);
  943. } else {
  944. // 如果是动态科目列
  945. $feeData = $currentProjectFees->get($header['id']);
  946. if ($feeData == null) {
  947. $rowValues[] = 0.0; // 没数据补0,保证列对齐
  948. continue;
  949. }
  950. // 如果是其他费用,不填充到动态科目列中(填充 0 占位防错位)
  951. if ($feeData['is_other']) {
  952. $rowValues[] = 0.0;
  953. continue;
  954. }
  955. // 正常填充金额
  956. $rowValues[] = (float)($feeData['total_amount'] ?? 0);
  957. }
  958. }
  959. $items[] = [
  960. 'no' => $v['code'] ?? '',
  961. 'name' => $v['title'] ?? '',
  962. 'status' => (($v['state'] ?? '') == "完结" ? 3 : 2),
  963. 'start_time' => $v['start_time'],
  964. 'end_time' => $v['end_time'],
  965. 'type' => $v['expense_type'] ?? '费用化支出',
  966. 'values' => $rowValues,
  967. 'val7_1' => $v['other_amount'],
  968. 'val7_2' => $v['jj_other_amount'],
  969. 'val8_1' => $val8_1,
  970. 'val8_3' => $val8_3,
  971. ];
  972. }
  973. // 年份获取逻辑
  974. $year = Carbon::parse($data['year'])
  975. ->setTimezone(config('app.timezone')) // 转换为 Laravel 配置的时区
  976. ->format('Y');
  977. //获取公司基本信息
  978. $company = EmployeeService::getCompanyDetail($user);
  979. // 3. 组织多 Sheet 格式数据
  980. $monthsData = [
  981. $year => [
  982. 'tax_id' => $company['code'] ?? '',
  983. 'company_name' => $company['title'] ?? '',
  984. 'items' => $items,
  985. 'dynamic_headers' => $dynamicHeaders
  986. ]
  987. ];
  988. // 4. 执行 Excel 存储
  989. $file_name = "研发支出辅助账汇总表_" . date("YmdHis") . "_" . rand(1000, 9999);
  990. $filename = $file_name . '.xlsx';
  991. Excel::store(
  992. new \App\Exports\ResearchExpenseSummaryMultipleSheetExport($monthsData),
  993. "public/export/{$filename}"
  994. );
  995. return [true, $filename];
  996. }
  997. // 人员活动考勤占比
  998. public function exportActivityTimeCard(array $data, $user)
  999. {
  1000. $service = new StatisticService();
  1001. // 1. 获取统计数据
  1002. list($status, $result) = $service->itemEmployeeSalaryStatistic($data, $user);
  1003. if (!$status) return [false, $result];
  1004. $rawList = collect($result ?? []);
  1005. // 2. 按 项目名称 和 年度 联合分组
  1006. $groupedData = $rawList->groupBy(function ($item) {
  1007. $year = substr($item['month'] ?? date('Y'), 0, 4);
  1008. return $year . "-" . $item['item_title'];
  1009. });
  1010. $allProjectsData = [];
  1011. foreach ($groupedData as $groupKey => $records) {
  1012. list($year, $projectTitle) = explode('-', $groupKey);
  1013. $projectRows = [];
  1014. $groupedByMonth = $records->groupBy('month');
  1015. foreach ($groupedByMonth as $monthStr => $monthRecords) {
  1016. $monthNum = substr($monthStr, 5, 2);
  1017. $monthSubTotal = array_fill(3, 15, 0); // 索引3-17的累加器
  1018. foreach ($monthRecords as $v) {
  1019. $radioVal = (float)($v['radio'] ?? 0);
  1020. $row = [
  1021. (int)$monthNum . '月', // 0. 月份
  1022. '技术人员', // 1. 类别
  1023. $v['employee_title'] ?? '', // 2. 姓名
  1024. (float)$v['total_min'], // 3. 应出勤
  1025. (float)$v['work_minutes'], // 4. 研发出勤
  1026. ($radioVal * 100) . '%', // 5. 占比 (字符串)
  1027. (float)$v['salary'], // 6. 归集工资
  1028. (float)$v['social_insurance'],// 7. 归集社保
  1029. (float)$v['public_housing_fund'], // 8. 归集公积金
  1030. (float)$v['work_salary'], // 9. 确定工资
  1031. (float)$v['work_social_insurance'], // 10. 确定社保
  1032. (float)$v['work_public_housing_fund'], // 11. 确定公积金
  1033. (float)$v['work_salary'], // 12. 研发确定总工资
  1034. (float)$v['work_social_insurance'], // 13. 研发确定总社保
  1035. (float)$v['work_public_housing_fund'], // 14. 研发确定总公积金
  1036. 0, 0, 0 // 15, 16, 17. 调整金额
  1037. ];
  1038. $projectRows[] = $row;
  1039. // 累加月份小计 (跳过索引5的百分比字符串)
  1040. for ($i = 3; $i <= 14; $i++) {
  1041. if ($i == 5) continue;
  1042. $monthSubTotal[$i] += (float)$row[$i];
  1043. }
  1044. }
  1045. // 构造月份小计行 (重新计算占比)
  1046. $mRadio = $monthSubTotal[3] > 0 ? round($monthSubTotal[4] / $monthSubTotal[3] * 100, 2) . '%' : '0%';
  1047. $projectRows[] = [
  1048. '小计:', '', '', $monthSubTotal[3], $monthSubTotal[4], $mRadio,
  1049. $monthSubTotal[6], $monthSubTotal[7], $monthSubTotal[8],
  1050. $monthSubTotal[9], $monthSubTotal[10], $monthSubTotal[11],
  1051. $monthSubTotal[12], $monthSubTotal[13], $monthSubTotal[14],
  1052. 0, 0, 0
  1053. ];
  1054. }
  1055. // 计算整年合计 (避开小计行,避开非数字)
  1056. $yearTotal = array_fill(3, 15, 0);
  1057. foreach ($projectRows as $row) {
  1058. if ($row[0] !== '小计:' && $row[0] !== '合计') {
  1059. for ($i = 3; $i <= 14; $i++) {
  1060. if ($i == 5) continue;
  1061. $yearTotal[$i] += (float)$row[$i];
  1062. }
  1063. }
  1064. }
  1065. $yRadio = $yearTotal[3] > 0 ? round($yearTotal[4] / $yearTotal[3] * 100, 2) . '%' : '0%';
  1066. $projectRows[] = [
  1067. '合计', '', '', $yearTotal[3], $yearTotal[4], $yRadio,
  1068. $yearTotal[6], $yearTotal[7], $yearTotal[8],
  1069. $yearTotal[9], $yearTotal[10], $yearTotal[11],
  1070. $yearTotal[12], $yearTotal[13], $yearTotal[14],
  1071. 0, 0, 0
  1072. ];
  1073. $allProjectsData[$groupKey] = [
  1074. 'project' => $projectTitle,
  1075. 'year' => $year,
  1076. 'data' => $projectRows
  1077. ];
  1078. }
  1079. $filename = "人员活动考勤占比统计表_" . date("YmdHis") . '.xlsx';
  1080. \Maatwebsite\Excel\Facades\Excel::store(
  1081. new \App\Exports\ManActivityTimeCardMultipleSheetExport($allProjectsData),
  1082. "public/export/{$filename}"
  1083. );
  1084. return [true, $filename];
  1085. }
  1086. //业研究开发活动汇总表
  1087. public function exportEnterpriseRdStatistic(array $data, $user)
  1088. {
  1089. $service = new StatisticService();
  1090. list($status, $result) = $service->enterpriseRdStatistic($data, $user);
  1091. if (!$status) return [false, '获取统计数据失败'];
  1092. $exportData = [];
  1093. $totalBudget = 0; // 预算总计累加器
  1094. $totalActual = 0; // 支出总计累加器
  1095. foreach ($result as $row) {
  1096. $budget = (float)($row['budget'] ?? 0);
  1097. $actual = (float)($row['actual_expenditure'] ?? 0);
  1098. $totalBudget = bcadd($totalBudget, $budget, 2);
  1099. $totalActual = bcadd($totalActual, $actual, 2);
  1100. $exportData[] = [
  1101. 'activity_name' => $row['title'] ?? '', // 研发活动名称
  1102. 'time_range' => $row['time_range'] ?? '', // 起止时间
  1103. 'from' => $row['from'] ?? '自有技术', // 起止时间
  1104. 'budget' => $budget, // 研发预算
  1105. 'actual_spending' => $actual, // 实际支出
  1106. 'tech_area' => $row['field'] ?? '', // 技术领域
  1107. 'remark' => $row['mark'] ?? '', // 备注
  1108. ];
  1109. }
  1110. $exportData[] = [
  1111. 'activity_name' => '',
  1112. 'time_range' => '',
  1113. 'from' => '',
  1114. 'budget' => $totalBudget,
  1115. 'actual_spending' => $totalActual,
  1116. 'tech_area' => '',
  1117. 'remark' => '',
  1118. ];
  1119. $file_name = "企业研究开发活动汇总表_" . date("YmdHis");
  1120. $filename = $file_name . '.xlsx';
  1121. $relative_path = "public/export/{$filename}";
  1122. \Maatwebsite\Excel\Facades\Excel::store(
  1123. new \App\Exports\CompanyRdActivityExport($exportData),
  1124. $relative_path
  1125. );
  1126. return [true, $filename];
  1127. }
  1128. //企业研究开发科技人员情况表
  1129. public function exportEnterpriseRdManStatistic(array $data, $user)
  1130. {
  1131. $service = new StatisticService();
  1132. list($status, $result) = $service->enterpriseRdManStatistic($data, $user);
  1133. if (!$status) return [false, '获取人员统计数据失败'];
  1134. // 2. 映射数据到导出类需要的字段格式
  1135. $exportData = [];
  1136. foreach ($result as $row) {
  1137. $exportData[] = [
  1138. 'name' => $row['title'] ?? '', // 姓名 (对应模型里的 title 字段)
  1139. 'id_card' => $row['id_card'] ?? '', // 身份证号码
  1140. 'education' => Employee::Education[$row['education']] ?? "", // 学历
  1141. 'major' => $row['major'] ?? '', // 专业
  1142. 'title_level' => $row['p_title'] ?? '', // 职称/职业资格
  1143. 'department_job' => $row['position_new'] ?? '', // 部门/岗位
  1144. 'employment_type' => $row['employee_type_title'] ?? "", // 聘用类型
  1145. ];
  1146. }
  1147. // 3. 定义文件名和路径
  1148. $file_name = "企业研究开发科技人员情况表_" . date("YmdHis");
  1149. $filename = $file_name . '.xlsx';
  1150. $relative_path = "public/export/{$filename}";
  1151. \Maatwebsite\Excel\Facades\Excel::store(
  1152. new \App\Exports\TechnicalStaffExport($exportData),
  1153. $relative_path
  1154. );
  1155. return [true, $filename];
  1156. }
  1157. //项目研发活动人员情况表
  1158. public function exportEnterpriseRdItemStatistic(array $data, $user)
  1159. {
  1160. $service = new StatisticService();
  1161. list($status, $result) = $service->enterpriseRdItemStatistic($data, $user);
  1162. if (!$status) return [false, '获取统计数据失败'];
  1163. // 2. 映射数据到导出类需要的字段格式
  1164. $exportData = [];
  1165. foreach ($result as $row) {
  1166. $exportData[] = [
  1167. 'title' => $row['title'] ?? '', // 姓名 (对应模型里的 title 字段)
  1168. 'education' => Employee::Education[$row['education']] ?? "", // 学历
  1169. 'major' => $row['major'] ?? '', // 专业
  1170. 'p_title' => $row['p_title'] ?? '', // 职称/职业资格
  1171. 'item_title' => $row['item_title'] ?? '', // 项目
  1172. 'item_role' => $row['item_role'] ?? '', // 项目角色
  1173. 'depart_title' => $row['depart_title'] ?? '', // 部门
  1174. 'duty' => $row['duty'] ?? "", // 职责
  1175. ];
  1176. }
  1177. // 3. 定义文件名和路径
  1178. $file_name = "项目研发活动人员情况表_" . date("YmdHis");
  1179. $filename = $file_name . '.xlsx';
  1180. $relative_path = "public/export/{$filename}";
  1181. \Maatwebsite\Excel\Facades\Excel::store(
  1182. new \App\Exports\ProjectStaffExport($exportData),
  1183. $relative_path
  1184. );
  1185. return [true, $filename];
  1186. }
  1187. public function itemMissionProgressList($ergs,$user){
  1188. // 导出数据
  1189. $return = [];
  1190. $header_default = $user['e_header_default'];
  1191. $column = array_column($header_default,'export');
  1192. $header = array_column($header_default,'value');
  1193. $service = new ItemService();
  1194. $model = $service->itemMissionProgressListCommon($ergs, $user);
  1195. $model->chunk(500,function ($data) use(&$return,$column,$service, $user){
  1196. $data = $data->toArray();
  1197. $list['data'] = $data;
  1198. //订单数据
  1199. $list = $service->fillItemMissionProgressList($list, $user);
  1200. //返回数据
  1201. $this->fillData($list['data'], $column, $return);
  1202. });
  1203. return [true, $this->saveExportData($return,$header)];
  1204. }
  1205. public function saveExportData($data, $headers, $type = 'default',$file_name = ''){
  1206. if(empty($file_name)) $file_name = self::$filename . "_". date("Y-m-d") . "_". rand(1000,9999);
  1207. $filename = $file_name . '.' . 'xlsx';
  1208. $bool = Excel::store(new ExportOrder($data,$type,$headers),"/public/export/{$filename}", null, 'Xlsx', []);
  1209. return $filename;
  1210. }
  1211. public function saveExportData2($data,$type = 1,$column,$timeRow, $file_name = ''){
  1212. if(empty($file_name)) $file_name = self::$filename . "_". date("Y-m-d") . "_". rand(1000,9999);
  1213. $filename = $file_name . '.' . 'xlsx';
  1214. \Maatwebsite\Excel\Facades\Excel::store(new MultiSheetExport($data, $type,$column,$timeRow),"/public/export/{$filename}", null, 'Xlsx', []);
  1215. return $filename;
  1216. }
  1217. }