ExportFileService.php 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  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. // 结构:[ '2024-04' => [ 'days' => 30, 'data' => [...] ], ... ]
  456. $monthsData = [];
  457. // 按月分组数据
  458. $groupedByMonth = $sourceData->groupBy(function ($item) {
  459. return date('Y年m月', strtotime($item['order_date']));
  460. });
  461. //获取公司基本信息
  462. $company = EmployeeService::getCompanyDetail($user);
  463. foreach ($groupedByMonth as $monthName => $monthItems) {
  464. // A. 计算该月总天数
  465. // 转换 '2024年04月' 为 '2024-04' 获取天数
  466. $formatMonth = str_replace(['年', '月'], ['-', ''], $monthName);
  467. $daysInMonth = date('t', strtotime($formatMonth . '-01'));
  468. // B. 进一步按 项目+人员 分组,因为一行显示一个项目一个人的全月工时
  469. $groupedByUserItem = $monthItems->groupBy(function ($item) {
  470. return $item['item_code'] . '_' . $item['employee_id'];
  471. });
  472. $sheetRows = [];
  473. foreach ($groupedByUserItem as $key => $records) {
  474. $first = $records->first();
  475. // 初始化行:前两列是 项目名称 和 姓名
  476. $row = [
  477. $first['item_title'],
  478. $first['employee_name']
  479. ];
  480. // C. 循环 1 号到该月最后一天,填充工时
  481. // 将该员工该项目在这个月的记录转为 日期 => 工时 的映射
  482. $dayMap = $records->keyBy(function($r){
  483. return (int)date('d', strtotime($r['order_date']));
  484. });
  485. for ($d = 1; $d <= $daysInMonth; $d++) {
  486. $workHour = $dayMap->get($d)['total_work_hours'] ?? '';
  487. // 如果工时为 0 或空,按你要求的格式传空字符串
  488. $row[] = ($workHour > 0) ?(float) $workHour : '';
  489. }
  490. $sheetRows[] = $row;
  491. }
  492. $monthsData[$monthName] = [
  493. 'days' => (int)$daysInMonth,
  494. 'data' => $sheetRows,
  495. 'company_name' => $company['title'] ?? '',
  496. ];
  497. }
  498. $file_name = "人员月工时统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  499. $filename = $file_name . '.' . 'xlsx';
  500. $bool = Excel::store(new ManMonthlyWorkHourMultipleSheetExport($monthsData), "/public/export/{$filename}", null, 'Xlsx', []);
  501. return [true, $filename];
  502. }
  503. // 项目设备折旧
  504. public function exportDeviceZj(array $data, $user)
  505. {
  506. $service = new StatisticService();
  507. list($status, $result) = $service->itemDeviceMonthStatistic($data, $user);
  508. if (!$status) return $result;
  509. // 2. 将数据按 [项目编号][月份] 进行分组
  510. // 预期结构:$monthsData['RD01']['months']['2025-01'] = [设备1, 设备2...]
  511. $groupedData = collect($result)->groupBy('item_code');
  512. $finalExportData = [];
  513. foreach ($groupedData as $itemCode => $itemRecords) {
  514. $firstRecord = $itemRecords->first();
  515. $projectName = $firstRecord['item_title'];
  516. $firstMonth = $firstRecord['month'];
  517. $year = substr($firstMonth, 0, 4);
  518. // 3. 构造新的 Key:年-项目 (例如: 2026-53code)
  519. $newSheetKey = $year . '年度项目' . $itemCode;
  520. // 按月份进一步分组
  521. $monthGroups = $itemRecords->groupBy('month');
  522. $monthsPayload = [];
  523. foreach ($monthGroups as $month => $devices) {
  524. $monthData = [];
  525. foreach ($devices as $dev) {
  526. $monthData[] = [
  527. 'device_name' => $dev['device_title'],
  528. 'original_value' => $dev['device_original'], // 设备原值
  529. 'total_depreciation' => $dev['total_depreciatio'], // 当月总折旧
  530. 'project_hours' => $dev['hours'], // 本项目工时
  531. 'total_hours' => $dev['total_hours'], // 当月总工时
  532. 'ratio' => bcmul($dev['ratio'], 100,2), // 研发工时占比
  533. 'allocated_depreciation' => $dev['allocated_depreciatio'], // 本项目分摊折旧
  534. ];
  535. }
  536. $monthsPayload[$month] = $monthData;
  537. }
  538. // 构造 Sheet 所需结构
  539. $finalExportData[$newSheetKey] = [
  540. 'project_name' => $projectName,
  541. 'months' => $monthsPayload
  542. ];
  543. }
  544. $file_name = "项目设备折旧费用统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  545. $filename = $file_name . '.' . 'xlsx';
  546. $bool = Excel::store(new ProjectDepreciationMultipleSheetExport($finalExportData), "/public/export/{$filename}", null, 'Xlsx', []);
  547. return [true, $filename];
  548. }
  549. // 项目工资分摊
  550. public function exportItemSalaryFT(array $data, $user)
  551. {
  552. $service = new StatisticService();
  553. list($status, $result) = $service->itemDaySalaryStatistic($data, $user);
  554. if (!$status) return $result;
  555. $sourceData = collect($result);
  556. $groupedByMonth = $sourceData->groupBy('month');
  557. $monthsData = [];
  558. foreach ($groupedByMonth as $month => $monthRecords) {
  559. // A. 获取本月参与的所有唯一项目编码
  560. $monthProjects = $monthRecords->pluck('item_code')->unique()->sort()->values()->all();
  561. // B. 按人员分组组织数据
  562. $groupedByEmployee = $monthRecords->groupBy('employee_id');
  563. $sheetRows = [];
  564. $index = 1;
  565. // 初始化列合计
  566. $colTotals = [
  567. 'total_salary' => 0,
  568. 'total_min_hours' => 0, // 月总工时合计
  569. 'project_days' => array_fill_keys($monthProjects, 0),
  570. 'project_salary' => array_fill_keys($monthProjects, 0),
  571. 'total_attendance_days' => 0, // 合计工时列的合计
  572. ];
  573. foreach ($groupedByEmployee as $employeeId => $records) {
  574. $first = $records->first();
  575. $empMonthSalary = (float)$first['total_salary'];
  576. $empTotalHours = $first['total_hours'];
  577. // 1-4列:序号、姓名、工资、月总工时
  578. $row = [$index++, $first['employee_title'], $empMonthSalary, $empTotalHours];
  579. // 5. 动态项目工时列
  580. $empMap = $records->keyBy('item_code');
  581. $rowProjectDaysSum = 0;
  582. foreach ($monthProjects as $code) {
  583. if ($empMap->has($code)) {
  584. $record = $empMap->get($code);
  585. $days = (float)($record['work_hours'] ?? 0);
  586. } else {
  587. $days = 0;
  588. }
  589. $row[] = $days > 0 ? $days : '';
  590. $rowProjectDaysSum += $days;
  591. $colTotals['project_days'][$code] += $days;
  592. }
  593. // 6. 合计工时列
  594. $row[] = $rowProjectDaysSum;
  595. $colTotals['total_attendance_days'] += $rowProjectDaysSum;
  596. // 7. 动态项目金额列
  597. foreach ($monthProjects as $code) {
  598. $salary = $empMap->has($code) ? (float)$empMap->get($code)['allocated_salary'] : 0;
  599. $row[] = $salary > 0 ? $salary : '';
  600. $colTotals['project_salary'][$code] += $salary;
  601. }
  602. // 8. 总计工资列
  603. $row[] = $empMonthSalary;
  604. // 累加合计
  605. $colTotals['total_salary'] += $empMonthSalary;
  606. $colTotals['total_min_hours'] += $empTotalHours;
  607. $sheetRows[] = $row;
  608. }
  609. // C. 构造合计行
  610. $totalRow = ['合计', '', $colTotals['total_salary'], $colTotals['total_min_hours']];
  611. foreach ($monthProjects as $code) { $totalRow[] = $colTotals['project_days'][$code]; }
  612. $totalRow[] = $colTotals['total_attendance_days'];
  613. foreach ($monthProjects as $code) { $totalRow[] = $colTotals['project_salary'][$code]; }
  614. $totalRow[] = $colTotals['total_salary'];
  615. $sheetRows[] = $totalRow;
  616. $monthsData[$month] = [
  617. 'projects' => $monthProjects,
  618. 'data' => $sheetRows
  619. ];
  620. }
  621. //获取公司基本信息
  622. $company = EmployeeService::getCompanyDetail($user);
  623. $file_name = "项目工资分摊统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  624. $filename = $file_name . '.xlsx';
  625. Excel::store(
  626. new ItemSalaryFTMultipleSheetExport($monthsData, $company['title'] ?? ''),
  627. "/public/export/{$filename}"
  628. );
  629. return [true, $filename];
  630. }
  631. // 年度研发支出辅助账汇总表
  632. public function exportResearchExpense1(array $data, $user)
  633. {
  634. $service = new StatisticService();
  635. list($status, $result) = $service->auxiliaryStatistic($data, $user);
  636. if (!$status) return [false, $result];
  637. $fee_type_list = $result['fee_type_list'];
  638. $raw_list = $result['list'];
  639. if(empty($raw_list)) return [false, '暂无导出数据'];
  640. // 预读年份和动态表头长度
  641. $year = date("Y", strtotime($raw_list[0]['voucher_date']));
  642. $company = Depart::where('id', $user['top_depart_id'])->value('title');
  643. $dynamicHeaderTitles = array_column($fee_type_list, 'title');
  644. $dynamicCount = count($dynamicHeaderTitles);
  645. $totalColCount = 8 + $dynamicCount + 2; // 基础6 + 固定2 + 动态N + 委托2
  646. $groupedData = [];
  647. foreach ($raw_list as $row) {
  648. $sheetKey = $year . $row['code'];
  649. if (!isset($groupedData[$sheetKey])) {
  650. $groupedData[$sheetKey] = [
  651. 'project' => [
  652. 'code' => $row['code'],
  653. 'name' => $row['title'],
  654. ],
  655. 'dynamic_headers' => $dynamicHeaderTitles,
  656. 'data' => [],
  657. 'year' => $company . $year,
  658. 'totals' => array_fill(0, $totalColCount, 0)
  659. ];
  660. $groupedData[$sheetKey]['totals'][0] = '合计'; // 第一列标识
  661. }
  662. // 组织明细行数据 (逻辑不变)
  663. $excelRow = [
  664. $row['voucher_date'], $row['voucher_type'], $row['voucher_no'], $row['voucher_remark'],
  665. (float)$row['voucher_amount'],
  666. (float)$row['aggregation_amount'],
  667. ($row['type'] == 1 ? (float)$row['total_amount'] : 0), // 人员
  668. ($row['type'] == 2 ? (float)$row['total_amount'] : 0) // 折旧
  669. ];
  670. // 动态列填充
  671. foreach ($fee_type_list as $feeId => $feeItem) {
  672. $excelRow[] = ($row['type'] == 3 && $row['fee_id'] == $feeId) ? (float)$row['total_amount'] : 0;
  673. }
  674. // 委托列
  675. $excelRow[] = (float)($row['entrust1_amount'] ?? 0);
  676. $excelRow[] = (float)($row['entrust2_amount'] ?? 0);
  677. // 【性能优化】:同步累加金额 (从索引 4 开始是金额列)
  678. for ($i = 4; $i < $totalColCount; $i++) {
  679. $groupedData[$sheetKey]['totals'][$i] += $excelRow[$i];
  680. }
  681. $groupedData[$sheetKey]['data'][] = $excelRow;
  682. }
  683. foreach ($groupedData as &$group) {
  684. $group['data'][] = $group['totals'];
  685. unset($group['totals']); // 释放内存
  686. }
  687. // 8. 导出逻辑保持不变
  688. $file_name = "年度研发支出辅助账汇总统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  689. $filename = $file_name . '.xlsx';
  690. Excel::store(
  691. new ResearchExpenseMultipleSheetExport($groupedData),
  692. "public/export/{$filename}"
  693. );
  694. return [true, $filename];
  695. }
  696. // 年度研发支出辅助账汇总表
  697. public function exportResearchExpense(array $data, $user)
  698. {
  699. $service = new StatisticService();
  700. list($status, $result) = $service->auxiliaryStatistic($data, $user);
  701. if (!$status) return [false, $result];
  702. $fee_type_list = $result['fee_type_list'];
  703. $raw_list = $result['list'];
  704. if(empty($raw_list)) return [false, '暂无导出数据'];
  705. // 预读年份和基本信息
  706. $year = date("Y", strtotime($raw_list[0]['voucher_date']));
  707. $company = Depart::where('id', $user['top_depart_id'])->value('title');
  708. // ================== 【核心修改 1:重构与排序所有金额列】 ==================
  709. // 1. 定义固定的人员和折旧列配置并赋予 sort
  710. $amountColumnsConfig = [
  711. [
  712. 'type_key' => 'type_1', // 对应原逻辑 type == 1 (人员)
  713. 'title' => '人员人工费用',
  714. 'sort' => -1,
  715. ],
  716. [
  717. 'type_key' => 'type_2', // 对应原逻辑 type == 2 (折旧)
  718. 'title' => '折旧费用',
  719. 'sort' => 1,
  720. ]
  721. ];
  722. // 2. 将动态费用类型塞入同一个配置池中
  723. foreach ($fee_type_list as $feeId => $feeItem) {
  724. $amountColumnsConfig[] = [
  725. 'type_key' => 'fee_' . $feeId, // 对应原逻辑 type == 3 && fee_id == $feeId
  726. 'fee_id' => $feeId,
  727. 'title' => $feeItem['title'] ?? '',
  728. 'sort' => (int)($feeItem['sort'] ?? 0),
  729. ];
  730. }
  731. // 3. 按照 sort 正序排序(值越小越靠前)
  732. $sortedAmountColumns = collect($amountColumnsConfig)->sortBy('sort')->values()->all();
  733. // 4. 提取出最终的动态表头名称供 Excel 使用
  734. $dynamicHeaderTitles = array_column($sortedAmountColumns, 'title');
  735. // 5. 计算总列数:
  736. // 前面基础4列(日期、凭证种类、凭证号、摘要)
  737. // 加上 2列(记账凭证金额、本期归集金额)
  738. // 加上 排序后的所有科目列数
  739. // 加上 2列(委托境内、委托境外)
  740. $baseColCount = 6; // 前面基础共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:依照排序配置填充科目金额】 ==================
  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. // 动态费用科目
  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. 'type' => $v['expense_type'] ?? '费用化支出',
  964. 'values' => $rowValues,
  965. 'val7_1' => $v['other_amount'],
  966. 'val7_2' => $v['jj_other_amount'],
  967. 'val8_1' => $val8_1,
  968. 'val8_3' => $val8_3,
  969. ];
  970. }
  971. // 年份获取逻辑
  972. $year = Carbon::parse($data['year'])
  973. ->setTimezone(config('app.timezone')) // 转换为 Laravel 配置的时区
  974. ->format('Y');
  975. //获取公司基本信息
  976. $company = EmployeeService::getCompanyDetail($user);
  977. // 3. 组织多 Sheet 格式数据
  978. $monthsData = [
  979. $year => [
  980. 'tax_id' => $company['code'] ?? '',
  981. 'company_name' => $company['title'] ?? '',
  982. 'items' => $items,
  983. 'dynamic_headers' => $dynamicHeaders
  984. ]
  985. ];
  986. // 4. 执行 Excel 存储
  987. $file_name = "研发支出辅助账汇总表_" . date("YmdHis") . "_" . rand(1000, 9999);
  988. $filename = $file_name . '.xlsx';
  989. Excel::store(
  990. new \App\Exports\ResearchExpenseSummaryMultipleSheetExport($monthsData),
  991. "public/export/{$filename}"
  992. );
  993. return [true, $filename];
  994. }
  995. // 人员活动考勤占比
  996. public function exportActivityTimeCard(array $data, $user)
  997. {
  998. $service = new StatisticService();
  999. // 1. 获取统计数据
  1000. list($status, $result) = $service->itemEmployeeSalaryStatistic($data, $user);
  1001. if (!$status) return [false, $result];
  1002. $rawList = collect($result ?? []);
  1003. // 2. 按 项目名称 和 年度 联合分组
  1004. $groupedData = $rawList->groupBy(function ($item) {
  1005. $year = substr($item['month'] ?? date('Y'), 0, 4);
  1006. return $year . "-" . $item['item_title'];
  1007. });
  1008. $allProjectsData = [];
  1009. foreach ($groupedData as $groupKey => $records) {
  1010. list($year, $projectTitle) = explode('-', $groupKey);
  1011. $projectRows = [];
  1012. $groupedByMonth = $records->groupBy('month');
  1013. foreach ($groupedByMonth as $monthStr => $monthRecords) {
  1014. $monthNum = substr($monthStr, 5, 2);
  1015. $monthSubTotal = array_fill(3, 15, 0); // 索引3-17的累加器
  1016. foreach ($monthRecords as $v) {
  1017. $radioVal = (float)($v['radio'] ?? 0);
  1018. $row = [
  1019. (int)$monthNum . '月', // 0. 月份
  1020. '技术人员', // 1. 类别
  1021. $v['employee_title'] ?? '', // 2. 姓名
  1022. (float)$v['total_min'], // 3. 应出勤
  1023. (float)$v['work_minutes'], // 4. 研发出勤
  1024. ($radioVal * 100) . '%', // 5. 占比 (字符串)
  1025. (float)$v['salary'], // 6. 归集工资
  1026. (float)$v['social_insurance'],// 7. 归集社保
  1027. (float)$v['public_housing_fund'], // 8. 归集公积金
  1028. (float)$v['work_salary'], // 9. 确定工资
  1029. (float)$v['work_social_insurance'], // 10. 确定社保
  1030. (float)$v['work_public_housing_fund'], // 11. 确定公积金
  1031. (float)$v['work_salary'], // 12. 研发确定总工资
  1032. (float)$v['work_social_insurance'], // 13. 研发确定总社保
  1033. (float)$v['work_public_housing_fund'], // 14. 研发确定总公积金
  1034. 0, 0, 0 // 15, 16, 17. 调整金额
  1035. ];
  1036. $projectRows[] = $row;
  1037. // 累加月份小计 (跳过索引5的百分比字符串)
  1038. for ($i = 3; $i <= 14; $i++) {
  1039. if ($i == 5) continue;
  1040. $monthSubTotal[$i] += (float)$row[$i];
  1041. }
  1042. }
  1043. // 构造月份小计行 (重新计算占比)
  1044. $mRadio = $monthSubTotal[3] > 0 ? round($monthSubTotal[4] / $monthSubTotal[3] * 100, 2) . '%' : '0%';
  1045. $projectRows[] = [
  1046. '小计:', '', '', $monthSubTotal[3], $monthSubTotal[4], $mRadio,
  1047. $monthSubTotal[6], $monthSubTotal[7], $monthSubTotal[8],
  1048. $monthSubTotal[9], $monthSubTotal[10], $monthSubTotal[11],
  1049. $monthSubTotal[12], $monthSubTotal[13], $monthSubTotal[14],
  1050. 0, 0, 0
  1051. ];
  1052. }
  1053. // 计算整年合计 (避开小计行,避开非数字)
  1054. $yearTotal = array_fill(3, 15, 0);
  1055. foreach ($projectRows as $row) {
  1056. if ($row[0] !== '小计:' && $row[0] !== '合计') {
  1057. for ($i = 3; $i <= 14; $i++) {
  1058. if ($i == 5) continue;
  1059. $yearTotal[$i] += (float)$row[$i];
  1060. }
  1061. }
  1062. }
  1063. $yRadio = $yearTotal[3] > 0 ? round($yearTotal[4] / $yearTotal[3] * 100, 2) . '%' : '0%';
  1064. $projectRows[] = [
  1065. '合计', '', '', $yearTotal[3], $yearTotal[4], $yRadio,
  1066. $yearTotal[6], $yearTotal[7], $yearTotal[8],
  1067. $yearTotal[9], $yearTotal[10], $yearTotal[11],
  1068. $yearTotal[12], $yearTotal[13], $yearTotal[14],
  1069. 0, 0, 0
  1070. ];
  1071. $allProjectsData[$groupKey] = [
  1072. 'project' => $projectTitle,
  1073. 'year' => $year,
  1074. 'data' => $projectRows
  1075. ];
  1076. }
  1077. $filename = "人员活动考勤占比统计表_" . date("YmdHis") . '.xlsx';
  1078. \Maatwebsite\Excel\Facades\Excel::store(
  1079. new \App\Exports\ManActivityTimeCardMultipleSheetExport($allProjectsData),
  1080. "public/export/{$filename}"
  1081. );
  1082. return [true, $filename];
  1083. }
  1084. //业研究开发活动汇总表
  1085. public function exportEnterpriseRdStatistic(array $data, $user)
  1086. {
  1087. $service = new StatisticService();
  1088. list($status, $result) = $service->enterpriseRdStatistic($data, $user);
  1089. if (!$status) return [false, '获取统计数据失败'];
  1090. $exportData = [];
  1091. $totalBudget = 0; // 预算总计累加器
  1092. $totalActual = 0; // 支出总计累加器
  1093. foreach ($result as $row) {
  1094. $budget = (float)($row['budget'] ?? 0);
  1095. $actual = (float)($row['actual_expenditure'] ?? 0);
  1096. $totalBudget = bcadd($totalBudget, $budget, 2);
  1097. $totalActual = bcadd($totalActual, $actual, 2);
  1098. $exportData[] = [
  1099. 'activity_name' => $row['title'] ?? '', // 研发活动名称
  1100. 'time_range' => $row['time_range'] ?? '', // 起止时间
  1101. 'from' => $row['from'] ?? '自有技术', // 起止时间
  1102. 'budget' => $budget, // 研发预算
  1103. 'actual_spending' => $actual, // 实际支出
  1104. 'tech_area' => $row['field'] ?? '', // 技术领域
  1105. 'remark' => $row['mark'] ?? '', // 备注
  1106. ];
  1107. }
  1108. $exportData[] = [
  1109. 'activity_name' => '',
  1110. 'time_range' => '',
  1111. 'from' => '',
  1112. 'budget' => $totalBudget,
  1113. 'actual_spending' => $totalActual,
  1114. 'tech_area' => '',
  1115. 'remark' => '',
  1116. ];
  1117. $file_name = "企业研究开发活动汇总表_" . date("YmdHis");
  1118. $filename = $file_name . '.xlsx';
  1119. $relative_path = "public/export/{$filename}";
  1120. \Maatwebsite\Excel\Facades\Excel::store(
  1121. new \App\Exports\CompanyRdActivityExport($exportData),
  1122. $relative_path
  1123. );
  1124. return [true, $filename];
  1125. }
  1126. //企业研究开发科技人员情况表
  1127. public function exportEnterpriseRdManStatistic(array $data, $user)
  1128. {
  1129. $service = new StatisticService();
  1130. list($status, $result) = $service->enterpriseRdManStatistic($data, $user);
  1131. if (!$status) return [false, '获取人员统计数据失败'];
  1132. // 2. 映射数据到导出类需要的字段格式
  1133. $exportData = [];
  1134. foreach ($result as $row) {
  1135. $exportData[] = [
  1136. 'name' => $row['title'] ?? '', // 姓名 (对应模型里的 title 字段)
  1137. 'id_card' => $row['id_card'] ?? '', // 身份证号码
  1138. 'education' => Employee::Education[$row['education']] ?? "", // 学历
  1139. 'major' => $row['major'] ?? '', // 专业
  1140. 'title_level' => $row['p_title'] ?? '', // 职称/职业资格
  1141. 'department_job' => $row['position_new'] ?? '', // 部门/岗位
  1142. 'employment_type' => $row['employee_type_title'] ?? "", // 聘用类型
  1143. ];
  1144. }
  1145. // 3. 定义文件名和路径
  1146. $file_name = "企业研究开发科技人员情况表_" . date("YmdHis");
  1147. $filename = $file_name . '.xlsx';
  1148. $relative_path = "public/export/{$filename}";
  1149. \Maatwebsite\Excel\Facades\Excel::store(
  1150. new \App\Exports\TechnicalStaffExport($exportData),
  1151. $relative_path
  1152. );
  1153. return [true, $filename];
  1154. }
  1155. //项目研发活动人员情况表
  1156. public function exportEnterpriseRdItemStatistic(array $data, $user)
  1157. {
  1158. $service = new StatisticService();
  1159. list($status, $result) = $service->enterpriseRdItemStatistic($data, $user);
  1160. if (!$status) return [false, '获取统计数据失败'];
  1161. // 2. 映射数据到导出类需要的字段格式
  1162. $exportData = [];
  1163. foreach ($result as $row) {
  1164. $exportData[] = [
  1165. 'title' => $row['title'] ?? '', // 姓名 (对应模型里的 title 字段)
  1166. 'education' => Employee::Education[$row['education']] ?? "", // 学历
  1167. 'major' => $row['major'] ?? '', // 专业
  1168. 'p_title' => $row['p_title'] ?? '', // 职称/职业资格
  1169. 'item_title' => $row['item_title'] ?? '', // 项目
  1170. 'item_role' => $row['item_role'] ?? '', // 项目角色
  1171. 'depart_title' => $row['depart_title'] ?? '', // 部门
  1172. 'duty' => $row['duty'] ?? "", // 职责
  1173. ];
  1174. }
  1175. // 3. 定义文件名和路径
  1176. $file_name = "项目研发活动人员情况表_" . date("YmdHis");
  1177. $filename = $file_name . '.xlsx';
  1178. $relative_path = "public/export/{$filename}";
  1179. \Maatwebsite\Excel\Facades\Excel::store(
  1180. new \App\Exports\ProjectStaffExport($exportData),
  1181. $relative_path
  1182. );
  1183. return [true, $filename];
  1184. }
  1185. public function saveExportData($data, $headers, $type = 'default',$file_name = ''){
  1186. if(empty($file_name)) $file_name = self::$filename . "_". date("Y-m-d") . "_". rand(1000,9999);
  1187. $filename = $file_name . '.' . 'xlsx';
  1188. $bool = Excel::store(new ExportOrder($data,$type,$headers),"/public/export/{$filename}", null, 'Xlsx', []);
  1189. return $filename;
  1190. }
  1191. public function saveExportData2($data,$type = 1,$column,$timeRow, $file_name = ''){
  1192. if(empty($file_name)) $file_name = self::$filename . "_". date("Y-m-d") . "_". rand(1000,9999);
  1193. $filename = $file_name . '.' . 'xlsx';
  1194. \Maatwebsite\Excel\Facades\Excel::store(new MultiSheetExport($data, $type,$column,$timeRow),"/public/export/{$filename}", null, 'Xlsx', []);
  1195. return $filename;
  1196. }
  1197. }