Decision.php 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use think\Db;
  5. use think\Request;
  6. /**
  7. * 决策支持
  8. */
  9. class Decision extends Api
  10. {
  11. protected $noNeedLogin = ['*'];
  12. protected $noNeedRight = ['*'];
  13. //月度产量统计菜单
  14. public function OutputSstatisticsMenu()
  15. {
  16. if ($this->request->isGet() === false){
  17. $this->error('请求错误');
  18. }
  19. $mouth = \db('设备_产量计酬')
  20. ->distinct(true)
  21. ->field('DATE_FORMAT(sczl_rq, "%Y-%m") AS month')
  22. ->order('month desc')
  23. ->select();
  24. $sist = \db('设备_基本资料')
  25. ->whereNotNull('设备编组')
  26. ->group('设备编组')
  27. ->column('rtrim(设备编组) as 设备编组');
  28. $data = [];
  29. foreach ($mouth as $key=>$value) {
  30. $arr = [
  31. 'date'=>date('Ym',strtotime($value['month'])),
  32. 'sbbh'=>$sist,
  33. ];
  34. array_push($data,$arr);
  35. }
  36. $this->success('成功',$data);
  37. }
  38. /**
  39. * 月度产量统计上方机台生产数据
  40. * @return void
  41. * @throws \think\db\exception\DataNotFoundException
  42. * @throws \think\db\exception\ModelNotFoundException
  43. * @throws \think\exception\DbException
  44. */
  45. public function MachineProduction()
  46. {
  47. // 验证请求方式
  48. if ($this->request->isGet() === false) {
  49. $this->error('请求错误');
  50. }
  51. // 获取请求参数
  52. $param = $this->request->param();
  53. if (empty($param['mouth'])) {
  54. $this->error('参数错误');
  55. }
  56. // 初始化查询条件
  57. $where = [];
  58. if (!empty($param['sist'])) {
  59. $where['b.设备编组'] = $param['sist'];
  60. }
  61. // 转换日期格式
  62. $mouth = date_create_from_format('Ym', $param['mouth'])->format('Y-m');
  63. // 使用单个查询获取所有需要的数据
  64. $results = \db('设备_产量计酬')
  65. ->alias('a')
  66. ->join('设备_基本资料 b', 'a.sczl_jtbh = b.设备编号')
  67. ->join('工单_印件资料 c', 'a.sczl_gdbh = c.Yj_Gdbh AND a.sczl_yjno = c.yj_Yjno', 'LEFT')
  68. ->join('工单_工艺资料 d', 'a.sczl_gdbh = d.Gy0_gdbh AND a.sczl_yjno = d.Gy0_yjno AND a.sczl_gxh = d.Gy0_gxh', 'LEFT')
  69. ->field([
  70. 'a.sczl_jtbh',
  71. 'a.sczl_bzdh',
  72. 'DATE_FORMAT(a.sczl_rq, "%Y-%m-%d") as day',
  73. 'SUM(a.sczl_cl) AS total_cl',
  74. 'c.yj_yjmc AS 印件名称',
  75. 'CONCAT(d.Gy0_gxmc,"(",d.Add_gxmc,")") AS 工序名称',
  76. 'RTRIM(d.印刷方式) AS 印刷方式',
  77. 'RTRIM(d.版距) AS 版距'
  78. ])
  79. ->where('a.sczl_rq', 'like', $mouth . '%')
  80. ->where('b.sys_sbID', '<>', '')
  81. ->where($where)
  82. ->group('a.sczl_jtbh, a.sczl_bzdh, day, c.yj_yjmc, d.Gy0_gxmc')
  83. ->order('a.sczl_jtbh, a.sczl_bzdh, day')
  84. ->select();
  85. // 数据处理
  86. $data = [];
  87. // 获取唯一日期并排序
  88. $data['head'] = array_unique(array_column($results, 'day'));
  89. // 将日期转为时间戳以排序
  90. usort($data['head'], function($a, $b) {
  91. return strtotime($a) - strtotime($b);
  92. });
  93. // 准备按设备和班组整理的数据
  94. $total_by_machine = [];
  95. foreach ($results as $item) {
  96. $machine_id = $item['sczl_jtbh'];
  97. $group_id = $item['sczl_bzdh'];
  98. $day = $item['day'];
  99. $printed_type = $item['印刷方式'];
  100. // 初始化设备和班组
  101. if (!isset($total_by_machine[$machine_id])) {
  102. $total_by_machine[$machine_id] = [];
  103. }
  104. if (!isset($total_by_machine[$machine_id][$group_id])) {
  105. $total_by_machine[$machine_id][$group_id] = [
  106. '机台编号' => $machine_id,
  107. '班组编号' => $group_id,
  108. '印件名称' => $item['印件名称'],
  109. '工序名称' => $item['工序名称'],
  110. 'total_cl' => 0,
  111. 'day_total' => []
  112. ];
  113. }
  114. // 更新累计数量
  115. if ($printed_type === '卷对卷') {
  116. $total_by_machine[$machine_id][$group_id]['total_cl'] += round($item['total_cl'] / $item['版距'] * 1000);
  117. } else {
  118. $total_by_machine[$machine_id][$group_id]['total_cl'] += $item['total_cl'];
  119. }
  120. // 更新每日总计
  121. if (!isset($total_by_machine[$machine_id][$group_id]['day_total'][$day])) {
  122. $total_by_machine[$machine_id][$group_id]['day_total'][$day] = 0;
  123. }
  124. if ($printed_type === '卷对卷') {
  125. $total_by_machine[$machine_id][$group_id]['day_total'][$day] += round($item['total_cl'] / $item['版距'] * 1000);
  126. } else {
  127. $total_by_machine[$machine_id][$group_id]['day_total'][$day] += $item['total_cl'];
  128. }
  129. }
  130. // 格式化输出数据
  131. $data['total'] = [];
  132. foreach ($total_by_machine as $machine_group) {
  133. foreach ($machine_group as $group_data) {
  134. $data['total'][] = $group_data;
  135. }
  136. }
  137. $this->success('成功', $data);
  138. }
  139. /**
  140. * 机台班次生产工单明细
  141. * @return void
  142. * @throws \think\db\exception\DataNotFoundException
  143. * @throws \think\db\exception\ModelNotFoundException
  144. * @throws \think\exception\DbException
  145. */
  146. public function MachineProductDetail()
  147. {
  148. if (!$this->request->isGet()) {
  149. $this->error('请求错误');
  150. }
  151. $param = $this->request->param();
  152. // 检查必需的参数
  153. if (empty($param['mouth'])) {
  154. $this->error('参数错误');
  155. }
  156. // Initializing where conditions
  157. $where = [];
  158. // 添加可选的查询条件
  159. if (!empty($param['machine'])) {
  160. $where['a.sczl_jtbh'] = $param['machine'];
  161. }
  162. if (!empty($param['team'])) {
  163. $where['a.sczl_bzdh'] = ['like', substr($param['team'], 0, 1) . '%'];
  164. }
  165. // 将参数转换成标准日期格式
  166. $mouth = date_create_from_format('Ym', $param['mouth'])->format('Y-m');
  167. $where['a.sczl_rq'] = ['like', $mouth . '%'];
  168. // 分页配置
  169. $page = !empty($param['page']) ? (int)$param['page'] : 1;
  170. $limit = !empty($param['limit']) ? (int)$param['limit'] : 9999; // 默认查询所有
  171. // 查询数据
  172. $list = \db('设备_产量计酬')
  173. ->alias('a')
  174. ->join('工单_印件资料 c', 'a.sczl_gdbh = c.Yj_Gdbh AND a.sczl_yjno = c.yj_Yjno')
  175. ->join('工单_工艺资料 d', 'a.sczl_gdbh = d.Gy0_gdbh AND a.sczl_yjno = d.Gy0_yjno AND a.sczl_gxh = d.Gy0_gxh')
  176. ->join('dic_lzde e', 'a.sczl_dedh = e.sys_bh')
  177. ->field([
  178. 'a.sczl_gdbh' => '工单编号',
  179. 'a.sczl_yjno' => '印件号',
  180. 'a.sczl_gxh' => '工序号',
  181. 'c.yj_yjmc' => '印件名称',
  182. 'CONCAT(d.Gy0_gxmc,"(",d.Add_gxmc,")")' => '工序名称',
  183. 'DATE(a.sczl_rq)' => '工作日期',
  184. 'a.sczl_jtbh' => '机台编号',
  185. 'a.sczl_bzdh' => '班组编号',
  186. 'SUM(a.sczl_cl)' => '产量',
  187. 'a.sczl_ms' => '墨色数',
  188. 'rtrim(d.印刷方式)' => '印刷方式',
  189. 'rtrim(d.版距)' => '版距',
  190. 'rtrim(e.补产标准)' => '补产标准',
  191. 'rtrim(d.工价系数)' => '工价系数'
  192. ])
  193. ->where($where)
  194. ->group('a.sczl_gdbh, a.sczl_yjno, a.sczl_gxh, a.sczl_rq, a.sczl_jtbh, a.sczl_bzdh')
  195. ->order('工作日期')
  196. ->page($page, $limit) // 使用 page 和 limit 实现分页
  197. ->select();
  198. // 数据处理
  199. if (!empty($list)) {
  200. foreach ($list as $key => $value) {
  201. $list[$key]['印件名称'] = $value['印件号'] . '-' . $value['印件名称'];
  202. $list[$key]['工序名称'] = $value['工序号'] . '-' . $value['工序名称'];
  203. unset($list[$key]['印件号'], $list[$key]['工序号']);
  204. // 产量计算
  205. if ($value['印刷方式'] === '卷对卷') {
  206. $list[$key]['产量'] = round($value['产量'] / $value['版距'] * 1000);
  207. }
  208. // 墨色数修正
  209. if ($value['墨色数'] === '0.00') {
  210. $list[$key]['墨色数'] = '1.00';
  211. }
  212. }
  213. }
  214. $this->success('成功', $list);
  215. }
  216. /**
  217. * 月度机台运行工时汇总
  218. * @return void
  219. * @throws \think\db\exception\DataNotFoundException
  220. * @throws \think\db\exception\ModelNotFoundException
  221. * @throws \think\exception\DbException
  222. */
  223. public function MachineOperation()
  224. {
  225. // 确保请求是GET
  226. if ($this->request->isGet() === false) {
  227. $this->error('请求错误');
  228. }
  229. // 获取请求参数
  230. $param = $this->request->param();
  231. if (empty($param['mouth'])) {
  232. $this->error('参数错误');
  233. }
  234. // 构建查询条件
  235. $where = [];
  236. if (!empty($param['sist'])) {
  237. $where['a.设备编组'] = $param['sist'];
  238. }
  239. // 将参数转换成标准日期格式
  240. $mouth = date_create_from_format('Ym', $param['mouth'])->format('Y-m');
  241. // 单次查询,计算产量和各项工时
  242. $list = \db('设备_基本资料')
  243. ->alias('a')
  244. ->join('设备_产量计酬 b', 'a.设备编号 = b.sczl_jtbh')
  245. ->join('工单_印件资料 c', 'b.sczl_gdbh = c.Yj_Gdbh AND b.sczl_yjno = c.yj_Yjno')
  246. ->join('工单_工艺资料 d', 'b.sczl_gdbh = d.Gy0_gdbh AND b.sczl_yjno = d.Gy0_yjno AND b.sczl_gxh = d.Gy0_gxh')
  247. ->field([
  248. 'a.设备编号' => '设备编号',
  249. 'rtrim(a.设备名称)' => '设备名称',
  250. 'SUM(CASE WHEN rtrim(d.版距) = "卷对卷" THEN b.sczl_cl / NULLIF(d.版距, 0) * 1000 ELSE b.sczl_cl END) AS 产量',
  251. 'SUM(b.sczl_设备运行工时)' => '设备运行工时',
  252. 'SUM(b.sczl_保养工时)' => '保养工时',
  253. 'SUM(b.sczl_打样总工时)' => '打样总工时',
  254. 'SUM(b.sczl_打样工时)' => '打样补产工时',
  255. 'SUM(b.sczl_装版总工时)' => '装版总工时',
  256. 'SUM(b.sczl_装版工时)' => '装版补产工时',
  257. 'SUM(b.sczl_异常停机工时)' => '异常停机工时',
  258. 'rtrim(d.印刷方式)' => '印刷方式',
  259. 'rtrim(d.版距)' => '版距'
  260. ])
  261. ->where($where)
  262. ->where('b.sczl_rq', 'like', $mouth . '%')
  263. ->group('a.设备编号')
  264. ->order('a.设备编号')
  265. ->select();
  266. // 处理总工时的计算
  267. $total = [
  268. '设备运行工时' => 0,
  269. '保养工时' => 0,
  270. '打样总工时' => 0,
  271. '打样补产工时' => 0,
  272. '装版总工时' => 0,
  273. '装版补产工时' => 0,
  274. '异常停机工时' => 0
  275. ];
  276. // 计算各项总工时
  277. foreach ($list as $item) {
  278. $total['设备运行工时'] += $item['设备运行工时'];
  279. $total['保养工时'] += $item['保养工时'];
  280. $total['打样总工时'] += $item['打样总工时'];
  281. $total['打样补产工时'] += $item['打样补产工时'];
  282. $total['装版总工时'] += $item['装版总工时'];
  283. $total['装版补产工时'] += $item['装版补产工时'];
  284. $total['异常停机工时'] += $item['异常停机工时'];
  285. }
  286. // 将总工时添加到列表中
  287. $list['total'] = $total;
  288. // 返回成功响应
  289. $this->success('成功', $list);
  290. }
  291. /**
  292. * 设备运行工时机台生产工单数据详情
  293. * @return void
  294. * @throws \think\db\exception\DataNotFoundException
  295. * @throws \think\db\exception\ModelNotFoundException
  296. * @throws \think\exception\DbException
  297. */
  298. public function MachineOperationProductDetail()
  299. {
  300. if (!$this->request->isGet()) {
  301. $this->error('请求错误');
  302. }
  303. $param = $this->request->param();
  304. if (empty($param['mouth'])) {
  305. $this->error('参数错误');
  306. }
  307. // Initialize where conditions
  308. $where = [];
  309. if (!empty($param['machine'])) {
  310. $where['a.sczl_jtbh'] = $param['machine'];
  311. }
  312. // 将参数转换成标准日期格式
  313. $mouth = date_create_from_format('Ym', $param['mouth'])->format('Y-m');
  314. $where['a.sczl_rq'] = ['like', $mouth . '%'];
  315. // 分页配置
  316. $page = !empty($param['page']) ? (int)$param['page'] : 1;
  317. $limit = !empty($param['limit']) ? (int)$param['limit'] : 9999; // 默认查询所有
  318. // 查询数据
  319. $list = \db('设备_产量计酬')
  320. ->alias('a')
  321. ->join('设备_基本资料 b', 'a.sczl_jtbh = b.设备编号')
  322. ->join('工单_印件资料 c', 'a.sczl_gdbh = c.Yj_Gdbh AND a.sczl_yjno = c.yj_Yjno')
  323. ->join('工单_工艺资料 d', 'a.sczl_gdbh = d.Gy0_gdbh AND a.sczl_yjno = d.Gy0_yjno AND a.sczl_gxh = d.Gy0_gxh')
  324. ->join('dic_lzde e', 'a.sczl_dedh = e.sys_bh')
  325. ->field([
  326. 'a.sczl_jtbh' => '设备编号',
  327. 'rtrim(b.设备名称)' => '设备名称',
  328. 'DATE(a.sczl_rq)' => '日期',
  329. 'a.sczl_gdbh' => '工单编号',
  330. 'a.sczl_yjno' => '印件号',
  331. 'a.sczl_gxh' => '工序号',
  332. 'c.yj_yjmc' => '印件名称',
  333. 'CONCAT(d.Gy0_gxmc, "(", d.Add_gxmc, ")")' => '工序名称',
  334. 'SUM(a.sczl_cl)' => '产量',
  335. 'SUM(a.sczl_设备运行工时)' => '设备运行工时',
  336. 'SUM(a.sczl_保养工时)' => '保养工时',
  337. 'SUM(a.sczl_打样总工时)' => '打样总工时',
  338. 'SUM(a.sczl_打样工时)' => '打样补产工时',
  339. 'SUM(a.sczl_装版总工时)' => '装板总工时',
  340. 'SUM(a.sczl_装版工时)' => '装板补产工时',
  341. 'SUM(a.sczl_异常停机工时)' => '异常停机工时',
  342. 'a.sczl_ms' => '墨色数',
  343. 'rtrim(d.印刷方式)' => '印刷方式',
  344. 'rtrim(d.版距)' => '版距',
  345. 'rtrim(e.补产标准)' => '补产标准',
  346. 'rtrim(d.工价系数)' => '工价系数'
  347. ])
  348. ->where($where)
  349. ->group('a.sczl_rq, a.sczl_gdbh, a.sczl_gxh, a.sczl_jtbh')
  350. ->order('a.sczl_rq')
  351. ->page($page, $limit) // 使用 page 和 limit 技术实现分页
  352. ->select();
  353. // 数据处理
  354. if (!empty($list)) {
  355. foreach ($list as $key => $value) {
  356. $list[$key]['工序名称'] = $value['印件号'] . '-' . $value['工序号'] . '-' . $value['工序名称'];
  357. // 移除不需要的字段
  358. unset($list[$key]['印件号'], $list[$key]['工序号']);
  359. // 产量计算
  360. if ($value['印刷方式'] === '卷对卷') {
  361. $list[$key]['产量'] = round($value['产量'] / $value['版距'] * 1000);
  362. }
  363. // 墨色数修正
  364. if ($value['墨色数'] === '0.00') {
  365. $list[$key]['墨色数'] = '1.00';
  366. }
  367. // 计算实际每小时车头产量and实际每小时计件产量与补产标准差额
  368. $output = $list[$key]['产量'];
  369. $runningHours = $value['设备运行工时'] ?: 0.0001;
  370. $standardOutput = $value['补产标准'] ?: 0;
  371. $priceCoefficient = $value['工价系数'] ?: 0;
  372. //修正前公式
  373. // 实际每小时车头产量 = 产量 / 设备运行工时
  374. // $list[$key]['实际每小时车头产量'] = $runningHours > 0 ? round($output / $runningHours, 2) : 0;
  375. //修正后公式
  376. //实际每小时车头产量=产量/(设备运行工时-保养工时-打样总工时-装版总工时-异常停机工时)
  377. $totalHours = $value['设备运行工时'] ?: 0
  378. - $value['保养工时'] ?: 0
  379. - $value['打样总工时'] ?: 0
  380. - $value['装版总工时'] ?: 0
  381. - $value['异常停机工时'] ?: 0;
  382. $totalHours = max($totalHours, 0.0001); // 防止除数为0
  383. $list[$key]['实际每小时车头产量'] = round($output / $totalHours, 2);
  384. // 实际每小时计件产量与补产标准差额 = 实际每小时车头产量 * 计件系数 - 补产标准
  385. $list[$key]['实际每小时计件产量与补产标准差额'] = round(
  386. $list[$key]['实际每小时车头产量'] * $priceCoefficient - $standardOutput, 2);
  387. }
  388. }
  389. $this->success('成功', $list);
  390. }
  391. /**
  392. * 工序产出率月度统计报表
  393. * @return void
  394. * @throws \think\db\exception\DataNotFoundException
  395. * @throws \think\db\exception\ModelNotFoundException
  396. * @throws \think\exception\DbException
  397. */
  398. public function ProcessOutputRate()
  399. {
  400. if (!$this->request->isGet()) {
  401. $this->error('请求错误');
  402. }
  403. $param = $this->request->param();
  404. if (empty($param) || empty($param['year'])) {
  405. $this->error('参数错误');
  406. }
  407. // 1. 获取设备分组,作为工序依据
  408. $sist = ['胶印车间','凹丝印车间','印后车间','检验车间'];
  409. $processOrder = \db('设备_基本资料')
  410. ->whereNotNull('设备编组')
  411. ->whereIn('使用部门', $sist)
  412. ->group('设备编组')
  413. ->column('RTRIM(设备编组) as 设备编组');
  414. if (empty($processOrder)) {
  415. $this->success('成功', []);
  416. }
  417. // 2. 初始化结果数组(按工序)
  418. $result = [];
  419. foreach ($processOrder as $process) {
  420. $key = substr($process, 5, 6);
  421. $result[$key] = [];
  422. for ($i = 1; $i <= 12; $i++) {
  423. $result[$key][str_pad($i, 2, '0', STR_PAD_LEFT) . '月'] = '';
  424. }
  425. $result[$key]['平均值'] = '0.00%';
  426. }
  427. // 3. 汇总所有年份内数据,一次查出所有“工序-月份”数据
  428. $dataList = \db('工单_质量考核汇总')
  429. ->alias('a')
  430. ->join('工单_工艺资料 b', 'a.Gy0_gdbh = b.Gy0_gdbh AND a.印件及工序 = b.Gy0_yjno AND a.工序 = b.Gy0_gxh')
  431. ->join('工单_印件资料 c', 'a.Gy0_gdbh = c.Yj_Gdbh AND a.印件及工序 = c.yj_Yjno')
  432. ->join('成品入仓 d', 'a.Gy0_gdbh = d.jjcp_gdbh AND a.印件及工序 = d.jjcp_yjno')
  433. ->join('设备_基本资料 e', 'a.sczl_jtbh = e.设备编号')
  434. ->whereIn('e.设备编组', $processOrder)
  435. ->where('d.jjcp_smb', 'like', '末%')
  436. ->where('a.sys_ny', 'like', $param['year'] . '%')
  437. ->field([
  438. 'e.设备编组',
  439. 'a.sys_ny',
  440. 'SUM(a.班组制程废品/ a.联数) AS 制程废品',
  441. 'SUM(a.班组质检废品/ a.联数) AS 质检废品',
  442. 'SUM(a.班组产量/ a.联数) AS 产量'
  443. ])
  444. ->group('e.设备编组, a.sys_ny')
  445. ->select();
  446. //修正前计算方式
  447. // // 4. 处理统计数据,填充到$result
  448. // $annual = []; // 年均合格率累加用
  449. // foreach ($dataList as $item) {
  450. // $processKey = substr($item['设备编组'], 5, 6);
  451. // $monthKey = substr($item['sys_ny'], 4, 2) . '月';
  452. //
  453. // $output = floatval($item['产量']);
  454. // $waste = floatval($item['制程废品']) + floatval($item['质检废品']);
  455. // $rate = $output > 0 ? (1 - $waste / $output) * 100 : 0;
  456. // $result[$processKey][$monthKey] = sprintf('%.2f%%', $rate);
  457. //
  458. // if (!isset($annual[$processKey])) {
  459. // $annual[$processKey] = ['sum' => 0, 'count' => 0];
  460. // }
  461. // $annual[$processKey]['sum'] += $rate;
  462. // $annual[$processKey]['count']++;
  463. // }
  464. // // 5. 补充“平均值”
  465. // foreach ($annual as $processKey => $v) {
  466. // if ($v['count'] > 0) {
  467. // $result[$processKey]['平均值'] = sprintf('%.2f%%', $v['sum']/$v['count']);
  468. // }
  469. // }
  470. //修正后计算方式
  471. // 【用于算平均值】
  472. $yearTotal = [];
  473. // 4. 处理每月数据
  474. foreach ($dataList as $item) {
  475. $processKey = substr($item['设备编组'], 5, 6);
  476. $monthKey = substr($item['sys_ny'], 4, 2) . '月';
  477. $output = floatval($item['产量']);
  478. $waste = floatval($item['制程废品']) + floatval($item['质检废品']);
  479. $rate = $output > 0 ? (1 - $waste / $output) * 100 : 0;
  480. $result[$processKey][$monthKey] = sprintf('%.2f%%', $rate);
  481. // 【累计:总产量、总废品】
  482. if (!isset($yearTotal[$processKey])) {
  483. $yearTotal[$processKey] = [
  484. 'totalOutput' => 0,
  485. 'totalWaste' => 0
  486. ];
  487. }
  488. $yearTotal[$processKey]['totalOutput'] += $output;
  489. $yearTotal[$processKey]['totalWaste'] += $waste;
  490. }
  491. //打印总计
  492. // echo "<pre>";
  493. // print_r($yearTotal);
  494. // echo "<pre>";
  495. // 【平均值:用全年总和计算】
  496. foreach ($yearTotal as $processKey => $val) {
  497. $totalOutput = $val['totalOutput'];
  498. $totalWaste = $val['totalWaste'];
  499. if ($totalOutput > 0) {
  500. $avgRate = (1 - $totalWaste / $totalOutput) * 100;
  501. $result[$processKey]['平均值'] = sprintf('%.2f%%', $avgRate);
  502. } else {
  503. $result[$processKey]['平均值'] = '0.00%';
  504. }
  505. }
  506. // 6. 转前端格式
  507. $formattedData = [];
  508. foreach ($result as $process => $data) {
  509. $row = array_merge(['工序类型' => $process], $data);
  510. $formattedData[] = $row;
  511. }
  512. $this->success('成功', $formattedData);
  513. }
  514. /**
  515. * 生产中心统计左侧菜单:年份 → 报表类型 → 下一级节点(全部从数据库动态取)
  516. * 10 个报表类型固定返回,下一级节点按报表类型从对应数据源取实际值:
  517. * - month_* 月度类 (7个) → 工单_质量考核汇总.sys_ny / 设备_产量计酬.sczl_rq 的 YYYYMM
  518. * - year_equipment_waste/box → 设备_基本资料.设备编组(有实际产量数据的)
  519. * - day_output 产量日报 → 设备_产量计酬.sczl_rq 日期列表
  520. */
  521. public function GetYear()
  522. {
  523. if ($this->request->isGet() === false) {
  524. $this->error('请求错误');
  525. }
  526. // 10 个报表类型(固定顺序)
  527. $reportTypes = [
  528. 'month_output' => '产量月统计报表',
  529. 'month_schedule' => '排产达成率月统计',
  530. 'month_workhour' => '工时达成率月统计报表',
  531. 'month_oee' => 'OEE月统计报表',
  532. 'month_changeover' => '换型效率月统计报表',
  533. 'month_ioi' => '投入产出率月统计报表',
  534. 'month_processrate' => '工序产出率月统计报表',
  535. 'year_equipment_waste' => '年度设备编组废品统计',
  536. 'year_equipment_box' => '年度设备大箱数统计',
  537. 'day_output' => '产量日报表统计',
  538. ];
  539. // 1. 工单_质量考核汇总 有数据的年份+月份(sys_ny = YYYYMM)
  540. $khMonths = Db::query("SELECT DISTINCT sys_ny AS ym FROM `工单_质量考核汇总` WHERE sys_ny REGEXP '^[0-9]{6}$' ORDER BY ym DESC");
  541. $khYears = [];
  542. foreach ($khMonths as $r) {
  543. $y = substr($r['ym'], 0, 4);
  544. $khYears[$y][] = $r['ym'];
  545. }
  546. // 2. 设备_产量计酬 有数据的年份+月份(过滤脏数据 0001xx)
  547. $scMonths = Db::query("SELECT DISTINCT DATE_FORMAT(sczl_rq, '%Y%m') AS ym FROM `设备_产量计酬` WHERE sczl_rq >= '2000-01-01' AND sczl_rq IS NOT NULL ORDER BY ym DESC");
  548. $scYears = [];
  549. foreach ($scMonths as $r) {
  550. $y = substr($r['ym'], 0, 4);
  551. $scYears[$y][] = $r['ym'];
  552. }
  553. // 3. 设备_产量计酬 有数据的日期列表(近 90 天,避免太长)
  554. $days = Db::query("SELECT DISTINCT DATE_FORMAT(sczl_rq, '%Y-%m-%d') AS d FROM `设备_产量计酬` WHERE sczl_rq >= DATE_SUB(CURDATE(), INTERVAL 90 DAY) AND sczl_rq IS NOT NULL ORDER BY d DESC");
  555. // 4. 设备_基本资料 有实际产量数据的设备编组
  556. $groups = Db::query("SELECT DISTINCT RTRIM(b.设备编组) AS `group`
  557. FROM `设备_产量计酬` s
  558. INNER JOIN `设备_基本资料` b
  559. ON RTRIM(b.设备编号) = RTRIM(s.sczl_jtbh)
  560. WHERE b.设备编组 IS NOT NULL AND b.设备编组 <> '' AND s.sczl_rq >= '2000-01-01'
  561. ORDER BY b.设备编组 ASC");
  562. // 所有出现过的年份(取并集,倒序)
  563. $allYears = array_unique(array_merge(array_keys($khYears), array_keys($scYears)));
  564. rsort($allYears);
  565. // 月份 label:从 YYYYMM 提取 MM
  566. $monthLabel = function ($ym) {
  567. return intval(substr($ym, 4, 2)) . '月';
  568. };
  569. $result = [];
  570. foreach ($allYears as $year) {
  571. $yearInt = intval($year);
  572. $yearNode = [
  573. 'key' => "year_{$yearInt}",
  574. 'label' => "{$yearInt}年",
  575. 'year' => $yearInt,
  576. 'children' => [],
  577. ];
  578. foreach ($reportTypes as $typeKey => $typeLabel) {
  579. $children = [];
  580. if (strpos($typeKey, 'month_') === 0) {
  581. // 月度类:优先用 质量考核汇总 的月份,没有则 fallback 到 产量计酬
  582. $months = isset($khYears[$year]) ? $khYears[$year] : (isset($scYears[$year]) ? $scYears[$year] : []);
  583. sort($months); // 升序
  584. foreach ($months as $ym) {
  585. $children[] = [
  586. 'key' => "{$yearInt}_{$ym}",
  587. 'label' => $monthLabel($ym),
  588. 'ym' => $ym,
  589. ];
  590. }
  591. } elseif (strpos($typeKey, 'year_') === 0) {
  592. // 年度类:设备编组列表(每年份显示全部编组,数据按年份过滤在后端处理)
  593. foreach ($groups as $g) {
  594. $gname = $g['group'];
  595. $children[] = [
  596. 'key' => "{$yearInt}_" . md5($gname),
  597. 'label' => $gname,
  598. 'group' => $gname,
  599. ];
  600. }
  601. } elseif ($typeKey === 'day_output') {
  602. // 日报表:近 90 天日期
  603. foreach ($days as $d) {
  604. $dateStr = $d['d'];
  605. $children[] = [
  606. 'key' => "{$yearInt}_{$dateStr}",
  607. 'label' => substr($dateStr, 5), // MM-DD
  608. 'date' => $dateStr,
  609. ];
  610. }
  611. }
  612. $yearNode['children'][] = [
  613. 'key' => "year_{$yearInt}_{$typeKey}",
  614. 'label' => $typeLabel,
  615. 'typeKey' => $typeKey,
  616. 'children' => $children,
  617. ];
  618. }
  619. $result[] = $yearNode;
  620. }
  621. $this->success('成功', $result);
  622. }
  623. /**
  624. * 数据透视表
  625. * @return null
  626. * @throws \think\Exception
  627. * @throws \think\db\exception\DataNotFoundException
  628. * @throws \think\db\exception\ModelNotFoundException
  629. * @throws \think\exception\DbException
  630. */
  631. public function PoductData()
  632. {
  633. if (!$this->request->isGet()) {
  634. $this->error('请求错误');
  635. }
  636. $param = $this->request->param();
  637. if (empty($param['year'])) {
  638. $this->error('参数错误');
  639. }
  640. // 获取设备编组列表(已按编号排序)
  641. $processGroups = \db('设备_基本资料')
  642. ->whereNotNull('设备编组')
  643. ->group('设备编组')
  644. ->column('rtrim(设备编组) as 设备编组');
  645. // 构建基础查询
  646. $query = \db('工单_质量考核汇总')
  647. ->alias('a')
  648. ->field('
  649. a.sczl_jtbh AS 机台编号,
  650. a.Gy0_gdbh AS 工单编号,
  651. a.印件及工序 AS 工序号,
  652. a.产品名称 AS 印件名称,
  653. a.工序 AS 工序,
  654. a.工序名称,
  655. b.Gy0_gxmc,
  656. a.联数,
  657. a.班组产量,
  658. a.班组制程废品,
  659. a.班组质检废品,
  660. a.sczl_bzdh AS 班组编号,
  661. b.印刷方式,
  662. b.版距,
  663. DATE_FORMAT(a.入仓日期, \'%Y%m\') AS 完工年月,
  664. d.设备编组
  665. ')
  666. ->join('工单_工艺资料 b', 'a.Gy0_gdbh = b.Gy0_gdbh AND a.印件及工序 = b.Gy0_yjno AND a.工序 = b.Gy0_gxh')
  667. ->join('成品入仓 c', 'a.Gy0_gdbh = c.jjcp_gdbh AND a.印件及工序 = c.jjcp_yjno')
  668. ->join('设备_基本资料 d', 'a.sczl_jtbh = d.设备编号')
  669. ->where('a.sys_ny', 'like', $param['year'] . '%')
  670. ->where('a.工序名称', 'not like', '%机检%')
  671. ->where('c.jjcp_smb', 'like', '末%')
  672. ->where('a.工序名称', 'not like', '%拆片%');
  673. // 获取总数
  674. $total = clone $query;
  675. $total = $total->count();
  676. // 执行查询
  677. $rawList = isset($param['page'], $param['limit'])
  678. ? $query->page($param['page'])->limit($param['limit'])->select()
  679. : $query->select();
  680. // 构建分类映射表
  681. $groupMap = [];
  682. foreach ($processGroups as $index => $group) {
  683. // 提取机组名称核心词(去除编号和"机组"字样)
  684. $groupName = preg_replace('/^\d+、/', '', $group); // 移除开头编号
  685. $coreName = str_replace('机组', '', $groupName); // 移除尾部的"机组"
  686. $groupMap[] = [
  687. 'id' => $index + 1,
  688. 'name' => $groupName,
  689. 'core' => $coreName
  690. ];
  691. }
  692. // 处理分类标记
  693. $processedList = [];
  694. foreach ($rawList as $item) {
  695. foreach ($groupMap as $group) {
  696. // 使用核心词进行模糊匹配
  697. if (strpos($item['设备编组'], $group['core']) !== false) {
  698. $item['type_id'] = $group['id'];
  699. $item['type_name'] = $group['name'];
  700. $processedList[] = $item;
  701. continue 2;
  702. }
  703. }
  704. }
  705. // 按分类ID排序
  706. usort($processedList, function($a, $b) {
  707. return $a['type_id'] <=> $b['type_id'];
  708. });
  709. // 返回结构
  710. $data['data'] = $processedList;
  711. $data['total'] = $total;
  712. $data['filtered_total'] = count($processedList);
  713. return count($processedList) > 0
  714. ? $this->success('成功', $data)
  715. : $this->error('未找到数据');
  716. }
  717. /**
  718. * 月度色度数导出
  719. * @return void
  720. * @throws \think\db\exception\DataNotFoundException
  721. * @throws \think\db\exception\ModelNotFoundException
  722. * @throws \think\exception\DbException
  723. */
  724. public function ChromaticityNumber()
  725. {
  726. if (!$this->request->isGet()) {
  727. $this->error('请求错误');
  728. }
  729. $param = $this->request->param();
  730. if (empty($param['month'])) {
  731. $this->error('参数错误');
  732. }
  733. $month = date_create_from_format('Ym', $param['month'])->format('Y-m');
  734. $where = ['a.sczl_rq' => ['like', $month . '%']];
  735. $list = \db('设备_产量计酬')
  736. ->alias('a')
  737. ->join('工单_印件资料 c', 'a.sczl_gdbh = c.Yj_Gdbh AND a.sczl_yjno = c.yj_Yjno')
  738. ->join('工单_工艺资料 d', 'a.sczl_gdbh = d.Gy0_gdbh AND a.sczl_yjno = d.Gy0_yjno AND a.sczl_gxh = d.Gy0_gxh')
  739. ->join('设备_基本资料 e', 'a.sczl_jtbh = e.设备编号')
  740. ->field([
  741. 'a.sczl_gdbh' => '工单编号',
  742. 'a.sczl_yjno' => '印件号',
  743. 'a.sczl_gxh' => '工序号',
  744. 'd.Gy0_gxmc' => '工序名称',
  745. 'SUM(a.sczl_cl)' => '产量',
  746. 'a.sczl_ms' => '墨色数',
  747. 'rtrim(d.印刷方式)' => '印刷方式',
  748. 'rtrim(d.版距)' => '版距',
  749. 'rtrim(d.Gy0_SITE)' => '车间名称',
  750. 'rtrim(e.设备编组)' => '设备编组',
  751. 'a.sczl_jtbh'
  752. ])
  753. ->where($where)
  754. ->group('a.sczl_gdbh, a.sczl_yjno, a.sczl_gxh, a.sczl_rq, a.sczl_jtbh, a.sczl_bzdh')
  755. ->select();
  756. $data = [];
  757. if (!empty($list)) {
  758. foreach ($list as $key => $value) {
  759. // Convert ALL outputs to integers
  760. $value['产量'] = (int)round($value['产量']);
  761. if ($value['印刷方式'] === '卷对卷' && $value['版距'] != 0) {
  762. $value['产量'] = (int)round($value['产量'] / $value['版距'] * 1000);
  763. }
  764. if($value['墨色数'] == 0 && $value['设备编组'] !== '11、检品机组'){
  765. $value['墨色数'] = 1;
  766. }
  767. if($value['设备编组'] === '11、检品机组'){
  768. $value['墨色数'] = 0;
  769. }
  770. $data[$key] = [
  771. 'gdbh' => $value['工单编号'],
  772. 'ms' => $value['墨色数'],
  773. '产量' => $value['产量'],
  774. '墨色' => $value['产量'] * $value['墨色数'],
  775. '设备编组' => $value['设备编组']
  776. ];
  777. }
  778. }
  779. $grouped = [];
  780. foreach ($data as $item) {
  781. $key = substr($item['设备编组'], 5, 6);
  782. if (!isset($grouped[$key])) {
  783. $grouped[$key] = [
  784. '产量合计' => 0,
  785. '工序名称' => $key,
  786. '色度数' => 0
  787. ];
  788. }
  789. $grouped[$key]['产量合计'] += (int)$item['产量'];
  790. $grouped[$key]['色度数'] += (int)$item['墨色'];
  791. }
  792. foreach ($grouped as &$group) {
  793. $group['产量合计'] = (int)$group['产量合计'];
  794. $group['色度数'] = (int)$group['色度数'];
  795. }
  796. $this->success('成功', array_values($grouped));
  797. }
  798. /**
  799. * 年度质检废品率统计左侧菜单
  800. * @return void
  801. * @throws \think\db\exception\DataNotFoundException
  802. * @throws \think\db\exception\ModelNotFoundException
  803. * @throws \think\exception\DbException
  804. */
  805. public function QualityInspectionGetTab()
  806. {
  807. if (!$this->request->isGet()) {
  808. $this->error('请求错误');
  809. }
  810. $monthStats = \db('db_qczl')
  811. ->group('month')
  812. ->order('month desc')
  813. ->column("DATE_FORMAT(qczl_rq, '%Y%m') AS month");
  814. // 按年月层次结构归类(返回树形结构)
  815. $treeData = \db('db_qczl')
  816. ->field([
  817. "DATE_FORMAT(qczl_rq, '%Y') AS year",
  818. "DATE_FORMAT(qczl_rq, '%m') AS month",
  819. "COUNT(*) AS total"
  820. ])
  821. ->order('year desc,month desc')
  822. ->group('year, month')
  823. ->select();
  824. // 构建树形结构
  825. $result = [];
  826. foreach ($treeData as $item) {
  827. $year = $item['year'];
  828. $month = $year . $item['month'];
  829. if (!isset($result[$year])) {
  830. $result[$year] = [
  831. 'year' => $year,
  832. 'children' => []
  833. ];
  834. }
  835. $result[$year]['children'][] = [
  836. 'month' => $month,
  837. 'total' => $item['total']
  838. ];
  839. }
  840. $this->success('成功', $result);
  841. }
  842. /**
  843. * 年度质检废品统计右侧上方列表
  844. * @return void
  845. * @throws \think\db\exception\DataNotFoundException
  846. * @throws \think\db\exception\ModelNotFoundException
  847. * @throws \think\exception\DbException
  848. */
  849. public function QualityInspectionList()
  850. {
  851. if (!$this->request->isGet()) {
  852. $this->error('请求错误');
  853. }
  854. $param = $this->request->param();
  855. $where = ['年月' => ['like', $param['month'] . '%']];
  856. // 查询工单列表
  857. $workList = \db('rec_月度废品汇总')
  858. ->where($where)
  859. ->field("CONCAT(Gd_gdbh,'-',印件号) as 工单,实际投料")
  860. ->group('工单')
  861. ->select();
  862. $work = [];
  863. foreach ($workList as $item) {
  864. $work[$item['工单']] = $item['实际投料'];
  865. }
  866. // 查询工单对应的废品类别首字母(按工单和首字母分组)
  867. $WasteWorkList = \db('rec_月度废品汇总')
  868. ->where($where)
  869. ->field("CONCAT(Gd_gdbh,'-',印件号) as 工单, left(废品类别,1) as 废品类别首字母")
  870. ->group('工单, 废品类别首字母')
  871. ->order('废品类别首字母 asc')
  872. ->select();
  873. $waste = [];
  874. foreach ($WasteWorkList as $item) {
  875. if (!isset($waste[$item['废品类别首字母']])) {
  876. $waste[$item['废品类别首字母']] = [];
  877. }
  878. $waste[$item['废品类别首字母']][] = $item['工单'];
  879. }
  880. // 计算每个首字母的实际投料总和
  881. $res = [];
  882. foreach ($waste as $key => $item) {
  883. $res[$key] = array_sum(array_intersect_key($work, array_flip($item)));
  884. }
  885. // 查询废品类别对应的废品数量
  886. $wasteList = \db('rec_月度废品汇总')
  887. ->where($where)
  888. ->group('废品类别')
  889. ->order('废品类别 asc')
  890. ->column("sum(废品数量) as 废品数量", "废品类别");
  891. // 从废品类别数据计算每个首字母的废品数量总和
  892. $classification = [];
  893. foreach ($wasteList as $category => $amount) {
  894. $firstChar = substr($category, 0, 1);
  895. if (!isset($classification[$firstChar])) {
  896. $classification[$firstChar] = 0;
  897. }
  898. $classification[$firstChar] += $amount;
  899. }
  900. // 构建数据数组
  901. $data = [];
  902. foreach ($wasteList as $category => $amount) {
  903. $firstChar = substr($category, 0, 1);
  904. $number = $res[$firstChar] ?? 0;
  905. $data[] = [
  906. '废品类别' => $category,
  907. '实际投料' => $number,
  908. '废品数量' => $amount,
  909. '质检废品率' => (round($amount/$number, 7) * 100) . '%',
  910. ];
  911. }
  912. // 添加首字母合计行
  913. foreach ($classification as $firstChar => $amount) {
  914. $number = $res[$firstChar] ?? 0;
  915. $data[] = [
  916. '废品类别' => $firstChar . '-合计',
  917. '实际投料' => $number,
  918. '废品数量' => $amount,
  919. '质检废品率' => (round($amount/$number, 7) * 100) . '%',
  920. ];
  921. }
  922. $this->success('成功', $data);
  923. }
  924. //判断字符串首位是否为英文字母
  925. function isFirstCharEnglish($str) {
  926. if (mb_strlen($str) == 0) return false;
  927. $firstChar = mb_substr($str, 0, 1);
  928. return preg_match('/^[A-Za-z]$/u', $firstChar);
  929. }
  930. /**
  931. * 年度质检废品率统计下方列表
  932. * @return void
  933. * @throws \think\db\exception\DataNotFoundException
  934. * @throws \think\db\exception\ModelNotFoundException
  935. * @throws \think\exception\DbException
  936. */
  937. public function QualityInspectionDetailList()
  938. {
  939. if ($this->request->isGet() === false) {
  940. $this->error('请求错误');
  941. }
  942. $param = $this->request->param();
  943. $where = [
  944. '年月' => ['like',$param['month'].'%'],
  945. '废品类别' => $param['class']
  946. ];
  947. $list = \db('rec_月度废品汇总')
  948. ->where($where)
  949. ->field('年月,客户编号,客户名称,产品名称,Gd_gdbh as 工单编号,印件号,实际投料,废品类别,sum(废品数量) as 废品数量,质检完工时间')
  950. ->group('工单编号,印件号,废品类别')
  951. ->select();
  952. foreach ($list as $key => $item) {
  953. $list[$key]['质检废品率'] = (round($item['废品数量']/$item['实际投料'], 7)*100).'%';
  954. $list[$key]['年周数'] = substr($list[$key]['质检完工时间'],0,4).'年第'.date('W',strtotime($item['质检完工时间'])).'周';
  955. }
  956. $this->success('成功', $list);
  957. }
  958. /**
  959. * 创建月度废品率系数
  960. * @return void
  961. * @throws \think\db\exception\DataNotFoundException
  962. * @throws \think\db\exception\ModelNotFoundException
  963. * @throws \think\exception\DbException
  964. */
  965. public function QualityInspectionAdd()
  966. {
  967. if (!$this->request->isGet()) {
  968. $this->error('请求错误');
  969. }
  970. $param = $this->request->param();
  971. // 1. 修复WHERE条件(原来的第二个WHERE会覆盖第一个)
  972. $where = ['jjcp_sj' => ['between', [$param['startMonth'], $param['endMonth']]]];
  973. $where = ['jjcp_smb' => ['like', '末%']];
  974. // 2. 优化字段选择,只选择必要的字段
  975. $field = [
  976. 'a.qczl_gdbh', 'a.qczl_yjno', 'a.qczl_rq',
  977. 'c.成品编码', 'c.成品名称', 'd.规格',
  978. 'b.实际投料', 'e.客户编号', 'e.客户名称',
  979. "DATE_FORMAT(c.jjcp_sj, '%Y%m') AS ym",
  980. 'c.jjcp_cpdh', 'c.jjcp_cpmc'
  981. ];
  982. // 3. 添加fp_lb和fp_sl字段
  983. for ($i = 1; $i <= 13; $i++) {
  984. $field[] = "a.fp_lb{$i}";
  985. $field[] = "a.fp_sl{$i}";
  986. }
  987. // 4. 执行查询
  988. $list = \db('db_qczl')
  989. ->alias('a')
  990. ->join('工单_基本资料 b', 'a.qczl_gdbh = b.Gd_gdbh and a.qczl_yjno = b.行号', 'LEFT')
  991. ->join('成品入仓 c', 'a.qczl_gdbh = c.jjcp_gdbh and a.qczl_yjno = c.jjcp_yjno', 'LEFT')
  992. ->join('物料_存货编码 d', 'c.jjcp_cpdh = d.物料代码', 'LEFT')
  993. ->join('产品_基本资料 e', 'c.成品编码 = e.产品编号', 'LEFT')
  994. ->field($field)
  995. ->where($where)
  996. ->select();
  997. if (empty($list)) {
  998. $this->error('没有找到符合条件的数据');
  999. }
  1000. $data = [];
  1001. $currentTime = date('Y-m-d H:i:s');
  1002. // 5. 优化循环处理
  1003. foreach ($list as $item) {
  1004. // 预先处理公共数据
  1005. $commonData = [
  1006. '年月' => $item['ym'],
  1007. '客户编号' => $item['客户编号'],
  1008. '客户名称' => $item['客户名称'],
  1009. '产品类别' => $item['规格'],
  1010. '产品编号' => $item['成品编码'],
  1011. '产品名称' => $item['成品名称'],
  1012. 'Gd_gdbh' => $item['qczl_gdbh'],
  1013. '印件号' => $item['qczl_yjno'],
  1014. 'Gd_cpdh' => $item['jjcp_cpdh'] ?? '',
  1015. 'Gd_cpmc' => $item['jjcp_cpmc'] ?? '',
  1016. '实际投料' => ($item['实际投料'] ?? 0) * 10000,
  1017. '质检完工时间' => $item['qczl_rq'],
  1018. 'sys_id' => $param['sys_id'],
  1019. 'Sys_rq' => $currentTime
  1020. ];
  1021. // 处理13个废品类别
  1022. for ($i = 1; $i <= 13; $i++) {
  1023. $lbField = "fp_lb{$i}";
  1024. $slField = "fp_sl{$i}";
  1025. if (!empty($item[$lbField]) && $this->isFirstCharEnglish($item[$lbField]) && $item[$slField] != 0) {
  1026. $data[] = array_merge($commonData, [
  1027. '废品类别' => $item[$lbField],
  1028. '废品数量' => $item[$slField] ?? 0
  1029. ]);
  1030. }
  1031. }
  1032. }
  1033. if (empty($data)) {
  1034. $this->error('没有符合条件的数据需要插入');
  1035. }
  1036. // 6. 分批插入避免单次数据量过大
  1037. $chunks = array_chunk($data, 100); // 每批100条
  1038. $successCount = 0;
  1039. foreach ($chunks as $chunk) {
  1040. $result = \db('rec_月度废品汇总')->insertAll($chunk);
  1041. if ($result !== false) {
  1042. $successCount += $result;
  1043. }
  1044. }
  1045. if ($successCount > 0) {
  1046. $this->success("成功插入 {$successCount} 条数据");
  1047. } else {
  1048. $this->error('插入数据失败');
  1049. }
  1050. }
  1051. /**
  1052. * 成品入仓印件名称分类
  1053. * 含“小盒” -> 小盒;含“面彩/围条/内贴/上盖/下盖” -> 其他;其余 -> 条盒
  1054. */
  1055. private function CprcCategory($cpmc)
  1056. {
  1057. $cpmc = trim((string)$cpmc);
  1058. if ($cpmc === '') {
  1059. return '条盒';
  1060. }
  1061. if (strpos($cpmc, '小盒') !== false) {
  1062. return '小盒';
  1063. }
  1064. foreach (['面彩', '围条', '内贴', '上盖', '下盖'] as $kw) {
  1065. if (strpos($cpmc, $kw) !== false) {
  1066. return '其他';
  1067. }
  1068. }
  1069. return '条盒';
  1070. }
  1071. /**
  1072. * 取成品入仓指定账期(年月)的入仓记录
  1073. * @param string $ny 6位年月(YYYYMM) 或 4位年份(YYYY)
  1074. */
  1075. private function CprcMonthRows($ny)
  1076. {
  1077. $ny = (string)$ny;
  1078. if (strlen($ny) === 4) {
  1079. $year = (int)$ny;
  1080. $start = $year . '-01-01 00:00:00';
  1081. $end = ($year + 1) . '-01-01 00:00:00';
  1082. } else {
  1083. $year = (int)substr($ny, 0, 4);
  1084. $month = (int)substr($ny, 4, 2);
  1085. $start = date('Y-m-01 00:00:00', mktime(0, 0, 0, $month, 1, $year));
  1086. $end = date('Y-m-01 00:00:00', mktime(0, 0, 0, $month + 1, 1, $year));
  1087. }
  1088. return \db('成品入仓')
  1089. ->field('jjcp_gdbh, jjcp_yjno, jjcp_cpdh, jjcp_cpmc, jjcp_sl, jjcp_dw, jjcp_sj')
  1090. ->where('jjcp_sj', '>=', $start)
  1091. ->where('jjcp_sj', '<', $end)
  1092. ->order('jjcp_sj desc')
  1093. ->select();
  1094. }
  1095. /**
  1096. * 成品入仓统计左侧菜单(年 -> 年月,值为入仓数量合计/10000)
  1097. */
  1098. public function CprctjLeft()
  1099. {
  1100. if ($this->request->isGet() === false) {
  1101. $this->error('请求错误');
  1102. }
  1103. $rows = \db('成品入仓')
  1104. ->field('jjcp_sj, jjcp_cpmc, jjcp_sl')
  1105. ->whereNotNull('jjcp_sj')
  1106. ->select();
  1107. // 先按月聚合
  1108. $months = [];
  1109. foreach ($rows as $row) {
  1110. $sj = trim((string)$row['jjcp_sj']);
  1111. if ($sj === '') {
  1112. continue;
  1113. }
  1114. $ny = substr(str_replace('-', '', substr($sj, 0, 10)), 0, 6);
  1115. if (!preg_match('/^\d{6}$/', $ny)) {
  1116. continue;
  1117. }
  1118. $cat = $this->CprcCategory($row['jjcp_cpmc']);
  1119. if ($cat === '其他') {
  1120. continue;
  1121. }
  1122. if (!isset($months[$ny])) {
  1123. $months[$ny] = ['小盒' => 0, '条盒' => 0];
  1124. }
  1125. $months[$ny][$cat] += (float)$row['jjcp_sl'];
  1126. }
  1127. krsort($months);
  1128. // 再按年聚合
  1129. $years = [];
  1130. foreach ($months as $ny => $item) {
  1131. $year = substr((string)$ny, 0, 4);
  1132. if (!isset($years[$year])) {
  1133. $years[$year] = ['小盒' => 0, '条盒' => 0, '月份' => []];
  1134. }
  1135. $years[$year]['小盒'] += $item['小盒'];
  1136. $years[$year]['条盒'] += $item['条盒'];
  1137. $years[$year]['月份'][] = [
  1138. '年月' => (string)$ny,
  1139. '小盒' => round($item['小盒'] / 10000, 3),
  1140. '条盒' => round($item['条盒'] / 10000, 3),
  1141. ];
  1142. }
  1143. krsort($years);
  1144. $data = [];
  1145. foreach ($years as $year => $item) {
  1146. $data[] = [
  1147. '年份' => (string)$year,
  1148. '小盒' => round($item['小盒'] / 10000, 2),
  1149. '条盒' => round($item['条盒'] / 10000, 2),
  1150. '月份' => $item['月份'],
  1151. ];
  1152. }
  1153. $this->success('成功', $data);
  1154. }
  1155. /**
  1156. * 成品入仓统计上方表格(按日期汇总)
  1157. */
  1158. public function CprctjList_hz()
  1159. {
  1160. if ($this->request->isGet() === false) {
  1161. $this->error('请求错误');
  1162. }
  1163. $param = $this->request->param();
  1164. $ny = trim((string)(isset($param['ym']) ? $param['ym'] : ''));
  1165. if (!preg_match('/^\d{4}(\d{2})?$/', $ny)) {
  1166. $this->error('参数错误');
  1167. }
  1168. $rows = $this->CprcMonthRows($ny);
  1169. $days = [];
  1170. foreach ($rows as $row) {
  1171. $day = substr(trim((string)$row['jjcp_sj']), 0, 10);
  1172. if (!isset($days[$day])) {
  1173. $days[$day] = [
  1174. '日期' => $day,
  1175. '小盒入仓数' => 0,
  1176. '条盒入仓数' => 0,
  1177. '其他类' => 0,
  1178. '入仓数量' => 0,
  1179. ];
  1180. }
  1181. $cat = $this->CprcCategory($row['jjcp_cpmc']);
  1182. $sl = (float)$row['jjcp_sl'];
  1183. if ($cat === '小盒') {
  1184. $days[$day]['小盒入仓数'] += $sl;
  1185. } elseif ($cat === '其他') {
  1186. $days[$day]['其他类'] += $sl;
  1187. } else {
  1188. $days[$day]['条盒入仓数'] += $sl;
  1189. }
  1190. $days[$day]['入仓数量'] += $sl;
  1191. }
  1192. krsort($days);
  1193. $this->success('成功', array_values($days));
  1194. }
  1195. /**
  1196. * 成品入仓统计下方表格(工单 + 印件明细)
  1197. * 客户信息成品入仓表中没有,取自 工单_基本资料
  1198. */
  1199. public function CprctjList_mx()
  1200. {
  1201. if ($this->request->isGet() === false) {
  1202. $this->error('请求错误');
  1203. }
  1204. $param = $this->request->param();
  1205. $ny = trim((string)(isset($param['ym']) ? $param['ym'] : ''));
  1206. if (!preg_match('/^\d{4}(\d{2})?$/', $ny)) {
  1207. $this->error('参数错误');
  1208. }
  1209. $date = trim((string)(isset($param['date']) ? $param['date'] : ''));
  1210. $rows = $this->CprcMonthRows($ny);
  1211. $list = [];
  1212. $gdbhList = [];
  1213. foreach ($rows as $row) {
  1214. $day = substr(trim((string)$row['jjcp_sj']), 0, 10);
  1215. if ($date !== '' && $day !== $date) {
  1216. continue;
  1217. }
  1218. $gdbh = trim((string)$row['jjcp_gdbh']);
  1219. $key = $gdbh . '|' . trim((string)$row['jjcp_cpdh']) . '|' . trim((string)$row['jjcp_cpmc']) . '|' . $day;
  1220. if (!isset($list[$key])) {
  1221. $list[$key] = [
  1222. '工单编号' => $gdbh,
  1223. '印件代号' => trim((string)$row['jjcp_cpdh']),
  1224. '印件名称' => trim((string)$row['jjcp_cpmc']),
  1225. '日期' => $day,
  1226. '小盒数' => 0,
  1227. '条盒数' => 0,
  1228. '其他类' => 0,
  1229. '入仓数量' => 0,
  1230. '单位' => trim((string)$row['jjcp_dw']),
  1231. '客户编号' => '',
  1232. '客户名称' => ''
  1233. ];
  1234. if ($gdbh !== '') {
  1235. $gdbhList[$gdbh] = 1;
  1236. }
  1237. }
  1238. $cat = $this->CprcCategory($row['jjcp_cpmc']);
  1239. $sl = (float)$row['jjcp_sl'];
  1240. if ($cat === '小盒') {
  1241. $list[$key]['小盒数'] += $sl;
  1242. } elseif ($cat === '其他') {
  1243. $list[$key]['其他类'] += $sl;
  1244. } else {
  1245. $list[$key]['条盒数'] += $sl;
  1246. }
  1247. $list[$key]['入仓数量'] += $sl;
  1248. }
  1249. // 客户信息:按工单编号取最新一条工单_基本资料
  1250. if (!empty($gdbhList)) {
  1251. $orders = \db('工单_基本资料')
  1252. ->field('Gd_gdbh, Gd_客户代号, Gd_客户名称')
  1253. ->whereIn('Gd_gdbh', array_keys($gdbhList))
  1254. ->order('Sys_rq desc')
  1255. ->select();
  1256. $customerMap = [];
  1257. foreach ($orders as $order) {
  1258. $gdbh = trim((string)$order['Gd_gdbh']);
  1259. if (!isset($customerMap[$gdbh])) {
  1260. $customerMap[$gdbh] = [
  1261. '编号' => trim((string)$order['Gd_客户代号']),
  1262. '名称' => trim((string)$order['Gd_客户名称'])
  1263. ];
  1264. }
  1265. }
  1266. foreach ($list as $key => $item) {
  1267. if (isset($customerMap[$item['工单编号']])) {
  1268. $list[$key]['客户编号'] = $customerMap[$item['工单编号']]['编号'];
  1269. $list[$key]['客户名称'] = $customerMap[$item['工单编号']]['名称'];
  1270. }
  1271. }
  1272. }
  1273. $data = array_values($list);
  1274. usort($data, function ($a, $b) {
  1275. if ($a['日期'] !== $b['日期']) {
  1276. return strcmp($b['日期'], $a['日期']);
  1277. }
  1278. return strcmp($a['工单编号'], $b['工单编号']);
  1279. });
  1280. $this->success('成功', $data);
  1281. }
  1282. /**
  1283. * 成品编码对应的客户信息(产品_基本资料)
  1284. */
  1285. private function CprcProductCustomer($codes)
  1286. {
  1287. $map = [];
  1288. $codes = array_values(array_unique(array_filter($codes, function ($code) {
  1289. return trim((string)$code) !== '';
  1290. })));
  1291. if (empty($codes)) {
  1292. return $map;
  1293. }
  1294. $rows = \db('产品_基本资料')
  1295. ->field('产品编号, 客户编号, 客户名称')
  1296. ->whereIn('产品编号', $codes)
  1297. ->select();
  1298. foreach ($rows as $row) {
  1299. $code = trim((string)$row['产品编号']);
  1300. if ($code === '' || isset($map[$code])) {
  1301. continue;
  1302. }
  1303. $map[$code] = [
  1304. '客户编号' => trim((string)$row['客户编号']),
  1305. '客户名称' => trim((string)$row['客户名称']),
  1306. ];
  1307. }
  1308. return $map;
  1309. }
  1310. /**
  1311. * 年度成品入仓统计左侧菜单(年 -> 客户)
  1312. */
  1313. public function YearcprctjLeft()
  1314. {
  1315. if ($this->request->isGet() === false) {
  1316. $this->error('请求错误');
  1317. }
  1318. $rows = \db('成品入仓')
  1319. ->field([
  1320. "DATE_FORMAT(jjcp_sj, '%Y') AS 年份",
  1321. '成品编码',
  1322. ])
  1323. ->where('jjcp_sj', '>=', '2000-01-01')
  1324. ->group('年份, 成品编码')
  1325. ->select();
  1326. $customerMap = $this->CprcProductCustomer(array_column($rows, '成品编码'));
  1327. $years = [];
  1328. foreach ($rows as $row) {
  1329. $year = trim((string)$row['年份']);
  1330. $code = trim((string)$row['成品编码']);
  1331. if ($year === '' || $year === '0' || !isset($customerMap[$code])) {
  1332. continue;
  1333. }
  1334. $customer = $customerMap[$code];
  1335. if ($customer['客户名称'] === '') {
  1336. continue;
  1337. }
  1338. if (!isset($years[$year])) {
  1339. $years[$year] = ['年份' => $year, '客户' => []];
  1340. }
  1341. $customerKey = $customer['客户编号'] !== '' ? $customer['客户编号'] : $customer['客户名称'];
  1342. $years[$year]['客户'][$customerKey] = [
  1343. '客户编号' => $customer['客户编号'],
  1344. '客户名称' => $customer['客户名称'],
  1345. ];
  1346. }
  1347. krsort($years);
  1348. $data = [];
  1349. foreach ($years as $year) {
  1350. ksort($year['客户']);
  1351. $year['客户'] = array_values($year['客户']);
  1352. $data[] = $year;
  1353. }
  1354. $this->success('成功', $data);
  1355. }
  1356. /**
  1357. * 年度成品入仓统计右侧表格
  1358. * 产品取自成品入仓(成品编码/成品名称),大箱数取自 db_包装产量预报 的 sczl_cl1-6,按 sczl_rq 月份汇总
  1359. */
  1360. public function YearcprctjList()
  1361. {
  1362. if ($this->request->isGet() === false) {
  1363. $this->error('请求错误');
  1364. }
  1365. $param = $this->request->param();
  1366. $year = trim((string)(isset($param['year']) ? $param['year'] : ''));
  1367. if (!preg_match('/^\d{4}$/', $year)) {
  1368. $this->error('参数错误');
  1369. }
  1370. $customer = trim((string)(isset($param['customer']) ? $param['customer'] : ''));
  1371. $search = trim((string)(isset($param['search']) ? $param['search'] : ''));
  1372. $start = $year . '-01-01 00:00:00';
  1373. $end = ((int)$year + 1) . '-01-01 00:00:00';
  1374. // 1、成品入仓:本年度有入仓记录的产品
  1375. $warehouseRows = \db('成品入仓')
  1376. ->field('jjcp_gdbh, 成品编码, 成品名称')
  1377. ->where('jjcp_sj', '>=', $start)
  1378. ->where('jjcp_sj', '<', $end)
  1379. ->where('jjcp_gdbh', '<>', '')
  1380. ->select();
  1381. $products = []; // 产品编号 => 行数据
  1382. $orderProduct = []; // 工单编号(大写) => 产品编号
  1383. foreach ($warehouseRows as $row) {
  1384. $code = trim((string)$row['成品编码']);
  1385. if ($code === '') {
  1386. continue;
  1387. }
  1388. if (!isset($products[$code])) {
  1389. $name = trim((string)$row['成品名称']);
  1390. $products[$code] = [
  1391. '产品编号' => $code,
  1392. '产品名称' => $name,
  1393. '产品类别' => strpos($name, '小盒') !== false ? '小盒' : '条盒',
  1394. '客户编号' => '',
  1395. '客户名称' => '',
  1396. 'monthly' => array_fill(1, 12, 0),
  1397. ];
  1398. }
  1399. $order = strtoupper(trim((string)$row['jjcp_gdbh']));
  1400. if ($order !== '' && !isset($orderProduct[$order])) {
  1401. $orderProduct[$order] = $code;
  1402. }
  1403. }
  1404. if (empty($products)) {
  1405. $this->success('成功', []);
  1406. }
  1407. // 2、包装产量预报:按 sczl_rq 的月份汇总对应工单的 sczl_cl1-6
  1408. $packRows = \db('db_包装产量预报')
  1409. ->field('sczl_rq, sczl_gdbh1, sczl_gdbh2, sczl_gdbh3, sczl_gdbh4, sczl_gdbh5, sczl_gdbh6, sczl_cl1, sczl_cl2, sczl_cl3, sczl_cl4, sczl_cl5, sczl_cl6')
  1410. ->where('sczl_rq', '>=', $start)
  1411. ->where('sczl_rq', '<', $end)
  1412. ->select();
  1413. foreach ($packRows as $row) {
  1414. $rq = str_replace('/', '-', trim((string)$row['sczl_rq']));
  1415. $month = (int)substr($rq, 5, 2);
  1416. if ($month < 1 || $month > 12) {
  1417. continue;
  1418. }
  1419. for ($i = 1; $i <= 6; $i++) {
  1420. $order = strtoupper(trim((string)$row['sczl_gdbh' . $i]));
  1421. if ($order === '' || !isset($orderProduct[$order])) {
  1422. continue;
  1423. }
  1424. $products[$orderProduct[$order]]['monthly'][$month] += (float)$row['sczl_cl' . $i];
  1425. }
  1426. }
  1427. // 3、客户信息:产品_基本资料(按成品编码)
  1428. $customerMap = $this->CprcProductCustomer(array_keys($products));
  1429. foreach ($products as $code => $product) {
  1430. if (isset($customerMap[$code])) {
  1431. $products[$code]['客户编号'] = $customerMap[$code]['客户编号'];
  1432. $products[$code]['客户名称'] = $customerMap[$code]['客户名称'];
  1433. }
  1434. }
  1435. // 4、组装数据:无数据的月份留空
  1436. $data = [];
  1437. foreach ($products as $product) {
  1438. if ($customer !== '' && $product['客户编号'] !== $customer) {
  1439. continue;
  1440. }
  1441. if ($search !== ''
  1442. && strpos($product['产品编号'], $search) === false
  1443. && strpos($product['产品名称'], $search) === false) {
  1444. continue;
  1445. }
  1446. $total = 0;
  1447. $months = [];
  1448. for ($m = 1; $m <= 12; $m++) {
  1449. $value = $product['monthly'][$m];
  1450. $total += $value;
  1451. $months[str_pad($m, 2, '0', STR_PAD_LEFT) . '月'] = $value > 0 ? round($value, 2) : '';
  1452. }
  1453. $data[] = array_merge([
  1454. '产品编号' => $product['产品编号'],
  1455. '产品名称' => $product['产品名称'],
  1456. '产品类别' => $product['产品类别'],
  1457. '每月合计' => round($total, 2),
  1458. ], $months, [
  1459. '客户编号' => $product['客户编号'],
  1460. '客户名称' => $product['客户名称'],
  1461. ]);
  1462. }
  1463. usort($data, function ($a, $b) {
  1464. return strcmp($a['产品编号'], $b['产品编号']);
  1465. });
  1466. // 5、底部合计行:小盒合计、条盒合计
  1467. $totalRows = [];
  1468. foreach (['小盒', '条盒'] as $category) {
  1469. $exists = false;
  1470. $total = 0;
  1471. $sums = array_fill(1, 12, 0);
  1472. foreach ($data as $row) {
  1473. if ($row['产品类别'] !== $category) {
  1474. continue;
  1475. }
  1476. $exists = true;
  1477. $total += (float)$row['每月合计'];
  1478. for ($m = 1; $m <= 12; $m++) {
  1479. $monthKey = str_pad($m, 2, '0', STR_PAD_LEFT) . '月';
  1480. $sums[$m] += $row[$monthKey] === '' ? 0 : (float)$row[$monthKey];
  1481. }
  1482. }
  1483. if (!$exists) {
  1484. continue;
  1485. }
  1486. $totalRow = [
  1487. '产品编号' => '',
  1488. '产品名称' => $category . '合计(大箱)',
  1489. '产品类别' => '',
  1490. '每月合计' => round($total, 2),
  1491. '合计类型' => $category,
  1492. ];
  1493. for ($m = 1; $m <= 12; $m++) {
  1494. $monthKey = str_pad($m, 2, '0', STR_PAD_LEFT) . '月';
  1495. $totalRow[$monthKey] = $sums[$m] > 0 ? round($sums[$m], 2) : '';
  1496. }
  1497. $totalRow['客户编号'] = '';
  1498. $totalRow['客户名称'] = '';
  1499. $totalRows[] = $totalRow;
  1500. }
  1501. $data = array_merge($data, $totalRows);
  1502. $this->success('成功', $data);
  1503. }
  1504. /**
  1505. * 客诉质量缺陷统计A 左侧菜单(年 -> 缺陷关键字)
  1506. */
  1507. public function KhtjLeftA()
  1508. {
  1509. if ($this->request->isGet() === false) {
  1510. $this->error('请求错误');
  1511. }
  1512. $rows = \db('db_客诉记录')
  1513. ->field("DATE_FORMAT(客诉日期, '%Y') AS 年份, rtrim(缺陷关键字) AS 缺陷关键字, count(1) AS num")
  1514. ->group("DATE_FORMAT(客诉日期, '%Y'), rtrim(缺陷关键字)")
  1515. ->select();
  1516. $years = [];
  1517. foreach ($rows as $row) {
  1518. $year = trim((string)$row['年份']);
  1519. if ($year === '' || $year === '0') {
  1520. continue;
  1521. }
  1522. if (!isset($years[$year])) {
  1523. $years[$year] = ['总数' => 0, '关键字' => []];
  1524. }
  1525. $num = (int)$row['num'];
  1526. $years[$year]['总数'] += $num;
  1527. $keyword = trim((string)$row['缺陷关键字']);
  1528. if ($keyword !== '') {
  1529. $years[$year]['关键字'][$keyword] = $num;
  1530. }
  1531. }
  1532. krsort($years);
  1533. $data = [];
  1534. foreach ($years as $year => $info) {
  1535. arsort($info['关键字']);
  1536. $children = [];
  1537. foreach ($info['关键字'] as $keyword => $num) {
  1538. $children[] = ['关键字' => $keyword, '次数' => $num];
  1539. }
  1540. $data[] = [
  1541. '年份' => $year,
  1542. '次数' => $info['总数'],
  1543. 'children' => $children,
  1544. ];
  1545. }
  1546. $this->success('成功', $data);
  1547. }
  1548. /**
  1549. * 客诉质量缺陷统计A 明细(年 + 缺陷关键字筛选)
  1550. */
  1551. public function KhtjListA()
  1552. {
  1553. if ($this->request->isGet() === false) {
  1554. $this->error('请求错误');
  1555. }
  1556. $param = $this->request->param();
  1557. $year = trim((string)(isset($param['year']) ? $param['year'] : ''));
  1558. if (!preg_match('/^\d{4}$/', $year)) {
  1559. $this->error('参数错误');
  1560. }
  1561. $keyword = trim((string)(isset($param['keyword']) ? $param['keyword'] : ''));
  1562. $search = trim((string)(isset($param['search']) ? $param['search'] : ''));
  1563. $data = $this->KhtjDetailRows(
  1564. $year . '-01-01 00:00:00',
  1565. ((int)$year + 1) . '-01-01 00:00:00',
  1566. '',
  1567. $keyword,
  1568. $search
  1569. );
  1570. $this->success('成功', $data);
  1571. }
  1572. /**
  1573. * 客诉质量缺陷统计B 左侧菜单(年 -> 客户)
  1574. */
  1575. public function KhtjLeftB()
  1576. {
  1577. if ($this->request->isGet() === false) {
  1578. $this->error('请求错误');
  1579. }
  1580. $rows = \db('db_客诉记录')
  1581. ->field("DATE_FORMAT(客诉日期, '%Y') AS 年份, rtrim(客户编号) AS 客户编号, rtrim(客户名称) AS 客户名称")
  1582. ->group("DATE_FORMAT(客诉日期, '%Y'), rtrim(客户编号), rtrim(客户名称)")
  1583. ->select();
  1584. $years = [];
  1585. foreach ($rows as $row) {
  1586. $year = trim((string)$row['年份']);
  1587. $code = trim((string)$row['客户编号']);
  1588. $name = trim((string)$row['客户名称']);
  1589. if ($year === '' || $year === '0' || $code === '') {
  1590. continue;
  1591. }
  1592. if (!isset($years[$year])) {
  1593. $years[$year] = [];
  1594. }
  1595. if (!isset($years[$year][$code]) && $name !== '') {
  1596. $years[$year][$code] = $name;
  1597. }
  1598. }
  1599. krsort($years);
  1600. $data = [];
  1601. foreach ($years as $year => $customers) {
  1602. ksort($customers);
  1603. $children = [];
  1604. foreach ($customers as $code => $name) {
  1605. $children[] = ['客户编号' => $code, '客户名称' => $name];
  1606. }
  1607. $data[] = ['年份' => $year, '客户' => $children];
  1608. }
  1609. $this->success('成功', $data);
  1610. }
  1611. /**
  1612. * 客诉质量缺陷统计B 月度汇总 + 明细
  1613. */
  1614. public function KhtjListB()
  1615. {
  1616. if ($this->request->isGet() === false) {
  1617. $this->error('请求错误');
  1618. }
  1619. $param = $this->request->param();
  1620. $year = trim((string)(isset($param['year']) ? $param['year'] : ''));
  1621. if (!preg_match('/^\d{4}$/', $year)) {
  1622. $this->error('参数错误');
  1623. }
  1624. $customer = trim((string)(isset($param['customer']) ? $param['customer'] : ''));
  1625. $search = trim((string)(isset($param['search']) ? $param['search'] : ''));
  1626. $start = $year . '-01-01 00:00:00';
  1627. $end = ((int)$year + 1) . '-01-01 00:00:00';
  1628. // 1、月度汇总:按客户统计全年及每月客诉次数(按客诉日期所在月份)
  1629. $summary = $this->KhtjSummaryRows($start, $end, $customer, $search);
  1630. // 2、客诉明细
  1631. $list = $this->KhtjDetailRows($start, $end, $customer, '', $search);
  1632. $this->success('成功', ['summary' => $summary, 'list' => $list]);
  1633. }
  1634. /**
  1635. * 客诉月度汇总(按客户统计全年及每月客诉次数)
  1636. */
  1637. private function KhtjSummaryRows($start, $end, $customer = '', $search = '')
  1638. {
  1639. $rows = \db('db_客诉记录')
  1640. ->field("rtrim(客户编号) AS 客户编号, rtrim(客户名称) AS 客户名称, DATE_FORMAT(客诉日期, '%m') AS 月")
  1641. ->where('客诉日期', '>=', $start)
  1642. ->where('客诉日期', '<', $end)
  1643. ->select();
  1644. $customers = [];
  1645. foreach ($rows as $row) {
  1646. $code = trim((string)$row['客户编号']);
  1647. if ($code === '') {
  1648. continue;
  1649. }
  1650. $month = (int)$row['月'];
  1651. if ($month < 1 || $month > 12) {
  1652. continue;
  1653. }
  1654. if (!isset($customers[$code])) {
  1655. $customers[$code] = [
  1656. '客户名称' => trim((string)$row['客户名称']),
  1657. '总数' => 0,
  1658. 'monthly' => array_fill(1, 12, 0),
  1659. ];
  1660. }
  1661. $customers[$code]['总数']++;
  1662. $customers[$code]['monthly'][$month]++;
  1663. }
  1664. $year = substr($start, 0, 4);
  1665. $summary = [];
  1666. foreach ($customers as $code => $info) {
  1667. if ($customer !== '' && $code !== $customer) {
  1668. continue;
  1669. }
  1670. if ($search !== '' && mb_stripos($code . ' ' . $info['客户名称'], $search) === false) {
  1671. continue;
  1672. }
  1673. $summaryRow = [
  1674. '年月' => $year,
  1675. '客户编号' => $code,
  1676. '客户名称' => $info['客户名称'],
  1677. '年度投诉次数' => $info['总数'],
  1678. ];
  1679. for ($m = 1; $m <= 12; $m++) {
  1680. $summaryRow['月份' . str_pad($m, 2, '0', STR_PAD_LEFT)] = $info['monthly'][$m] > 0 ? $info['monthly'][$m] : '';
  1681. }
  1682. $summary[] = $summaryRow;
  1683. }
  1684. usort($summary, function ($a, $b) {
  1685. return strcmp($a['客户编号'], $b['客户编号']);
  1686. });
  1687. return $summary;
  1688. }
  1689. /**
  1690. * 客诉明细查询(统计A/B共用)
  1691. */
  1692. private function KhtjDetailRows($start, $end, $customer = '', $keyword = '', $search = '')
  1693. {
  1694. $field = 'rtrim(客诉单号) AS 客诉单号, 客诉日期, rtrim(客诉方式) AS 客诉方式, rtrim(订单编号) AS 订单编号, '
  1695. . 'rtrim(产品编号) AS 产品编号, rtrim(产品名称) AS 产品名称, rtrim(客户编号) AS 客户编号, rtrim(客户名称) AS 客户名称, '
  1696. . 'rtrim(客诉描述) AS 客诉描述, rtrim(缺陷关键字) AS 缺陷关键字, rtrim(客诉性质) AS 客诉性质, 扣分, '
  1697. . 'rtrim(主要责任部门) AS 主要责任部门, rtrim(次要责任部门) AS 次要责任部门, rtrim(Sys_id) AS 创建用户, '
  1698. . 'Sys_rq AS 创建时间, 关闭时间 AS 结案时间, UniqID';
  1699. $query = \db('db_客诉记录')
  1700. ->field($field)
  1701. ->where('客诉日期', '>=', $start)
  1702. ->where('客诉日期', '<', $end);
  1703. if ($customer !== '') {
  1704. $query->where('客户编号', $customer);
  1705. }
  1706. if ($keyword !== '') {
  1707. $query->where('缺陷关键字', $keyword);
  1708. }
  1709. if ($search !== '') {
  1710. $query->where('客诉单号|订单编号|产品编号|产品名称|客户编号|客户名称|客诉描述|缺陷关键字', 'like', '%' . $search . '%');
  1711. }
  1712. return $query->order('客诉日期 desc')->select();
  1713. }
  1714. /**
  1715. * 年度打样效率统计 左侧菜单(年 -> 年月)
  1716. */
  1717. public function DyxlLeft()
  1718. {
  1719. if ($this->request->isGet() === false) {
  1720. $this->error('请求错误');
  1721. }
  1722. $list = \db('工单_基本资料')
  1723. ->field([
  1724. "DATE_FORMAT(工单完工日期, '%Y') AS 年份",
  1725. "DATE_FORMAT(工单完工日期, '%Y%m') AS 年月",
  1726. ])
  1727. ->where('gd_statu', '1-已完工')
  1728. ->whereRaw($this->DyxlOrderWhere())
  1729. ->whereRaw('工单完工日期 IS NOT NULL')
  1730. ->group("DATE_FORMAT(工单完工日期, '%Y'), DATE_FORMAT(工单完工日期, '%Y%m')")
  1731. ->orderRaw("DATE_FORMAT(工单完工日期, '%Y%m') DESC")
  1732. ->select();
  1733. $years = [];
  1734. foreach ($list as $row) {
  1735. $year = trim((string)$row['年份']);
  1736. $ym = trim((string)$row['年月']);
  1737. if ($year === '' || $ym === '') {
  1738. continue;
  1739. }
  1740. if (!isset($years[$year])) {
  1741. $years[$year] = [];
  1742. }
  1743. if (!in_array($ym, $years[$year], true)) {
  1744. $years[$year][] = $ym;
  1745. }
  1746. }
  1747. $data = [];
  1748. foreach ($years as $year => $months) {
  1749. rsort($months);
  1750. $data[] = ['年份' => (string)$year, '月份' => $months];
  1751. }
  1752. usort($data, function ($a, $b) {
  1753. return strcmp($b['年份'], $a['年份']);
  1754. });
  1755. $this->success('成功', $data);
  1756. }
  1757. /**
  1758. * 年度打样效率统计 汇总 + 明细
  1759. */
  1760. public function DyxlList()
  1761. {
  1762. if ($this->request->isGet() === false) {
  1763. $this->error('请求错误');
  1764. }
  1765. $param = $this->request->param();
  1766. $date = trim((string)(isset($param['date']) ? $param['date'] : ''));
  1767. if (!preg_match('/^(\d{4})(\d{2})?$/', $date, $match)) {
  1768. $this->error('参数错误');
  1769. }
  1770. $year = (int)$match[1];
  1771. if (isset($match[2]) && $match[2] !== '') {
  1772. $month = (int)$match[2];
  1773. if ($month < 1 || $month > 12) {
  1774. $this->error('参数错误');
  1775. }
  1776. $start = sprintf('%04d-%02d-01', $year, $month);
  1777. if ($month === 12) {
  1778. $end = sprintf('%04d-01-01', $year + 1);
  1779. } else {
  1780. $end = sprintf('%04d-%02d-01', $year, $month + 1);
  1781. }
  1782. } else {
  1783. $start = sprintf('%04d-01-01', $year);
  1784. $end = sprintf('%04d-01-01', $year + 1);
  1785. }
  1786. // 1、打样工单(按工单编号去重)
  1787. $orders = \db('工单_基本资料')
  1788. ->field([
  1789. "RTRIM(Gd_gdbh) AS 工单编号",
  1790. "DATE_FORMAT(工单完工日期, '%Y%m') AS 年月",
  1791. "RTRIM(Gd_客户代号) AS 客户编号",
  1792. "RTRIM(Gd_客户名称) AS 客户名称",
  1793. "RTRIM(成品名称) AS 成品名称",
  1794. ])
  1795. ->where('gd_statu', '1-已完工')
  1796. ->where('工单完工日期', '>=', $start)
  1797. ->where('工单完工日期', '<', $end)
  1798. ->whereRaw($this->DyxlOrderWhere())
  1799. ->order('工单编号')
  1800. ->select();
  1801. $orderMap = [];
  1802. foreach ($orders as $row) {
  1803. $gdbh = trim((string)$row['工单编号']);
  1804. if ($gdbh === '') {
  1805. continue;
  1806. }
  1807. if (!isset($orderMap[$gdbh])) {
  1808. $orderMap[$gdbh] = [
  1809. '年月' => trim((string)$row['年月']),
  1810. '客户编号' => trim((string)$row['客户编号']),
  1811. '客户名称' => trim((string)$row['客户名称']),
  1812. '工单编号' => $gdbh,
  1813. '成品名称' => trim((string)$row['成品名称']),
  1814. ];
  1815. } else {
  1816. if ($orderMap[$gdbh]['客户编号'] === '') {
  1817. $orderMap[$gdbh]['客户编号'] = trim((string)$row['客户编号']);
  1818. }
  1819. if ($orderMap[$gdbh]['客户名称'] === '') {
  1820. $orderMap[$gdbh]['客户名称'] = trim((string)$row['客户名称']);
  1821. }
  1822. if ($orderMap[$gdbh]['成品名称'] === '') {
  1823. $orderMap[$gdbh]['成品名称'] = trim((string)$row['成品名称']);
  1824. }
  1825. }
  1826. }
  1827. if (empty($orderMap)) {
  1828. $this->success('成功', ['summary' => [], 'detail' => []]);
  1829. }
  1830. $gdbhs = array_keys($orderMap);
  1831. $categories = ['胶印', '凹印', '单凹', '喷码', '丝印', '烫金', '模切'];
  1832. // 2、工艺资料:工单 + 印件 + 工序
  1833. $crafts = \db('工单_工艺资料')
  1834. ->field([
  1835. "RTRIM(Gy0_gdbh) AS 工单编号",
  1836. "FLOOR(Gy0_yjno) AS 印件号",
  1837. "FLOOR(Gy0_gxh) AS 工序号",
  1838. "RTRIM(Gy0_gxmc) AS 工序名称",
  1839. "RTRIM(Gy0_sbbh) AS 设备编号",
  1840. "Gy0_计划接货数 AS 计划接货数",
  1841. "Gy0_ks AS 开数",
  1842. "Gy0_ls AS 联数",
  1843. "Gy0_小时产能 AS 小时产能",
  1844. ])
  1845. ->whereIn('Gy0_gdbh', $gdbhs)
  1846. ->order('工单编号, 印件号, 工序号')
  1847. ->select();
  1848. // 3、实际工时:设备_产量计酬 中同工单+印件+工序的记录,按 sczl_sj1~sczl_sj2 时间区间合并计算
  1849. // 同一工单记录基本连续,不连续时中间换成其他工单的时间自然被排除(只做区间并集,不跨区间累加)
  1850. $actualRows = \db('设备_产量计酬')
  1851. ->field([
  1852. "RTRIM(sczl_gdbh) AS 工单编号",
  1853. "FLOOR(sczl_yjno) AS 印件号",
  1854. "FLOOR(sczl_gxh) AS 工序号",
  1855. "sczl_sj1",
  1856. "sczl_sj2",
  1857. ])
  1858. ->whereIn('sczl_gdbh', $gdbhs)
  1859. ->select();
  1860. // 按 工单+印件+工序 收集时间区间
  1861. $intervalMap = [];
  1862. foreach ($actualRows as $row) {
  1863. $t1 = strtotime(trim((string)$row['sczl_sj1']));
  1864. $t2 = strtotime(trim((string)$row['sczl_sj2']));
  1865. if ($t1 === false || $t2 === false || $t1 <= 0 || $t2 <= 0) {
  1866. continue;
  1867. }
  1868. if ($t2 < $t1) {
  1869. // 跨午夜:结束时间顺延一天
  1870. $t2 += 86400;
  1871. }
  1872. if ($t2 <= $t1) {
  1873. continue;
  1874. }
  1875. $key = $this->DyxlKey($row['工单编号'], $row['印件号'], $row['工序号']);
  1876. if (!isset($intervalMap[$key])) {
  1877. $intervalMap[$key] = [];
  1878. }
  1879. $intervalMap[$key][] = [$t1, $t2];
  1880. }
  1881. // 合并时间区间并计算总时长(小时)
  1882. $actualMap = [];
  1883. foreach ($intervalMap as $key => $intervals) {
  1884. usort($intervals, function ($a, $b) {
  1885. return $a[0] - $b[0];
  1886. });
  1887. $total = 0;
  1888. $curStart = $intervals[0][0];
  1889. $curEnd = $intervals[0][1];
  1890. $count = count($intervals);
  1891. for ($i = 1; $i < $count; $i++) {
  1892. if ($intervals[$i][0] <= $curEnd) {
  1893. // 区间重叠或相连,合并
  1894. if ($intervals[$i][1] > $curEnd) {
  1895. $curEnd = $intervals[$i][1];
  1896. }
  1897. } else {
  1898. // 不连续:结算当前区间,中间其他工单时间不计入
  1899. $total += $curEnd - $curStart;
  1900. $curStart = $intervals[$i][0];
  1901. $curEnd = $intervals[$i][1];
  1902. }
  1903. }
  1904. $total += $curEnd - $curStart;
  1905. $actualMap[$key] = $total / 3600;
  1906. }
  1907. $sumPlan = [];
  1908. $sumActual = [];
  1909. $detail = [];
  1910. foreach ($crafts as $craft) {
  1911. $gdbh = trim((string)$craft['工单编号']);
  1912. if (!isset($orderMap[$gdbh])) {
  1913. continue;
  1914. }
  1915. $category = $this->DyxlProcessCategory($craft['设备编号'], $craft['工序名称']);
  1916. if ($category === '') {
  1917. continue;
  1918. }
  1919. $yjno = (int)$craft['印件号'];
  1920. $gxh = (int)$craft['工序号'];
  1921. $plan = $this->DyxlPlanHours($craft);
  1922. $key = $this->DyxlKey($gdbh, $yjno, $gxh);
  1923. $actual = isset($actualMap[$key]) ? $actualMap[$key] : null;
  1924. if ($plan !== null) {
  1925. if (!isset($sumPlan[$gdbh][$category])) {
  1926. $sumPlan[$gdbh][$category] = 0;
  1927. }
  1928. $sumPlan[$gdbh][$category] += $plan;
  1929. }
  1930. if ($actual !== null) {
  1931. if (!isset($sumActual[$gdbh][$category])) {
  1932. $sumActual[$gdbh][$category] = 0;
  1933. }
  1934. $sumActual[$gdbh][$category] += $actual;
  1935. }
  1936. $detailRow = $orderMap[$gdbh];
  1937. $detailRow['印件及工序'] = str_pad($gxh, 2, '0', STR_PAD_LEFT) . '-' . trim((string)$craft['工序名称']);
  1938. foreach ($categories as $cat) {
  1939. $detailRow[$cat . '计划工时'] = '';
  1940. $detailRow[$cat . '实际工时'] = '';
  1941. }
  1942. if ($plan !== null) {
  1943. $detailRow[$category . '计划工时'] = $this->DyxlNumber($plan);
  1944. }
  1945. if ($actual !== null) {
  1946. $detailRow[$category . '实际工时'] = $this->DyxlNumber($actual);
  1947. }
  1948. $detail[] = $detailRow;
  1949. }
  1950. // 4、按工单汇总
  1951. $summary = [];
  1952. $totalPlan = array_fill_keys($categories, 0);
  1953. $totalActual = array_fill_keys($categories, 0);
  1954. $hasPlan = [];
  1955. $hasActual = [];
  1956. foreach ($orderMap as $gdbh => $info) {
  1957. $row = $info;
  1958. foreach ($categories as $cat) {
  1959. $plan = isset($sumPlan[$gdbh][$cat]) ? $sumPlan[$gdbh][$cat] : null;
  1960. $actual = isset($sumActual[$gdbh][$cat]) ? $sumActual[$gdbh][$cat] : null;
  1961. $row[$cat . '计划工时'] = $plan === null ? '' : $this->DyxlNumber($plan);
  1962. $row[$cat . '实际工时'] = $actual === null ? '' : $this->DyxlNumber($actual);
  1963. if ($plan !== null) {
  1964. $totalPlan[$cat] += $plan;
  1965. $hasPlan[$cat] = true;
  1966. }
  1967. if ($actual !== null) {
  1968. $totalActual[$cat] += $actual;
  1969. $hasActual[$cat] = true;
  1970. }
  1971. }
  1972. $summary[] = $row;
  1973. }
  1974. $totalRow = ['年月' => '合计:', '客户编号' => '', '客户名称' => '', '工单编号' => '', '成品名称' => ''];
  1975. foreach ($categories as $cat) {
  1976. $totalRow[$cat . '计划工时'] = !empty($hasPlan[$cat]) ? $this->DyxlNumber($totalPlan[$cat]) : '';
  1977. $totalRow[$cat . '实际工时'] = !empty($hasActual[$cat]) ? $this->DyxlNumber($totalActual[$cat]) : '';
  1978. }
  1979. $totalRow['isTotal'] = true;
  1980. if (!empty($summary)) {
  1981. $summary[] = $totalRow;
  1982. }
  1983. $this->success('成功', ['summary' => $summary, 'detail' => $detail]);
  1984. }
  1985. /**
  1986. * 打样工单条件:工单编号第3位(带Y前缀则第4位)为8
  1987. */
  1988. private function DyxlOrderWhere()
  1989. {
  1990. return "SUBSTRING(RTRIM(Gd_gdbh), IF(LEFT(RTRIM(Gd_gdbh), 1) = 'Y', 4, 3), 1) = '8'";
  1991. }
  1992. /**
  1993. * 按设备编号前缀判定工序类别
  1994. */
  1995. private function DyxlProcessCategory($sbbh, $gxmc)
  1996. {
  1997. $map = ['YJY' => '胶印', 'YWY' => '凹印', 'YDW' => '单凹', 'YPM' => '喷码', 'YSY' => '丝印', 'YTJ' => '烫金', 'YMQ' => '模切'];
  1998. $prefix = strtoupper(substr(trim((string)$sbbh), 0, 3));
  1999. if (isset($map[$prefix])) {
  2000. return $map[$prefix];
  2001. }
  2002. $name = trim((string)$gxmc);
  2003. foreach (['单凹' => '单凹', '凹印' => '凹印', '卷凹' => '凹印', '胶印' => '胶印', '喷码' => '喷码', '丝印' => '丝印', '烫金' => '烫金', '模切' => '模切'] as $keyword => $category) {
  2004. if (strpos($name, $keyword) !== false) {
  2005. return $category;
  2006. }
  2007. }
  2008. return '';
  2009. }
  2010. /**
  2011. * 计划工时 = 计划接货数 * 开数 * 联数 / 小时产能
  2012. */
  2013. private function DyxlPlanHours($craft)
  2014. {
  2015. $qty = (float)$craft['计划接货数'];
  2016. $ks = (float)$craft['开数'];
  2017. $ls = (float)$craft['联数'];
  2018. $capacity = (float)$craft['小时产能'];
  2019. if ($qty <= 0 || $ks <= 0 || $ls <= 0 || $capacity <= 0) {
  2020. return null;
  2021. }
  2022. return $qty * $ks * $ls / $capacity;
  2023. }
  2024. private function DyxlKey($gdbh, $yjno, $gxh)
  2025. {
  2026. return trim((string)$gdbh) . '|' . (int)$yjno . '|' . (int)$gxh;
  2027. }
  2028. private function DyxlNumber($value)
  2029. {
  2030. return number_format(round((float)$value, 2), 2, '.', '');
  2031. }
  2032. /**
  2033. * 年度手工检验统计 左侧菜单(年 -> 客户)
  2034. * 两阶段:先查手工检验取工单号 → 再工单_基本资料去重取客户
  2035. */
  2036. public function YearSgyjLeft()
  2037. {
  2038. if ($this->request->isGet() === false) {
  2039. $this->error('请求错误');
  2040. }
  2041. $inspectRows = \db('db_手工检验')
  2042. ->field([
  2043. "DATE_FORMAT(sczl_rq, '%Y') AS 年份",
  2044. 'UPPER(RTRIM(sczl_gdbh)) AS 工单编号',
  2045. ])
  2046. ->where('sczl_rq', '>=', '2000-01-01')
  2047. ->group('年份, 工单编号')
  2048. ->select();
  2049. if (empty($inspectRows)) {
  2050. $this->success('成功', []);
  2051. }
  2052. // 提取工单编号,查工单_基本资料并按 Gd_gdbh 去重
  2053. $gdbhs = array_values(array_unique(array_column($inspectRows, '工单编号')));
  2054. $orderMap = $this->YearSgyjOrderMap($gdbhs);
  2055. $years = [];
  2056. foreach ($inspectRows as $row) {
  2057. $year = trim((string)$row['年份']);
  2058. $gdbh = $row['工单编号'];
  2059. if ($year === '' || !isset($orderMap[$gdbh])) {
  2060. continue;
  2061. }
  2062. $info = $orderMap[$gdbh];
  2063. $code = $info['客户编号'];
  2064. $name = $info['客户名称'];
  2065. if ($code === '' && $name === '') {
  2066. continue;
  2067. }
  2068. if (!isset($years[$year])) {
  2069. $years[$year] = ['年份' => $year, '客户' => []];
  2070. }
  2071. $customerKey = $code !== '' ? $code : $name;
  2072. if (!isset($years[$year]['客户'][$customerKey])) {
  2073. $years[$year]['客户'][$customerKey] = [
  2074. '客户编号' => $code,
  2075. '客户名称' => $name,
  2076. ];
  2077. }
  2078. }
  2079. krsort($years);
  2080. $data = [];
  2081. foreach ($years as $year) {
  2082. ksort($year['客户']);
  2083. $year['客户'] = array_values($year['客户']);
  2084. $data[] = $year;
  2085. }
  2086. $this->success('成功', $data);
  2087. }
  2088. /**
  2089. * 年度手工检验统计 右侧数据
  2090. * 两阶段:先查手工检验 → 工单_基本资料按 Gd_gdbh 去重后 PHP 关联
  2091. */
  2092. public function YearSgyjList()
  2093. {
  2094. if ($this->request->isGet() === false) {
  2095. $this->error('请求错误');
  2096. }
  2097. $param = $this->request->param();
  2098. $year = trim((string)(isset($param['year']) ? $param['year'] : ''));
  2099. if (!preg_match('/^\d{4}$/', $year)) {
  2100. $this->error('参数错误');
  2101. }
  2102. $customer = trim((string)(isset($param['customer']) ? $param['customer'] : ''));
  2103. $search = trim((string)(isset($param['search']) ? $param['search'] : ''));
  2104. $start = $year . '-01-01 00:00:00';
  2105. $end = ((int)$year + 1) . '-01-01 00:00:00';
  2106. // 1、手工检验数据(不 join)
  2107. $inspectRows = \db('db_手工检验')
  2108. ->field([
  2109. "DATE_FORMAT(sczl_rq, '%Y%m') AS 年月",
  2110. 'UPPER(RTRIM(sczl_gdbh)) AS 工单编号',
  2111. 'DATE_FORMAT(sczl_rq, \'%m\') AS 月份',
  2112. '(sczl_cl0+sczl_cl1+sczl_cl2+sczl_cl3+sczl_cl4+sczl_cl5+sczl_cl6+sczl_cl7+sczl_cl8+sczl_cl9+sczl_cl10+sczl_cl11+sczl_cl12) AS 总产量',
  2113. ])
  2114. ->where('sczl_rq', '>=', $start)
  2115. ->where('sczl_rq', '<', $end)
  2116. ->select();
  2117. if (empty($inspectRows)) {
  2118. $this->success('成功', ['summary' => [], 'detail' => []]);
  2119. }
  2120. // 2、工单编号 → 工单信息(去重)
  2121. $gdbhs = array_values(array_unique(array_filter(array_column($inspectRows, '工单编号'))));
  2122. $orderMap = $this->YearSgyjOrderMap($gdbhs);
  2123. // 3、组装完整行:合并工单信息到手工检验
  2124. $mergedRows = [];
  2125. foreach ($inspectRows as $row) {
  2126. $gdbh = $row['工单编号'];
  2127. if (!isset($orderMap[$gdbh])) {
  2128. continue;
  2129. }
  2130. $info = $orderMap[$gdbh];
  2131. $mergedRows[] = [
  2132. '年月' => trim((string)$row['年月']),
  2133. '工单编号' => $gdbh,
  2134. '月份' => (int)$row['月份'],
  2135. '总产量' => (float)$row['总产量'],
  2136. '产品编号' => $info['产品编号'],
  2137. '产品名称' => $info['产品名称'],
  2138. '客户编号' => $info['客户编号'],
  2139. '客户名称' => $info['客户名称'],
  2140. '产品类别' => $info['产品类别'],
  2141. ];
  2142. }
  2143. // 4、客户过滤 + 搜索过滤
  2144. if ($customer !== '') {
  2145. $mergedRows = array_values(array_filter($mergedRows, function ($r) use ($customer) {
  2146. return $r['客户编号'] === $customer;
  2147. }));
  2148. }
  2149. if ($search !== '') {
  2150. $mergedRows = array_values(array_filter($mergedRows, function ($r) use ($search) {
  2151. return strpos($r['产品编号'], $search) !== false || strpos($r['产品名称'], $search) !== false;
  2152. }));
  2153. }
  2154. if (empty($mergedRows)) {
  2155. $this->success('成功', ['summary' => [], 'detail' => []]);
  2156. }
  2157. // 5、summary:按 产品编号 聚合(产品编号为空时用产品名称兜底),按月份分月汇总
  2158. $products = [];
  2159. foreach ($mergedRows as $row) {
  2160. $code = $row['产品编号'];
  2161. if ($code === '') {
  2162. continue;
  2163. }
  2164. $m = $row['月份'];
  2165. if ($m < 1 || $m > 12) {
  2166. continue;
  2167. }
  2168. if (!isset($products[$code])) {
  2169. $products[$code] = [
  2170. '产品编号' => $code,
  2171. '产品名称' => $row['产品名称'],
  2172. '产品类别' => $row['产品类别'],
  2173. '客户编号' => $row['客户编号'],
  2174. '客户名称' => $row['客户名称'],
  2175. 'monthly' => array_fill(1, 12, 0),
  2176. ];
  2177. }
  2178. $products[$code]['monthly'][$m] += $row['总产量'];
  2179. }
  2180. // 6、组装 summary 数组
  2181. $summary = [];
  2182. foreach ($products as $product) {
  2183. $totalAll = 0;
  2184. $months = [];
  2185. for ($m = 1; $m <= 12; $m++) {
  2186. $value = $product['monthly'][$m];
  2187. $totalAll += $value;
  2188. $months[str_pad($m, 2, '0', STR_PAD_LEFT) . '月'] = $value > 0 ? round($value, 2) : '';
  2189. }
  2190. $summary[] = array_merge([
  2191. '产品编号' => $product['产品编号'],
  2192. '产品名称' => $product['产品名称'],
  2193. '产品类别' => $product['产品类别'],
  2194. '每月合计' => round($totalAll, 2),
  2195. ], $months, [
  2196. '客户编号' => $product['客户编号'],
  2197. '客户名称' => $product['客户名称'],
  2198. ]);
  2199. }
  2200. usort($summary, function ($a, $b) {
  2201. return strcmp($a['产品编号'], $b['产品编号']);
  2202. });
  2203. // 7、summary 合计行:小盒合计、条盒合计
  2204. $totalRows = [];
  2205. foreach (['小盒', '条盒'] as $category) {
  2206. $exists = false;
  2207. $total = 0;
  2208. $sums = array_fill(1, 12, 0);
  2209. foreach ($summary as $row) {
  2210. if ($row['产品类别'] !== $category) {
  2211. continue;
  2212. }
  2213. $exists = true;
  2214. $total += (float)$row['每月合计'];
  2215. for ($m = 1; $m <= 12; $m++) {
  2216. $mk = str_pad($m, 2, '0', STR_PAD_LEFT) . '月';
  2217. $sums[$m] += $row[$mk] === '' ? 0 : (float)$row[$mk];
  2218. }
  2219. }
  2220. if (!$exists) continue;
  2221. $totalRow = [
  2222. '产品编号' => $category . '合计',
  2223. '产品名称' => '',
  2224. '产品类别' => '',
  2225. '每月合计' => round($total, 2),
  2226. '合计类型' => true,
  2227. '客户编号' => '',
  2228. '客户名称' => '',
  2229. ];
  2230. for ($m = 1; $m <= 12; $m++) {
  2231. $totalRow[str_pad($m, 2, '0', STR_PAD_LEFT) . '月'] = round($sums[$m], 2);
  2232. }
  2233. $totalRows[] = $totalRow;
  2234. }
  2235. $summary = array_merge($summary, $totalRows);
  2236. // 8、detail:按 工单编号+年月 聚合
  2237. $detailMap = [];
  2238. foreach ($mergedRows as $row) {
  2239. $dKey = $row['工单编号'] . '|' . $row['年月'];
  2240. if (!isset($detailMap[$dKey])) {
  2241. $detailMap[$dKey] = [
  2242. '年月' => $row['年月'],
  2243. '工单编号' => $row['工单编号'],
  2244. '产品编号' => $row['产品编号'],
  2245. '产品名称' => $row['产品名称'],
  2246. '产品类别' => $row['产品类别'],
  2247. '总产量' => 0,
  2248. '客户编号' => $row['客户编号'],
  2249. '客户名称' => $row['客户名称'],
  2250. ];
  2251. }
  2252. $detailMap[$dKey]['总产量'] += $row['总产量'];
  2253. }
  2254. $detail = array_values($detailMap);
  2255. usort($detail, function ($a, $b) {
  2256. $c = strcmp($a['年月'], $b['年月']);
  2257. if ($c !== 0) return $c;
  2258. return strcmp($a['工单编号'], $b['工单编号']);
  2259. });
  2260. foreach ($detail as &$d) {
  2261. $d['总产量'] = round($d['总产量'], 2);
  2262. }
  2263. unset($d);
  2264. $this->success('成功', ['summary' => $summary, 'detail' => $detail]);
  2265. }
  2266. /**
  2267. * 工单_基本资料 按 Gd_gdbh 去重取一条
  2268. * 取第一个有客户代号且有成品编号的行;都没有时取第一条非空行
  2269. */
  2270. private function YearSgyjOrderMap(array $gdbhs)
  2271. {
  2272. if (empty($gdbhs)) {
  2273. return [];
  2274. }
  2275. $rows = \db('工单_基本资料')
  2276. ->field([
  2277. 'UPPER(RTRIM(Gd_gdbh)) AS 工单编号',
  2278. 'RTRIM(Gd_cpdh) AS 产品编号',
  2279. 'RTRIM(成品名称) AS 产品名称',
  2280. 'RTRIM(Gd_客户代号) AS 客户编号',
  2281. 'RTRIM(Gd_客户名称) AS 客户名称',
  2282. ])
  2283. ->whereIn('Gd_gdbh', $gdbhs)
  2284. ->select();
  2285. $map = [];
  2286. foreach ($rows as $row) {
  2287. $gdbh = trim((string)$row['工单编号']);
  2288. if ($gdbh === '') continue;
  2289. $code = trim((string)$row['产品编号']);
  2290. $name = trim((string)$row['产品名称']);
  2291. $khdh = trim((string)$row['客户编号']);
  2292. $khmc = trim((string)$row['客户名称']);
  2293. $category = $name !== '' ? (strpos($name, '小盒') !== false ? '小盒' : '条盒') : '';
  2294. if (!isset($map[$gdbh])) {
  2295. // 第一次见到:如果有客户代号且有成品编号,直接用;否则先占坑
  2296. $map[$gdbh] = [
  2297. '产品编号' => $code,
  2298. '产品名称' => $name,
  2299. '客户编号' => $khdh,
  2300. '客户名称' => $khmc,
  2301. '产品类别' => $category,
  2302. ];
  2303. } else {
  2304. // 已存在:如果现有记录缺客户,新记录有客户则覆盖;同理产品编号
  2305. if ($map[$gdbh]['客户编号'] === '' && $khdh !== '') {
  2306. $map[$gdbh]['客户编号'] = $khdh;
  2307. $map[$gdbh]['客户名称'] = $khmc;
  2308. }
  2309. if ($map[$gdbh]['产品编号'] === '' && $code !== '') {
  2310. $map[$gdbh]['产品编号'] = $code;
  2311. $map[$gdbh]['产品名称'] = $name;
  2312. $map[$gdbh]['产品类别'] = $category;
  2313. }
  2314. }
  2315. }
  2316. return $map;
  2317. }
  2318. /**
  2319. * 设备周数据统计 左侧菜单(车间 -> 机台)
  2320. * 参考 facility/getTab,但去掉日期子节点
  2321. */
  2322. public function EqwdtLeft()
  2323. {
  2324. if ($this->request->isGet() === false) {
  2325. $this->error('请求错误');
  2326. }
  2327. $department = \db('设备_基本资料')
  2328. ->distinct(true)
  2329. ->where('使用部门', '<>', '研发中心')
  2330. ->where('设备编组', '<>', '')
  2331. ->where('sys_sbID', '<>', '')
  2332. ->order('设备编组')
  2333. ->column('rtrim(使用部门) as 使用部门');
  2334. if (empty($department)) {
  2335. $this->success('成功', []);
  2336. }
  2337. $data = [];
  2338. foreach ($department as $dept) {
  2339. $machines = \db('设备_基本资料')
  2340. ->where('使用部门', $dept)
  2341. ->where('sys_sbID', '<>', '')
  2342. ->field('rtrim(设备编号) as 设备编号, rtrim(设备名称) as 设备名称')
  2343. ->order('设备编号')
  2344. ->select();
  2345. $machineNodes = [];
  2346. foreach ($machines as $m) {
  2347. $code = trim((string)$m['设备编号']);
  2348. if ($code === '') continue;
  2349. $machineNodes[] = [
  2350. 'label' => $code . '-->' . trim((string)$m['设备名称']),
  2351. 'key' => 'M' . $code,
  2352. 'machine' => $code,
  2353. ];
  2354. }
  2355. $data[] = [
  2356. 'label' => $dept,
  2357. 'key' => 'D' . $dept,
  2358. 'children' => $machineNodes,
  2359. ];
  2360. }
  2361. $this->success('成功', $data);
  2362. }
  2363. /**
  2364. * 设备周数据统计 右侧汇总 + 明细
  2365. * 固定取数据库中最新日期往前 6 天(共 7 天)
  2366. * 参数: machine (可选机台编号)
  2367. */
  2368. public function EqwdtList()
  2369. {
  2370. if ($this->request->isGet() === false) {
  2371. $this->error('请求错误');
  2372. }
  2373. $param = $this->request->param();
  2374. $machine = trim((string)(isset($param['machine']) ? $param['machine'] : ''));
  2375. // 以数据库最新日期为基准,取最近 7 天
  2376. $maxDate = \db('设备_产量计酬')->max('sczl_rq');
  2377. if (!$maxDate) {
  2378. $this->success('成功', ['summary' => [], 'detail' => [], 'days' => [], 'range' => ['start' => '', 'end' => '']]);
  2379. }
  2380. $maxTs = strtotime($maxDate);
  2381. $end = date('Y-m-d', $maxTs);
  2382. $start = date('Y-m-d', $maxTs - 6 * 86400);
  2383. $startTime = $start . ' 00:00:00';
  2384. $endTime = date('Y-m-d', $maxTs + 86400) . ' 00:00:00';
  2385. // 7 天日期列表(新 -> 旧)
  2386. $days = [];
  2387. for ($i = 0; $i < 7; $i++) {
  2388. $days[] = date('Y-m-d', $maxTs - $i * 86400);
  2389. }
  2390. $dayLabels = [];
  2391. foreach ($days as $d) {
  2392. $dayLabels[] = date('m.d', strtotime($d));
  2393. }
  2394. // 机台清单(与左侧树口径一致:排除研发中心、设备编组/机台编号为空)
  2395. $machineQuery = \db('设备_基本资料')
  2396. ->where('使用部门', '<>', '研发中心')
  2397. ->where('设备编组', '<>', '')
  2398. ->where('sys_sbID', '<>', '')
  2399. ->field('RTRIM(设备编号) AS 机台编号, RTRIM(设备名称) AS 设备名称')
  2400. ->order('设备编号');
  2401. if ($machine !== '') {
  2402. $machineQuery->where('设备编号', $machine);
  2403. }
  2404. $machineList = $machineQuery->select();
  2405. // 1、汇总:机台 x 日期 => 产量(当天汇总)+ 工时(sczl_sj2 - sczl_sj1 合计)
  2406. $recordQuery = \db('设备_产量计酬')
  2407. ->field([
  2408. 'RTRIM(sczl_jtbh) AS 机台编号',
  2409. "DATE_FORMAT(sczl_rq, '%Y-%m-%d') AS 日期",
  2410. 'sczl_cl',
  2411. 'sczl_sj1',
  2412. 'sczl_sj2',
  2413. ])
  2414. ->where('sczl_rq', '>=', $startTime)
  2415. ->where('sczl_rq', '<', $endTime);
  2416. if ($machine !== '') {
  2417. $recordQuery->where('sczl_jtbh', $machine);
  2418. }
  2419. $records = $recordQuery->select();
  2420. $agg = [];
  2421. foreach ($records as $r) {
  2422. $code = trim((string)$r['机台编号']);
  2423. $day = trim((string)$r['日期']);
  2424. if ($code === '' || $day === '') {
  2425. continue;
  2426. }
  2427. if (!isset($agg[$code])) {
  2428. $agg[$code] = [];
  2429. }
  2430. if (!isset($agg[$code][$day])) {
  2431. $agg[$code][$day] = ['产量' => 0, '工时' => 0];
  2432. }
  2433. $agg[$code][$day]['产量'] += (float)$r['sczl_cl'];
  2434. $t1 = strtotime(trim((string)$r['sczl_sj1']));
  2435. $t2 = strtotime(trim((string)$r['sczl_sj2']));
  2436. if ($t1 !== false && $t2 !== false && $t1 > 0 && $t2 > 0) {
  2437. if ($t2 < $t1) {
  2438. // 跨午夜:结束时间顺延一天
  2439. $t2 += 86400;
  2440. }
  2441. if ($t2 > $t1) {
  2442. $agg[$code][$day]['工时'] += ($t2 - $t1) / 3600;
  2443. }
  2444. }
  2445. }
  2446. $summary = [];
  2447. foreach ($machineList as $m) {
  2448. $code = trim((string)$m['机台编号']);
  2449. if ($code === '') {
  2450. continue;
  2451. }
  2452. $row = [
  2453. '机台编号' => $code,
  2454. '设备名称' => trim((string)$m['设备名称']),
  2455. ];
  2456. foreach ($days as $idx => $day) {
  2457. $label = $dayLabels[$idx];
  2458. $cl = isset($agg[$code][$day]) ? $agg[$code][$day]['产量'] : 0;
  2459. $gs = isset($agg[$code][$day]) ? $agg[$code][$day]['工时'] : 0;
  2460. $row['产量_' . $label] = $cl == 0 ? '' : round($cl, 2);
  2461. $row['工时_' . $label] = $gs == 0 ? '' : round($gs, 2);
  2462. }
  2463. $summary[] = $row;
  2464. }
  2465. // 2、明细:工单级(按 机台编号 + 工单编号 + 日期 聚合)
  2466. $detailQuery = \db('设备_产量计酬')
  2467. ->alias('s')
  2468. ->join('设备_基本资料 b', 'RTRIM(b.设备编号) = RTRIM(s.sczl_jtbh)', 'LEFT')
  2469. ->join('工单_基本资料 g', 'RTRIM(g.Gd_gdbh) = RTRIM(s.sczl_gdbh)', 'LEFT')
  2470. ->field([
  2471. 'DATE_FORMAT(s.sczl_rq, \'%Y-%m-%d\') AS 日期',
  2472. 'RTRIM(s.sczl_jtbh) AS 机台编号',
  2473. 'RTRIM(b.设备名称) AS 设备名称',
  2474. 'RTRIM(s.sczl_gdbh) AS 工单编号',
  2475. 'CONCAT(FLOOR(s.sczl_yjno), \'-\', RTRIM(s.sczl_gxmc)) AS 印件及工序',
  2476. 'RTRIM(g.Gd_cpdh) AS 产品编号',
  2477. 'RTRIM(g.成品名称) AS 成品名称',
  2478. 'RTRIM(g.Gd_客户名称) AS 客户名称',
  2479. 'SUM(s.sczl_cl) AS 产量',
  2480. 'SUM(s.sczl_设备运行工时) AS 设备运行工时',
  2481. 'SUM(s.sczl_装版工时) AS 装版工时',
  2482. 'SUM(s.sczl_保养工时) AS 保养工时',
  2483. 'SUM(s.sczl_打样工时) AS 打样工时',
  2484. 'SUM(s.sczl_异常停机工时) AS 异常停机工时',
  2485. 'SUM(s.sczl_zcfp) AS 制程废品',
  2486. 'SUM(s.sczl_zccp) AS 制程次品',
  2487. ])
  2488. ->where('s.sczl_rq', '>=', $startTime)
  2489. ->where('s.sczl_rq', '<', $endTime);
  2490. if ($machine !== '') {
  2491. $detailQuery->where('s.sczl_jtbh', $machine);
  2492. }
  2493. $detail = $detailQuery
  2494. ->group('日期, 机台编号, 设备名称, 工单编号, 印件及工序, 产品编号, 成品名称, 客户名称')
  2495. ->order('日期, 机台编号, 工单编号')
  2496. ->select();
  2497. // 数值格式化(0 显示为空字符串)
  2498. foreach ($detail as &$row) {
  2499. foreach (['产量', '设备运行工时', '装版工时', '保养工时', '打样工时', '异常停机工时', '制程废品', '制程次品'] as $k) {
  2500. $v = (float)$row[$k];
  2501. $row[$k] = $v === 0 ? '' : round($v, 2);
  2502. }
  2503. }
  2504. unset($row);
  2505. $this->success('成功', [
  2506. 'summary' => $summary,
  2507. 'detail' => $detail,
  2508. 'days' => $dayLabels,
  2509. 'range' => ['start' => $start, 'end' => $end],
  2510. ]);
  2511. }
  2512. /**
  2513. * 完工工单生产周期统计 左侧菜单(年月 → 客户)
  2514. * 参考 order_super_loss/getTab
  2515. */
  2516. public function CopsTab()
  2517. {
  2518. if ($this->request->isGet() === false) {
  2519. $this->error('请求错误');
  2520. }
  2521. // 条件:近12个月内「末版入仓完工」的工单(末版入仓 jjcp_smb like 末% 即视为完工)
  2522. // 月份分组 = 末版入仓完工日期 MAX(jjcp_sj)
  2523. // 客户代号/客户名称:产品_基本资料(按成品编码 Gd_cpdh 关联),工单自身客户字段只做兜底
  2524. $sql = "SELECT
  2525. DATE_FORMAT(c.完工时间, '%Y%m') AS date,
  2526. COUNT(DISTINCT a.Gd_gdbh) AS cnt,
  2527. RTRIM(COALESCE(p.客户编号, a.Gd_客户代号)) AS code,
  2528. RTRIM(COALESCE(p.客户名称, a.Gd_客户名称)) AS name
  2529. FROM `工单_基本资料` a
  2530. LEFT JOIN `产品_基本资料` p
  2531. ON RTRIM(a.Gd_cpdh) = RTRIM(p.产品编号)
  2532. INNER JOIN (
  2533. SELECT jjcp_gdbh, jjcp_yjno, MAX(jjcp_sj) AS 完工时间
  2534. FROM `成品入仓`
  2535. WHERE jjcp_smb LIKE '末%'
  2536. GROUP BY jjcp_gdbh, jjcp_yjno
  2537. ) c
  2538. ON a.Gd_gdbh = c.jjcp_gdbh AND CAST(a.行号 AS UNSIGNED) = CAST(c.jjcp_yjno AS UNSIGNED)
  2539. WHERE c.完工时间 >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
  2540. AND c.完工时间 IS NOT NULL
  2541. GROUP BY date, code, name
  2542. ORDER BY date DESC, code ASC";
  2543. $rows = Db::query($sql);
  2544. // 组装为 { date-total: [{code, name, total}] } 结构
  2545. $organized = [];
  2546. foreach ($rows as $r) {
  2547. $date = $r['date'];
  2548. if (!isset($organized[$date])) {
  2549. $organized[$date] = ['total_count' => 0, 'items' => []];
  2550. }
  2551. $organized[$date]['items'][] = [
  2552. 'code' => $r['code'],
  2553. 'name' => $r['name'],
  2554. 'total' => intval($r['cnt']),
  2555. ];
  2556. $organized[$date]['total_count'] += intval($r['cnt']);
  2557. }
  2558. $data = [];
  2559. foreach ($organized as $date => $info) {
  2560. $key = $date . '-' . $info['total_count'];
  2561. foreach ($info['items'] as $it) {
  2562. $data[$key][] = $it;
  2563. }
  2564. }
  2565. $this->success('成功', $data);
  2566. }
  2567. /**
  2568. * 完工工单生产周期统计 右侧列表(纯 SQL 避免 TP5 Query 方法缺失)
  2569. * 参数: date (年月 YYYYMM), code (客户代号), search (关键字搜索),
  2570. * page (页码, 默认1), limit (每页条数, 默认50), export (1=导出全量, 不分页)
  2571. */
  2572. public function CopsList()
  2573. {
  2574. if ($this->request->isGet() === false) {
  2575. $this->error('请求错误');
  2576. }
  2577. $param = $this->request->param();
  2578. $date = trim((string)(isset($param['date']) ? $param['date'] : ''));
  2579. $code = trim((string)(isset($param['code']) ? $param['code'] : ''));
  2580. $search = trim((string)(isset($param['search']) ? $param['search'] : ''));
  2581. $page = empty($param['page']) ? 1 : max(1, intval($param['page']));
  2582. $limit = empty($param['limit']) ? 50 : max(1, intval($param['limit']));
  2583. $isExport = !empty($param['export']);
  2584. // 导出全量时限制上限,避免一次性拉爆内存
  2585. if ($isExport) {
  2586. $page = 1;
  2587. $limit = 50000;
  2588. }
  2589. $offset = ($page - 1) * $limit;
  2590. $where = [];
  2591. $where[] = "c.完工时间 >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)";
  2592. $where[] = "c.完工时间 IS NOT NULL";
  2593. if ($date !== '') {
  2594. $where[] = "DATE_FORMAT(c.完工时间, '%Y%m') = " . intval($date);
  2595. }
  2596. if ($code !== '') {
  2597. $escaped = str_replace("'", "''", $code);
  2598. $where[] = "UPPER(RTRIM(COALESCE(p.客户编号, a.Gd_客户代号))) = UPPER(RTRIM('{$escaped}'))";
  2599. }
  2600. if ($search !== '') {
  2601. $escaped = str_replace("'", "''", $search);
  2602. $where[] = "(a.Gd_gdbh LIKE '%{$escaped}%' OR a.成品名称 LIKE '%{$escaped}%' OR a.Gd_cpdh LIKE '%{$escaped}%')";
  2603. }
  2604. $whereSql = implode(' AND ', $where);
  2605. // 公共 FROM 段(成品入仓只取末版 jjcp_smb like 末%,无末版入仓的工单不参与统计)
  2606. $fromSql = "FROM `工单_基本资料` a
  2607. LEFT JOIN `产品_基本资料` p
  2608. ON RTRIM(a.Gd_cpdh) = RTRIM(p.产品编号)
  2609. LEFT JOIN `工单_印件资料` b
  2610. ON a.Gd_gdbh = b.Yj_Gdbh AND CAST(a.行号 AS UNSIGNED) = CAST(b.yj_Yjno AS UNSIGNED)
  2611. INNER JOIN (
  2612. SELECT jjcp_gdbh, jjcp_yjno,
  2613. SUM(jjcp_sl) AS 入仓数量,
  2614. MIN(jjcp_sj) AS 检验时间,
  2615. MAX(jjcp_sj) AS 完工时间
  2616. FROM `成品入仓`
  2617. WHERE jjcp_smb LIKE '末%'
  2618. GROUP BY jjcp_gdbh, jjcp_yjno
  2619. ) c
  2620. ON a.Gd_gdbh = c.jjcp_gdbh AND CAST(a.行号 AS UNSIGNED) = CAST(c.jjcp_yjno AS UNSIGNED)
  2621. LEFT JOIN (
  2622. SELECT RTRIM(sczl_gdbh) AS gdbh, sczl_yjno,
  2623. MIN(sczl_rq) AS 生产开工时间,
  2624. MIN(CASE WHEN sczl_gxmc LIKE '%模切%' THEN sczl_rq END) AS 模切开工时间
  2625. FROM `设备_产量计酬`
  2626. WHERE sczl_rq >= DATE_SUB(CURDATE(), INTERVAL 13 MONTH)
  2627. GROUP BY RTRIM(sczl_gdbh), sczl_yjno
  2628. ) gy
  2629. ON a.Gd_gdbh = gy.gdbh AND CAST(a.行号 AS UNSIGNED) = CAST(gy.sczl_yjno AS UNSIGNED)
  2630. LEFT JOIN (
  2631. SELECT Gy0_gdbh, 印件及工序 AS 印件号, SUM(DISTINCT 计划损耗) AS 计划损耗
  2632. FROM `工单_质量考核汇总`
  2633. GROUP BY Gy0_gdbh, 印件及工序
  2634. ) q
  2635. ON a.Gd_gdbh = q.Gy0_gdbh AND CAST(a.行号 AS UNSIGNED) = CAST(q.印件号 AS UNSIGNED)
  2636. WHERE {$whereSql}";
  2637. // 总数
  2638. $totalRow = Db::query("SELECT COUNT(*) AS total {$fromSql}");
  2639. $total = isset($totalRow[0]['total']) ? (int)$totalRow[0]['total'] : 0;
  2640. $sql = "SELECT
  2641. RTRIM(a.Gd_生产分类) AS 生产分类,
  2642. RTRIM(a.Gd_gdbh) AS 工单编号,
  2643. RTRIM(b.yj_Yjdh) AS 印件代号,
  2644. RTRIM(a.Gd_cpdh) AS 产品代号,
  2645. RTRIM(a.成品名称) AS 产品名称,
  2646. a.订单数量,
  2647. a.实际投料,
  2648. RTRIM(a.计量单位) AS 计量单位,
  2649. IFNULL(c.入仓数量, 0) AS 入仓数量,
  2650. DATE(c.检验时间) AS 检验日期,
  2651. DATE(COALESCE(c.完工时间, NULLIF(a.入仓日期, '1900-01-01 00:00:00'), NULLIF(a.工单完工日期, '1900-01-01 00:00:00'))) AS 入仓完工日期,
  2652. DATE(a.接单日期) AS 接单日期,
  2653. DATE(gy.生产开工时间) AS 生产开工日期,
  2654. DATE(gy.模切开工时间) AS 模切开工日期,
  2655. IFNULL(q.计划损耗, 0) AS 计划损耗,
  2656. RTRIM(COALESCE(p.客户编号, a.Gd_客户代号)) AS 客户代号,
  2657. RTRIM(COALESCE(p.客户名称, a.Gd_客户名称)) AS 客户名称,
  2658. RTRIM(a.销售订单号) AS 销售订单号
  2659. {$fromSql}
  2660. ORDER BY COALESCE(c.完工时间, a.工单完工日期) DESC, a.Gd_gdbh DESC
  2661. LIMIT {$offset}, {$limit}";
  2662. $list = Db::query($sql);
  2663. // 月度公休记录(用于生产公休/检验公休/工单公休)
  2664. $holidayMap = $this->CopsHolidayMap();
  2665. foreach ($list as &$row) {
  2666. // 先取原始数值,避免格式化后再次转换出错
  2667. $rawOrder = (float)$row['订单数量'];
  2668. $rawActual = (float)$row['实际投料'];
  2669. $warehouseNum = (int)$row['入仓数量'];
  2670. $planLoss = (float)$row['计划损耗'];
  2671. $row['订单数量'] = $rawOrder == 0 ? '' : number_format($rawOrder, 2);
  2672. $row['实际投料'] = $rawActual == 0 ? '' : number_format($rawActual, 2);
  2673. $row['入仓数量'] = $warehouseNum === 0 ? '' : $warehouseNum;
  2674. // 目标合格率 = (实际投料*10000 - 计划损耗) / (实际投料*10000)
  2675. $row['目标合格率'] = $rawActual > 0
  2676. ? number_format(($rawActual * 10000 - $planLoss) / ($rawActual * 10000) * 100, 2) . '%'
  2677. : '';
  2678. // 实际合格率 = 入仓数量 / (实际投料*10000)
  2679. $row['实际合格率'] = ($warehouseNum > 0 && $rawActual > 0)
  2680. ? number_format($warehouseNum / ($rawActual * 10000) * 100, 2) . '%'
  2681. : '';
  2682. // 日期空值处理
  2683. foreach (['检验日期', '接单日期', '入仓完工日期', '生产开工日期', '模切开工日期'] as $k) {
  2684. $v = (string)$row[$k];
  2685. if ($v === '' || $v === '0000-00-00' || strpos($v, '1900-01-01') === 0) {
  2686. $row[$k] = '';
  2687. }
  2688. }
  2689. // 周期(自然日)
  2690. // $row['生产周期'] = $this->CopsCycle($row['生产开工日期'], $row['检验日期']);
  2691. // $row['检验周期'] = $this->CopsCycle($row['检验日期'], $row['入仓完工日期']);
  2692. $row['工单周期'] = $this->CopsCycle($row['接单日期'], $row['入仓完工日期']);
  2693. // // 公休天数(区间内 人事_班组公休记录 之和)
  2694. // $row['生产公休'] = $this->CopsHolidaySum($holidayMap, $row['生产开工日期'], $row['检验日期']);
  2695. // $row['检验公休'] = $this->CopsHolidaySum($holidayMap, $row['检验日期'], $row['入仓完工日期']);
  2696. // $row['工单公休'] = $this->CopsHolidaySum($holidayMap, $row['接单日期'], $row['入仓完工日期']);
  2697. unset($row['计划损耗']);
  2698. }
  2699. unset($row);
  2700. $this->success('成功', [
  2701. 'list' => $list,
  2702. 'total' => $total,
  2703. 'page' => $page,
  2704. 'limit' => $limit,
  2705. ]);
  2706. }
  2707. /**
  2708. * 读取月度公休记录(人事_班组公休记录),返回 [Y-m-d => 公休天数]
  2709. */
  2710. private function CopsHolidayMap()
  2711. {
  2712. $map = [];
  2713. $rows = Db::query("SELECT DATE_FORMAT(公休_日期, '%Y-%m-%d') AS d, SUM(公休_天数) AS days
  2714. FROM `人事_班组公休记录`
  2715. WHERE 公休_日期 IS NOT NULL
  2716. GROUP BY d");
  2717. foreach ($rows as $r) {
  2718. $map[$r['d']] = (float)$r['days'];
  2719. }
  2720. return $map;
  2721. }
  2722. /**
  2723. * 统计区间 (start, end] 内的公休天数
  2724. */
  2725. private function CopsHolidaySum(array $map, $start, $end)
  2726. {
  2727. if (empty($start) || empty($end)) {
  2728. return '';
  2729. }
  2730. $s = strtotime($start);
  2731. $e = strtotime($end);
  2732. if ($s === false || $e === false || $e <= $s) {
  2733. return 0;
  2734. }
  2735. $sum = 0;
  2736. foreach ($map as $d => $days) {
  2737. $t = strtotime($d);
  2738. if ($t !== false && $t > $s && $t <= $e) {
  2739. $sum += $days;
  2740. }
  2741. }
  2742. return round($sum, 1);
  2743. }
  2744. /**
  2745. * 两个日期之间的自然日天数
  2746. */
  2747. private function CopsCycle($start, $end)
  2748. {
  2749. if (empty($start) || empty($end)) {
  2750. return '';
  2751. }
  2752. $s = strtotime($start);
  2753. $e = strtotime($end);
  2754. if ($s === false || $e === false) {
  2755. return '';
  2756. }
  2757. return (int)round(($e - $s) / 86400);
  2758. }
  2759. }