WorkOrderProcess.php 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use PhpOffice\PhpSpreadsheet\IOFactory;
  5. use think\Db;
  6. /**
  7. * 工单工艺管理
  8. *
  9. */
  10. class WorkOrderProcess extends Api
  11. {
  12. protected $noNeedLogin = ['*'];
  13. protected $noNeedRight = ['*'];
  14. /**
  15. * 工单大工序列表
  16. * @param workorder 工单编号
  17. */
  18. public function MajorprocessList()
  19. {
  20. if (!$this->request->isGet()) {
  21. $this->error('请求方法错误');
  22. }
  23. $params = $this->request->param();
  24. if (empty($params['workorder'])) {
  25. $this->error('工单编号不能为空');
  26. }
  27. $list = db('工单_工艺资料')
  28. ->where('订单编号', $params['workorder'])
  29. ->field('工序编号,工序名称,工序备注')
  30. ->distinct('工序名称')
  31. ->select();
  32. if(empty($list)){
  33. $this->error('该工单没有大工序');
  34. }
  35. $this->success('成功', $list);
  36. }
  37. /**
  38. * 工单部件列表
  39. * @param workorder 工单编号
  40. */
  41. public function PartList()
  42. {
  43. if (!$this->request->isGet()) {
  44. $this->error('请求方法错误');
  45. }
  46. $params = $this->request->param();
  47. if (empty($params['workorder'])) {
  48. $this->error('工单编号不能为空');
  49. }
  50. $list = db('工单_部件资料')
  51. ->where('work_order', $params['workorder'])
  52. ->where('del_rq', null)
  53. ->field('part_code as 部件编号,part_name as 部件名称,remark as 部件备注,part_type as 部件类型,status as 状态,
  54. sys_id as 操作人,sys_rq as 操作时间,mod_rq as 修改时间,mod_id as 修改人,id as 部件ID')
  55. ->orderRaw('CAST(part_code AS UNSIGNED)')
  56. ->select();
  57. if(empty($list)){
  58. // $this->error('该工单没有部件,请先添加部件');
  59. }
  60. $this->success('成功', $list);
  61. }
  62. /**
  63. * 新增工单部件
  64. * @param workorder 工单编号
  65. * @param part_code 部件编号
  66. * @param part_name 部件名称
  67. * @param remark 部件备注
  68. * @param part_type 部件类型
  69. * @param sys_id 操作人
  70. */
  71. public function AddPart()
  72. {
  73. if (!$this->request->isPost()) {
  74. $this->error('请求方法错误');
  75. }
  76. $params = $this->request->post();
  77. if (empty($params['workorder'])) {
  78. $this->error('工单编号不能为空');
  79. }
  80. if (empty($params['part_name'])) {
  81. $this->error('部件名称不能为空');
  82. }
  83. // 检查是否传入了part_code
  84. if (!empty($params['part_code'])) {
  85. $code = $params['part_code'];
  86. // 检查是否存在冲突
  87. $exists = db('工单_部件资料')
  88. ->where('work_order', $params['workorder'])
  89. ->where('part_code', '>=', $code)
  90. ->count();
  91. if ($exists > 0) {
  92. // 如果存在冲突,将后续编号自动加1
  93. db('工单_部件资料')
  94. ->where('work_order', $params['workorder'])
  95. ->where('part_code', '>=', $code)
  96. ->setInc('part_code');
  97. }
  98. } else {
  99. // 如果没有传入part_code,按照原来的逻辑生成
  100. $code = db('工单_部件资料')
  101. ->where('work_order', $params['workorder'])
  102. ->max('part_code');
  103. $code = $code ? $code + 1 : 1;
  104. }
  105. $data = [
  106. 'work_order' => $params['workorder'],
  107. 'part_code' => $code,
  108. 'part_name' => $params['part_name'],
  109. 'remark' => $params['remark'],
  110. 'part_type' => $params['part_type'],
  111. 'status' => 1,
  112. 'sys_id' => $params['sys_id'],
  113. 'sys_rq' => date('Y-m-d H:i:s'),
  114. ];
  115. $result = db('工单_部件资料')->insert($data);
  116. if (!$result) {
  117. $this->error('新增失败');
  118. }
  119. $this->success('新增成功');
  120. }
  121. /**
  122. * 修改部件状态
  123. * @param id 部件ID
  124. * @param status 状态
  125. */
  126. public function UpdatePartStatus()
  127. {
  128. if (!$this->request->isPost()) {
  129. $this->error('请求方法错误');
  130. }
  131. $params = $this->request->post();
  132. if (empty($params['id'])) {
  133. $this->error('部件ID不能为空');
  134. }
  135. if (!isset($params['status'])) {
  136. $this->error('状态不能为空');
  137. }
  138. $result = db('工单_部件资料')
  139. ->where('id', $params['id'])
  140. ->update(['status' => $params['status']]);
  141. if (!$result) {
  142. $this->error('修改失败');
  143. }
  144. $this->success('修改成功');
  145. }
  146. /**
  147. * 修改部件信息
  148. * @param workorder 工单编号
  149. * @param part_code 部件编号
  150. * @param part_name 部件名称
  151. * @param remark 部件备注
  152. * @param part_type 部件类型
  153. */
  154. public function UpdatePartInfo()
  155. {
  156. if (!$this->request->isPost()) {
  157. $this->error('请求方法错误');
  158. }
  159. $params = $this->request->post();
  160. if (empty($params['part_name'])) {
  161. $this->error('部件名称不能为空');
  162. }
  163. if (empty($params['remark'])) {
  164. $this->error('部件备注不能为空');
  165. }
  166. if (empty($params['part_type'])) {
  167. $this->error('部件类型不能为空');
  168. }
  169. if(empty($params['mod_id'])){
  170. $this->error('修改人不能为空');
  171. }
  172. if(empty($params['id'])){
  173. $this->error('部件ID不能为空');
  174. }
  175. $result = db('工单_部件资料')
  176. ->where('id', $params['id'])
  177. ->update([
  178. 'part_name' => $params['part_name'],
  179. 'remark' => $params['remark'],
  180. 'part_type' => $params['part_type'],
  181. 'mod_id' => $params['mod_id'],
  182. 'mod_rq' => date('Y-m-d H:i:s'),
  183. ]);
  184. if (!$result) {
  185. $this->error('修改失败');
  186. }
  187. $this->success('修改成功');
  188. }
  189. /** 软删除部件信息
  190. * @param id 部件ID
  191. */
  192. public function DeletePart()
  193. {
  194. if (!$this->request->isPost()) {
  195. $this->error('请求方法错误');
  196. }
  197. $params = $this->request->post();
  198. if (empty($params['id'])) {
  199. $this->error('部件ID不能为空');
  200. }
  201. $ids = explode(',', $params['id']);
  202. $ids = array_filter(array_map('intval', $ids));
  203. if (empty($ids)) {
  204. $this->error('无效的部件ID');
  205. }
  206. $result = db('工单_部件资料')
  207. ->whereIn('id', $ids)
  208. ->whereNull('del_rq')
  209. ->update(['del_rq' => date('Y-m-d H:i:s')]);
  210. if ($result === false) {
  211. $this->error('删除失败');
  212. }
  213. if ($result === 0) {
  214. $this->error('未找到可删除的部件');
  215. }
  216. $this->success('删除成功');
  217. }
  218. /**
  219. * 工单工艺列表
  220. * @param workorder 工单编号
  221. */
  222. public function GetProcessList()
  223. {
  224. if (!$this->request->isGet()) {
  225. $this->error('请求方法错误');
  226. }
  227. $params = $this->request->param();
  228. if (empty($params['workorder'])) {
  229. $this->error('工单编号不能为空');
  230. }
  231. $list = db('工单_基础工艺资料')
  232. ->alias('a')
  233. ->join('工单_部件资料 b', 'a.part_code = b.part_code and a.work_order = b.work_order', 'LEFT')
  234. ->where('a.del_rq', null)
  235. ->where('a.work_order', $params['workorder'])
  236. ->where('b.del_rq', null)
  237. ->field('a.id,a.part_code as 部件编号,
  238. IFNULL(b.part_name, "") as 部件名称,
  239. a.process_code as 工艺编号,
  240. a.process_name as 工艺名称,
  241. a.big_process as 大工艺,
  242. a.standard_hour as 标准工时,
  243. a.standard_score as 标准公分,
  244. a.remark as 备注,
  245. a.coefficient as 系数,
  246. a.sys_id as 系统人,
  247. a.sys_rq as 系统时间,
  248. a.mod_id as 修改人,
  249. a.mod_rq as 修改时间,
  250. a.status as 状态')
  251. ->orderRaw('CAST(a.process_code AS UNSIGNED)')
  252. ->select();
  253. $this->success('成功', $list);
  254. }
  255. /**
  256. * 工单工艺列表
  257. * @param workorder 工单编号
  258. */
  259. // public function GetProcessList()
  260. // {
  261. // if (!$this->request->isGet()) {
  262. // $this->error('请求方法错误');
  263. // }
  264. // $params = $this->request->param();
  265. // if (empty($params['workorder'])) {
  266. // $this->error('工单编号不能为空');
  267. // }
  268. // $list = db('工单_基础工艺资料')
  269. // ->alias('a')
  270. // ->join('工单_部件资料 b', 'a.part_code = b.part_code and a.work_order = b.work_order')
  271. // ->where('a.del_rq', null)
  272. // ->where('a.work_order', $params['workorder'])
  273. // ->where('b.del_rq', null)
  274. // ->field('a.id,a.part_code as 部件编号,b.part_name as 部件名称,a.process_code as 序号,
  275. // a.process_name as 工序名称,a.big_process as 大工艺,a.standard_hour as 秒,a.standard_minutes as 分钟,
  276. // a.standard_score as 标准公分,a.money as 金额,a.remark as 备注,a.coefficient as 难度系数,a.sys_id as 操作人员,
  277. // a.sys_rq as 系统时间,a.mod_id as 修改人,a.mod_rq as 修改时间')
  278. // ->order('process_code')
  279. // ->select();
  280. // $this->success('成功', $list);
  281. // }
  282. /**
  283. * 获取部件列表
  284. * @param workorder 工单编号
  285. */
  286. public function getpartlist()
  287. {
  288. if(!$this->request->isGet()){
  289. $this->error('请求方法错误');
  290. }
  291. $params = $this->request->get();
  292. if (empty($params['workorder'])) {
  293. $this->error('工单编号不能为空');
  294. }
  295. $list = db('工单_部件资料')
  296. ->where('work_order', $params['workorder'])
  297. ->where('del_rq', null)
  298. ->field('part_code as 部件编号,part_name as 部件名称')
  299. ->order('part_code')
  300. ->select();
  301. if(empty($list)){
  302. $this->error('该工单没有部件,请先添加部件');
  303. }
  304. $this->success('成功', $list);
  305. }
  306. /**
  307. * 新增工单工艺资料
  308. * @param workorder 工单编号
  309. * @param part_code 部件编号
  310. * @param process_code 工艺编号
  311. * @param process_name 工艺名称
  312. * @param big_process 大工艺
  313. * @param standard_hour 标准工时
  314. * @param standard_score 标准公分
  315. * @param sys_id 系统人
  316. * @param coefficient 系数
  317. * @param remark 备注
  318. */
  319. public function AddProcess()
  320. {
  321. if (!$this->request->isPost()) {
  322. $this->error('请求方法错误');
  323. }
  324. $params = $this->request->post();
  325. if (empty($params['workorder'])) {
  326. $this->error('工单编号不能为空');
  327. }
  328. if (empty($params['part_code'])) {
  329. $this->error('部件编号不能为空');
  330. }
  331. if (empty($params['process_name'])) {
  332. $this->error('工艺名称不能为空');
  333. }
  334. if (empty($params['big_process'])) {
  335. $this->error('大工艺不能为空');
  336. }
  337. if (empty($params['sys_id'])) {
  338. $this->error('系统人不能为空');
  339. }
  340. if (!empty($params['process_code'])) {
  341. $code = intval($params['process_code']);
  342. $exists = db('工单_基础工艺资料')
  343. ->where('work_order', $params['workorder'])
  344. ->where('part_code', $params['part_code'])
  345. ->where('process_code', $code)
  346. ->whereNull('del_rq')
  347. ->count();
  348. if ($exists > 0) {
  349. $this->error('工序编号已存在');
  350. }
  351. } else {
  352. $code = db('工单_基础工艺资料')
  353. ->where('work_order', $params['workorder'])
  354. ->where('part_code', $params['part_code'])
  355. ->whereNull('del_rq')
  356. ->max('process_code');
  357. $code = $code ? $code + 1 : 1;
  358. }
  359. $data = [
  360. 'work_order' => $params['workorder'],
  361. 'part_code' => $params['part_code'],
  362. 'part_name' => $params['part_name'],
  363. 'process_code' => $code,
  364. 'process_name' => $params['process_name'],
  365. 'big_process' => $params['big_process'],
  366. 'standard_hour' => $params['standard_hour'],
  367. 'standard_score' => $params['standard_score'],
  368. 'coefficient' => $params['coefficient'],
  369. 'remark' => $params['remark'],
  370. 'sys_id' => $params['sys_id'],
  371. 'sys_rq' => date('Y-m-d H:i:s'),
  372. ];
  373. $result = db('工单_基础工艺资料')->insert($data);
  374. if ($result === false) {
  375. $this->error('新增失败');
  376. }
  377. $this->success('新增成功');
  378. }
  379. /**
  380. * 更新工单工艺资料
  381. * @param id 工艺ID
  382. * @param mod_id 修改人
  383. * @param process_name 工艺名称
  384. * @param big_process 大工艺
  385. * @param standard_hour 标准工时
  386. * @param standard_score 标准公分
  387. * @param coefficient 系数
  388. * @param remark 备注
  389. */
  390. public function UpdateProcess()
  391. {
  392. if (!$this->request->isPost()) {
  393. $this->error('请求方法错误');
  394. }
  395. $params = $this->request->post();
  396. if (empty($params['id'])) {
  397. $this->error('工艺ID不能为空');
  398. }
  399. if (empty($params['mod_id'])) {
  400. $this->error('修改人不能为空');
  401. }
  402. if (empty($params['process_name'])) {
  403. $this->error('工艺名称不能为空');
  404. }
  405. if (empty($params['big_process'])) {
  406. $this->error('大工艺不能为空');
  407. }
  408. if (!isset($params['coefficient']) || $params['coefficient'] === '') {
  409. $params['coefficient'] = 'C';
  410. }
  411. $process = Db::table('工单_基础工艺资料')
  412. ->where('id', intval($params['id']))
  413. ->whereNull('del_rq')
  414. ->find();
  415. if (empty($process)) {
  416. $this->error('工艺不存在');
  417. }
  418. $data = [
  419. 'part_code' => $params['part_code'],
  420. 'part_name' => $params['part_name'],
  421. 'standard_minutes' => $params['standard_minutes'],
  422. 'money' => $params['money'],
  423. 'remark' => $params['remark'],
  424. 'process_name' => $params['process_name'],
  425. 'big_process' => $params['big_process'],
  426. 'standard_hour' => $params['standard_hour'],
  427. 'standard_score' => $params['standard_score'],
  428. 'coefficient' => $params['coefficient'],
  429. 'mod_id' => $params['mod_id'],
  430. 'mod_rq' => date('Y-m-d H:i:s'),
  431. ];
  432. $fieldLabels = [
  433. 'part_code' => '部件编号',
  434. 'part_name' => '部件名称',
  435. 'standard_minutes' => '分',
  436. 'money' => '金额',
  437. 'remark' => '备注',
  438. 'process_name' => '工序名称',
  439. 'big_process' => '大工序',
  440. 'standard_hour' => '秒',
  441. 'standard_score' => '定额分',
  442. 'coefficient' => '难度系数',
  443. ];
  444. $operTime = date('Y-m-d H:i:s');
  445. $logList = [];
  446. foreach ($fieldLabels as $field => $label) {
  447. $oldValue = isset($process[$field]) ? $process[$field] : '';
  448. $newValue = $data[$field];
  449. if ((string)$oldValue === (string)$newValue) {
  450. continue;
  451. }
  452. $logList[] = [
  453. 'order_no' => $process['work_order'],
  454. 'process_code' => $params['process_code'],
  455. 'change_field' => $label,
  456. 'old_value' => $oldValue === null ? '' : (string)$oldValue,
  457. 'new_value' => (string)$newValue,
  458. 'oper_type' => '修改工单工艺',
  459. 'oper_user_name' => $params['mod_id'],
  460. 'oper_time' => $operTime,
  461. ];
  462. }
  463. if (empty($logList)) {
  464. $this->error('未找到可更新的工艺或数据无变化');
  465. }
  466. $standardScoreChanged = (string)$process['standard_score'] !== (string)$params['standard_score'];
  467. if ($standardScoreChanged && (string)$process['status'] === '0') {
  468. $workOrder = Db::table('工单_基本资料')
  469. ->where('订单编号', $process['work_order'])
  470. ->where('Mod_rq', null)
  471. ->field('计划制造工分')
  472. ->find();
  473. if (empty($workOrder)) {
  474. $this->error('工单不存在');
  475. }
  476. $totalStandardScore = Db::table('工单_基础工艺资料')
  477. ->where('work_order', $process['work_order'])
  478. ->where('status', 0)
  479. ->whereNull('del_rq')
  480. ->sum('standard_score');
  481. $totalStandardScore = $totalStandardScore ? floatval($totalStandardScore) : 0;
  482. $newTotal = $totalStandardScore - floatval($process['standard_score']) + floatval($params['standard_score']);
  483. if ($newTotal > floatval($workOrder['计划制造工分'])) {
  484. $this->error('工序定额分和大于制造工分,请确认之后再修改');
  485. }
  486. }
  487. Db::startTrans();
  488. try {
  489. if (!empty($params['part_code'])) {
  490. $partExists = Db::table('工单_部件资料')
  491. ->where('work_order', $process['work_order'])
  492. ->where('part_code', $params['part_code'])
  493. ->whereNull('del_rq')
  494. ->find();
  495. if (empty($partExists)) {
  496. $partData = [
  497. 'work_order' => $process['work_order'],
  498. 'part_code' => $params['part_code'],
  499. 'part_name' => $params['part_name'],
  500. 'remark' => '',
  501. 'part_type' => $params['big_process'],
  502. 'status' => 1,
  503. 'sys_id' => $params['mod_id'],
  504. 'sys_rq' => date('Y-m-d H:i:s'),
  505. ];
  506. $partInsertResult = Db::table('工单_部件资料')->insert($partData);
  507. if ($partInsertResult === false) {
  508. $dbError = Db::getError();
  509. $detail = is_array($dbError) && !empty($dbError) ? json_encode($dbError, JSON_UNESCAPED_UNICODE) : '';
  510. throw new \Exception('新增部件资料失败' . ($detail !== '' ? ':' . $detail : ''));
  511. }
  512. }
  513. }
  514. $updateResult = Db::table('工单_基础工艺资料')
  515. ->where('id', intval($params['id']))
  516. ->whereNull('del_rq')
  517. ->update($data);
  518. if ($updateResult === false) {
  519. $dbError = Db::getError();
  520. $detail = is_array($dbError) && !empty($dbError) ? json_encode($dbError, JSON_UNESCAPED_UNICODE) : '';
  521. throw new \Exception('更新工艺失败' . ($detail !== '' ? ':' . $detail : ''));
  522. }
  523. if ($updateResult === 0) {
  524. throw new \Exception('未找到可更新的工艺');
  525. }
  526. $logResult = Db::name('work_order_operation_log')->insertAll($logList);
  527. if ($logResult === false || $logResult === 0) {
  528. $dbError = Db::getError();
  529. $detail = is_array($dbError) && !empty($dbError) ? json_encode($dbError, JSON_UNESCAPED_UNICODE) : '';
  530. throw new \Exception('写入操作日志失败' . ($detail !== '' ? ':' . $detail : ''));
  531. }
  532. Db::commit();
  533. } catch (\think\exception\HttpResponseException $e) {
  534. throw $e;
  535. } catch (\Exception $e) {
  536. Db::rollback();
  537. $msg = trim($e->getMessage());
  538. $this->error('更新失败' . ($msg !== '' ? $msg : '未知错误'));
  539. }
  540. $this->success('更新成功');
  541. }
  542. /**
  543. * 工单工艺资料软删除
  544. * @param id 工艺ID
  545. */
  546. public function DeleteProcess()
  547. {
  548. if (!$this->request->isPost()) {
  549. $this->error('请求方法错误');
  550. }
  551. $params = $this->request->post();
  552. if (empty($params['id'])) {
  553. $this->error('工艺ID不能为空');
  554. }
  555. $ids = explode(',', $params['id']);
  556. $ids = array_filter(array_map('intval', $ids));
  557. if (empty($ids)) {
  558. $this->error('无效的工艺ID');
  559. }
  560. $processes = db('工单_基础工艺资料')
  561. ->whereIn('id', $ids)
  562. ->whereNull('del_rq')
  563. ->field('id,work_order,process_code,process_name,part_code')
  564. ->select();
  565. if (empty($processes)) {
  566. $this->error('未找到可删除的工艺');
  567. }
  568. foreach ($processes as $process) {
  569. $reportQuery = Db::table('设备_工分计酬')
  570. ->where('work_order', $process['work_order'])
  571. ->where('process_code', $process['process_code'])
  572. ->whereNull('del_rq');
  573. if ($process['part_code'] !== null && $process['part_code'] !== '') {
  574. $reportQuery->where('part_code', $process['part_code']);
  575. }
  576. $hasReport = (int)$reportQuery->count();
  577. if ($hasReport > 0) {
  578. $this->error(
  579. '工序' . $process['process_code'] . '「' . $process['process_name']
  580. . '」已有报工记录,禁止删除。'
  581. );
  582. }
  583. }
  584. $result = db('工单_基础工艺资料')
  585. ->whereIn('id', $ids)
  586. ->whereNull('del_rq')
  587. ->update(['del_rq' => date('Y-m-d H:i:s')]);
  588. if ($result === false) {
  589. $this->error('删除失败');
  590. }
  591. if ($result === 0) {
  592. $this->error('未找到可删除的工艺');
  593. }
  594. $this->success('删除成功');
  595. }
  596. /**
  597. * 工单工艺复制
  598. * @param workorder 工单编号
  599. * @param product_code 产品编号
  600. * @param sys_id 操作人
  601. * @return array
  602. * @throws \think\db\exception\DataNotFoundException
  603. * @throws \think\db\exception\ModelNotFoundException
  604. * @throws \think\exception\DbException
  605. * @throws \think\exception\PDOException
  606. */
  607. public function workorderprocessCopy()
  608. {
  609. if (!$this->request->isGet()) {
  610. $this->error('请求方法错误');
  611. }
  612. $params = $this->request->param();
  613. if (empty($params['workorder'])) {
  614. $this->error('工单编号不能为空');
  615. }
  616. if (empty($params['product_code'])) {
  617. $this->error('产品编号不能为空');
  618. }
  619. if (empty($params['sys_id'])) {
  620. $this->error('操作人不能为空');
  621. }
  622. $now = date('Y-m-d H:i:s');
  623. $productParts = db('产品_部件资料')
  624. ->where('product_code', $params['product_code'])
  625. ->where('mod_rq', null)
  626. ->field('part_sort as part_code,part_name')
  627. ->select();
  628. if (empty($productParts)) {
  629. $this->error('该产品没有有效的部件');
  630. }
  631. $productProcesses = db('产品_工艺资料')
  632. ->where('product_code', $params['product_code'])
  633. ->field('part_sort as part_code,part_name,gy_sort as process_code,gy_name as process_name,
  634. big_process,standard_hour,standard_score,difficulty_coef as coefficient')
  635. ->select();
  636. if (empty($productProcesses)) {
  637. $this->error('该产品没有工艺');
  638. }
  639. $workOrderParts = [];
  640. //配置工单部件数据
  641. foreach ($productParts as $value) {
  642. $workOrderParts[] = [
  643. 'work_order' => $params['workorder'],
  644. 'part_code' => $value['part_code'],
  645. 'part_name' => trim((string)$value['part_name']),
  646. 'part_type' => '',
  647. 'remark' => '',
  648. 'status' => 1,
  649. 'sys_id' => $params['sys_id'],
  650. 'sys_rq' => $now,
  651. ];
  652. }
  653. $workOrderProcesses = [];
  654. //配置工单工艺数据
  655. foreach ($productProcesses as $value) {
  656. $workOrderProcesses[] = [
  657. 'work_order' => $params['workorder'],
  658. 'part_code' => $value['part_code'],
  659. 'part_name' => trim((string)$value['part_name']),
  660. 'process_code' => $value['process_code'],
  661. 'process_name' => trim((string)$value['process_name']),
  662. 'big_process' => trim((string)$value['big_process']),
  663. 'standard_hour' => $value['standard_hour'],
  664. 'standard_score' => $value['standard_score'],
  665. 'coefficient' => $value['coefficient'],
  666. 'remark' => '',
  667. 'sys_id' => $params['sys_id'],
  668. 'sys_rq' => $now,
  669. ];
  670. }
  671. Db::startTrans();
  672. try {
  673. //删除数据库现有的工单部件数据
  674. Db::name('工单_部件资料')->where('work_order', $params['workorder'])->delete();
  675. //删除数据库现有的工单工艺数据
  676. Db::name('工单_基础工艺资料')->where('work_order', $params['workorder'])->delete();
  677. //插入工单部件数据
  678. $partInsertCount = Db::name('工单_部件资料')->insertAll($workOrderParts);
  679. if ($partInsertCount === false) {
  680. throw new \Exception('工单部件复制失败');
  681. }
  682. //插入工单工艺数据
  683. $processInsertCount = Db::name('工单_基础工艺资料')->insertAll($workOrderProcesses);
  684. if ($processInsertCount === false) {
  685. throw new \Exception('工单工艺复制失败');
  686. }
  687. //提交事务
  688. Db::commit();
  689. } catch (\Exception $e) {
  690. Db::rollback();
  691. $this->error('复制失败');
  692. }
  693. $this->success('复制成功');
  694. }
  695. /**
  696. * 查询产品类型
  697. * @ApiMethod (GET)
  698. * @param string $workorder 工单编号
  699. * @return array
  700. * @throws \think\db\exception\DataNotFoundException
  701. * @throws \think\db\exception\ModelNotFoundException
  702. * @throws \think\exception\DbException
  703. */
  704. public function getproducttype()
  705. {
  706. if(!$this->request->isGet()){
  707. $this->error('请求方法错误');
  708. }
  709. $params = $this->request->get();
  710. if (empty($params['product'])) {
  711. $this->error('产品类型不能为空');
  712. }
  713. $list = db('产品_基本资料')
  714. ->where('product_type', $params['product'])
  715. ->where('status', 1)
  716. ->field('product_code as 产品编号,product_type as 产品类型,product_name as 产品名称')
  717. ->select();
  718. if(empty($list)){
  719. $this->error('该产品类型没有产品');
  720. }
  721. $this->success('成功', $list);
  722. }
  723. /**
  724. * 工单工艺排序
  725. * @param workorder 工单编号
  726. * @param part_code 部件编号
  727. * @param process_code 工艺编号
  728. * @param process_name 工艺名称
  729. * @param big_process 大工艺
  730. * @param standard_hour 标准工时
  731. * @param standard_score 标准公分
  732. * @param coefficient 系数
  733. * @param remark 备注
  734. */
  735. public function sortProcess()
  736. {
  737. if (!$this->request->isPost()) {
  738. $this->error('请求方法错误');
  739. }
  740. $params = $this->request->post();
  741. if (empty($params)) {
  742. $this->error('参数不能为空');
  743. }
  744. if (!is_array($params)) {
  745. $this->error('参数格式错误');
  746. }
  747. Db::startTrans();
  748. try {
  749. foreach ($params as $value) {
  750. if (empty($value['id'])) {
  751. throw new \Exception('缺少工艺ID');
  752. }
  753. if (!isset($value['process_code']) || $value['process_code'] === '') {
  754. throw new \Exception('缺少工艺编号');
  755. }
  756. $process = db('工单_基础工艺资料')
  757. ->where('id', intval($value['id']))
  758. ->whereNull('del_rq')
  759. ->field('id,work_order,process_code,process_name')
  760. ->find();
  761. if (empty($process)) {
  762. throw new \Exception('工艺不存在或已删除');
  763. }
  764. $newCode = intval($value['process_code']);
  765. $oldCode = intval($process['process_code']);
  766. // 有报工时禁止改工序号,避免历史报工挂空/错挂
  767. if ($newCode !== $oldCode) {
  768. $hasReport = (int)Db::table('设备_工分计酬')
  769. ->where('work_order', $process['work_order'])
  770. ->whereNull('del_rq')
  771. ->count();
  772. if ($hasReport > 0) {
  773. throw new \Exception(
  774. '该工单已有工分报工记录,禁止调整工序号(原'
  775. . $process['process_code'] . '「' . $process['process_name']
  776. . '」不可改为' . $newCode . ')。如需新增工序请在最大序号后追加'
  777. );
  778. }
  779. }
  780. $result = db('工单_基础工艺资料')
  781. ->where('id', intval($value['id']))
  782. ->whereNull('del_rq')
  783. ->update(['process_code' => $newCode]);
  784. if ($result === false) {
  785. throw new \Exception('排序失败');
  786. }
  787. }
  788. Db::commit();
  789. } catch (\Exception $e) {
  790. Db::rollback();
  791. $this->error($e->getMessage());
  792. }
  793. $this->success('排序成功');
  794. }
  795. /**
  796. * 工单工艺excel导入
  797. * @param workorder 工单编号
  798. *
  799. */
  800. public function importProcess()
  801. {
  802. if (!$this->request->isPost()) {
  803. $this->error('请求方法错误');
  804. }
  805. $params = $this->request->post();
  806. if (empty($params['workorder'])) {
  807. $this->error('工单编号不能为空');
  808. }
  809. if (empty($params['sys_id'])) {
  810. $this->error('操作人不能为空');
  811. }
  812. $file = $this->request->file('file');
  813. if (!$file) {
  814. $this->error('文件不能为空');
  815. }
  816. $uploadDir = ROOT_PATH . 'public' . DS . 'uploads';
  817. $info = $file->validate(['size' => 1024 * 1024 * 10, 'ext' => 'xlsx,xls,csv,txt'])
  818. ->move($uploadDir);
  819. if (!$info) {
  820. $this->error($file->getError());
  821. }
  822. $filePath = $uploadDir . DS . $info->getSaveName();
  823. // 定额表:上方为标题与元数据,第 5 行表头,第 6 行起为数据
  824. $data = $this->readExcel($filePath, 5, 6);
  825. if (empty($data)) {
  826. $this->error('文件内容为空');
  827. }
  828. $seenSeq = [];
  829. foreach ($data as $row) {
  830. $seq = isset($row['序号']) ? $row['序号'] : null;
  831. if ($seq === null || $seq === '') {
  832. continue;
  833. }
  834. $seqKey = is_scalar($seq) ? (string)$seq : $seq;
  835. if (isset($seenSeq[$seqKey])) {
  836. $this->error('工序序号重复,请重新调整之后再上传');
  837. }
  838. $seenSeq[$seqKey] = true;
  839. }
  840. $now = date('Y-m-d H:i:s');
  841. $partMap = [];
  842. $nextPartCode = 0;
  843. foreach ($data as $row) {
  844. $partName = isset($row['部件名称']) ? trim((string)$row['部件名称']) : '';
  845. if ($partName === '') {
  846. continue;
  847. }
  848. $partType = isset($row['生产工序']) ? trim((string)$row['生产工序']) : '';
  849. if (!isset($partMap[$partName])) {
  850. $partMap[$partName] = [
  851. 'part_code' => ++$nextPartCode,
  852. 'part_type' => $partType,
  853. ];
  854. } elseif ($partType !== '' && $partMap[$partName]['part_type'] === '') {
  855. $partMap[$partName]['part_type'] = $partType;
  856. }
  857. }
  858. $workOrderParts = [];
  859. foreach ($partMap as $partName => $partInfo) {
  860. $workOrderParts[] = [
  861. 'work_order' => $params['workorder'],
  862. 'part_name' => $partName,
  863. 'part_code' => $partInfo['part_code'],
  864. 'part_type' => $partInfo['part_type'],
  865. 'remark' => '',
  866. 'status' => 1,
  867. 'sys_id' => $params['sys_id'],
  868. 'sys_rq' => $now,
  869. ];
  870. }
  871. $workOrderProcesses = [];
  872. foreach ($data as $value) {
  873. $seq = isset($value['序号']) ? $value['序号'] : null;
  874. if ($seq === null || $seq === '') {
  875. continue;
  876. }
  877. $name = isset($value['部件名称']) ? trim((string)$value['部件名称']) : '';
  878. $partCode = ($name !== '' && isset($partMap[$name])) ? $partMap[$name]['part_code'] : '';
  879. $workOrderProcesses[] = [
  880. 'work_order' => $params['workorder'],
  881. 'part_code' => $partCode,
  882. 'part_name' => $name,
  883. 'process_code' => $seq,
  884. 'process_name' => isset($value['工序名称']) ? trim((string)$value['工序名称']) : '',
  885. 'big_process' => isset($value['生产工序']) ? trim((string)$value['生产工序']) : '',
  886. 'standard_hour' => $value['秒'],
  887. 'standard_minutes' => $value['分'],
  888. 'standard_score' => $value['定额分'],
  889. 'money' => $value['金额'],
  890. 'coefficient' => $value['难度系数'],
  891. 'remark' => isset($value['备注']) ? $value['备注'] : '',
  892. 'sys_id' => $params['sys_id'],
  893. 'sys_rq' => $now,
  894. ];
  895. }
  896. if (empty($workOrderProcesses)) {
  897. $this->error('没有可导入的工序数据');
  898. }
  899. // 已有工分报工时:仅允许尾部追加(旧序号/名称/部件顺序不变),禁止中间插入或重排序号
  900. $hasReport = (int)Db::table('设备_工分计酬')
  901. ->where('work_order', $params['workorder'])
  902. ->whereNull('del_rq')
  903. ->count();
  904. if ($hasReport > 0) {
  905. $oldProcesses = Db::table('工单_基础工艺资料')
  906. ->where('work_order', $params['workorder'])
  907. ->whereNull('del_rq')
  908. ->field('process_code,process_name,part_code,part_name')
  909. ->select();
  910. if (empty($oldProcesses)) {
  911. // 工艺表为空时,用已报工快照做兼容校验
  912. $oldProcesses = Db::table('设备_工分计酬')
  913. ->where('work_order', $params['workorder'])
  914. ->whereNull('del_rq')
  915. ->field('process_code,process_name,part_code')
  916. ->group('process_code,process_name,part_code')
  917. ->select();
  918. foreach ($oldProcesses as $k => $row) {
  919. $oldProcesses[$k]['part_name'] = '';
  920. }
  921. }
  922. if (empty($oldProcesses)) {
  923. $this->error('禁止中间插入或重排序号');
  924. }
  925. $oldParts = Db::table('工单_部件资料')
  926. ->where('work_order', $params['workorder'])
  927. ->whereNull('del_rq')
  928. ->field('part_code,part_name')
  929. ->orderRaw('CAST(part_code AS UNSIGNED) ASC')
  930. ->select();
  931. $normCode = function ($code) {
  932. $code = trim((string)$code);
  933. if ($code !== '' && is_numeric($code)) {
  934. return (string)intval($code);
  935. }
  936. return $code;
  937. };
  938. $newProcessMap = [];
  939. foreach ($workOrderProcesses as $p) {
  940. $codeKey = $normCode($p['process_code']);
  941. if ($codeKey === '') {
  942. continue;
  943. }
  944. $newProcessMap[$codeKey] = [
  945. 'process_name' => trim((string)$p['process_name']),
  946. 'part_name' => trim((string)$p['part_name']),
  947. 'process_code' => $codeKey,
  948. ];
  949. }
  950. $conflicts = [];
  951. $oldCodeSet = [];
  952. $oldMaxCode = 0;
  953. foreach ($oldProcesses as $old) {
  954. $oldCode = $normCode($old['process_code']);
  955. if ($oldCode === '') {
  956. continue;
  957. }
  958. $oldCodeSet[$oldCode] = true;
  959. $oldCodeInt = intval($oldCode);
  960. if ($oldCodeInt > $oldMaxCode) {
  961. $oldMaxCode = $oldCodeInt;
  962. }
  963. $oldName = trim((string)$old['process_name']);
  964. $oldPartName = isset($old['part_name']) ? trim((string)$old['part_name']) : '';
  965. if (!isset($newProcessMap[$oldCode])) {
  966. $conflicts[] = [
  967. 'process_code' => $oldCode,
  968. 'message' => '原工序在新表中不存在',
  969. 'old_value' => $oldName,
  970. 'new_value' => '',
  971. ];
  972. continue;
  973. }
  974. $newName = $newProcessMap[$oldCode]['process_name'];
  975. $newPartName = $newProcessMap[$oldCode]['part_name'];
  976. if ($oldName !== '' && $newName !== $oldName) {
  977. $conflicts[] = [
  978. 'process_code' => $oldCode,
  979. 'message' => '与已有工序不一致',
  980. 'old_value' => $oldName,
  981. 'new_value' => $newName,
  982. ];
  983. }
  984. if ($oldPartName !== '' && $newPartName !== $oldPartName) {
  985. $conflicts[] = [
  986. 'process_code' => $oldCode,
  987. 'message' => '与已有部件不一致',
  988. 'old_value' => $oldPartName,
  989. 'new_value' => $newPartName,
  990. ];
  991. }
  992. }
  993. foreach ($newProcessMap as $codeKey => $p) {
  994. if (isset($oldCodeSet[$codeKey])) {
  995. continue;
  996. }
  997. if (intval($codeKey) <= $oldMaxCode) {
  998. $conflicts[] = [
  999. 'process_code' => $codeKey,
  1000. 'message' => '中间插入,请将新增序号设为' . ($oldMaxCode + 1) . '及以后',
  1001. 'old_value' => '旧最大序号' . $oldMaxCode,
  1002. 'new_value' => $p['process_name'],
  1003. ];
  1004. }
  1005. }
  1006. foreach ($oldParts as $oldPart) {
  1007. $oldPartName = trim((string)$oldPart['part_name']);
  1008. $oldPartCode = intval($oldPart['part_code']);
  1009. if ($oldPartName === '') {
  1010. continue;
  1011. }
  1012. if (!isset($partMap[$oldPartName])) {
  1013. $conflicts[] = [
  1014. 'process_code' => '',
  1015. 'message' => '原部件在新表中不存在',
  1016. 'old_value' => $oldPartName . '(编号' . $oldPartCode . ')',
  1017. 'new_value' => '',
  1018. ];
  1019. continue;
  1020. }
  1021. $newPartCode = intval($partMap[$oldPartName]['part_code']);
  1022. if ($newPartCode !== $oldPartCode) {
  1023. $conflicts[] = [
  1024. 'process_code' => '',
  1025. 'message' => '部件编号将变更',
  1026. 'old_value' => $oldPartName . '→编号' . $oldPartCode,
  1027. 'new_value' => $oldPartName . '→编号' . $newPartCode,
  1028. ];
  1029. }
  1030. }
  1031. if (!empty($conflicts)) {
  1032. // 冲突序号集合,供左右列表高亮
  1033. $diffCodeMap = [];
  1034. foreach ($conflicts as $c) {
  1035. $pc = isset($c['process_code']) ? trim((string)$c['process_code']) : '';
  1036. if ($pc !== '') {
  1037. $diffCodeMap[$pc] = true;
  1038. }
  1039. }
  1040. $oldList = [];
  1041. foreach ($oldProcesses as $old) {
  1042. $code = $normCode($old['process_code']);
  1043. if ($code === '') {
  1044. continue;
  1045. }
  1046. $oldList[] = [
  1047. 'process_code' => $code,
  1048. 'process_name' => trim((string)$old['process_name']),
  1049. 'part_name' => isset($old['part_name']) ? trim((string)$old['part_name']) : '',
  1050. 'diff' => isset($diffCodeMap[$code]),
  1051. ];
  1052. }
  1053. usort($oldList, function ($a, $b) {
  1054. return intval($a['process_code']) - intval($b['process_code']);
  1055. });
  1056. $newList = [];
  1057. foreach ($workOrderProcesses as $p) {
  1058. $code = $normCode($p['process_code']);
  1059. if ($code === '') {
  1060. continue;
  1061. }
  1062. $newList[] = [
  1063. 'process_code' => $code,
  1064. 'process_name' => trim((string)$p['process_name']),
  1065. 'part_name' => trim((string)$p['part_name']),
  1066. 'diff' => isset($diffCodeMap[$code]),
  1067. ];
  1068. }
  1069. usort($newList, function ($a, $b) {
  1070. return intval($a['process_code']) - intval($b['process_code']);
  1071. });
  1072. // 约定:msg 短提示;data 含左右完整列表 + conflicts,供前端左右对比弹窗
  1073. $this->error(
  1074. '禁止中间插入或重排序号',
  1075. [
  1076. 'error_type' => 'import_append_only',
  1077. 'conflict_count' => count($conflicts),
  1078. 'suggest_min_new_code' => $oldMaxCode + 1,
  1079. 'old_list' => $oldList,
  1080. 'new_list' => $newList,
  1081. 'conflicts' => $conflicts,
  1082. ]
  1083. );
  1084. }
  1085. }
  1086. Db::startTrans();
  1087. try {
  1088. Db::name('工单_部件资料')->where('work_order', $params['workorder'])->delete();
  1089. if (!empty($workOrderParts)) {
  1090. $partInsertCount = Db::name('工单_部件资料')->insertAll($workOrderParts);
  1091. if ($partInsertCount === false || $partInsertCount === 0) {
  1092. throw new \Exception('工单部件导入失败');
  1093. }
  1094. }
  1095. Db::name('工单_基础工艺资料')->where('work_order', $params['workorder'])->delete();
  1096. $processInsertCount = Db::name('工单_基础工艺资料')->insertAll($workOrderProcesses);
  1097. if ($processInsertCount === false || $processInsertCount === 0) {
  1098. throw new \Exception('工单工艺导入失败');
  1099. }
  1100. Db::commit();
  1101. } catch (\think\exception\HttpResponseException $e) {
  1102. throw $e;
  1103. } catch (\Exception $e) {
  1104. Db::rollback();
  1105. $this->error('导入失败:' . $e->getMessage());
  1106. }
  1107. $this->success('导入成功', [
  1108. 'part_count' => count($workOrderParts),
  1109. 'process_count' => count($workOrderProcesses),
  1110. ]);
  1111. }
  1112. /**
  1113. * 读取 Excel/CSV(PhpSpreadsheet)
  1114. *
  1115. * @param string $filePath
  1116. * @param int $headerRowNum 表头所在行(1 起计,如定额表为第 5 行)
  1117. * @param int $dataStartRowNum 首条数据行(1 起计,须大于表头行,如第 6 行)
  1118. * @return array 每行一条关联数组,键为表头单元格文本
  1119. */
  1120. public function readExcel($filePath, $headerRowNum = 5, $dataStartRowNum = 6)
  1121. {
  1122. if (!is_file($filePath) || !is_readable($filePath)) {
  1123. return [];
  1124. }
  1125. if ($dataStartRowNum <= $headerRowNum) {
  1126. return [];
  1127. }
  1128. $spreadsheet = IOFactory::load($filePath);
  1129. $sheet = $spreadsheet->getActiveSheet();
  1130. $rows = $sheet->toArray();
  1131. if (empty($rows)) {
  1132. return [];
  1133. }
  1134. $headerIdx = $headerRowNum - 1;
  1135. $dataStartIdx = $dataStartRowNum - 1;
  1136. if (!isset($rows[$headerIdx])) {
  1137. return [];
  1138. }
  1139. $headers = array_map(function ($cell) {
  1140. return is_string($cell) ? trim($cell) : $cell;
  1141. }, $rows[$headerIdx]);
  1142. $data = [];
  1143. $rowCount = count($rows);
  1144. for ($r = $dataStartIdx; $r < $rowCount; $r++) {
  1145. $row = $rows[$r];
  1146. $hasCell = false;
  1147. foreach ($row as $cell) {
  1148. if ($cell !== null && $cell !== '') {
  1149. $hasCell = true;
  1150. break;
  1151. }
  1152. }
  1153. if (!$hasCell) {
  1154. continue;
  1155. }
  1156. $assoc = [];
  1157. foreach ($headers as $i => $key) {
  1158. if ($key === '' || $key === null) {
  1159. continue;
  1160. }
  1161. $assoc[$key] = array_key_exists($i, $row) ? $row[$i] : null;
  1162. }
  1163. $data[] = $assoc;
  1164. }
  1165. return $data;
  1166. }
  1167. /**
  1168. * 获取工单工艺信息
  1169. * @param workorder 工单编号
  1170. * @return array
  1171. * @throws \think\db\exception\DataNotFoundException
  1172. * @throws \think\db\exception\ModelNotFoundException
  1173. * @throws \think\exception\DbException
  1174. */
  1175. public function getWorkOrderProcess()
  1176. {
  1177. if (!$this->request->isGet()) {
  1178. $this->error('请求方法错误');
  1179. }
  1180. $params = $this->request->param();
  1181. if (empty($params['workorder'])) {
  1182. $this->error('工单编号不能为空');
  1183. }
  1184. $where = [
  1185. 'work_order' => $params['workorder'],
  1186. 'del_rq' => null,
  1187. ];
  1188. $workOrderProcess = Db::table('工单_基础工艺资料')
  1189. ->where($where)
  1190. ->field('id,part_code as 部件编号,part_name as 部件名称,process_code as 工序编号,process_name as 工序名称,
  1191. big_process as 大工序,standard_hour as 秒,standard_minutes as 分,standard_score as 定额分,money as 金额,
  1192. coefficient as 难度系数,remark as 备注,status as 状态,pid')
  1193. ->orderRaw('CAST(process_code AS UNSIGNED)')
  1194. ->select();
  1195. if (empty($workOrderProcess)) {
  1196. $this->error('工单工艺不存在');
  1197. }
  1198. $pidList = [];
  1199. foreach ($workOrderProcess as $row) {
  1200. if (!empty($row['pid'])) {
  1201. $pidList[(int)$row['pid']] = true;
  1202. }
  1203. }
  1204. $parentCodeMap = [];
  1205. if (!empty($pidList)) {
  1206. $parentCodeMap = Db::table('工单_基础工艺资料')
  1207. ->whereIn('id', array_keys($pidList))
  1208. ->column('process_code', 'id');
  1209. }
  1210. foreach ($workOrderProcess as &$row) {
  1211. $row['母工序编号'] = !empty($row['pid']) && isset($parentCodeMap[(int)$row['pid']])
  1212. ? $parentCodeMap[(int)$row['pid']]
  1213. : '';
  1214. }
  1215. unset($row);
  1216. $this->success('成功', $workOrderProcess);
  1217. }
  1218. /**
  1219. * 修改工单计划制造工分
  1220. * @param id 工单Uniqid或订单编号
  1221. * @param number 计划制造工分
  1222. * @param sys_id 操作人
  1223. */
  1224. public function updateWorkOrderPlanManufacture()
  1225. {
  1226. if (!$this->request->isPost()) {
  1227. $this->error('请求方法错误');
  1228. }
  1229. $params = $this->request->post();
  1230. if (empty($params['id'])) {
  1231. $this->error('工单ID不能为空');
  1232. }
  1233. if (!isset($params['number']) || $params['number'] === '') {
  1234. $this->error('制造工分不能为空');
  1235. }
  1236. if (empty($params['sys_id'])) {
  1237. $this->error('操作人不能为空');
  1238. }
  1239. $workOrder = Db::table('工单_基本资料')
  1240. ->where('Uniqid|订单编号', $params['id'])
  1241. ->where('Mod_rq', null)
  1242. ->field('Uniqid,订单编号,计划制造工分')
  1243. ->find();
  1244. if (empty($workOrder)) {
  1245. $this->error('工单不存在');
  1246. }
  1247. $oldValue = $workOrder['计划制造工分'];
  1248. $newValue = $params['number'];
  1249. if ((string)$oldValue === (string)$newValue) {
  1250. $this->error('计划制造工分未发生变化');
  1251. }
  1252. $totalStandardScore = Db::table('工单_基础工艺资料')
  1253. ->where('work_order', $workOrder['订单编号'])
  1254. ->where('status', 0)
  1255. ->whereNull('del_rq')
  1256. ->sum('standard_score');
  1257. $totalStandardScore = $totalStandardScore ? floatval($totalStandardScore) : 0;
  1258. if ($totalStandardScore > floatval($newValue)) {
  1259. $this->error('工序定额分和大于制造工分,请确认之后再修改');
  1260. }
  1261. $operTime = date('Y-m-d H:i:s');
  1262. $logData = [
  1263. 'order_no' => $workOrder['订单编号'],
  1264. 'change_field' => '计划制造工分',
  1265. 'old_value' => $oldValue === null ? '' : (string)$oldValue,
  1266. 'new_value' => (string)$newValue,
  1267. 'oper_type' => '修改工单计划制造工分',
  1268. 'oper_user_name' => $params['sys_id'],
  1269. 'oper_time' => $operTime,
  1270. ];
  1271. Db::startTrans();
  1272. try {
  1273. $updateResultSql = Db::table('工单_基本资料')
  1274. ->where('Uniqid', $workOrder['Uniqid'])
  1275. ->fetchSql(true)
  1276. ->update(['计划制造工分' => $newValue]);
  1277. $updateResult = Db::query($updateResultSql);
  1278. if ($updateResult === false) {
  1279. throw new \Exception('更新工单失败');
  1280. }
  1281. $logResult = Db::name('work_order_operation_log')->insert($logData);
  1282. if ($logResult === false) {
  1283. throw new \Exception('写入操作日志失败');
  1284. }
  1285. Db::commit();
  1286. } catch (\Exception $e) {
  1287. Db::rollback();
  1288. $this->error('修改失败');
  1289. }
  1290. $this->success('修改成功');
  1291. }
  1292. /**
  1293. * 拆分工序时判断工序是否存在报工
  1294. * @param workorder 工单编号
  1295. * @param process_code 工艺编号
  1296. * @return array
  1297. * @throws \think\db\exception\DataNotFoundException
  1298. * @throws \think\db\exception\ModelNotFoundException
  1299. * @throws \think\exception\DbException
  1300. */
  1301. public function checkProcessReport()
  1302. {
  1303. if (!$this->request->isPost()) {
  1304. $this->error('请求方法错误');
  1305. }
  1306. $params = $this->request->post();
  1307. if (empty($params['workorder'])) {
  1308. $this->error('工单编号不能为空');
  1309. }
  1310. if (empty($params['process_code'])) {
  1311. $this->error('工艺编号不能为空');
  1312. }
  1313. $process = db('设备_工分计酬')
  1314. ->where('work_order', $params['workorder'])
  1315. ->where('process_code', $params['process_code'])
  1316. ->find();
  1317. if (!empty($process)) {
  1318. $this->error('');
  1319. }
  1320. $this->success('工序不存在报工,可以拆分');
  1321. }
  1322. /**
  1323. * 确认拆分工序:number>0 时母工序置为已拆分并生成子工序(子工序 pid 为母工序 id);
  1324. * number=0 时恢复母工序 status=0 并软删除其子工序
  1325. * @param id 工艺ID
  1326. * @param number 拆分数量(0 表示取消拆分)
  1327. * @param sys_id 操作人员
  1328. * @param sys_rq 操作时间(可选,默认当前时间)
  1329. */
  1330. public function confirmProcessSplit()
  1331. {
  1332. if (!$this->request->isPost()) {
  1333. $this->error('请求方法错误');
  1334. }
  1335. $params = $this->request->post();
  1336. if (empty($params['id'])) {
  1337. $this->error('工艺ID不能为空');
  1338. }
  1339. if (!isset($params['number']) || $params['number'] === '' || $params['number'] === null) {
  1340. $this->error('拆分工序数量不能为空');
  1341. }
  1342. if (empty($params['sys_id'])) {
  1343. $this->error('操作人不能为空');
  1344. }
  1345. $splitCount = intval($params['number']);
  1346. $operTime = !empty($params['sys_rq']) ? $params['sys_rq'] : date('Y-m-d H:i:s');
  1347. $processId = intval($params['id']);
  1348. $process = Db::table('工单_基础工艺资料')
  1349. ->where('id', $processId)
  1350. ->whereNull('del_rq')
  1351. ->find();
  1352. if (empty($process)) {
  1353. $this->error('工序不存在');
  1354. }
  1355. $workorder = $process['work_order'];
  1356. if ($splitCount === 0) {
  1357. $children = Db::table('工单_基础工艺资料')
  1358. ->where('pid', $processId)
  1359. ->whereNull('del_rq')
  1360. ->field('id,process_code')
  1361. ->select();
  1362. $logList = [
  1363. [
  1364. 'order_no' => $workorder,
  1365. 'process_code' => $process['process_code'],
  1366. 'change_field' => '状态',
  1367. 'old_value' => '1',
  1368. 'new_value' => '0',
  1369. 'oper_type' => '取消拆分工序',
  1370. 'oper_user_name' => $params['sys_id'],
  1371. 'oper_time' => $operTime,
  1372. ],
  1373. ];
  1374. foreach ($children as $child) {
  1375. $logList[] = [
  1376. 'order_no' => $workorder,
  1377. 'process_code' => $child['process_code'],
  1378. 'change_field' => '工序拆分',
  1379. 'old_value' => (string)$process['process_code'],
  1380. 'new_value' => '删除子工序',
  1381. 'oper_type' => '取消拆分工序',
  1382. 'oper_user_name' => $params['sys_id'],
  1383. 'oper_time' => $operTime,
  1384. ];
  1385. }
  1386. Db::startTrans();
  1387. try {
  1388. if (!empty($children)) {
  1389. $deleteResult = Db::table('工单_基础工艺资料')
  1390. ->where('pid', $processId)
  1391. ->whereNull('del_rq')
  1392. ->update(['del_rq' => $operTime]);
  1393. if ($deleteResult === false) {
  1394. throw new \Exception('删除子工序失败');
  1395. }
  1396. }
  1397. $updateResult = Db::table('工单_基础工艺资料')
  1398. ->where('id', $processId)
  1399. ->whereNull('del_rq')
  1400. ->update(['status' => 0]);
  1401. if ($updateResult === false) {
  1402. throw new \Exception('恢复母工序状态失败');
  1403. }
  1404. if (!empty($logList)) {
  1405. $logResult = Db::name('work_order_operation_log')->insertAll($logList);
  1406. if ($logResult === false || $logResult === 0) {
  1407. throw new \Exception('写入操作日志失败');
  1408. }
  1409. }
  1410. Db::commit();
  1411. } catch (\think\exception\HttpResponseException $e) {
  1412. throw $e;
  1413. } catch (\Exception $e) {
  1414. Db::rollback();
  1415. $this->error('取消拆分失败:' . $e->getMessage());
  1416. }
  1417. $this->success('取消拆分工序成功', ['count' => count($children)]);
  1418. return;
  1419. }
  1420. if ($splitCount < 1) {
  1421. $this->error('拆分工序数量必须大于0');
  1422. }
  1423. if (!in_array($process['status'], [0, '0'], true)) {
  1424. $this->error('工序不存在或已确认拆分');
  1425. }
  1426. $processCodes = Db::table('工单_基础工艺资料')
  1427. ->where('work_order', $workorder)
  1428. ->whereNull('del_rq')
  1429. ->column('process_code');
  1430. $maxNumeric = 0;
  1431. foreach ($processCodes as $code) {
  1432. if (preg_match('/^(\d+)/', (string)$code, $match)) {
  1433. $num = intval($match[1]);
  1434. if ($num > $maxNumeric) {
  1435. $maxNumeric = $num;
  1436. }
  1437. }
  1438. }
  1439. $baseCode = $maxNumeric + 1;
  1440. $splitFields = ['standard_hour', 'standard_minutes', 'standard_score', 'money'];
  1441. $splitValues = [];
  1442. foreach ($splitFields as $field) {
  1443. $splitValues[$field] = $this->splitNumericValue($process[$field], $splitCount);
  1444. }
  1445. $insertList = [];
  1446. for ($i = 1; $i <= $splitCount; $i++) {
  1447. $newProcessCode = $baseCode + $i - 1;
  1448. $exists = Db::table('工单_基础工艺资料')
  1449. ->where('work_order', $workorder)
  1450. ->where('process_code', $newProcessCode)
  1451. ->whereNull('del_rq')
  1452. ->count();
  1453. if ($exists > 0) {
  1454. $this->error('工序编号已存在:' . $newProcessCode);
  1455. }
  1456. $insertList[] = [
  1457. 'work_order' => $workorder,
  1458. 'part_code' => $process['part_code'],
  1459. 'part_name' => isset($process['part_name']) ? $process['part_name'] : '',
  1460. 'process_code' => $newProcessCode,
  1461. 'process_name' => $process['process_name'] . '-' . $i,
  1462. 'big_process' => $process['big_process'],
  1463. 'standard_hour' => $splitValues['standard_hour'][$i - 1],
  1464. 'standard_minutes' => $splitValues['standard_minutes'][$i - 1],
  1465. 'standard_score' => $splitValues['standard_score'][$i - 1],
  1466. 'money' => $splitValues['money'][$i - 1],
  1467. 'coefficient' => isset($process['coefficient']) && $process['coefficient'] !== '' && $process['coefficient'] !== null
  1468. ? $process['coefficient'] : 'C',
  1469. 'remark' => isset($process['remark']) && $process['remark'] !== null ? $process['remark'] : '',
  1470. 'status' => 0,
  1471. 'pid' => $processId,
  1472. 'sys_id' => $params['sys_id'],
  1473. 'sys_rq' => $operTime,
  1474. ];
  1475. }
  1476. $logList = [
  1477. [
  1478. 'order_no' => $workorder,
  1479. 'process_code' => $process['process_code'],
  1480. 'change_field' => '状态',
  1481. 'old_value' => '0',
  1482. 'new_value' => '1',
  1483. 'oper_type' => '确认拆分工序',
  1484. 'oper_user_name' => $params['sys_id'],
  1485. 'oper_time' => $operTime,
  1486. ],
  1487. ];
  1488. foreach ($insertList as $row) {
  1489. $logList[] = [
  1490. 'order_no' => $workorder,
  1491. 'process_code' => $row['process_code'],
  1492. 'change_field' => '工序拆分',
  1493. 'old_value' => (string)$process['process_code'],
  1494. 'new_value' => sprintf(
  1495. '秒:%s,分:%s,定额分:%s,金额:%s',
  1496. $row['standard_hour'],
  1497. $row['standard_minutes'],
  1498. $row['standard_score'],
  1499. $row['money']
  1500. ),
  1501. 'oper_type' => '确认拆分工序',
  1502. 'oper_user_name' => $params['sys_id'],
  1503. 'oper_time' => $operTime,
  1504. ];
  1505. }
  1506. Db::startTrans();
  1507. try {
  1508. $updateResult = Db::table('工单_基础工艺资料')
  1509. ->where('id', $process['id'])
  1510. ->where('status', 'in', [0, '0'])
  1511. ->update(['status' => 1]);
  1512. if ($updateResult === false) {
  1513. throw new \Exception('更新母工序状态失败');
  1514. }
  1515. if ($updateResult === 0) {
  1516. throw new \Exception('母工序状态已变更,请刷新后重试');
  1517. }
  1518. $insertResult = Db::name('工单_基础工艺资料')->insertAll($insertList);
  1519. if ($insertResult === false || $insertResult === 0) {
  1520. throw new \Exception('拆分工序新增失败');
  1521. }
  1522. $logResult = Db::name('work_order_operation_log')->insertAll($logList);
  1523. if ($logResult === false || $logResult === 0) {
  1524. throw new \Exception('写入操作日志失败,请确认日志表已包含 process_code 字段');
  1525. }
  1526. Db::commit();
  1527. } catch (\think\exception\HttpResponseException $e) {
  1528. throw $e;
  1529. } catch (\Exception $e) {
  1530. Db::rollback();
  1531. $this->error('修改失败:' . $e->getMessage());
  1532. }
  1533. $this->success('确认拆分工序成功', ['count' => $splitCount]);
  1534. }
  1535. /**
  1536. * 按拆分数量分配数值:不能整除时第一条为剩余后的最大值,其余为向下取整的平均值
  1537. * @param mixed $total
  1538. * @param int $count
  1539. * @return array
  1540. */
  1541. private function splitNumericValue($total, $count)
  1542. {
  1543. $count = intval($count);
  1544. if ($count <= 0) {
  1545. return [];
  1546. }
  1547. $total = floatval($total);
  1548. $avg = floor($total / $count * 100) / 100;
  1549. $first = round($total - $avg * ($count - 1), 2);
  1550. $values = [$first];
  1551. for ($i = 1; $i < $count; $i++) {
  1552. $values[] = $avg;
  1553. }
  1554. return $values;
  1555. }
  1556. /**
  1557. * 根据款号查询工单信息
  1558. * @param search 搜索内容
  1559. * @return array
  1560. * @throws \think\db\exception\DataNotFoundException
  1561. * @throws \think\db\exception\ModelNotFoundException
  1562. * @throws \think\exception\DbException
  1563. */
  1564. public function getWorkOrderInfoByStyle()
  1565. {
  1566. if (!$this->request->isGet()) {
  1567. $this->error('请求方法错误');
  1568. }
  1569. $params = $this->request->param();
  1570. if (empty($params['search'])) {
  1571. $this->error('搜索内容不能为空');
  1572. }
  1573. $where = [
  1574. 'a.订单编号|a.生产款号|a.款式' => ['like', '%' . $params['search'] . '%'],
  1575. 'a.Mod_rq' => null,
  1576. ];
  1577. $workOrder = db('工单_基本资料')->alias('a')
  1578. ->join('工单_基础工艺资料 b', 'a.订单编号 = b.work_order')
  1579. ->field('a.订单编号,a.生产款号,a.款式,a.客户编号')
  1580. ->where($where)
  1581. ->group('a.订单编号')
  1582. ->select();
  1583. if (empty($workOrder)) {
  1584. $this->error('未找到工单信息');
  1585. }
  1586. $this->success('成功', $workOrder);
  1587. }
  1588. /**
  1589. * 复制目标工单的部件与工艺到当前工单
  1590. * @param target_workorder 目标工单编号
  1591. * @param current_workorder 当前工单编号
  1592. * @param sys_id 操作人
  1593. */
  1594. public function copyProcessToCurrentWorkOrder()
  1595. {
  1596. if (!$this->request->isPost()) {
  1597. $this->error('请求方法错误');
  1598. }
  1599. $params = $this->request->post();
  1600. if (empty($params['target_workorder'])) {
  1601. $this->error('目标工单编号不能为空');
  1602. }
  1603. if (empty($params['current_workorder'])) {
  1604. $this->error('当前工单编号不能为空');
  1605. }
  1606. if (empty($params['sys_id'])) {
  1607. $this->error('操作人不能为空');
  1608. }
  1609. if ($params['target_workorder'] === $params['current_workorder']) {
  1610. $this->error('目标工单与当前工单不能相同');
  1611. }
  1612. if (!$this->workOrderExists($params['target_workorder'])) {
  1613. $this->error('目标工单不存在');
  1614. }
  1615. if (!$this->workOrderExists($params['current_workorder'])) {
  1616. $this->error('当前工单不存在');
  1617. }
  1618. $targetWorkOrderInfo = $this->getWorkOrderInfo($params['target_workorder']);
  1619. if (empty($targetWorkOrderInfo['partInfo']) && empty($targetWorkOrderInfo['processInfo'])) {
  1620. $this->error('目标工单没有可复制的部件或工艺');
  1621. }
  1622. $currentWorkOrderInfo = $this->getWorkOrderInfo($params['current_workorder']);
  1623. $oldPartCount = count($currentWorkOrderInfo['partInfo']);
  1624. $oldProcessCount = count($currentWorkOrderInfo['processInfo']);
  1625. if ($oldPartCount > 0 || $oldProcessCount > 0) {
  1626. $this->error('当前工单已有部件或工艺数据,不允许复制');
  1627. }
  1628. $now = date('Y-m-d H:i:s');
  1629. $partInsertList = $this->buildWorkOrderPartCopyRows(
  1630. $targetWorkOrderInfo['partInfo'],
  1631. $params['current_workorder'],
  1632. $params['sys_id'],
  1633. $now
  1634. );
  1635. $processInsertList = $this->buildWorkOrderProcessCopyRows(
  1636. $targetWorkOrderInfo['processInfo'],
  1637. $params['current_workorder'],
  1638. $params['sys_id'],
  1639. $now
  1640. );
  1641. $logData = [
  1642. 'order_no' => $params['current_workorder'],
  1643. 'change_field' => $params['target_workorder'],
  1644. 'old_value' => sprintf('部件%d条,工艺%d条', $oldPartCount, $oldProcessCount),
  1645. 'new_value' => sprintf('部件%d条,工艺%d条', count($partInsertList), count($processInsertList)),
  1646. 'oper_type' => '复制工单工艺',
  1647. 'oper_user_name' => $params['sys_id'],
  1648. 'oper_time' => $now,
  1649. ];
  1650. Db::startTrans();
  1651. try {
  1652. if ($oldPartCount > 0 || $oldProcessCount > 0) {
  1653. $partDeleteResult = Db::table('工单_部件资料')
  1654. ->where('work_order', $params['current_workorder'])
  1655. ->whereNull('del_rq')
  1656. ->update(['del_rq' => $now]);
  1657. if ($partDeleteResult === false) {
  1658. throw new \Exception('清除当前工单部件失败');
  1659. }
  1660. $processDeleteResult = Db::table('工单_基础工艺资料')
  1661. ->where('work_order', $params['current_workorder'])
  1662. ->whereNull('del_rq')
  1663. ->update(['del_rq' => $now]);
  1664. if ($processDeleteResult === false) {
  1665. throw new \Exception('清除当前工单工艺失败');
  1666. }
  1667. }
  1668. if (!empty($partInsertList)) {
  1669. $partInsertResult = Db::name('工单_部件资料')->insertAll($partInsertList);
  1670. if ($partInsertResult === false || $partInsertResult === 0) {
  1671. throw new \Exception('复制部件失败');
  1672. }
  1673. }
  1674. if (!empty($processInsertList)) {
  1675. $processInsertResult = Db::name('工单_基础工艺资料')->insertAll($processInsertList);
  1676. if ($processInsertResult === false || $processInsertResult === 0) {
  1677. throw new \Exception('复制工艺失败');
  1678. }
  1679. }
  1680. // 同步复制工单_基本资料中的"计划制造工分"字段(中文表名/字段名改用原生SQL,避免参数化语法错误)
  1681. $safeTarget = addslashes($params['target_workorder']);
  1682. $gfRow = \db()->query("SELECT `计划制造工分` FROM `工单_基本资料` WHERE `订单编号` = '{$safeTarget}' AND `Mod_rq` IS NULL LIMIT 1");
  1683. $targetGf = isset($gfRow[0]['计划制造工分']) ? $gfRow[0]['计划制造工分'] : null;
  1684. if ($targetGf !== null && $targetGf !== '') {
  1685. $safeCurrent = addslashes($params['current_workorder']);
  1686. $safeGf = addslashes($targetGf);
  1687. $gfUpdateResult = \db()->query(
  1688. "UPDATE `工单_基本资料` SET `计划制造工分` = '{$safeGf}' WHERE `订单编号` = '{$safeCurrent}' AND `Mod_rq` IS NULL"
  1689. );
  1690. if ($gfUpdateResult === false) {
  1691. throw new \Exception('复制计划制造工分失败');
  1692. }
  1693. }
  1694. $logResult = Db::name('work_order_operation_log')->insert($logData);
  1695. if ($logResult === false || $logResult === 0) {
  1696. throw new \Exception('写入操作日志失败');
  1697. }
  1698. Db::commit();
  1699. } catch (\think\exception\HttpResponseException $e) {
  1700. throw $e;
  1701. } catch (\Exception $e) {
  1702. Db::rollback();
  1703. $this->error('复制失败:' . $e->getMessage());
  1704. }
  1705. $this->success('复制成功', [
  1706. 'part_count' => count($partInsertList),
  1707. 'process_count' => count($processInsertList),
  1708. ]);
  1709. }
  1710. /**
  1711. * 判断工单是否存在
  1712. * @param string $workorder
  1713. * @return bool
  1714. */
  1715. private function workOrderExists($workorder)
  1716. {
  1717. return Db::table('工单_基本资料')
  1718. ->where('订单编号', $workorder)
  1719. ->whereNull('Mod_rq')
  1720. ->count() > 0;
  1721. }
  1722. /**
  1723. * 查询工单部件与工艺(未删除、工艺仅 status=0)
  1724. * @param string $workorder
  1725. * @return array
  1726. */
  1727. private function getWorkOrderInfo($workorder)
  1728. {
  1729. $partInfo = db('工单_部件资料')
  1730. ->where('work_order', $workorder)
  1731. ->whereNull('del_rq')
  1732. ->field('part_code,part_name,remark,part_type,status')
  1733. ->order('part_code')
  1734. ->select();
  1735. $processInfo = db('工单_基础工艺资料')
  1736. ->where('work_order', $workorder)
  1737. ->whereNull('del_rq')
  1738. ->where('status', 0)
  1739. ->field('part_code,part_name,process_code,process_name,standard_hour,standard_minutes,
  1740. standard_score,money,coefficient,remark,big_process')
  1741. ->order('process_code')
  1742. ->select();
  1743. return [
  1744. 'partInfo' => $partInfo ?: [],
  1745. 'processInfo' => $processInfo ?: [],
  1746. ];
  1747. }
  1748. /**
  1749. * 组装待复制的部件数据
  1750. */
  1751. private function buildWorkOrderPartCopyRows($partList, $workOrder, $sysId, $operTime)
  1752. {
  1753. $rows = [];
  1754. foreach ($partList as $part) {
  1755. $rows[] = [
  1756. 'work_order' => $workOrder,
  1757. 'part_code' => $part['part_code'],
  1758. 'part_name' => trim((string)$part['part_name']),
  1759. 'remark' => isset($part['remark']) ? $part['remark'] : '',
  1760. 'part_type' => isset($part['part_type']) ? trim((string)$part['part_type']) : '',
  1761. 'status' => 0,
  1762. 'sys_id' => $sysId,
  1763. 'sys_rq' => $operTime,
  1764. ];
  1765. }
  1766. return $rows;
  1767. }
  1768. /**
  1769. * 组装待复制的工艺数据
  1770. */
  1771. private function buildWorkOrderProcessCopyRows($processList, $workOrder, $sysId, $operTime)
  1772. {
  1773. $rows = [];
  1774. foreach ($processList as $process) {
  1775. $rows[] = [
  1776. 'work_order' => $workOrder,
  1777. 'part_code' => $process['part_code'],
  1778. 'part_name' => isset($process['part_name']) ? trim((string)$process['part_name']) : '',
  1779. 'process_code' => $process['process_code'],
  1780. 'process_name' => trim((string)$process['process_name']),
  1781. 'big_process' => trim((string)$process['big_process']),
  1782. 'standard_hour' => $process['standard_hour'],
  1783. 'standard_minutes' => $process['standard_minutes'],
  1784. 'standard_score' => $process['standard_score'],
  1785. 'money' => $process['money'],
  1786. 'coefficient' => $process['coefficient'],
  1787. 'remark' => isset($process['remark']) ? $process['remark'] : '',
  1788. 'status' => 0,
  1789. 'pid' => 0,
  1790. 'sys_id' => $sysId,
  1791. 'sys_rq' => $operTime,
  1792. ];
  1793. }
  1794. return $rows;
  1795. }
  1796. /**
  1797. * 批量新增工序资料(请求体为 JSON 数组,每条含 work_order 等字段)
  1798. * @param processList 工序信息
  1799. * @return array
  1800. * @throws \think\db\exception\DataNotFoundException
  1801. * @throws \think\db\exception\ModelNotFoundException
  1802. * @throws \think\exception\DbException
  1803. **/
  1804. public function batchAddProcess()
  1805. {
  1806. if (!$this->request->isPost()) {
  1807. $this->error('请求方法错误');
  1808. }
  1809. $processList = $this->parseBatchProcessList();
  1810. if (empty($processList)) {
  1811. $this->error('工艺数据不能为空');
  1812. }
  1813. $requiredFields = [
  1814. 'work_order' => '工单编号',
  1815. 'part_code' => '部件编号',
  1816. 'part_name' => '部件名称',
  1817. 'process_code' => '工序编号',
  1818. 'process_name' => '工序名称',
  1819. 'big_process' => '大工序',
  1820. 'standard_hour' => '秒',
  1821. 'standard_score' => '定额分',
  1822. 'coefficient' => '难度系数',
  1823. 'standard_minutes' => '分',
  1824. 'money' => '金额',
  1825. 'remark' => '备注',
  1826. 'sys_id' => '操作人员',
  1827. ];
  1828. $workorder = '';
  1829. $now = date('Y-m-d H:i:s');
  1830. $insertList = [];
  1831. $processCodeMap = [];
  1832. $newBatchStatus0Sum = 0;
  1833. foreach ($processList as $index => $process) {
  1834. $rowNo = $index + 1;
  1835. if (!is_array($process)) {
  1836. $this->error('第' . $rowNo . '条工艺数据格式错误');
  1837. }
  1838. // foreach ($requiredFields as $field => $label) {
  1839. // if (!isset($process[$field]) || $process[$field] === '' || $process[$field] === null) {
  1840. // $this->error('第' . $rowNo . '条' . $label . '不能为空');
  1841. // }
  1842. // }
  1843. $itemWorkOrder = trim($process['work_order']);
  1844. if ($workorder === '') {
  1845. $workorder = $itemWorkOrder;
  1846. } elseif ($itemWorkOrder !== $workorder) {
  1847. $this->error('第' . $rowNo . '条工单编号与其它数据不一致');
  1848. }
  1849. $processCode = (string)$process['process_code'];
  1850. if (isset($processCodeMap[$processCode])) {
  1851. $this->error('批量数据中存在重复的工序编号:' . $processCode);
  1852. }
  1853. $processCodeMap[$processCode] = true;
  1854. $status = isset($process['status']) ? $process['status'] : 0;
  1855. if (in_array($status, [0, '0'], true)) {
  1856. $newBatchStatus0Sum += floatval($process['standard_score']);
  1857. }
  1858. $insertList[] = [
  1859. 'work_order' => $workorder,
  1860. 'part_code' => $process['part_code'],
  1861. 'part_name' => $process['part_name'],
  1862. 'process_code' => $processCode,
  1863. 'process_name' => $process['process_name'],
  1864. 'big_process' => $process['big_process'],
  1865. 'standard_hour' => $process['standard_hour'],
  1866. 'standard_minutes' => $process['standard_minutes'],
  1867. 'standard_score' => $process['standard_score'],
  1868. 'coefficient' => $process['coefficient'],
  1869. 'money' => $process['money'],
  1870. 'remark' => $process['remark'],
  1871. 'status' => $status,
  1872. 'sys_id' => $process['sys_id'],
  1873. 'sys_rq' => $now,
  1874. ];
  1875. }
  1876. $existingCodes = Db::table('工单_基础工艺资料')
  1877. ->where('work_order', $workorder)
  1878. ->whereIn('process_code', array_keys($processCodeMap))
  1879. ->whereNull('del_rq')
  1880. ->column('process_code');
  1881. if (!empty($existingCodes)) {
  1882. $this->error('工序编号已存在:' . $existingCodes[0]);
  1883. }
  1884. $workOrder = Db::table('工单_基本资料')
  1885. ->where('订单编号', $workorder)
  1886. ->where('Mod_rq', null)
  1887. ->field('订单编号,计划制造工分')
  1888. ->find();
  1889. if (empty($workOrder)) {
  1890. $this->error('工单不存在');
  1891. }
  1892. $existingTotal = Db::table('工单_基础工艺资料')
  1893. ->where('work_order', $workorder)
  1894. ->where('status', 0)
  1895. ->whereNull('del_rq')
  1896. ->sum('standard_score');
  1897. $existingTotal = $existingTotal ? floatval($existingTotal) : 0;
  1898. if ($existingTotal + $newBatchStatus0Sum > floatval($workOrder['计划制造工分'])) {
  1899. $this->error('工序定额分和大于制造工分,请确认之后再修改');
  1900. }
  1901. Db::startTrans();
  1902. try {
  1903. $insertResult = Db::name('工单_基础工艺资料')->insertAll($insertList);
  1904. if ($insertResult === false || $insertResult === 0) {
  1905. throw new \Exception('批量新增工序失败');
  1906. }
  1907. Db::commit();
  1908. } catch (\think\exception\HttpResponseException $e) {
  1909. throw $e;
  1910. } catch (\Exception $e) {
  1911. Db::rollback();
  1912. $this->error('批量新增工序资料失败');
  1913. }
  1914. $this->success('批量新增工序资料成功', ['count' => count($insertList)]);
  1915. }
  1916. /**
  1917. * 解析批量工序请求体(form 数组 / JSON 数组 / 单字段 JSON 字符串)
  1918. * @return array
  1919. */
  1920. private function parseBatchProcessList()
  1921. {
  1922. $params = $this->request->post();
  1923. if (isset($params[0]) && is_array($params[0])) {
  1924. return $params;
  1925. }
  1926. $decoded = json_decode($this->request->getInput(), true);
  1927. if (is_array($decoded) && isset($decoded[0]) && is_array($decoded[0])) {
  1928. return $decoded;
  1929. }
  1930. $jsonStr = is_string($params) ? $params : (count($params) === 1 ? reset($params) : null);
  1931. if (is_string($jsonStr)) {
  1932. $decoded = json_decode($jsonStr, true);
  1933. return is_array($decoded) ? $decoded : [];
  1934. }
  1935. return [];
  1936. }
  1937. /**
  1938. * 工序产量核查:按工单查询报工汇总(工单信息 / 工序列表 / 人员报工明细)
  1939. * @param workorder 工单编号
  1940. * @param process 工序(可选,按big_process过滤)
  1941. * @return array
  1942. */
  1943. public function checkProcessProduction()
  1944. {
  1945. if (!$this->request->isGet()) {
  1946. $this->error('请求方法错误');
  1947. }
  1948. $params = $this->request->param();
  1949. if (empty($params['workorder'])) {
  1950. $this->error('工单编号不能为空');
  1951. }
  1952. $workorder = $params['workorder'];
  1953. $processFilter = $params['process'] ?? '';
  1954. // 1. 查询工单基本信息
  1955. $workOrderInfo = Db::name('工单_基本资料')
  1956. ->where('订单编号', $workorder)
  1957. ->whereNull('Mod_rq')
  1958. ->field('订单编号, 生产款号, 款式, 订单数量')
  1959. ->find();
  1960. if (empty($workOrderInfo)) {
  1961. $this->error('工单不存在');
  1962. }
  1963. // 2. 查询工单基础工艺资料(所有工序)
  1964. $processQuery = Db::name('工单_基础工艺资料')
  1965. ->where('work_order', $workorder)
  1966. ->whereNull('del_rq');
  1967. // 如果传了工序参数,按 big_process 过滤
  1968. if (!empty($processFilter)) {
  1969. $processQuery->where('big_process', $processFilter);
  1970. }
  1971. $processList = $processQuery
  1972. ->field('process_code as 工序号, process_name as 工序名称, part_name as 部件名称')
  1973. ->select();
  1974. if (empty($processList)) {
  1975. $this->error('该工单暂无工艺资料');
  1976. }
  1977. // 按工序号数字排序
  1978. usort($processList, function ($a, $b) {
  1979. return intval($a['工序号']) - intval($b['工序号']);
  1980. });
  1981. // 3. 查询设备_工分计酬中的报工数据,补齐staff_no字段
  1982. $reportList = Db::name('设备_工分计酬')->alias('a')
  1983. ->where('a.work_order', $workorder)
  1984. ->whereNull('a.del_rq')
  1985. ->field('a.process_code as 工序号, a.process_name as 工序名称, a.staff_no as 员工号, a.staff_name as 员工姓名,
  1986. a.sys_id as 小组,
  1987. SUM(a.number) as 数量, MIN(a.date) as 开工日期, MAX(a.date) as 完工日期,
  1988. SUM(a.standard_score) as 工分, SUM(a.production_score) as 工时, SUM(a.salary) as 工资')
  1989. ->group('a.process_code, a.process_name, a.staff_no, a.staff_name, a.sys_id')
  1990. ->select();
  1991. // 按工序号、员工号数字排序
  1992. if (!empty($reportList)) {
  1993. usort($reportList, function ($a, $b) {
  1994. $codeCmp = intval($a['工序号']) - intval($b['工序号']);
  1995. if ($codeCmp !== 0) return $codeCmp;
  1996. return intval($a['员工号'] ?? 0) - intval($b['员工号'] ?? 0);
  1997. });
  1998. }
  1999. // 4. 组装返回数据
  2000. $manufactureQty = $workOrderInfo['订单数量'] ?? 0;
  2001. $data = [
  2002. '订单编号' => $workOrderInfo['订单编号'],
  2003. '生产款号' => $workOrderInfo['生产款号'],
  2004. '款式' => $workOrderInfo['款式'],
  2005. '订单数量' => $manufactureQty,
  2006. '工序列表' => [],
  2007. ];
  2008. // 5. 构建工序映射【核心修复:仅使用工序号匹配,不再受工序名称不一致影响】
  2009. $processMap = [];
  2010. foreach ($processList as $process) {
  2011. $processCode = trim((string)$process['工序号']);
  2012. if (!isset($processMap[$processCode])) {
  2013. $processMap[$processCode] = [
  2014. '工序号' => $process['工序号'],
  2015. '工序名称' => $process['工序名称'],
  2016. '部件名称' => $process['部件名称'] ?? '',
  2017. '制造数量' => $manufactureQty,
  2018. '累计完成数' => 0,
  2019. '未完成数' => floatval($manufactureQty),
  2020. 'staffs' => [],
  2021. ];
  2022. }
  2023. }
  2024. // 6. 将报工数据合并到对应工序
  2025. if (!empty($reportList)) {
  2026. foreach ($reportList as $report) {
  2027. $processCode = trim((string)$report['工序号']);
  2028. if (isset($processMap[$processCode])) {
  2029. $startDate = !empty($report['开工日期']) ? date('Y-m-d', strtotime($report['开工日期'])) : '';
  2030. $endDate = !empty($report['完工日期']) ? date('Y-m-d', strtotime($report['完工日期'])) : '';
  2031. $processMap[$processCode]['staffs'][] = [
  2032. '员工姓名' => $report['员工姓名'],
  2033. '小组' => $report['小组'],
  2034. '数量' => floatval($report['数量']),
  2035. '开工日期' => $startDate,
  2036. '完工日期' => $endDate,
  2037. '工分' => round(floatval($report['工分']), 4),
  2038. '工时' => round(floatval($report['工时']), 4),
  2039. '工资' => round(floatval($report['工资']), 4),
  2040. ];
  2041. }
  2042. }
  2043. }
  2044. // 7. 计算每道工序累计完成数、未完成数
  2045. foreach ($processMap as $processCode => $process) {
  2046. $completedQty = 0;
  2047. foreach ($process['staffs'] as $staff) {
  2048. $completedQty += floatval($staff['数量']);
  2049. }
  2050. $processMap[$processCode]['累计完成数'] = $completedQty;
  2051. $processMap[$processCode]['未完成数'] = floatval($manufactureQty) - $completedQty;
  2052. }
  2053. $resultList = array_values($processMap);
  2054. // 最终按工序号数字排序
  2055. usort($resultList, function ($a, $b) {
  2056. return intval($a['工序号']) - intval($b['工序号']);
  2057. });
  2058. $data['工序列表'] = $resultList;
  2059. $this->success('成功', $data);
  2060. }
  2061. }