Browse Source

成品入仓优化

unknown 1 month ago
parent
commit
ea276df5f9

+ 158 - 82
application/api/controller/FinishedProductWarehousing.php

@@ -502,98 +502,104 @@ public function getList()
 
 
     /**
     /**
      * 修改
      * 修改
+     * 前端仅传:UniqId、数量(jjcp_sl)、smb(jjcp_smb)、sys_id(Sys_id)
      * @ApiMethod (POST)
      * @ApiMethod (POST)
      */
      */
     public function edit()
     public function edit()
     {
     {
-        if(!$this->request->isPost()){
+        if (!$this->request->isPost()) {
             $this->error('请求方式错误');
             $this->error('请求方式错误');
         }
         }
-        //连接mongodb
-        $mongodb = Db::connect(config('database.mongodb'));
+
         $req = $this->request->param();
         $req = $this->request->param();
-        $arr = [
-            '入仓类型', '仓库编号', '仓库名称',
-            'jjcp_num',
-            'jjcp_gdbh', 'jjcp_yjno', '订单编号',
-            'jjcp_cpdh', 'jjcp_cpmc',
-            '成品编码', '成品名称',
-            '客户料号',
-            'jjcp_smb', 'jjcp_sj',
-            'jjcp_sl', 'jjcp_dw',
-            '机型备注',
-            'jjcp_desc'
-        ];
-        $data = [];
-        foreach ($arr as $key => $value){
-            if (!isset($req[$value])){
-                continue;
-            }
-            $data[$value] = $req[$value];
+        $uniqId = $req['UniqId'] ?? ($req['UniaId'] ?? null);
+        if ($uniqId === null || trim((string)$uniqId) === '') {
+            $this->error('参数错误', 'UniqId', 100);
+        }
+        $uniqId = (int)$uniqId;
+
+        $old = db('成品入仓')->where('UniqId', $uniqId)->find();
+        if (empty($old)) {
+            $this->error('未找到成品入仓记录');
         }
         }
-        if (!(isset($req['UniqId']) && trim($req['UniqId'])!='')){
-            $this->error('参数错误','UniqId',100);
+
+        $hasQty = array_key_exists('jjcp_sl', $req) || array_key_exists('数量', $req);
+        $hasSmb = array_key_exists('jjcp_smb', $req) || array_key_exists('smb', $req);
+        $sysId = $req['Sys_id'] ?? ($req['sys_id'] ?? null);
+        if (!$hasQty && !$hasSmb && ($sysId === null || $sysId === '')) {
+            $this->error('参数错误', '', 111);
         }
         }
-        if (count($data)==0){
-            $this->error('参数错误','',111);
+
+        $data = ['Mod_rq' => date('Y-m-d H:i:s')];
+        if ($sysId !== null && $sysId !== '') {
+            $data['Sys_id'] = $sysId;
         }
         }
-        $data['Mod_rq'] = date('Y-m-d H:i:s');
 
 
-        //判断当前工单是否存在已提交模版
-        if ($data['jjcp_smb'] === '末 板'){
-            $existingRecord = db('成品入仓')
-                ->where('jjcp_gdbh', $data['jjcp_gdbh'])
-                ->where('jjcp_yjno', $data['jjcp_yjno'])
-                ->where('jjcp_smb', '<>', '') // 判断 jjcp_smb 不为空
-                ->find();
-            if ($existingRecord && $existingRecord['UniqId'] !== (int)$req['UniqId']) {
-                $this->error($existingRecord['jjcp_gdbh'].'工单 -- 印件'.$existingRecord['jjcp_yjno'].'已经进入末版,无法继续操作');
+        $oldQty = (float)$old['jjcp_sl'];
+        $newQty = $oldQty;
+        $qtyChanged = false;
+        if ($hasQty) {
+            $newQty = (float)($req['jjcp_sl'] ?? $req['数量']);
+            $data['jjcp_sl'] = $newQty;
+            $qtyChanged = abs($newQty - $oldQty) > 0.00001;
+        }
+
+        $oldSmb = (string)$old['jjcp_smb'];
+        $newSmb = $oldSmb;
+        $smbChanged = false;
+        if ($hasSmb) {
+            $newSmb = (string)($req['jjcp_smb'] ?? $req['smb']);
+            $data['jjcp_smb'] = $newSmb;
+            $smbChanged = trim($newSmb) !== trim($oldSmb);
+        }
+
+        // 改为末板时,校验同工单同印件是否已有其他末板记录
+        if ($smbChanged && $this->isEndBoard($newSmb)) {
+            $existingEndBoard = $this->findExistingEndBoard($old['jjcp_gdbh'], $old['jjcp_yjno']);
+            if ($existingEndBoard && (int)$existingEndBoard['UniqId'] !== $uniqId) {
+                $this->error(
+                    $existingEndBoard['jjcp_gdbh'] . '工单 -- 印件' . $existingEndBoard['jjcp_yjno'] . '已经进入末版,无法继续操作'
+                );
             }
             }
-        };
-        //开启事务
+        }
+
+        $mongodb = Db::connect(config('database.mongodb'));
         db()->startTrans();
         db()->startTrans();
-        try{
-            $sql = db('成品入仓')->where('UniqId',$req['UniqId'])->fetchSql(true)->update($data);
+        try {
+            $sql = db('成品入仓')->where('UniqId', $uniqId)->fetchSql(true)->update($data);
             $bool = db()->query($sql);
             $bool = db()->query($sql);
-            //同步更新monodb数据
-             $res = $mongodb->name('finished_products')
-                ->where('UniqId', (int)$req['UniqId']) // 使用实际的UniqId值
+            $mongodb->name('finished_products')
+                ->where('UniqId', $uniqId)
                 ->update($data);
                 ->update($data);
-            // 提交事务
             db()->commit();
             db()->commit();
         } catch (\Exception $e) {
         } catch (\Exception $e) {
-            // 回滚事务
             db()->rollback();
             db()->rollback();
             $this->error($e->getMessage());
             $this->error($e->getMessage());
         }
         }
-        if($bool===false) $this->error('失败');
+        if ($bool === false) {
+            $this->error('失败');
+        }
 
 
-        $gdbh = isset($data['jjcp_gdbh']) ? $data['jjcp_gdbh'] : db('成品入仓')->where('UniqId', $req['UniqId'])->value('jjcp_gdbh');
-        // 接单日期在 2026-08-01 及以后,且中间库 U8_06工单资料存在该工单时才同步
-        if ($this->shouldSyncFinishStockMiddle($gdbh)) {
+        // 同步中间表:
+        // - 数量变更:插入差值为新同步数据(增加为正、减少为负)
+        // - 仅修改 smb:正常同步完整数量
+        // - 二者同时改:只同步差值(此时记录已是新 smb,中间表会带上末板标记)
+        if ($this->shouldSyncFinishStockMiddle($old['jjcp_gdbh']) && ($qtyChanged || $smbChanged)) {
             try {
             try {
                 $synchronization = new \app\api\controller\Synchronization();
                 $synchronization = new \app\api\controller\Synchronization();
-                $synchronization->syncFinishStockMiddle($req['UniqId'], '修改');
+                if ($qtyChanged) {
+                    $qtyDiff = $newQty - $oldQty; // 增加为正,减少为负
+                    $synchronization->syncFinishStockMiddle($uniqId, '修改', $qtyDiff);
+                } else {
+                    $synchronization->syncFinishStockMiddle($uniqId, '修改');
+                }
             } catch (\Exception $e) {
             } catch (\Exception $e) {
-                $this->error('成品入仓已保存,但' . $e->getMessage(), ['UniqId' => $req['UniqId']]);
+                $this->error('成品入仓已保存,但' . $e->getMessage(), ['UniqId' => $uniqId]);
             }
             }
         }
         }
 
 
-        $oederLoss = new \app\api\controller\OrderSuperLoss();
-        if (isset($data['jjcp_smb']) && strpos($data['jjcp_smb'],'末') !== false){
-            try {
-                $result = $oederLoss->OneOrderSuperLoss($data['jjcp_gdbh'], $data['jjcp_yjno']);
-            } catch (DataNotFoundException $e) {
-            } catch (ModelNotFoundException $e) {
-            } catch (DbException $e) {
-            }
-            db('工单_质量考核汇总')
-                ->where('Gy0_gdbh',$data['jjcp_gdbh'])
-                ->where('印件及工序',$data['jjcp_yjno'])
-                ->delete();
-            $sql = db('工单_质量考核汇总')->fetchSql(true)->insertAll($result);
-            $res = db()->query($sql);
-            if($res===false) $this->error('失败');
+        if ($smbChanged && $this->isEndBoard($newSmb)) {
+            $this->handleEndBoardSuperLoss($old['jjcp_gdbh'], $old['jjcp_yjno']);
         }
         }
 
 
         $this->success('成功');
         $this->success('成功');
@@ -601,43 +607,64 @@ public function getList()
 
 
     /**
     /**
      * 删除
      * 删除
+     * 前端传:UniqId、sys_id(Sys_id)
      * @ApiMethod (POST)
      * @ApiMethod (POST)
-     * @param string 'UniqId'
      */
      */
     public function del()
     public function del()
     {
     {
-        if(!$this->request->isPost()){
+        if (!$this->request->isPost()) {
             $this->error('请求方式错误');
             $this->error('请求方式错误');
         }
         }
-         //连接mongodb
-        $mongodb = Db::connect(config('database.mongodb'));
+
         $req = $this->request->param();
         $req = $this->request->param();
+        if (!(isset($req['UniqId']) && trim($req['UniqId']) != '')) {
+            $this->error('参数错误', 'UniqId', 100);
+        }
+        $sysId = $req['Sys_id'] ?? ($req['sys_id'] ?? null);
+        if ($sysId === null || trim((string)$sysId) === '') {
+            $this->error('参数错误', 'sys_id', 101);
+        }
+        $uniqId = (int)$req['UniqId'];
 
 
-        if (!(isset($req['UniqId']) && trim($req['UniqId'])!='')){
-            $this->error('参数错误','UniqId',100);
+        $old = db('成品入仓')->where('UniqId', $uniqId)->find();
+        if (empty($old)) {
+            $this->error('未找到成品入仓记录');
         }
         }
 
 
-        //开启事务
+        // 删除前同步中间表:MES插入类型=新增,数量取负;同步失败则不删除
+        if ($this->shouldSyncFinishStockOnDelete($old['jjcp_gdbh'], $uniqId)) {
+            try {
+                $synchronization = new \app\api\controller\Synchronization();
+                $synchronization->syncFinishStockMiddle(
+                    $uniqId,
+                    '新增',
+                    -1 * (float)$old['jjcp_sl'],
+                    $sysId
+                );
+            } catch (\Exception $e) {
+                $this->error('同步中间表失败,未删除:' . $e->getMessage(), ['UniqId' => $uniqId]);
+            }
+        }
+
+        $mongodb = Db::connect(config('database.mongodb'));
         db()->startTrans();
         db()->startTrans();
-        try{
-            $bool = db('成品入仓')->where('UniqId',$req['UniqId'])->delete();
-            //同时删除mongdb数据
-            //同步更新monodb数据
-             $res = $mongodb->name('finished_products')
-                ->where('UniqId', (int)$req['UniqId']) // 使用实际的UniqId值
+        try {
+            $sql = db('成品入仓')->where('UniqId', $uniqId)->fetchSql(true)->delete();
+            $bool = db()->query($sql);
+            $mongodb->name('finished_products')
+                ->where('UniqId', $uniqId)
                 ->delete();
                 ->delete();
-            // 提交事务
             db()->commit();
             db()->commit();
         } catch (\Exception $e) {
         } catch (\Exception $e) {
-            // 回滚事务
             db()->rollback();
             db()->rollback();
             $this->error($e->getMessage());
             $this->error($e->getMessage());
         }
         }
 
 
-        if($bool===false) $this->error('失败');
+        if ($bool === false) {
+            $this->error('失败');
+        }
 
 
         $this->success('成功');
         $this->success('成功');
-
     }
     }
 
 
     /**
     /**
@@ -1515,6 +1542,55 @@ public function getList()
         return $exists > 0;
         return $exists > 0;
     }
     }
 
 
+    /**
+     * 删除时是否需要回冲同步
+     * 1. 该 UniqId 已有成功同步记录/中间表数据
+     * 2. 或满足新增同步条件
+     * 3. 或工单为 Y 且 >= Y2608001(删除回冲放宽,避免 U8_06 查不到导致静默跳过)
+     * @param string $gdbh
+     * @param int $uniqId
+     * @return bool
+     */
+    protected function shouldSyncFinishStockOnDelete($gdbh, $uniqId)
+    {
+        if ($this->hasFinishStockMiddleSynced($uniqId)) {
+            return true;
+        }
+        if ($this->shouldSyncFinishStockMiddle($gdbh)) {
+            return true;
+        }
+
+        $gdbh = strtoupper(trim((string)$gdbh));
+        if ($gdbh === '' || $gdbh[0] !== 'Y') {
+            return false;
+        }
+        return (int)substr($gdbh, 1) >= 2608001;
+    }
+
+    /**
+     * 该成品入仓是否已成功同步过(日志或中间表)
+     * @param int $uniqId
+     * @return bool
+     */
+    protected function hasFinishStockMiddleSynced($uniqId)
+    {
+        $uniqId = (int)$uniqId;
+        $logCount = db('工单_成品入仓同步操作日志')
+            ->where('UniqId', $uniqId)
+            ->where('status', '同步成功')
+            ->count();
+        if ($logCount > 0) {
+            return true;
+        }
+
+        try {
+            $middleDb = Db::connect(config('database.db8'));
+            return $middleDb->name('U8_成品入仓')->where('UniqId', $uniqId)->count() > 0;
+        } catch (\Exception $e) {
+            return false;
+        }
+    }
+
     /**
     /**
      * 末版入仓后进入超节损
      * 末版入仓后进入超节损
      * @param string $gdbh
      * @param string $gdbh

+ 9 - 2
application/api/controller/Synchronization.php

@@ -2097,10 +2097,12 @@ class Synchronization extends Api
      * 成品入仓数据同步中间表
      * 成品入仓数据同步中间表
      * @param int|string $uniqId 成品入仓 UniqId
      * @param int|string $uniqId 成品入仓 UniqId
      * @param string $insertType 插入类型:新增/修改/删除
      * @param string $insertType 插入类型:新增/修改/删除
+     * @param float|int|null $iQtyOverride 数量覆盖(修改数量时传差值:增加为正、减少为负;null 则用记录原数量)
+     * @param string|null $usernameOverride 操作人覆盖(删除/修改时前端传入的 sys_id)
      * @return bool
      * @return bool
      * @throws \Exception 同步失败时抛出,便于调用方提示
      * @throws \Exception 同步失败时抛出,便于调用方提示
      */
      */
-    public function syncFinishStockMiddle($uniqId, $insertType = '新增')
+    public function syncFinishStockMiddle($uniqId, $insertType = '新增', $iQtyOverride = null, $usernameOverride = null)
     {
     {
         if (empty($uniqId)) {
         if (empty($uniqId)) {
             throw new \Exception('同步失败:UniqId 为空');
             throw new \Exception('同步失败:UniqId 为空');
@@ -2111,6 +2113,10 @@ class Synchronization extends Api
             throw new \Exception('同步失败:未找到成品入仓记录 UniqId=' . $uniqId);
             throw new \Exception('同步失败:未找到成品入仓记录 UniqId=' . $uniqId);
         }
         }
 
 
+        if ($usernameOverride !== null && trim((string)$usernameOverride) !== '') {
+            $record['Sys_id'] = $usernameOverride;
+        }
+
         // 测试库:database.db8(MySQL);正式库可改为 database.db3(SQL Server)
         // 测试库:database.db8(MySQL);正式库可改为 database.db3(SQL Server)
         $targetDb = Db::connect(config('database.db8'));
         $targetDb = Db::connect(config('database.db8'));
         $targetTable = 'U8_成品入仓';
         $targetTable = 'U8_成品入仓';
@@ -2119,6 +2125,7 @@ class Synchronization extends Api
         $isEndBoard = (strpos((string)$record['jjcp_smb'], '末') !== false) ? '末板' : '';
         $isEndBoard = (strpos((string)$record['jjcp_smb'], '末') !== false) ? '末板' : '';
         $id = 0;
         $id = 0;
         $errorMsg = '';
         $errorMsg = '';
+        $iQty = $iQtyOverride !== null ? $iQtyOverride : $record['jjcp_sl'];
 
 
         try {
         try {
             $maxId = (int)$targetDb->name($targetTable)->max('id');
             $maxId = (int)$targetDb->name($targetTable)->max('id');
@@ -2133,7 +2140,7 @@ class Synchronization extends Api
                 'cMemo'       => $record['jjcp_desc'],                 // 备注
                 'cMemo'       => $record['jjcp_desc'],                 // 备注
                 'cInvCode'    => $record['jjcp_cpdh'],                 // 物料编码
                 'cInvCode'    => $record['jjcp_cpdh'],                 // 物料编码
                 'cInvName'    => $record['jjcp_cpmc'],                 // 物料名称
                 'cInvName'    => $record['jjcp_cpmc'],                 // 物料名称
-                'iQty'        => $record['jjcp_sl'],                   // 数量
+                'iQty'        => $iQty,                                // 数量(修改数量时可传差值)
                 'cBatch'      => $record['订单编号'],                   // 批次号
                 'cBatch'      => $record['订单编号'],                   // 批次号
                 'username'    => $record['Sys_id'],                    // 用户名
                 'username'    => $record['Sys_id'],                    // 用户名
                 '是否末版'    => $isEndBoard,                          // 是否末版
                 '是否末版'    => $isEndBoard,                          // 是否末版