UnifiedCostCalculationService.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  1. <?php
  2. namespace app\service;
  3. use think\Db;
  4. use think\Exception;
  5. use think\Log;
  6. /**
  7. * 统一成本核算服务类
  8. * 五项计算完成后统一插入数据库
  9. */
  10. class UnifiedCostCalculationService
  11. {
  12. // 存储中间数据的数组
  13. protected $monthlyCostDetails = [];
  14. protected $allocationFactors = [];
  15. // 配置常量
  16. const FLOOR_GROUP_MAP = [
  17. '1' => ['02、胶印机组', '03、卷凹机组', '06、单凹机组', '05、圆切机组', '04、圆烫机组', '10、模切机组', '09、烫金机组'],
  18. '2' => ['01、切纸机组', '11、检品机组', '07、丝印机组', '12、覆膜机组', '08、喷码机组'],
  19. ];
  20. // 科目名称映射
  21. const SUBJECT_MAPPING = [
  22. '废气处理' => '废气处理',
  23. '锅炉' => '锅炉',
  24. '空压机' => '空压机',
  25. '热水锅炉' => '热水锅炉',
  26. '真空鼓风机' => '真空鼓风机',
  27. '中央空调' => '中央空调',
  28. '待分摊总额' => '待分摊总额',
  29. ];
  30. // 字段默认值
  31. const DEFAULT_FIELD_VALUES = [
  32. '直接水电' => 0,
  33. '分摊材料' => 0,
  34. '车间人工' => 0,
  35. '部门人工附加' => 0,
  36. '分摊水电' => 0,
  37. '废气处理' => 0,
  38. '锅炉' => 0,
  39. '空压机' => 0,
  40. '热水锅炉' => 0,
  41. '真空鼓风机' => 0,
  42. '中央空调' => 0,
  43. '分摊其他' => 0,
  44. 'A_小时折旧额' => 0,
  45. '直接材料' => 0,
  46. '考核直接材料' => 0,
  47. '直接折旧' => 0,
  48. '分摊折旧' => 0,
  49. '场地租金' => 0,
  50. '成本合计' => 0,
  51. ];
  52. // 添加科目名称到数据库字段的映射
  53. const SUBJECT_TO_FIELD_MAP = [
  54. // 真空鼓风机相关
  55. '真空鼓风机' => '真空鼓风机',
  56. '真空鼓风' => '真空鼓风机',
  57. '6#楼真空鼓风' => '真空鼓风机',
  58. '真空风机' => '真空鼓风机',
  59. // 废气处理相关
  60. '废气处理' => '废气处理',
  61. '废气' => '废气处理',
  62. // 锅炉相关
  63. '锅炉' => '锅炉',
  64. '热水锅炉' => '热水锅炉',
  65. // 空压机相关
  66. '空压机' => '空压机',
  67. '空压' => '空压机',
  68. // 中央空调相关
  69. '中央空调' => '中央空调',
  70. '空调' => '中央空调',
  71. // 待分摊总额
  72. '待分摊总额' => '分摊水电',
  73. '分摊总额' => '分摊水电',
  74. ];
  75. // 批次大小
  76. const BATCH_SIZE = 100;
  77. /**
  78. * 主入口:执行所有成本计算并统一入库
  79. */
  80. public function calculateAndSaveAll(array $param): array
  81. {
  82. Log::info("开始成本计算,参数: " . json_encode($param));
  83. Db::startTrans();
  84. try {
  85. if (!isset($param['month'])) {
  86. throw new Exception("缺少必要参数: month");
  87. }
  88. $month = $param['month'];
  89. $sysId = $param['sys_id'] ?? uniqid();
  90. Log::info("开始清空旧数据");
  91. $this->clearOldData($month);
  92. Log::info("开始计算直接人工");
  93. $this->calculateDirectLabor($param);
  94. Log::info("直接人工计算完成,记录数: " . count($this->monthlyCostDetails));
  95. Log::info("开始计算直接水电");
  96. $this->calculateDirectUtilities($param);
  97. Log::info("开始计算间接材料");
  98. $this->calculateIndirectMaterials($month);
  99. Log::info("开始计算间接人工");
  100. $this->calculateIndirectLabor($month);
  101. Log::info("开始计算分摊水电");
  102. $this->calculateApportionedUtilities($param);
  103. Log::info("开始保存数据");
  104. $this->saveAllData($month, $sysId);
  105. Db::commit();
  106. $this->logSuccess($month);
  107. return $this->buildSuccessResponse($month);
  108. } catch (\Throwable $t) { // 使用 Throwable 而不是 Exception
  109. Db::rollback();
  110. // 记录详细的错误信息
  111. $errorInfo = [
  112. 'message' => $t->getMessage(),
  113. 'code' => $t->getCode(),
  114. 'file' => $t->getFile(),
  115. 'line' => $t->getLine(),
  116. 'trace' => $t->getTraceAsString(),
  117. 'param' => $param
  118. ];
  119. Log::error("统一成本核算失败: " . json_encode($errorInfo, JSON_UNESCAPED_UNICODE));
  120. return [
  121. 'success' => false,
  122. 'message' => '成本核算失败: ' . $t->getMessage(),
  123. 'error' => $t->getMessage(),
  124. 'error_details' => $errorInfo
  125. ];
  126. }
  127. }
  128. /**
  129. * 清空旧数据
  130. */
  131. protected function clearOldData(string $month): void
  132. {
  133. $this->monthlyCostDetails = [];
  134. $this->allocationFactors = [];
  135. }
  136. /**
  137. * 1. 计算直接人工
  138. */
  139. protected function calculateDirectLabor(array $param): void
  140. {
  141. try {
  142. $month = $param['month'];
  143. $sysId = $param['sys_id'] ?? '';
  144. $now = date('Y-m-d H:i:s');
  145. $list = Db::name('绩效工资汇总')
  146. ->alias('a')
  147. ->join('工单_工艺资料 b', 'a.sczl_gdbh = b.Gy0_gdbh and a.sczl_yjno = b.Gy0_yjno and a.sczl_gxh = b.Gy0_gxh')
  148. ->join('设备_基本资料 c', 'a.sczl_jtbh = c.设备编号', 'LEFT')
  149. ->join('工单_印件资料 d', 'a.sczl_gdbh = d.Yj_Gdbh and a.sczl_yjno = d.yj_Yjno')
  150. ->field($this->getDirectLaborFields())
  151. ->where('a.sys_ny', $month)
  152. ->group('a.sczl_gdbh,a.sczl_yjno,a.sczl_gxh,a.sczl_jtbh')
  153. ->select();
  154. // 转换为数组(如果返回的是对象)
  155. if (!is_array($list)) {
  156. $list = $list->toArray();
  157. }
  158. Log::info("直接人工查询结果数: " . count($list));
  159. foreach ($list as $item) {
  160. // 确保 $item 是数组
  161. $itemArray = is_object($item) ? (array)$item : $item;
  162. if (!is_array($itemArray)) {
  163. Log::warning("直接人工数据项格式不正确: " . gettype($item));
  164. continue;
  165. }
  166. $this->monthlyCostDetails[] = $this->buildMonthlyCostDetail($itemArray, $month, $sysId, $now);
  167. }
  168. } catch (\Exception $e) {
  169. Log::error("计算直接人工失败: " . $e->getMessage());
  170. throw new Exception("直接人工计算失败: " . $e->getMessage());
  171. }
  172. }
  173. /**
  174. * 获取直接人工查询字段
  175. */
  176. protected function getDirectLaborFields(): string
  177. {
  178. return 'a.sczl_gdbh as 工单编号,a.sczl_yjno as 印件号,a.sczl_gxh as 工序号,
  179. sum(a.班组车头产量) as 班组车头产量,b.Gy0_gxmc as 工序名称,
  180. a.sczl_ms as 墨色数,c.使用部门,b.印刷方式,b.版距,b.工价系数,
  181. a.sczl_jtbh,d.yj_yjmc as 印件名称,sum(a.车头产量占用机时) as 占用机时,
  182. a.sys_rq as 年月,a.工序难度系数,sum(a.班组换算产量) as 班组换算产量,
  183. a.千件工价';
  184. }
  185. /**
  186. * 构建月度成本明细记录
  187. */
  188. protected function buildMonthlyCostDetail(array $data, string $month, string $sysId, string $now): array
  189. {
  190. $banju = $data['版距'] === '0.0' ? 1000 : $data['版距'];
  191. $moshushu = $this->calculateMoshushu($data);
  192. $chanliang = $this->calculateChanliang($data);
  193. $renGongFenTan = $this->calculateRenGongFenTan($chanliang, $data);
  194. return array_merge([
  195. '车间名称' => $data['使用部门'] ?? '',
  196. 'sys_ny' => $month,
  197. 'sczl_gdbh' => $data['工单编号'],
  198. '印件名称' => $data['印件名称'] ?? '',
  199. 'sczl_yjno' => $data['印件号'],
  200. 'sczl_gxh' => $data['工序号'],
  201. '工序名称' => $data['工序名称'] ?? '',
  202. 'sczl_jtbh' => $data['sczl_jtbh'] ?? '',
  203. '卷张换算系数' => floatval($banju) / 1000,
  204. '占用机时' => floatval($data['占用机时']) ?? 0,
  205. '班组车头产量' => floatval($data['班组车头产量']) ?? 0,
  206. 'sczl_ms' => floatval($moshushu),
  207. '工序难度系数' => floatval($data['工序难度系数']) ?? 1,
  208. '班组换算产量' => floatval($data['班组换算产量']) ?? 0,
  209. '千件工价' => floatval($data['千件工价']) ?? 0,
  210. '计件产量' => floatval($chanliang),
  211. '水电分摊因子' => floatval($data['占用机时']) ?? 0,
  212. '材料分摊因子' => floatval($chanliang),
  213. '人工分摊因子' => floatval($renGongFenTan),
  214. 'Sys_id' => $sysId,
  215. 'Sys_rq' => $now
  216. ], self::DEFAULT_FIELD_VALUES);
  217. }
  218. /**
  219. * 计算墨色数
  220. */
  221. protected function calculateMoshushu(array $data): float
  222. {
  223. if (strpos($data['工序名称'] ?? '', '切废') !== false) {
  224. return 0.2;
  225. }
  226. return $data['墨色数'] === '0.00' ? 1.0 : floatval($data['墨色数']);
  227. }
  228. /**
  229. * 计算产量
  230. */
  231. protected function calculateChanliang(array $data): float
  232. {
  233. return ($data['班组车头产量'] * $data['工序难度系数']) + $data['班组换算产量'];
  234. }
  235. /**
  236. * 计算人工分摊
  237. */
  238. protected function calculateRenGongFenTan(float $chanliang, array $data): float
  239. {
  240. return ($chanliang / 1000) * $data['千件工价'];
  241. }
  242. /**
  243. * 2. 计算直接水电
  244. */
  245. protected function calculateDirectUtilities(array $param): void
  246. {
  247. $month = $param['month'];
  248. if (empty($this->monthlyCostDetails)) {
  249. throw new Exception("请先执行直接人工计算");
  250. }
  251. $utilityData = $this->fetchDirectUtilities($month);
  252. if (empty($utilityData)) {
  253. Log::info("{$month}月份未找到直接水电费用数据");
  254. return;
  255. }
  256. $machineUtilities = $this->calculateMachineUtilities($utilityData);
  257. $workOrderHours = $this->getMachineWorkHours();
  258. $machineTotalHours = $this->calculateMachineTotalHours($workOrderHours);
  259. $allocationResults = $this->allocateUtilitiesToWorkOrders(
  260. $machineUtilities,
  261. $workOrderHours,
  262. $machineTotalHours
  263. );
  264. $this->updateDirectUtilitiesToCostDetails($allocationResults);
  265. }
  266. /**
  267. * 获取直接水电数据
  268. */
  269. protected function fetchDirectUtilities(string $month): array
  270. {
  271. return Db::name('成本_各月水电气')
  272. ->where('Sys_ny', $month)
  273. ->where('费用类型', '直接')
  274. ->field('设备编号, 部门名称, 科目名称, 耗电量, 单位电价, 耗气量, 单位气价')
  275. ->select();
  276. }
  277. /**
  278. * 计算机台水电费用
  279. */
  280. protected function calculateMachineUtilities(array $utilityData): array
  281. {
  282. $machineUtilities = [];
  283. foreach ($utilityData as $item) {
  284. $machineCode = $item['设备编号'] ?? '';
  285. if (empty($machineCode)) {
  286. continue;
  287. }
  288. $electricityCost = $this->calculateElectricityCost($item);
  289. $gasCost = $this->calculateGasCost($item);
  290. $totalCost = $electricityCost + $gasCost;
  291. if (!isset($machineUtilities[$machineCode])) {
  292. $machineUtilities[$machineCode] = [
  293. '机器编号' => $machineCode,
  294. '部门名称' => $item['部门名称'] ?? '',
  295. '总费用' => 0,
  296. '电费' => 0,
  297. '气费' => 0,
  298. ];
  299. }
  300. $machineUtilities[$machineCode]['总费用'] += $totalCost;
  301. $machineUtilities[$machineCode]['电费'] += $electricityCost;
  302. $machineUtilities[$machineCode]['气费'] += $gasCost;
  303. }
  304. return $machineUtilities;
  305. }
  306. /**
  307. * 计算电费
  308. */
  309. protected function calculateElectricityCost(array $item): float
  310. {
  311. return round(floatval($item['耗电量'] ?? 0) * floatval($item['单位电价'] ?? 0), 2);
  312. }
  313. /**
  314. * 计算气费
  315. */
  316. protected function calculateGasCost(array $item): float
  317. {
  318. return round(floatval($item['耗气量'] ?? 0) * floatval($item['单位气价'] ?? 0), 2);
  319. }
  320. /**
  321. * 获取机台工作小时数
  322. */
  323. protected function getMachineWorkHours(): array
  324. {
  325. $workHours = [];
  326. foreach ($this->monthlyCostDetails as $detail) {
  327. try {
  328. // 确保 $detail 是数组
  329. $detailArray = is_object($detail) ? (array)$detail : $detail;
  330. if (!is_array($detailArray)) {
  331. Log::warning("成本明细数据格式不正确: " . gettype($detail));
  332. continue;
  333. }
  334. $machineCode = $detailArray['sczl_jtbh'] ?? '';
  335. $hours = floatval($detailArray['占用机时'] ?? 0);
  336. if (!empty($machineCode) && $hours > 0) {
  337. $workHours[] = [
  338. 'sczl_gdbh' => $detailArray['sczl_gdbh'] ?? '',
  339. 'sczl_yjno' => $detailArray['sczl_yjno'] ?? '',
  340. 'sczl_gxh' => $detailArray['sczl_gxh'] ?? '',
  341. 'sczl_jtbh' => $machineCode,
  342. '占用机时' => $hours,
  343. '车间名称' => $detailArray['车间名称'] ?? '',
  344. ];
  345. }
  346. } catch (\Exception $e) {
  347. Log::error("处理机台工作小时数时出错: " . $e->getMessage());
  348. continue;
  349. }
  350. }
  351. Log::info("从月度成本明细数据中获取机台运行时间,记录数: " . count($workHours));
  352. return $workHours;
  353. }
  354. /**
  355. * 计算机台总小时数
  356. */
  357. protected function calculateMachineTotalHours(array $workOrderHours): array
  358. {
  359. $machineTotalHours = [];
  360. foreach ($workOrderHours as $workOrder) {
  361. $machineCode = $workOrder['sczl_jtbh'] ?? '';
  362. $hours = floatval($workOrder['占用机时'] ?? 0);
  363. if (!empty($machineCode) && $hours > 0) {
  364. $machineTotalHours[$machineCode] = ($machineTotalHours[$machineCode] ?? 0) + $hours;
  365. }
  366. }
  367. return $machineTotalHours;
  368. }
  369. /**
  370. * 分摊水电到工单
  371. */
  372. protected function allocateUtilitiesToWorkOrders(
  373. array $machineUtilities,
  374. array $workOrderHours,
  375. array $machineTotalHours
  376. ): array {
  377. $allocationResults = [];
  378. $processedCount = 0;
  379. $skippedCount = 0;
  380. foreach ($workOrderHours as $workOrder) {
  381. try {
  382. // 确保 $workOrder 是数组
  383. $orderArray = is_object($workOrder) ? (array)$workOrder : $workOrder;
  384. if (!is_array($orderArray)) {
  385. Log::warning("工单小时数据格式不正确: " . gettype($workOrder));
  386. $skippedCount++;
  387. continue;
  388. }
  389. $machineCode = $orderArray['sczl_jtbh'] ?? '';
  390. $hours = floatval($orderArray['占用机时'] ?? 0);
  391. if (empty($machineCode)) {
  392. Log::debug("工单缺少机器编号: " . json_encode($orderArray));
  393. $skippedCount++;
  394. continue;
  395. }
  396. if (!isset($machineUtilities[$machineCode])) {
  397. Log::debug("机器 {$machineCode} 没有水电费用数据");
  398. $skippedCount++;
  399. continue;
  400. }
  401. if ($machineUtilities[$machineCode]['总费用'] <= 0) {
  402. Log::debug("机器 {$machineCode} 水电费用为0");
  403. $skippedCount++;
  404. continue;
  405. }
  406. if (!isset($machineTotalHours[$machineCode]) || $machineTotalHours[$machineCode] <= 0) {
  407. Log::warning("机器 {$machineCode} 总运行时间为0,无法分摊");
  408. $skippedCount++;
  409. continue;
  410. }
  411. $allocationRatio = $hours / $machineTotalHours[$machineCode];
  412. $allocatedAmount = round($machineUtilities[$machineCode]['总费用'] * $allocationRatio, 2);
  413. $uniqueKey = $this->getWorkOrderUniqueKey($orderArray);
  414. $allocationResults[$uniqueKey] = [
  415. 'unique_key' => $uniqueKey,
  416. 'sczl_gdbh' => $orderArray['sczl_gdbh'] ?? '',
  417. 'sczl_yjno' => $orderArray['sczl_yjno'] ?? '',
  418. 'sczl_gxh' => $orderArray['sczl_gxh'] ?? '',
  419. 'sczl_jtbh' => $machineCode,
  420. '占用机时' => $hours,
  421. '分摊比例' => $allocationRatio,
  422. '分摊金额' => $allocatedAmount,
  423. '机台总费用' => $machineUtilities[$machineCode]['总费用'],
  424. '机台总工时' => $machineTotalHours[$machineCode],
  425. ];
  426. $processedCount++;
  427. } catch (\Exception $e) {
  428. Log::error("分摊水电到工单时出错: " . $e->getMessage());
  429. $skippedCount++;
  430. continue;
  431. }
  432. }
  433. Log::info("分摊水电处理完成,成功: {$processedCount}, 跳过: {$skippedCount}, 总计: " . count($workOrderHours));
  434. return $allocationResults;
  435. }
  436. /**
  437. * 获取工单唯一键
  438. */
  439. protected function getWorkOrderUniqueKey($workOrder): string
  440. {
  441. // 记录传入参数的类型和内容(用于调试)
  442. $type = gettype($workOrder);
  443. Log::debug("getWorkOrderUniqueKey 接收参数类型: {$type}");
  444. // 如果是对象,转换为数组
  445. if (is_object($workOrder)) {
  446. $workOrder = (array)$workOrder;
  447. }
  448. // 确保是数组
  449. if (!is_array($workOrder)) {
  450. Log::error("getWorkOrderUniqueKey 参数不是数组: {$type}, 值: " . print_r($workOrder, true));
  451. return 'invalid-' . uniqid();
  452. }
  453. // 调试:记录数组内容
  454. if (count($workOrder) < 4) {
  455. Log::debug("getWorkOrderUniqueKey 数组内容: " . json_encode($workOrder));
  456. }
  457. // 安全地获取所有可能键名
  458. $gdbh = '';
  459. $yjno = '';
  460. $gxh = '';
  461. $jtbh = '';
  462. // 尝试各种可能的键名
  463. if (isset($workOrder['sczl_gdbh'])) {
  464. $gdbh = $workOrder['sczl_gdbh'];
  465. } elseif (isset($workOrder['工单编号'])) {
  466. $gdbh = $workOrder['工单编号'];
  467. }
  468. if (isset($workOrder['sczl_yjno'])) {
  469. $yjno = $workOrder['sczl_yjno'];
  470. } elseif (isset($workOrder['印件号'])) {
  471. $yjno = $workOrder['印件号'];
  472. }
  473. if (isset($workOrder['sczl_gxh'])) {
  474. $gxh = $workOrder['sczl_gxh'];
  475. } elseif (isset($workOrder['工序号'])) {
  476. $gxh = $workOrder['工序号'];
  477. }
  478. if (isset($workOrder['sczl_jtbh'])) {
  479. $jtbh = $workOrder['sczl_jtbh'];
  480. } elseif (isset($workOrder['机器编号'])) {
  481. $jtbh = $workOrder['机器编号'];
  482. }
  483. // 验证所有字段都不为空
  484. if (empty($gdbh) || empty($yjno) || empty($gxh) || empty($jtbh)) {
  485. Log::warning("工单唯一键字段不完整: gdbh={$gdbh}, yjno={$yjno}, gxh={$gxh}, jtbh={$jtbh}");
  486. }
  487. $key = sprintf('%s-%s-%s-%s', $gdbh, $yjno, $gxh, $jtbh);
  488. Log::debug("生成的唯一键: {$key}");
  489. return $key;
  490. }
  491. /**
  492. * 更新直接水电到成本明细
  493. */
  494. protected function updateDirectUtilitiesToCostDetails(array $allocationResults): void
  495. {
  496. if (empty($allocationResults) || empty($this->monthlyCostDetails)) {
  497. Log::warning("水电费分配结果或成本明细数据为空,无法更新");
  498. return;
  499. }
  500. $updatedCount = 0;
  501. $totalAllocatedAmount = 0;
  502. $notFoundCount = 0;
  503. foreach ($this->monthlyCostDetails as &$costDetail) {
  504. try {
  505. // 确保 $costDetail 是数组
  506. $detailArray = is_object($costDetail) ? (array)$costDetail : $costDetail;
  507. $uniqueKey = $this->getWorkOrderUniqueKey($detailArray);
  508. if (isset($allocationResults[$uniqueKey])) {
  509. $allocatedAmount = $allocationResults[$uniqueKey]['分摊金额'] ?? 0;
  510. $costDetail['直接水电'] = $allocatedAmount;
  511. $totalAllocatedAmount += $allocatedAmount;
  512. $updatedCount++;
  513. } else {
  514. $notFoundCount++;
  515. }
  516. } catch (\Exception $e) {
  517. Log::error("更新直接水电费时出错: " . $e->getMessage());
  518. continue;
  519. }
  520. }
  521. Log::info("已更新直接水电费的工单数量: {$updatedCount}, 未找到的工单数: {$notFoundCount}, 分配总金额: {$totalAllocatedAmount}");
  522. // 如果有大量未找到的工单,记录详细信息
  523. if ($notFoundCount > 0 && $notFoundCount > $updatedCount) {
  524. Log::warning("有大量工单未匹配到水电费分配结果,可能键名不匹配");
  525. }
  526. }
  527. /**
  528. * 3. 计算间接材料分摊
  529. */
  530. protected function calculateIndirectMaterials(string $month): void
  531. {
  532. if (empty($this->monthlyCostDetails)) {
  533. return;
  534. }
  535. $date = substr($month, 0, 4) . '-' . substr($month, 4, 2);
  536. $totalMoney = $this->getIndirectMaterialTotal($date);
  537. if (!$totalMoney || $totalMoney <= 0) {
  538. return;
  539. }
  540. $totalChroma = $this->calculateTotalChroma();
  541. if ($totalChroma <= 0) {
  542. return;
  543. }
  544. $this->allocateIndirectMaterials($totalMoney, $totalChroma);
  545. }
  546. /**
  547. * 获取间接材料总额
  548. */
  549. protected function getIndirectMaterialTotal(string $date): float
  550. {
  551. $result = Db::name('材料出库单列表')
  552. ->where([
  553. '出库日期' => ['like', $date . '%'],
  554. '部门' => '印刷成本中心'
  555. ])
  556. ->whereNull('表体生产订单号')
  557. ->field('SUM(金额) as money')
  558. ->find();
  559. return $result ? floatval($result['money']) : 0;
  560. }
  561. /**
  562. * 计算总色度数
  563. */
  564. protected function calculateTotalChroma(): float
  565. {
  566. $totalChroma = 0;
  567. foreach ($this->monthlyCostDetails as $detail) {
  568. $totalChroma += floatval($detail['班组车头产量']) * floatval($detail['sczl_ms']);
  569. }
  570. return $totalChroma;
  571. }
  572. /**
  573. * 分摊间接材料
  574. */
  575. protected function allocateIndirectMaterials(float $totalMoney, float $totalChroma): void
  576. {
  577. foreach ($this->monthlyCostDetails as &$detail) {
  578. $chroma = floatval($detail['班组车头产量']) * floatval($detail['sczl_ms']);
  579. $money = round($totalMoney * ($chroma / $totalChroma), 2);
  580. $detail['分摊材料'] = $money;
  581. }
  582. }
  583. /**
  584. * 4. 计算间接人工分摊
  585. */
  586. protected function calculateIndirectLabor(string $month): void
  587. {
  588. $wageRatio = $this->getWageRatio();
  589. if (empty($wageRatio)) {
  590. return;
  591. }
  592. $monthWage = $this->getMonthlyWage($month);
  593. if (empty($monthWage)) {
  594. return;
  595. }
  596. $this->allocateIndirectLabor($wageRatio, $monthWage);
  597. }
  598. /**
  599. * 获取工资比例
  600. */
  601. protected function getWageRatio(): array
  602. {
  603. $workshopTotals = [];
  604. foreach ($this->monthlyCostDetails as $detail) {
  605. $workshop = $detail['车间名称'];
  606. $amount = floatval($detail['人工分摊因子']);
  607. $workshopTotals[$workshop] = ($workshopTotals[$workshop] ?? 0) + $amount;
  608. }
  609. $total = array_sum($workshopTotals);
  610. if ($total <= 0) {
  611. return [];
  612. }
  613. $ratios = [];
  614. foreach ($workshopTotals as $workshop => $workshopTotal) {
  615. $ratios[$workshop] = round($workshopTotal / $total, 4);
  616. }
  617. return $ratios;
  618. }
  619. /**
  620. * 获取月度工资数据
  621. */
  622. protected function getMonthlyWage(string $month): array
  623. {
  624. return Db::name('成本_各月其他费用')
  625. ->where('sys_ny', $month)
  626. ->field('部门人员工资,管理人员工资')
  627. ->find() ?: [];
  628. }
  629. /**
  630. * 分摊间接人工
  631. */
  632. protected function allocateIndirectLabor(array $wageRatio, array $monthWage): void
  633. {
  634. foreach ($wageRatio as $workshopName => $ratio) {
  635. $chromaData = $this->getChromaDataForWorkshop($workshopName);
  636. if (empty($chromaData['list']) || $chromaData['total'] == 0) {
  637. continue;
  638. }
  639. $this->allocateWageToWorkshop($workshopName, $ratio, $monthWage, $chromaData);
  640. }
  641. }
  642. /**
  643. * 获取车间色度数数据
  644. */
  645. protected function getChromaDataForWorkshop(string $workshop): array
  646. {
  647. $data = ['total' => 0, 'list' => []];
  648. foreach ($this->monthlyCostDetails as $detail) {
  649. if ($detail['车间名称'] === $workshop) {
  650. $chroma = floatval($detail['班组车头产量']) * floatval($detail['sczl_ms']);
  651. $data['total'] += $chroma;
  652. $data['list'][] = [
  653. 'sczl_gdbh' => $detail['sczl_gdbh'],
  654. 'sczl_yjno' => $detail['sczl_yjno'],
  655. 'sczl_gxh' => $detail['sczl_gxh'],
  656. 'sczl_jtbh' => $detail['sczl_jtbh'],
  657. 'chroma' => $chroma
  658. ];
  659. }
  660. }
  661. return $data;
  662. }
  663. /**
  664. * 分配工资到车间
  665. */
  666. protected function allocateWageToWorkshop(
  667. string $workshop,
  668. float $ratio,
  669. array $monthWage,
  670. array $chromaData
  671. ): void {
  672. $wageTypes = [
  673. '部门人员工资' => '车间人工',
  674. '管理人员工资' => '部门人工附加'
  675. ];
  676. foreach ($wageTypes as $wageType => $fieldName) {
  677. if (empty($monthWage[$wageType]) || $monthWage[$wageType] <= 0) {
  678. continue;
  679. }
  680. $workshopAmount = $ratio * $monthWage[$wageType];
  681. if ($chromaData['total'] <= 0) {
  682. continue;
  683. }
  684. $this->allocateWageToDetails($workshop, $workshopAmount, $chromaData, $fieldName);
  685. }
  686. }
  687. /**
  688. * 分配工资到明细记录
  689. */
  690. protected function allocateWageToDetails(
  691. string $workshop,
  692. float $workshopAmount,
  693. array $chromaData,
  694. string $fieldName
  695. ): void {
  696. foreach ($this->monthlyCostDetails as &$detail) {
  697. if ($detail['车间名称'] === $workshop) {
  698. $chroma = floatval($detail['班组车头产量']) * floatval($detail['sczl_ms']);
  699. $amount = round($chroma / $chromaData['total'] * $workshopAmount, 2);
  700. $detail[$fieldName] += $amount;
  701. }
  702. }
  703. }
  704. /**
  705. * 5. 计算分摊水电
  706. */
  707. protected function calculateApportionedUtilities(array $param): void
  708. {
  709. try {
  710. $month = $param['month'];
  711. $sysId = $param['sys_id'] ?? '';
  712. $utilityData = $this->fetchApportionedUtilities($month);
  713. if (empty($utilityData)) {
  714. Log::info("{$month}月份未找到分摊水电数据");
  715. return;
  716. }
  717. // 记录原始科目名称用于调试
  718. $originalSubjects = array_unique(array_column($utilityData, '科目名称'));
  719. Log::info("原始科目名称: " . implode(', ', $originalSubjects));
  720. $machineAllocations = $this->calculateMachineAllocations($utilityData);
  721. if (!empty($machineAllocations)) {
  722. $this->generateAllocationFactors($machineAllocations, $month, $sysId);
  723. $this->allocateApportionedUtilities($machineAllocations);
  724. }
  725. } catch (\Exception $e) {
  726. Log::error("计算分摊水电时出错: " . $e->getMessage());
  727. throw new Exception("分摊水电计算失败: " . $e->getMessage());
  728. }
  729. }
  730. /**
  731. * 获取分摊水电数据
  732. */
  733. protected function fetchApportionedUtilities(string $month): array
  734. {
  735. return Db::name('成本_各月水电气')
  736. ->where('Sys_ny', $month)
  737. ->whereLike('费用类型', '%分摊%')
  738. ->select();
  739. }
  740. /**
  741. * 计算机台分摊金额
  742. */
  743. protected function calculateMachineAllocations(array $utilityData): array
  744. {
  745. $allocations = [];
  746. $machineHours = $this->getMachineHours();
  747. foreach ($utilityData as $item) {
  748. try {
  749. $subject = $this->simplifySubjectName($item['科目名称']);
  750. $amount = $this->calculateUtilityAmount($item);
  751. if ($amount <= 0) {
  752. continue;
  753. }
  754. $this->allocateBySubject($allocations, $subject, $amount, $machineHours);
  755. } catch (\Exception $e) {
  756. Log::error("计算机台分摊金额时出错: " . $e->getMessage());
  757. continue;
  758. }
  759. }
  760. return $allocations;
  761. }
  762. /**
  763. * 获取机台运行时间
  764. */
  765. protected function getMachineHours(): array
  766. {
  767. $hours = [];
  768. foreach ($this->monthlyCostDetails as $detail) {
  769. $machine = $detail['sczl_jtbh'];
  770. $hour = floatval($detail['占用机时']);
  771. if (!empty($machine)) {
  772. $hours[$machine] = ($hours[$machine] ?? 0) + $hour;
  773. }
  774. }
  775. return $hours;
  776. }
  777. /**
  778. * 按科目分摊
  779. */
  780. protected function allocateBySubject(
  781. array &$allocations,
  782. string $subject,
  783. float $amount,
  784. array $machineHours
  785. ): void {
  786. try {
  787. if ($subject === '待分摊总额') {
  788. $this->allocateByFloor($allocations, $amount, $machineHours);
  789. } elseif (in_array($subject, ['锅炉', '热水锅炉'])) {
  790. $this->allocateToRollCoater($allocations, $subject, $amount, $machineHours);
  791. } else {
  792. $this->allocateGlobally($allocations, $subject, $amount, $machineHours);
  793. }
  794. } catch (\Exception $e) {
  795. Log::error("按科目分摊时出错 (科目: {$subject}): " . $e->getMessage());
  796. }
  797. }
  798. /**
  799. * 按楼层分摊
  800. */
  801. protected function allocateByFloor(array &$allocations, float $amount, array $machineHours): void
  802. {
  803. $floorData = $this->groupMachinesByFloor($machineHours);
  804. if ($floorData['totalHours'] <= 0) {
  805. return;
  806. }
  807. foreach ($floorData['floors'] as $floor => $data) {
  808. if ($data['hours'] <= 0) {
  809. continue;
  810. }
  811. $floorAmount = $amount * ($data['hours'] / $floorData['totalHours']);
  812. $this->allocateToFloorMachines($allocations, $floorAmount, $data['machines'], $machineHours);
  813. }
  814. }
  815. /**
  816. * 按楼层分组机台
  817. */
  818. protected function groupMachinesByFloor(array $machineHours): array
  819. {
  820. $floors = ['1' => ['hours' => 0, 'machines' => []], '2' => ['hours' => 0, 'machines' => []]];
  821. $totalHours = 0;
  822. foreach ($machineHours as $machine => $hours) {
  823. $floor = $this->getFloorByMachine($machine);
  824. if ($floor && isset($floors[$floor])) {
  825. $floors[$floor]['hours'] += $hours;
  826. $floors[$floor]['machines'][] = $machine;
  827. $totalHours += $hours;
  828. }
  829. }
  830. return ['floors' => $floors, 'totalHours' => $totalHours];
  831. }
  832. /**
  833. * 分摊到楼层机台
  834. */
  835. protected function allocateToFloorMachines(
  836. array &$allocations,
  837. float $floorAmount,
  838. array $machines,
  839. array $machineHours
  840. ): void {
  841. $floorHours = 0;
  842. foreach ($machines as $machine) {
  843. $floorHours += $machineHours[$machine];
  844. }
  845. if ($floorHours <= 0) {
  846. return;
  847. }
  848. foreach ($machines as $machine) {
  849. $machineHoursAmount = $machineHours[$machine];
  850. if ($machineHoursAmount <= 0) {
  851. continue;
  852. }
  853. $allocations[$machine]['待分摊总额'] =
  854. ($allocations[$machine]['待分摊总额'] ?? 0) +
  855. round($floorAmount * ($machineHoursAmount / $floorHours), 2);
  856. }
  857. }
  858. /**
  859. * 只分摊到卷凹机组
  860. */
  861. protected function allocateToRollCoater(
  862. array &$allocations,
  863. string $subject,
  864. float $amount,
  865. array $machineHours
  866. ): void {
  867. $rollCoaterMachines = $this->filterRollCoaterMachines(array_keys($machineHours));
  868. $totalHours = 0;
  869. foreach ($rollCoaterMachines as $machine) {
  870. $totalHours += $machineHours[$machine];
  871. }
  872. if ($totalHours <= 0) {
  873. return;
  874. }
  875. foreach ($rollCoaterMachines as $machine) {
  876. $machineHoursAmount = $machineHours[$machine];
  877. if ($machineHoursAmount <= 0) {
  878. continue;
  879. }
  880. $allocations[$machine][$subject] =
  881. ($allocations[$machine][$subject] ?? 0) +
  882. round($amount * ($machineHoursAmount / $totalHours), 2);
  883. }
  884. }
  885. /**
  886. * 全局分摊
  887. */
  888. protected function allocateGlobally(
  889. array &$allocations,
  890. string $subject,
  891. float $amount,
  892. array $machineHours
  893. ): void {
  894. $totalHours = array_sum($machineHours);
  895. if ($totalHours <= 0) {
  896. Log::warning("全局分摊失败:总机时为0");
  897. return;
  898. }
  899. foreach ($machineHours as $machine => $hours) {
  900. try {
  901. // 确保 $machine 是有效的字符串键名
  902. if (!is_string($machine) && !is_numeric($machine)) {
  903. Log::warning("无效的机器键名: " . print_r($machine, true));
  904. continue;
  905. }
  906. $machine = (string)$machine;
  907. if ($hours <= 0) {
  908. continue;
  909. }
  910. if (!isset($allocations[$machine])) {
  911. $allocations[$machine] = [];
  912. }
  913. $machineAmount = round($amount * ($hours / $totalHours), 2);
  914. $allocations[$machine][$subject] =
  915. ($allocations[$machine][$subject] ?? 0) + $machineAmount;
  916. } catch (\Exception $e) {
  917. Log::error("全局分摊到机器 {$machine} 时出错: " . $e->getMessage());
  918. continue;
  919. }
  920. }
  921. }
  922. /**
  923. * 根据机台获取楼层
  924. */
  925. protected function getFloorByMachine(string $machine): ?string
  926. {
  927. $group = Db::name('设备_基本资料')
  928. ->where('设备编号', $machine)
  929. ->value('设备编组');
  930. if (!$group) {
  931. return null;
  932. }
  933. foreach (self::FLOOR_GROUP_MAP as $floor => $groupNames) {
  934. foreach ($groupNames as $groupName) {
  935. if (strpos($group, $groupName) !== false) {
  936. return $floor;
  937. }
  938. }
  939. }
  940. return null;
  941. }
  942. /**
  943. * 筛选卷凹机组的机台
  944. */
  945. protected function filterRollCoaterMachines(array $machines): array
  946. {
  947. $rollCoater = [];
  948. foreach ($machines as $machine) {
  949. $group = Db::name('设备_基本资料')
  950. ->where('设备编号', $machine)
  951. ->value('设备编组');
  952. if ($group && strpos($group, '03、卷凹机组') !== false) {
  953. $rollCoater[] = $machine;
  954. }
  955. }
  956. return $rollCoater;
  957. }
  958. /**
  959. * 简化科目名称
  960. */
  961. protected function simplifySubjectName(string $subject): string
  962. {
  963. // 先尝试完全匹配
  964. $subject = trim($subject);
  965. foreach (self::SUBJECT_TO_FIELD_MAP as $keyword => $mappedField) {
  966. if ($subject === $keyword) {
  967. return $mappedField;
  968. }
  969. }
  970. // 尝试部分匹配
  971. foreach (self::SUBJECT_TO_FIELD_MAP as $keyword => $mappedField) {
  972. if (strpos($subject, $keyword) !== false) {
  973. Log::debug("科目名称部分匹配: {$subject} => {$mappedField} (关键词: {$keyword})");
  974. return $mappedField;
  975. }
  976. }
  977. // 如果都不匹配,使用默认映射
  978. Log::warning("未识别的科目名称: {$subject}, 将映射到 '分摊水电'");
  979. return '分摊水电';
  980. }
  981. /**
  982. * 计算水电金额
  983. */
  984. protected function calculateUtilityAmount(array $item): float
  985. {
  986. $electricity = $this->calculateElectricityCost($item);
  987. $gas = $this->calculateGasCost($item);
  988. return $electricity + $gas;
  989. }
  990. /**
  991. * 生成分摊系数记录
  992. */
  993. protected function generateAllocationFactors(array $allocations, string $month, string $sysId): void
  994. {
  995. $now = date('Y-m-d H:i:s');
  996. foreach ($allocations as $machine => $subjects) {
  997. if (!is_string($machine) && !is_numeric($machine)) {
  998. Log::warning("无效的机台标识: " . print_r($machine, true));
  999. continue;
  1000. }
  1001. foreach ($subjects as $subject => $amount) {
  1002. if (!is_string($subject)) {
  1003. Log::warning("无效的科目名称: " . print_r($subject, true));
  1004. continue;
  1005. }
  1006. // 使用简化后的科目名称
  1007. $simplifiedSubject = $this->simplifySubjectName($subject);
  1008. $this->allocationFactors[] = [
  1009. 'Sys_ny' => $month,
  1010. '科目名称' => $simplifiedSubject, // 原始科目名称
  1011. '设备编号' => (string)$machine,
  1012. '分摊系数' => 1,
  1013. '分摊金额' => floatval($amount),
  1014. 'Sys_id' => $sysId,
  1015. 'Sys_rq' => $now,
  1016. ];
  1017. }
  1018. }
  1019. }
  1020. /**
  1021. * 分配分摊水电
  1022. */
  1023. protected function allocateApportionedUtilities(array $machineAllocations): void
  1024. {
  1025. $machineRates = $this->calculateMachineRates($machineAllocations);
  1026. foreach ($this->monthlyCostDetails as &$detail) {
  1027. $machine = $detail['sczl_jtbh'];
  1028. $hours = floatval($detail['占用机时']);
  1029. if ($hours <= 0 || !isset($machineRates[$machine])) {
  1030. continue;
  1031. }
  1032. // 直接水电费(保持不变)
  1033. $detail['直接水电'] = round($hours * 0.69, 2);
  1034. // 分摊水电费 - 使用映射后的字段名
  1035. foreach ($machineRates[$machine] as $subject => $rate) {
  1036. $field = $this->getUtilityFieldName($subject);
  1037. if (!isset($detail[$field])) {
  1038. Log::warning("数据库字段不存在: {$field},跳过该分摊");
  1039. continue;
  1040. }
  1041. $detail[$field] = round($hours * $rate, 2);
  1042. }
  1043. }
  1044. }
  1045. /**
  1046. * 计算机台每机时费用
  1047. */
  1048. protected function calculateMachineRates(array $allocations): array
  1049. {
  1050. $rates = [];
  1051. $machineHours = $this->getMachineHours();
  1052. foreach ($allocations as $machine => $subjects) {
  1053. $totalHours = $machineHours[$machine] ?? 0;
  1054. if ($totalHours <= 0) {
  1055. continue;
  1056. }
  1057. $rates[$machine] = [];
  1058. foreach ($subjects as $subject => $amount) {
  1059. $rates[$machine][$subject] = round($amount / $totalHours, 4);
  1060. }
  1061. }
  1062. return $rates;
  1063. }
  1064. /**
  1065. * 获取水电字段名
  1066. */
  1067. protected function getUtilityFieldName(string $subject): string
  1068. {
  1069. // 使用映射表
  1070. if (isset(self::SUBJECT_TO_FIELD_MAP[$subject])) {
  1071. return self::SUBJECT_TO_FIELD_MAP[$subject];
  1072. }
  1073. // 尝试部分匹配
  1074. foreach (self::SUBJECT_TO_FIELD_MAP as $keyword => $mappedField) {
  1075. if (strpos($subject, $keyword) !== false) {
  1076. return $mappedField;
  1077. }
  1078. }
  1079. // 默认映射到 '分摊水电'
  1080. Log::warning("未知的科目字段: {$subject}, 映射到 '分摊水电'");
  1081. return '分摊水电';
  1082. }
  1083. /**
  1084. * 统一保存所有数据
  1085. */
  1086. protected function saveAllData(string $month, string $sysId): void
  1087. {
  1088. // 1. 删除旧数据
  1089. $this->deleteOldData($month);
  1090. // 2. 插入前检查数据结构
  1091. $this->validateDataStructure();
  1092. // 3. 插入新数据
  1093. $this->insertAllData();
  1094. }
  1095. /**
  1096. * 删除旧数据
  1097. */
  1098. protected function deleteOldData(string $month): void
  1099. {
  1100. Db::name('成本v23_月度成本明细')->where('sys_ny', $month)->delete();
  1101. Db::name('成本_各月分摊系数')->where('Sys_ny', $month)->delete();
  1102. }
  1103. /**
  1104. * 验证数据结构
  1105. */
  1106. protected function validateDataStructure(): void
  1107. {
  1108. if (empty($this->monthlyCostDetails)) {
  1109. Log::warning("月度成本明细数据为空");
  1110. return;
  1111. }
  1112. $tableName = '成本v23_月度成本明细';
  1113. try {
  1114. // 获取数据库表结构
  1115. $columns = Db::query("DESCRIBE `{$tableName}`");
  1116. $columnNames = array_column($columns, 'Field');
  1117. Log::info("表{$tableName}结构字段数: " . count($columnNames));
  1118. Log::debug("表字段列表: " . implode(', ', $columnNames));
  1119. // 检查并修正每行数据
  1120. foreach ($this->monthlyCostDetails as $index => &$row) {
  1121. // 确保行是数组
  1122. $rowArray = is_object($row) ? (array)$row : $row;
  1123. // 1. 移除表中不存在的字段
  1124. foreach ($rowArray as $key => $value) {
  1125. if (!in_array($key, $columnNames)) {
  1126. Log::warning("移除无效字段 (行 {$index}): {$key}");
  1127. unset($rowArray[$key]);
  1128. }
  1129. }
  1130. // 2. 确保所有表字段都存在
  1131. foreach ($columnNames as $column) {
  1132. if (!array_key_exists($column, $rowArray)) {
  1133. // 设置默认值
  1134. if (in_array($column, ['直接水电', '分摊材料', '车间人工', '部门人工附加', '分摊水电',
  1135. '废气处理', '锅炉', '空压机', '热水锅炉', '真空鼓风机', '中央空调', '分摊其他'])) {
  1136. $rowArray[$column] = 0;
  1137. } else {
  1138. $rowArray[$column] = null;
  1139. }
  1140. Log::debug("添加缺失字段 (行 {$index}): {$column}");
  1141. }
  1142. }
  1143. // 3. 确保字段顺序与表一致
  1144. $orderedRow = [];
  1145. foreach ($columnNames as $column) {
  1146. $orderedRow[$column] = $rowArray[$column] ?? null;
  1147. }
  1148. // 4. 修复字段名中的特殊字符
  1149. $this->sanitizeFieldNames($orderedRow);
  1150. $row = $orderedRow;
  1151. // 记录第一行的字段信息用于调试
  1152. if ($index === 0) {
  1153. Log::debug("第一行字段数: " . count($orderedRow) . ", 字段: " . implode(', ', array_keys($orderedRow)));
  1154. }
  1155. }
  1156. Log::info("数据结构验证完成,总记录数: " . count($this->monthlyCostDetails));
  1157. } catch (\Exception $e) {
  1158. Log::error("验证数据结构时出错: " . $e->getMessage());
  1159. }
  1160. }
  1161. /**
  1162. * 修复行数据
  1163. */
  1164. protected function fixRowData(array &$row, array $columnNames, int $index): void
  1165. {
  1166. $fixedRow = [];
  1167. foreach ($columnNames as $column) {
  1168. $fixedRow[$column] = $row[$column] ?? 0;
  1169. }
  1170. $this->monthlyCostDetails[$index] = $fixedRow;
  1171. Log::info("已修复第" . ($index + 1) . "行数据");
  1172. }
  1173. /**
  1174. * 插入所有数据
  1175. */
  1176. protected function insertAllData(): void
  1177. {
  1178. $this->insertMonthlyCostDetails();
  1179. $this->insertAllocationFactors();
  1180. }
  1181. /**
  1182. * 插入月度成本明细
  1183. */
  1184. protected function insertMonthlyCostDetails(): void
  1185. {
  1186. if (empty($this->monthlyCostDetails)) {
  1187. return;
  1188. }
  1189. $total = count($this->monthlyCostDetails);
  1190. for ($i = 0; $i < $total; $i += self::BATCH_SIZE) {
  1191. $batch = array_slice($this->monthlyCostDetails, $i, self::BATCH_SIZE);
  1192. $this->insertBatch($batch, '成本v23_月度成本明细', $i);
  1193. }
  1194. }
  1195. /**
  1196. * 插入批次数据
  1197. */
  1198. protected function insertBatch(array $batch, string $tableName, int $startIndex): void
  1199. {
  1200. if (empty($batch)) {
  1201. Log::warning("批次数据为空,跳过插入");
  1202. return;
  1203. }
  1204. $firstRow = reset($batch);
  1205. $fields = array_keys($firstRow);
  1206. // 验证字段名不包含特殊字符
  1207. foreach ($fields as $field) {
  1208. if (preg_match('/[#@$%^&*()+\-=\[\]{}|;:"<>,.?\/]/', $field)) {
  1209. Log::error("字段名包含特殊字符: {$field}");
  1210. throw new Exception("字段名 '{$field}' 包含非法字符");
  1211. }
  1212. }
  1213. $fieldStr = '`' . implode('`,`', $fields) . '`';
  1214. $values = [];
  1215. foreach ($batch as $rowIndex => $row) {
  1216. $rowValues = [];
  1217. foreach ($fields as $field) {
  1218. $value = $row[$field] ?? null;
  1219. if (is_numeric($value)) {
  1220. $rowValues[] = $value;
  1221. } elseif (is_null($value)) {
  1222. $rowValues[] = 'NULL';
  1223. } else {
  1224. $rowValues[] = "'" . addslashes((string)$value) . "'";
  1225. }
  1226. }
  1227. $values[] = '(' . implode(',', $rowValues) . ')';
  1228. // 记录第一行数据用于调试
  1229. if ($rowIndex === 0 && $startIndex === 0) {
  1230. Log::debug("第一行数据字段: " . implode(', ', $fields));
  1231. Log::debug("第一行数据值: " . implode(', ', $rowValues));
  1232. }
  1233. }
  1234. $sql = "INSERT INTO `{$tableName}` ({$fieldStr}) VALUES " . implode(',', $values);
  1235. // 记录SQL语句(前200个字符)
  1236. Log::debug("SQL语句: " . substr($sql, 0, 200) . "...");
  1237. try {
  1238. $result = Db::execute($sql);
  1239. Log::info("成功插入批次 " . (($startIndex / self::BATCH_SIZE) + 1) . ", 影响行数: " . $result);
  1240. } catch (\Exception $e) {
  1241. Log::error("插入批次失败: " . $e->getMessage());
  1242. Log::error("失败SQL: " . $sql);
  1243. throw $e;
  1244. }
  1245. }
  1246. /**
  1247. * 插入分摊系数
  1248. */
  1249. protected function insertAllocationFactors(): void
  1250. {
  1251. if (!empty($this->allocationFactors)) {
  1252. $total = count($this->allocationFactors);
  1253. for ($i = 0; $i < $total; $i += self::BATCH_SIZE) {
  1254. $batch = array_slice($this->allocationFactors, $i, self::BATCH_SIZE);
  1255. $this->insertBatch($batch, '成本_各月分摊系数', $i);
  1256. }
  1257. }
  1258. }
  1259. /**
  1260. * 记录成功日志
  1261. */
  1262. protected function logSuccess(string $month): void
  1263. {
  1264. Log::info("成本核算完成", [
  1265. 'month' => $month,
  1266. '月度成本明细记录数' => count($this->monthlyCostDetails),
  1267. '分摊系数记录数' => count($this->allocationFactors)
  1268. ]);
  1269. }
  1270. /**
  1271. * 构建成功响应
  1272. */
  1273. protected function buildSuccessResponse(string $month): array
  1274. {
  1275. return [
  1276. 'success' => true,
  1277. 'message' => '成本核算完成',
  1278. 'month' => $month,
  1279. 'stats' => [
  1280. 'monthly_cost_details' => count($this->monthlyCostDetails),
  1281. 'allocation_factors' => count($this->allocationFactors)
  1282. ]
  1283. ];
  1284. }
  1285. /**
  1286. * 记录错误日志
  1287. */
  1288. protected function logError(\Throwable $t): void
  1289. {
  1290. $errorDetails = [
  1291. '时间' => date('Y-m-d H:i:s'),
  1292. '错误类型' => get_class($t),
  1293. '错误信息' => $t->getMessage(),
  1294. '错误代码' => $t->getCode(),
  1295. '文件' => $t->getFile(),
  1296. '行号' => $t->getLine(),
  1297. '堆栈跟踪' => $t->getTraceAsString(),
  1298. '月度成本明细数' => count($this->monthlyCostDetails),
  1299. '分摊系数数' => count($this->allocationFactors),
  1300. ];
  1301. Log::error("统一成本核算失败详情: " . json_encode($errorDetails, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
  1302. }
  1303. /**
  1304. * 构建错误响应
  1305. */
  1306. protected function buildErrorResponse(Exception $e): array
  1307. {
  1308. return [
  1309. 'success' => false,
  1310. 'message' => '成本核算失败: ' . $e->getMessage(),
  1311. 'error' => $e->getMessage()
  1312. ];
  1313. }
  1314. /**
  1315. * 清理字段名中的特殊字符
  1316. */
  1317. protected function sanitizeFieldNames(array &$row): void
  1318. {
  1319. $sanitized = [];
  1320. foreach ($row as $key => $value) {
  1321. // 移除字段名中的特殊字符,只保留字母、数字、下划线和中文字符
  1322. $cleanKey = preg_replace('/[^\w\x{4e00}-\x{9fa5}]/u', '', $key);
  1323. if ($cleanKey !== $key) {
  1324. Log::debug("清理字段名: {$key} => {$cleanKey}");
  1325. }
  1326. $sanitized[$cleanKey] = $value;
  1327. }
  1328. $row = $sanitized;
  1329. }
  1330. }