UnifiedCostCalculationService.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581
  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. '科目名称' => $subject, // 原始科目名称
  1011. '简化科目名称' => $simplifiedSubject, // 简化后的科目名称
  1012. '设备编号' => (string)$machine,
  1013. '分摊系数' => 1,
  1014. '分摊金额' => floatval($amount),
  1015. 'Sys_id' => $sysId,
  1016. 'Sys_rq' => $now,
  1017. ];
  1018. }
  1019. }
  1020. }
  1021. /**
  1022. * 分配分摊水电
  1023. */
  1024. protected function allocateApportionedUtilities(array $machineAllocations): void
  1025. {
  1026. $machineRates = $this->calculateMachineRates($machineAllocations);
  1027. foreach ($this->monthlyCostDetails as &$detail) {
  1028. $machine = $detail['sczl_jtbh'];
  1029. $hours = floatval($detail['占用机时']);
  1030. if ($hours <= 0 || !isset($machineRates[$machine])) {
  1031. continue;
  1032. }
  1033. // 直接水电费(保持不变)
  1034. $detail['直接水电'] = round($hours * 0.69, 2);
  1035. // 分摊水电费 - 使用映射后的字段名
  1036. foreach ($machineRates[$machine] as $subject => $rate) {
  1037. $field = $this->getUtilityFieldName($subject);
  1038. if (!isset($detail[$field])) {
  1039. Log::warning("数据库字段不存在: {$field},跳过该分摊");
  1040. continue;
  1041. }
  1042. $detail[$field] = round($hours * $rate, 2);
  1043. }
  1044. }
  1045. }
  1046. /**
  1047. * 计算机台每机时费用
  1048. */
  1049. protected function calculateMachineRates(array $allocations): array
  1050. {
  1051. $rates = [];
  1052. $machineHours = $this->getMachineHours();
  1053. foreach ($allocations as $machine => $subjects) {
  1054. $totalHours = $machineHours[$machine] ?? 0;
  1055. if ($totalHours <= 0) {
  1056. continue;
  1057. }
  1058. $rates[$machine] = [];
  1059. foreach ($subjects as $subject => $amount) {
  1060. $rates[$machine][$subject] = round($amount / $totalHours, 4);
  1061. }
  1062. }
  1063. return $rates;
  1064. }
  1065. /**
  1066. * 获取水电字段名
  1067. */
  1068. protected function getUtilityFieldName(string $subject): string
  1069. {
  1070. // 使用映射表
  1071. if (isset(self::SUBJECT_TO_FIELD_MAP[$subject])) {
  1072. return self::SUBJECT_TO_FIELD_MAP[$subject];
  1073. }
  1074. // 尝试部分匹配
  1075. foreach (self::SUBJECT_TO_FIELD_MAP as $keyword => $mappedField) {
  1076. if (strpos($subject, $keyword) !== false) {
  1077. return $mappedField;
  1078. }
  1079. }
  1080. // 默认映射到 '分摊水电'
  1081. Log::warning("未知的科目字段: {$subject}, 映射到 '分摊水电'");
  1082. return '分摊水电';
  1083. }
  1084. /**
  1085. * 统一保存所有数据
  1086. */
  1087. protected function saveAllData(string $month, string $sysId): void
  1088. {
  1089. // 1. 删除旧数据
  1090. $this->deleteOldData($month);
  1091. // 2. 插入前检查数据结构
  1092. $this->validateDataStructure();
  1093. // 3. 插入新数据
  1094. $this->insertAllData();
  1095. }
  1096. /**
  1097. * 删除旧数据
  1098. */
  1099. protected function deleteOldData(string $month): void
  1100. {
  1101. Db::name('成本v23_月度成本明细')->where('sys_ny', $month)->delete();
  1102. Db::name('成本_各月分摊系数')->where('Sys_ny', $month)->delete();
  1103. }
  1104. /**
  1105. * 验证数据结构
  1106. */
  1107. protected function validateDataStructure(): void
  1108. {
  1109. if (empty($this->monthlyCostDetails)) {
  1110. Log::warning("月度成本明细数据为空");
  1111. return;
  1112. }
  1113. $tableName = '成本v23_月度成本明细';
  1114. try {
  1115. // 获取数据库表结构
  1116. $columns = Db::query("DESCRIBE `{$tableName}`");
  1117. $columnNames = array_column($columns, 'Field');
  1118. Log::info("表{$tableName}结构字段数: " . count($columnNames));
  1119. Log::debug("表字段列表: " . implode(', ', $columnNames));
  1120. // 检查并修正每行数据
  1121. foreach ($this->monthlyCostDetails as $index => &$row) {
  1122. // 确保行是数组
  1123. $rowArray = is_object($row) ? (array)$row : $row;
  1124. // 1. 移除表中不存在的字段
  1125. foreach ($rowArray as $key => $value) {
  1126. if (!in_array($key, $columnNames)) {
  1127. Log::warning("移除无效字段 (行 {$index}): {$key}");
  1128. unset($rowArray[$key]);
  1129. }
  1130. }
  1131. // 2. 确保所有表字段都存在
  1132. foreach ($columnNames as $column) {
  1133. if (!array_key_exists($column, $rowArray)) {
  1134. // 设置默认值
  1135. if (in_array($column, ['直接水电', '分摊材料', '车间人工', '部门人工附加', '分摊水电',
  1136. '废气处理', '锅炉', '空压机', '热水锅炉', '真空鼓风机', '中央空调', '分摊其他'])) {
  1137. $rowArray[$column] = 0;
  1138. } else {
  1139. $rowArray[$column] = null;
  1140. }
  1141. Log::debug("添加缺失字段 (行 {$index}): {$column}");
  1142. }
  1143. }
  1144. // 3. 确保字段顺序与表一致
  1145. $orderedRow = [];
  1146. foreach ($columnNames as $column) {
  1147. $orderedRow[$column] = $rowArray[$column] ?? null;
  1148. }
  1149. // 4. 修复字段名中的特殊字符
  1150. $this->sanitizeFieldNames($orderedRow);
  1151. $row = $orderedRow;
  1152. // 记录第一行的字段信息用于调试
  1153. if ($index === 0) {
  1154. Log::debug("第一行字段数: " . count($orderedRow) . ", 字段: " . implode(', ', array_keys($orderedRow)));
  1155. }
  1156. }
  1157. Log::info("数据结构验证完成,总记录数: " . count($this->monthlyCostDetails));
  1158. } catch (\Exception $e) {
  1159. Log::error("验证数据结构时出错: " . $e->getMessage());
  1160. }
  1161. }
  1162. /**
  1163. * 修复行数据
  1164. */
  1165. protected function fixRowData(array &$row, array $columnNames, int $index): void
  1166. {
  1167. $fixedRow = [];
  1168. foreach ($columnNames as $column) {
  1169. $fixedRow[$column] = $row[$column] ?? 0;
  1170. }
  1171. $this->monthlyCostDetails[$index] = $fixedRow;
  1172. Log::info("已修复第" . ($index + 1) . "行数据");
  1173. }
  1174. /**
  1175. * 插入所有数据
  1176. */
  1177. protected function insertAllData(): void
  1178. {
  1179. $this->insertMonthlyCostDetails();
  1180. $this->insertAllocationFactors();
  1181. }
  1182. /**
  1183. * 插入月度成本明细
  1184. */
  1185. protected function insertMonthlyCostDetails(): void
  1186. {
  1187. if (empty($this->monthlyCostDetails)) {
  1188. return;
  1189. }
  1190. $total = count($this->monthlyCostDetails);
  1191. for ($i = 0; $i < $total; $i += self::BATCH_SIZE) {
  1192. $batch = array_slice($this->monthlyCostDetails, $i, self::BATCH_SIZE);
  1193. $this->insertBatch($batch, '成本v23_月度成本明细', $i);
  1194. }
  1195. }
  1196. /**
  1197. * 插入批次数据
  1198. */
  1199. protected function insertBatch(array $batch, string $tableName, int $startIndex): void
  1200. {
  1201. if (empty($batch)) {
  1202. Log::warning("批次数据为空,跳过插入");
  1203. return;
  1204. }
  1205. $firstRow = reset($batch);
  1206. $fields = array_keys($firstRow);
  1207. // 验证字段名不包含特殊字符
  1208. foreach ($fields as $field) {
  1209. if (preg_match('/[#@$%^&*()+\-=\[\]{}|;:"<>,.?\/]/', $field)) {
  1210. Log::error("字段名包含特殊字符: {$field}");
  1211. throw new Exception("字段名 '{$field}' 包含非法字符");
  1212. }
  1213. }
  1214. $fieldStr = '`' . implode('`,`', $fields) . '`';
  1215. $values = [];
  1216. foreach ($batch as $rowIndex => $row) {
  1217. $rowValues = [];
  1218. foreach ($fields as $field) {
  1219. $value = $row[$field] ?? null;
  1220. if (is_numeric($value)) {
  1221. $rowValues[] = $value;
  1222. } elseif (is_null($value)) {
  1223. $rowValues[] = 'NULL';
  1224. } else {
  1225. $rowValues[] = "'" . addslashes((string)$value) . "'";
  1226. }
  1227. }
  1228. $values[] = '(' . implode(',', $rowValues) . ')';
  1229. // 记录第一行数据用于调试
  1230. if ($rowIndex === 0 && $startIndex === 0) {
  1231. Log::debug("第一行数据字段: " . implode(', ', $fields));
  1232. Log::debug("第一行数据值: " . implode(', ', $rowValues));
  1233. }
  1234. }
  1235. $sql = "INSERT INTO `{$tableName}` ({$fieldStr}) VALUES " . implode(',', $values);
  1236. // 记录SQL语句(前200个字符)
  1237. Log::debug("SQL语句: " . substr($sql, 0, 200) . "...");
  1238. try {
  1239. $result = Db::execute($sql);
  1240. Log::info("成功插入批次 " . (($startIndex / self::BATCH_SIZE) + 1) . ", 影响行数: " . $result);
  1241. } catch (\Exception $e) {
  1242. Log::error("插入批次失败: " . $e->getMessage());
  1243. Log::error("失败SQL: " . $sql);
  1244. throw $e;
  1245. }
  1246. }
  1247. /**
  1248. * 插入分摊系数
  1249. */
  1250. protected function insertAllocationFactors(): void
  1251. {
  1252. if (!empty($this->allocationFactors)) {
  1253. $total = count($this->allocationFactors);
  1254. for ($i = 0; $i < $total; $i += self::BATCH_SIZE) {
  1255. $batch = array_slice($this->allocationFactors, $i, self::BATCH_SIZE);
  1256. $this->insertBatch($batch, '成本_各月分摊系数', $i);
  1257. }
  1258. }
  1259. }
  1260. /**
  1261. * 记录成功日志
  1262. */
  1263. protected function logSuccess(string $month): void
  1264. {
  1265. Log::info("成本核算完成", [
  1266. 'month' => $month,
  1267. '月度成本明细记录数' => count($this->monthlyCostDetails),
  1268. '分摊系数记录数' => count($this->allocationFactors)
  1269. ]);
  1270. }
  1271. /**
  1272. * 构建成功响应
  1273. */
  1274. protected function buildSuccessResponse(string $month): array
  1275. {
  1276. return [
  1277. 'success' => true,
  1278. 'message' => '成本核算完成',
  1279. 'month' => $month,
  1280. 'stats' => [
  1281. 'monthly_cost_details' => count($this->monthlyCostDetails),
  1282. 'allocation_factors' => count($this->allocationFactors)
  1283. ]
  1284. ];
  1285. }
  1286. /**
  1287. * 记录错误日志
  1288. */
  1289. protected function logError(\Throwable $t): void
  1290. {
  1291. $errorDetails = [
  1292. '时间' => date('Y-m-d H:i:s'),
  1293. '错误类型' => get_class($t),
  1294. '错误信息' => $t->getMessage(),
  1295. '错误代码' => $t->getCode(),
  1296. '文件' => $t->getFile(),
  1297. '行号' => $t->getLine(),
  1298. '堆栈跟踪' => $t->getTraceAsString(),
  1299. '月度成本明细数' => count($this->monthlyCostDetails),
  1300. '分摊系数数' => count($this->allocationFactors),
  1301. ];
  1302. Log::error("统一成本核算失败详情: " . json_encode($errorDetails, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
  1303. }
  1304. /**
  1305. * 构建错误响应
  1306. */
  1307. protected function buildErrorResponse(Exception $e): array
  1308. {
  1309. return [
  1310. 'success' => false,
  1311. 'message' => '成本核算失败: ' . $e->getMessage(),
  1312. 'error' => $e->getMessage()
  1313. ];
  1314. }
  1315. /**
  1316. * 清理字段名中的特殊字符
  1317. */
  1318. protected function sanitizeFieldNames(array &$row): void
  1319. {
  1320. $sanitized = [];
  1321. foreach ($row as $key => $value) {
  1322. // 移除字段名中的特殊字符,只保留字母、数字、下划线和中文字符
  1323. $cleanKey = preg_replace('/[^\w\x{4e00}-\x{9fa5}]/u', '', $key);
  1324. if ($cleanKey !== $key) {
  1325. Log::debug("清理字段名: {$key} => {$cleanKey}");
  1326. }
  1327. $sanitized[$cleanKey] = $value;
  1328. }
  1329. $row = $sanitized;
  1330. }
  1331. }