ExportFileService.php 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  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. $empTotalCQHours = $first['total_cq_hours'];
  581. // 1-4列:序号、姓名、工资、当月出勤总工时
  582. $row = [$index++, $first['employee_title'], $empMonthSalary, $empTotalCQHours];
  583. // 5. 动态项目工时列
  584. $empMap = $records->keyBy('item_code');
  585. $rowProjectDaysSum = 0;
  586. foreach ($monthProjects as $code) {
  587. if ($empMap->has($code)) {
  588. $record = $empMap->get($code);
  589. $days = (float)($record['work_hours'] ?? 0);
  590. } else {
  591. $days = 0;
  592. }
  593. $row[] = $days > 0 ? $days : '';
  594. $rowProjectDaysSum += $days;
  595. $colTotals['project_days'][$code] += $days;
  596. }
  597. // 6. 合计工时列
  598. $row[] = $rowProjectDaysSum;
  599. $colTotals['total_attendance_days'] += $rowProjectDaysSum;
  600. // 7. 动态项目金额列
  601. foreach ($monthProjects as $code) {
  602. $salary = $empMap->has($code) ? (float)$empMap->get($code)['allocated_salary'] : 0;
  603. $row[] = $salary > 0 ? $salary : '';
  604. $colTotals['project_salary'][$code] += $salary;
  605. }
  606. // 8. 总计工资列
  607. $row[] = $empMonthSalary;
  608. // 累加合计
  609. $colTotals['total_salary'] += $empMonthSalary;
  610. $colTotals['total_min_hours'] += $empTotalHours;
  611. $sheetRows[] = $row;
  612. }
  613. // C. 构造合计行
  614. $totalRow = ['合计', '', $colTotals['total_salary'], $colTotals['total_min_hours']];
  615. foreach ($monthProjects as $code) { $totalRow[] = $colTotals['project_days'][$code]; }
  616. $totalRow[] = $colTotals['total_attendance_days'];
  617. foreach ($monthProjects as $code) { $totalRow[] = $colTotals['project_salary'][$code]; }
  618. $totalRow[] = $colTotals['total_salary'];
  619. $sheetRows[] = $totalRow;
  620. $monthsData[$month] = [
  621. 'projects' => $monthProjects,
  622. 'data' => $sheetRows
  623. ];
  624. }
  625. //获取公司基本信息
  626. $company = EmployeeService::getCompanyDetail($user);
  627. $file_name = "项目工资分摊统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  628. $filename = $file_name . '.xlsx';
  629. Excel::store(
  630. new ItemSalaryFTMultipleSheetExport($monthsData, $company['title'] ?? ''),
  631. "/public/export/{$filename}"
  632. );
  633. return [true, $filename];
  634. }
  635. // 年度研发支出辅助账汇总表
  636. public function exportResearchExpense1(array $data, $user)
  637. {
  638. $service = new StatisticService();
  639. list($status, $result) = $service->auxiliaryStatistic($data, $user);
  640. if (!$status) return [false, $result];
  641. $fee_type_list = $result['fee_type_list'];
  642. $raw_list = $result['list'];
  643. if(empty($raw_list)) return [false, '暂无导出数据'];
  644. // 预读年份和动态表头长度
  645. $year = date("Y", strtotime($raw_list[0]['voucher_date']));
  646. $company = Depart::where('id', $user['top_depart_id'])->value('title');
  647. $dynamicHeaderTitles = array_column($fee_type_list, 'title');
  648. $dynamicCount = count($dynamicHeaderTitles);
  649. $totalColCount = 8 + $dynamicCount + 2; // 基础6 + 固定2 + 动态N + 委托2
  650. $groupedData = [];
  651. foreach ($raw_list as $row) {
  652. $sheetKey = $year . $row['code'];
  653. if (!isset($groupedData[$sheetKey])) {
  654. $groupedData[$sheetKey] = [
  655. 'project' => [
  656. 'code' => $row['code'],
  657. 'name' => $row['title'],
  658. ],
  659. 'dynamic_headers' => $dynamicHeaderTitles,
  660. 'data' => [],
  661. 'year' => $company . $year,
  662. 'totals' => array_fill(0, $totalColCount, 0)
  663. ];
  664. $groupedData[$sheetKey]['totals'][0] = '合计'; // 第一列标识
  665. }
  666. // 组织明细行数据 (逻辑不变)
  667. $excelRow = [
  668. $row['voucher_date'], $row['voucher_type'], $row['voucher_no'], $row['voucher_remark'],
  669. (float)$row['voucher_amount'],
  670. (float)$row['aggregation_amount'],
  671. ($row['type'] == 1 ? (float)$row['total_amount'] : 0), // 人员
  672. ($row['type'] == 2 ? (float)$row['total_amount'] : 0) // 折旧
  673. ];
  674. // 动态列填充
  675. foreach ($fee_type_list as $feeId => $feeItem) {
  676. $excelRow[] = ($row['type'] == 3 && $row['fee_id'] == $feeId) ? (float)$row['total_amount'] : 0;
  677. }
  678. // 委托列
  679. $excelRow[] = (float)($row['entrust1_amount'] ?? 0);
  680. $excelRow[] = (float)($row['entrust2_amount'] ?? 0);
  681. // 【性能优化】:同步累加金额 (从索引 4 开始是金额列)
  682. for ($i = 4; $i < $totalColCount; $i++) {
  683. $groupedData[$sheetKey]['totals'][$i] += $excelRow[$i];
  684. }
  685. $groupedData[$sheetKey]['data'][] = $excelRow;
  686. }
  687. foreach ($groupedData as &$group) {
  688. $group['data'][] = $group['totals'];
  689. unset($group['totals']); // 释放内存
  690. }
  691. // 8. 导出逻辑保持不变
  692. $file_name = "年度研发支出辅助账汇总统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  693. $filename = $file_name . '.xlsx';
  694. Excel::store(
  695. new ResearchExpenseMultipleSheetExport($groupedData),
  696. "public/export/{$filename}"
  697. );
  698. return [true, $filename];
  699. }
  700. // 年度研发支出辅助账汇总表
  701. public function exportResearchExpense(array $data, $user)
  702. {
  703. $service = new StatisticService();
  704. list($status, $result) = $service->auxiliaryStatistic($data, $user);
  705. if (!$status) return [false, $result];
  706. $fee_type_list = $result['fee_type_list'];
  707. $raw_list = $result['list'];
  708. if(empty($raw_list)) return [false, '暂无导出数据'];
  709. // 预读年份和基本信息
  710. $year = date("Y", strtotime($raw_list[0]['voucher_date']));
  711. $company = Depart::where('id', $user['top_depart_id'])->value('title');
  712. // ================== 【核心修复 1:精准使用 $feeItem['id'] 参与排序与映射】 ==================
  713. // 1. 定义固定的人员和折旧列配置并赋予 sort
  714. $amountColumnsConfig = [
  715. [
  716. 'type_key' => 'type_1', // 对应原逻辑 type == 1 (人员)
  717. 'title' => '人员人工费用',
  718. 'sort' => -1,
  719. ],
  720. [
  721. 'type_key' => 'type_2', // 对应原逻辑 type == 2 (折旧)
  722. 'title' => '折旧费用',
  723. 'sort' => 1,
  724. ]
  725. ];
  726. // 2. 将动态费用类型塞入同一个配置池中(【修复点】:从 $feeItem['id'] 读出真实的 55, 56 等真实ID)
  727. foreach ($fee_type_list as $feeItem) {
  728. $realFeeId = $feeItem['id'] ?? 0;
  729. $amountColumnsConfig[] = [
  730. 'type_key' => 'fee_' . $realFeeId,
  731. 'fee_id' => $realFeeId, // 显式留存住真实的数据库 ID,不再受数组索引干扰
  732. 'title' => $feeItem['title'] ?? '',
  733. 'sort' => (int)($feeItem['sort'] ?? 0),
  734. ];
  735. }
  736. // 3. 按照 sort 正序排序(值越小越靠前)
  737. $sortedAmountColumns = collect($amountColumnsConfig)->sortBy('sort')->values()->all();
  738. // 4. 提取出最终的动态表头名称供 Excel 使用
  739. $dynamicHeaderTitles = array_column($sortedAmountColumns, 'title');
  740. // 5. 计算总列数
  741. $baseColCount = 6;
  742. $sortedColCount = count($sortedAmountColumns);
  743. $totalColCount = $baseColCount + $sortedColCount + 2;
  744. // =========================================================================
  745. $groupedData = [];
  746. foreach ($raw_list as $row) {
  747. $sheetKey = $year . $row['code'];
  748. if (!isset($groupedData[$sheetKey])) {
  749. $groupedData[$sheetKey] = [
  750. 'project' => [
  751. 'code' => $row['code'],
  752. 'name' => $row['title'],
  753. ],
  754. 'dynamic_headers' => $dynamicHeaderTitles,
  755. 'data' => [],
  756. 'year' => $company . $year,
  757. 'totals' => array_fill(0, $totalColCount, 0)
  758. ];
  759. $groupedData[$sheetKey]['totals'][0] = '合计'; // 第一列标识
  760. }
  761. // 1. 初始化明细行的前 6 列(基础信息 + 基础金额)
  762. $excelRow = [
  763. $row['voucher_date'],
  764. $row['voucher_type'],
  765. $row['voucher_no'],
  766. $row['voucher_remark'],
  767. (float)($row['voucher_amount'] ?? 0),
  768. (float)($row['aggregation_amount'] ?? 0),
  769. ];
  770. // ================== 【核心修复 2:依照正确的真实 fee_id 填充科目金额】 ==================
  771. foreach ($sortedAmountColumns as $col) {
  772. $colValue = 0.0;
  773. if ($col['type_key'] === 'type_1') {
  774. // 人员人工
  775. $colValue = ($row['type'] == 1 ? (float)$row['total_amount'] : 0);
  776. } elseif ($col['type_key'] === 'type_2') {
  777. // 折旧费用
  778. $colValue = ($row['type'] == 2 ? (float)$row['total_amount'] : 0);
  779. } else {
  780. // 动态费用科目(【修复点】:此时的 $col['fee_id'] 已经能够完美匹配 $row['fee_id'])
  781. $colValue = ($row['type'] == 3 && $row['fee_id'] == $col['fee_id']) ? (float)$row['total_amount'] : 0;
  782. }
  783. $excelRow[] = $colValue;
  784. }
  785. // =========================================================================
  786. // 3. 追加尾部的委托列
  787. $excelRow[] = (float)($row['entrust1_amount'] ?? 0);
  788. $excelRow[] = (float)($row['entrust2_amount'] ?? 0);
  789. // 同步累加金额 (从索引 4 [记账凭证金额] 开始一直到最后一列)
  790. for ($i = 4; $i < $totalColCount; $i++) {
  791. $groupedData[$sheetKey]['totals'][$i] += $excelRow[$i];
  792. }
  793. $groupedData[$sheetKey]['data'][] = $excelRow;
  794. }
  795. foreach ($groupedData as &$group) {
  796. $group['data'][] = $group['totals'];
  797. unset($group['totals']); // 释放内存
  798. }
  799. // 8. 导出逻辑
  800. $file_name = "年度研发支出辅助账汇总统计表_" . date("Y-m-d") . "_". rand(1000,9999);
  801. $filename = $file_name . '.xlsx';
  802. Excel::store(
  803. new ResearchExpenseMultipleSheetExport($groupedData),
  804. "public/export/{$filename}"
  805. );
  806. return [true, $filename];
  807. }
  808. // 研发支出辅助帐汇总表
  809. public function exportFormalSummary1(array $data, $user)
  810. {
  811. $service = new StatisticService();
  812. // 1. 调用业务逻辑获取原始数据
  813. list($status, $result) = $service->employeeAttendanceMonthStatistic($data, $user);
  814. if (!$status) return [false, $result];
  815. $rawList = $result['list'] ?? [];
  816. $feeTypes = $result['fee_type_list'] ?? [];
  817. // 2. 构造动态表头名称
  818. $dynamicHeaderTitles = [];
  819. foreach ($feeTypes as $value){
  820. if(! $value['is_after']) $dynamicHeaderTitles[] = $value['title'];
  821. }
  822. // $dynamicHeaderTitles = array_column($feeTypes, 'title');
  823. $dynamicHeaders = array_merge(['人员人工费用', '折旧费用'], $dynamicHeaderTitles);
  824. $items = [];
  825. foreach ($rawList as $v) {
  826. $rowValues = [];
  827. // A. 填充基础固定两项:人工和折旧
  828. $rowValues[] = (float)($v['employee_salary'] ?? 0);
  829. $rowValues[] = (float)($v['device_depreciation'] ?? 0);
  830. // B. 初始化累加变量
  831. // $val7_1 = 0; // 其他相关费用合计 (所有 total_amount 之和)
  832. $val8_1 = 0; // 委托境内合计 (所有 entrust1_amount 之和)
  833. $val8_3 = 0; // 委托境外合计 (所有 entrust2_amount 之和)
  834. // 将当前项目的 fee_list 转为集合以便按 ID 快速查找
  835. $currentProjectFees = collect($v['fee_list'] ?? [])->keyBy('id');
  836. // 遍历所有可能的费用类型,确保 values 数组长度与表头一致
  837. foreach ($feeTypes as $type) {
  838. $feeData = $currentProjectFees->get($type['id']);
  839. if($feeData == null) continue;
  840. $amount = (float)($feeData['total_amount'] ?? 0);
  841. // 2. 累加委托费用 (8.1 和 8.3)
  842. $val8_1 += (float)($feeData['entrust1_amount'] ?? 0);
  843. $val8_3 += (float)($feeData['entrust2_amount'] ?? 0);
  844. if($feeData['is_other']) continue;
  845. // 填充到动态科目列
  846. $rowValues[] = $amount;
  847. // 1. 累加其他相关费用合计 (7.1)
  848. // if(! empty($feeData['is_other']) && $feeData['is_other'] == Fee::IS_OTHER_ONE) $val7_1 += $amount;
  849. }
  850. $items[] = [
  851. 'no' => $v['code'] ?? '',
  852. 'name' => $v['title'] ?? '',
  853. 'status' => (($v['state'] ?? '') == "完结" ? 3 : 2),
  854. 'type' => $v['expense_type'] ?? '费用化支出',
  855. 'values' => $rowValues,
  856. 'val7_1' => $v['other_amount'],
  857. 'val7_2' => $v['jj_other_amount'],
  858. 'val8_1' => $val8_1,
  859. 'val8_3' => $val8_3,
  860. ];
  861. }
  862. // 年份获取逻辑
  863. $year = Carbon::parse($data['year'])
  864. ->setTimezone(config('app.timezone')) // 转换为 Laravel 配置的时区
  865. ->format('Y');
  866. //获取公司基本信息
  867. $company = EmployeeService::getCompanyDetail($user);
  868. // 3. 组织多 Sheet 格式数据
  869. $monthsData = [
  870. $year => [
  871. 'tax_id' => $company['code'] ?? '',
  872. 'company_name' => $company['title'] ?? '',
  873. 'items' => $items,
  874. 'dynamic_headers' => $dynamicHeaders
  875. ]
  876. ];
  877. // 4. 执行 Excel 存储
  878. $file_name = "研发支出辅助账汇总表_" . date("YmdHis") . "_" . rand(1000, 9999);
  879. $filename = $file_name . '.xlsx';
  880. Excel::store(
  881. new \App\Exports\ResearchExpenseSummaryMultipleSheetExport($monthsData),
  882. "public/export/{$filename}"
  883. );
  884. return [true, $filename];
  885. }
  886. public function exportFormalSummary(array $data, $user)
  887. {
  888. $service = new StatisticService();
  889. // 1. 调用业务逻辑获取原始数据
  890. list($status, $result) = $service->employeeAttendanceMonthStatistic($data, $user);
  891. if (!$status) return [false, $result];
  892. $rawList = $result['list'] ?? [];
  893. $feeTypes = $result['fee_type_list'] ?? [];
  894. // ================== 1. 统一表头与排序 ==================
  895. // 定义固定表头并赋予默认 sort
  896. $allHeadersTemp = [
  897. [
  898. 'id' => 'employee_salary', // 用特殊标识代表固定列
  899. 'title' => '人员人工费用',
  900. 'sort' => -1,
  901. 'is_fixed' => true
  902. ],
  903. [
  904. 'id' => 'device_depreciation',
  905. 'title' => '折旧费用',
  906. 'sort' => 1,
  907. 'is_fixed' => true
  908. ]
  909. ];
  910. // 将符合条件的动态表头合并进来
  911. foreach ($feeTypes as $value) {
  912. if (!$value['is_after']) {
  913. $allHeadersTemp[] = [
  914. 'id' => $value['id'],
  915. 'title' => $value['title'],
  916. 'sort' => (int)($value['sort'] ?? 0), // 确保是整型
  917. 'is_fixed' => false
  918. ];
  919. }
  920. }
  921. // 使用 collect 按照 sort 正序排序(值越小越靠前)
  922. $sortedHeaders = collect($allHeadersTemp)->sortBy('sort')->values()->all();
  923. // 提取出最终传给 Excel 的纯文本表头数组
  924. $dynamicHeaders = array_column($sortedHeaders, 'title');
  925. // =======================================================
  926. $items = [];
  927. foreach ($rawList as $v) {
  928. $rowValues = [];
  929. $val8_1 = 0; // 委托境内合计
  930. $val8_3 = 0; // 委托境外合计
  931. // 1. 先把当前项目所有的 fee_list 进行全量费用累加(修复漏计 Bug)
  932. $currentFeeList = $v['fee_list'] ?? [];
  933. foreach ($currentFeeList as $feeData) {
  934. $val8_1 += (float)($feeData['entrust1_amount'] ?? 0);
  935. $val8_3 += (float)($feeData['entrust2_amount'] ?? 0);
  936. }
  937. // 2. 将当前项目的 fee_list 转为集合,以便按 ID 快速查找对齐
  938. $currentProjectFees = collect($currentFeeList)->keyBy('id');
  939. // 3. 依照排序后的表头填充 Excel 列数据
  940. foreach ($sortedHeaders as $header) {
  941. if ($header['is_fixed']) {
  942. // 如果是固定的基础两项(人员人工、折旧),直接从主记录 $v 中取值
  943. $rowValues[] = (float)($v[$header['id']] ?? 0);
  944. } else {
  945. // 如果是动态科目列
  946. $feeData = $currentProjectFees->get($header['id']);
  947. if ($feeData == null) {
  948. $rowValues[] = 0.0; // 没数据补0,保证列对齐
  949. continue;
  950. }
  951. // 如果是其他费用,不填充到动态科目列中(填充 0 占位防错位)
  952. if ($feeData['is_other']) {
  953. $rowValues[] = 0.0;
  954. continue;
  955. }
  956. // 正常填充金额
  957. $rowValues[] = (float)($feeData['total_amount'] ?? 0);
  958. }
  959. }
  960. $items[] = [
  961. 'no' => $v['code'] ?? '',
  962. 'name' => $v['title'] ?? '',
  963. 'status' => (($v['state'] ?? '') == "完结" ? 3 : 2),
  964. 'start_time' => $v['start_time'],
  965. 'end_time' => $v['end_time'],
  966. 'type' => $v['expense_type'] ?? '费用化支出',
  967. 'values' => $rowValues,
  968. 'val7_1' => $v['other_amount'],
  969. 'val7_2' => $v['jj_other_amount'],
  970. 'val8_1' => $val8_1,
  971. 'val8_3' => $val8_3,
  972. ];
  973. }
  974. // 年份获取逻辑
  975. $year = Carbon::parse($data['year'])
  976. ->setTimezone(config('app.timezone')) // 转换为 Laravel 配置的时区
  977. ->format('Y');
  978. //获取公司基本信息
  979. $company = EmployeeService::getCompanyDetail($user);
  980. // 3. 组织多 Sheet 格式数据
  981. $monthsData = [
  982. $year => [
  983. 'tax_id' => $company['code'] ?? '',
  984. 'company_name' => $company['title'] ?? '',
  985. 'items' => $items,
  986. 'dynamic_headers' => $dynamicHeaders
  987. ]
  988. ];
  989. // 4. 执行 Excel 存储
  990. $file_name = "研发支出辅助账汇总表_" . date("YmdHis") . "_" . rand(1000, 9999);
  991. $filename = $file_name . '.xlsx';
  992. Excel::store(
  993. new \App\Exports\ResearchExpenseSummaryMultipleSheetExport($monthsData),
  994. "public/export/{$filename}"
  995. );
  996. return [true, $filename];
  997. }
  998. // 人员活动考勤占比
  999. public function exportActivityTimeCard(array $data, $user)
  1000. {
  1001. $service = new StatisticService();
  1002. // 1. 获取统计数据
  1003. list($status, $result) = $service->itemEmployeeSalaryStatistic($data, $user);
  1004. if (!$status) return [false, $result];
  1005. $rawList = collect($result ?? []);
  1006. // 2. 按 项目名称 和 年度 联合分组
  1007. $groupedData = $rawList->groupBy(function ($item) {
  1008. $year = substr($item['month'] ?? date('Y'), 0, 4);
  1009. return $year . "-" . $item['item_title'];
  1010. });
  1011. $allProjectsData = [];
  1012. foreach ($groupedData as $groupKey => $records) {
  1013. list($year, $projectTitle) = explode('-', $groupKey);
  1014. $projectRows = [];
  1015. $groupedByMonth = $records->groupBy('month');
  1016. foreach ($groupedByMonth as $monthStr => $monthRecords) {
  1017. $monthNum = substr($monthStr, 5, 2);
  1018. $monthSubTotal = array_fill(3, 15, 0); // 索引3-17的累加器
  1019. foreach ($monthRecords as $v) {
  1020. $radioVal = (float)($v['radio'] ?? 0);
  1021. $row = [
  1022. (int)$monthNum . '月', // 0. 月份
  1023. '技术人员', // 1. 类别
  1024. $v['employee_title'] ?? '', // 2. 姓名
  1025. (float)$v['total_min'], // 3. 应出勤
  1026. (float)$v['work_minutes'], // 4. 研发出勤
  1027. ($radioVal * 100) . '%', // 5. 占比 (字符串)
  1028. (float)$v['salary'], // 6. 归集工资
  1029. (float)$v['social_insurance'],// 7. 归集社保
  1030. (float)$v['public_housing_fund'], // 8. 归集公积金
  1031. (float)$v['work_salary'], // 9. 确定工资
  1032. (float)$v['work_social_insurance'], // 10. 确定社保
  1033. (float)$v['work_public_housing_fund'], // 11. 确定公积金
  1034. (float)$v['work_salary'], // 12. 研发确定总工资
  1035. (float)$v['work_social_insurance'], // 13. 研发确定总社保
  1036. (float)$v['work_public_housing_fund'], // 14. 研发确定总公积金
  1037. 0, 0, 0 // 15, 16, 17. 调整金额
  1038. ];
  1039. $projectRows[] = $row;
  1040. // 累加月份小计 (跳过索引5的百分比字符串)
  1041. for ($i = 3; $i <= 14; $i++) {
  1042. if ($i == 5) continue;
  1043. $monthSubTotal[$i] += (float)$row[$i];
  1044. }
  1045. }
  1046. // 构造月份小计行 (重新计算占比)
  1047. $mRadio = $monthSubTotal[3] > 0 ? round($monthSubTotal[4] / $monthSubTotal[3] * 100, 2) . '%' : '0%';
  1048. $projectRows[] = [
  1049. '小计:', '', '', $monthSubTotal[3], $monthSubTotal[4], $mRadio,
  1050. $monthSubTotal[6], $monthSubTotal[7], $monthSubTotal[8],
  1051. $monthSubTotal[9], $monthSubTotal[10], $monthSubTotal[11],
  1052. $monthSubTotal[12], $monthSubTotal[13], $monthSubTotal[14],
  1053. 0, 0, 0
  1054. ];
  1055. }
  1056. // 计算整年合计 (避开小计行,避开非数字)
  1057. $yearTotal = array_fill(3, 15, 0);
  1058. foreach ($projectRows as $row) {
  1059. if ($row[0] !== '小计:' && $row[0] !== '合计') {
  1060. for ($i = 3; $i <= 14; $i++) {
  1061. if ($i == 5) continue;
  1062. $yearTotal[$i] += (float)$row[$i];
  1063. }
  1064. }
  1065. }
  1066. $yRadio = $yearTotal[3] > 0 ? round($yearTotal[4] / $yearTotal[3] * 100, 2) . '%' : '0%';
  1067. $projectRows[] = [
  1068. '合计', '', '', $yearTotal[3], $yearTotal[4], $yRadio,
  1069. $yearTotal[6], $yearTotal[7], $yearTotal[8],
  1070. $yearTotal[9], $yearTotal[10], $yearTotal[11],
  1071. $yearTotal[12], $yearTotal[13], $yearTotal[14],
  1072. 0, 0, 0
  1073. ];
  1074. $allProjectsData[$groupKey] = [
  1075. 'project' => $projectTitle,
  1076. 'year' => $year,
  1077. 'data' => $projectRows
  1078. ];
  1079. }
  1080. $filename = "人员活动考勤占比统计表_" . date("YmdHis") . '.xlsx';
  1081. \Maatwebsite\Excel\Facades\Excel::store(
  1082. new \App\Exports\ManActivityTimeCardMultipleSheetExport($allProjectsData),
  1083. "public/export/{$filename}"
  1084. );
  1085. return [true, $filename];
  1086. }
  1087. //业研究开发活动汇总表
  1088. public function exportEnterpriseRdStatistic(array $data, $user)
  1089. {
  1090. $service = new StatisticService();
  1091. list($status, $result) = $service->enterpriseRdStatistic($data, $user);
  1092. if (!$status) return [false, '获取统计数据失败'];
  1093. $exportData = [];
  1094. $totalBudget = 0; // 预算总计累加器
  1095. $totalActual = 0; // 支出总计累加器
  1096. foreach ($result as $row) {
  1097. $budget = (float)($row['budget'] ?? 0);
  1098. $actual = (float)($row['actual_expenditure'] ?? 0);
  1099. $totalBudget = bcadd($totalBudget, $budget, 2);
  1100. $totalActual = bcadd($totalActual, $actual, 2);
  1101. $exportData[] = [
  1102. 'activity_name' => $row['title'] ?? '', // 研发活动名称
  1103. 'time_range' => $row['time_range'] ?? '', // 起止时间
  1104. 'from' => $row['from'] ?? '自有技术', // 起止时间
  1105. 'budget' => $budget, // 研发预算
  1106. 'actual_spending' => $actual, // 实际支出
  1107. 'tech_area' => $row['field'] ?? '', // 技术领域
  1108. 'remark' => $row['mark'] ?? '', // 备注
  1109. ];
  1110. }
  1111. $exportData[] = [
  1112. 'activity_name' => '',
  1113. 'time_range' => '',
  1114. 'from' => '',
  1115. 'budget' => $totalBudget,
  1116. 'actual_spending' => $totalActual,
  1117. 'tech_area' => '',
  1118. 'remark' => '',
  1119. ];
  1120. $file_name = "企业研究开发活动汇总表_" . date("YmdHis");
  1121. $filename = $file_name . '.xlsx';
  1122. $relative_path = "public/export/{$filename}";
  1123. \Maatwebsite\Excel\Facades\Excel::store(
  1124. new \App\Exports\CompanyRdActivityExport($exportData),
  1125. $relative_path
  1126. );
  1127. return [true, $filename];
  1128. }
  1129. //企业研究开发科技人员情况表
  1130. public function exportEnterpriseRdManStatistic(array $data, $user)
  1131. {
  1132. $service = new StatisticService();
  1133. list($status, $result) = $service->enterpriseRdManStatistic($data, $user);
  1134. if (!$status) return [false, '获取人员统计数据失败'];
  1135. // 2. 映射数据到导出类需要的字段格式
  1136. $exportData = [];
  1137. foreach ($result as $row) {
  1138. $exportData[] = [
  1139. 'name' => $row['title'] ?? '', // 姓名 (对应模型里的 title 字段)
  1140. 'id_card' => $row['id_card'] ?? '', // 身份证号码
  1141. 'education' => Employee::Education[$row['education']] ?? "", // 学历
  1142. 'major' => $row['major'] ?? '', // 专业
  1143. 'title_level' => $row['p_title'] ?? '', // 职称/职业资格
  1144. 'department_job' => $row['position_new'] ?? '', // 部门/岗位
  1145. 'employment_type' => $row['employee_type_title'] ?? "", // 聘用类型
  1146. ];
  1147. }
  1148. // 3. 定义文件名和路径
  1149. $file_name = "企业研究开发科技人员情况表_" . date("YmdHis");
  1150. $filename = $file_name . '.xlsx';
  1151. $relative_path = "public/export/{$filename}";
  1152. \Maatwebsite\Excel\Facades\Excel::store(
  1153. new \App\Exports\TechnicalStaffExport($exportData),
  1154. $relative_path
  1155. );
  1156. return [true, $filename];
  1157. }
  1158. //项目研发活动人员情况表
  1159. public function exportEnterpriseRdItemStatistic(array $data, $user)
  1160. {
  1161. $service = new StatisticService();
  1162. list($status, $result) = $service->enterpriseRdItemStatistic($data, $user);
  1163. if (!$status) return [false, '获取统计数据失败'];
  1164. // 2. 映射数据到导出类需要的字段格式
  1165. $exportData = [];
  1166. foreach ($result as $row) {
  1167. $exportData[] = [
  1168. 'title' => $row['title'] ?? '', // 姓名 (对应模型里的 title 字段)
  1169. 'education' => Employee::Education[$row['education']] ?? "", // 学历
  1170. 'major' => $row['major'] ?? '', // 专业
  1171. 'p_title' => $row['p_title'] ?? '', // 职称/职业资格
  1172. 'item_title' => $row['item_title'] ?? '', // 项目
  1173. 'item_role' => $row['item_role'] ?? '', // 项目角色
  1174. 'depart_title' => $row['depart_title'] ?? '', // 部门
  1175. 'duty' => $row['duty'] ?? "", // 职责
  1176. ];
  1177. }
  1178. // 3. 定义文件名和路径
  1179. $file_name = "项目研发活动人员情况表_" . date("YmdHis");
  1180. $filename = $file_name . '.xlsx';
  1181. $relative_path = "public/export/{$filename}";
  1182. \Maatwebsite\Excel\Facades\Excel::store(
  1183. new \App\Exports\ProjectStaffExport($exportData),
  1184. $relative_path
  1185. );
  1186. return [true, $filename];
  1187. }
  1188. public function itemMissionProgressList($ergs,$user){
  1189. // 导出数据
  1190. $return = [];
  1191. $header_default = $user['e_header_default'];
  1192. $column = array_column($header_default,'export');
  1193. $header = array_column($header_default,'value');
  1194. $service = new ItemService();
  1195. $model = $service->itemMissionProgressListCommon($ergs, $user);
  1196. $model->chunk(500,function ($data) use(&$return,$column,$service, $user){
  1197. $data = $data->toArray();
  1198. $list['data'] = $data;
  1199. //订单数据
  1200. $list = $service->fillItemMissionProgressList($list, $user);
  1201. //返回数据
  1202. $this->fillData($list['data'], $column, $return);
  1203. });
  1204. return [true, $this->saveExportData($return,$header)];
  1205. }
  1206. public function saveExportData($data, $headers, $type = 'default',$file_name = ''){
  1207. if(empty($file_name)) $file_name = self::$filename . "_". date("Y-m-d") . "_". rand(1000,9999);
  1208. $filename = $file_name . '.' . 'xlsx';
  1209. $bool = Excel::store(new ExportOrder($data,$type,$headers),"/public/export/{$filename}", null, 'Xlsx', []);
  1210. return $filename;
  1211. }
  1212. public function saveExportData2($data,$type = 1,$column,$timeRow, $file_name = ''){
  1213. if(empty($file_name)) $file_name = self::$filename . "_". date("Y-m-d") . "_". rand(1000,9999);
  1214. $filename = $file_name . '.' . 'xlsx';
  1215. \Maatwebsite\Excel\Facades\Excel::store(new MultiSheetExport($data, $type,$column,$timeRow),"/public/export/{$filename}", null, 'Xlsx', []);
  1216. return $filename;
  1217. }
  1218. }