zhanglinxin преди 1 година
родител
ревизия
02057ac4ef
променени са 3 файла, в които са добавени 420 реда и са изтрити 70 реда
  1. 190 2
      application/api/controller/Common.php
  2. 208 61
      application/common/service/ApproveInfoService.php
  3. 22 7
      application/common/service/ApproveService.php

+ 190 - 2
application/api/controller/Common.php

@@ -18,6 +18,19 @@ use think\db\exception\BindParamException;
 use think\Exception;
 use think\exception\PDOException;
 
+Use Jsyqw\PdfTable\DrawContent;
+Use Jsyqw\PdfTable\DrawContentTitle;
+Use Jsyqw\PdfTable\DrawTable;
+use Jsyqw\PdfTable\DrawTables;
+use Jsyqw\PdfTable\data\ContentData;
+Use Jsyqw\PdfTable\data\ContentTitleData;
+Use Jsyqw\PdfTable\data\TableData;
+Use Jsyqw\PdfTable\data\TableRowData;
+Use Jsyqw\PdfTable\data\TableTitleData;
+Use Jsyqw\PdfTable\models\ImageModel;
+Use Jsyqw\PdfTable\models\TextModel;
+
+
 /**
  * @Apidoc\Title("公用")
  * @Apidoc\Group("api")
@@ -28,9 +41,11 @@ class Common extends Base
     // 需要登录
     protected $need_login = ['get_user_list'];
 
+    protected $pdf;
     public function initialize()
     {
         parent::initialize();
+        $this->pdf = new \TCPDF();
     }
 
     /**
@@ -39,12 +54,185 @@ class Common extends Base
      * @Apidoc\Method("POST")
      * @Apidoc\Param("id", type="integer",require=true, desc="ID")
      */
-    public function edit()
+    public function test()
     {
-        $id = input('id');
+        //保存文件
+        $subPath = date('Ymd');
+        $savePath = './upload/pdf/' . $subPath;
+        // 检查上传目录
+        if (!is_dir($savePath)) {
+            // 检查目录是否编码后的
+            if (is_dir(base64_decode($savePath))) {
+                $savePath = base64_decode($savePath);
+            } else {
+                // 尝试创建目录
+                if (!mkdir($savePath, 0755, true)) {
+                    $this->error = '上传目录' . $savePath . '不存在';
+                    return false;
+                }
+            }
+        } else {
+            if (!is_writeable($savePath)) {
+                $this->error = '上传目录' . $savePath . '不可写';
+                return false;
+            }
+        }
+        $filename = date('Ymd') . sha1(date('YmdHis', time()) . uniqid());
+        $suffix = '.pdf';
+        $realpath = substr($savePath, 1) . '/' . $filename . $suffix;
+        self::exportPdf($_SERVER['DOCUMENT_ROOT'] . $realpath);
+//        self::tablePdf('测试文件',$_SERVER['DOCUMENT_ROOT'] . $realpath);
+
         $this->success('测试');
     }
 
+    // 设置PDF参数
+    protected function setPdfAttr()
+    {
+        $this->pdf->setCreator(PDF_CREATOR);
+        $this->pdf->setAuthor('Dya');
+        $this->pdf->SetSubject('TCPDF Tutorial');
+        $this->pdf->SetKeywords('TCPDF, PDF, example, test, guide');
+
+        //页眉页脚
+        $this->pdf->setPrintHeader(false);
+        $this->pdf->setPrintFooter(true);
+        // 页脚信息
+        $this->pdf->setFooterData(array(0,64,0), array(0,64,128));
+        $this->pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
+        $this->pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
+        // 自动分页 (第二个参数可以设置距离底部多少距离时分页)
+        $this->pdf->setAutoPageBreak(true, 15);
+
+        // 设置边距(左 上 右 下) 右边距默认左侧值 下边距是bool值(是否覆盖默认页边距)
+        $this->pdf->setMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
+        // 定义默认的单间距字体 (设置为等宽字体)
+        $this->pdf->SetDefaultMonospacedFont('courier');
+        // 设置图像比例因子
+        $this->pdf->setImageScale(1.25);
+    }
+
+
+    /**
+     * 绘制表格
+     * @param $title
+     * @param $fileName
+     */
+    public function tablePdf($title, $fileName)
+    {
+        $this->setPdfAttr();
+        $this->pdf->setTitle($title);
+        // 新增页面
+        $this->pdf->AddPage();
+
+        // 设置字体
+        $this->pdf->SetFont('stsongstdlight', 'B', 24, '', true);
+        // 参数 1:w 2:h 3:内容 4:边框 5:是否换行 6:内容居中等
+        $this->pdf->Cell(0, 0, '财务收款收据', '0', 1, 'C');
+
+        $this->pdf->SetFont('stsongstdlight', '', 18, '', true);
+        $this->pdf->Cell(90, 30, 'TEL:888888', '0', 0, 'L');
+        // 颜色 RGB颜色代码
+        $this->pdf->setTextColor(255, 0, 0);
+        $this->pdf->Cell(90, 30, 'NO.20221215', '0', 0, 'R');
+
+        // 换行
+        $this->pdf->Ln();
+
+        // 重置颜色
+        $this->pdf->setTextColor();
+        $this->pdf->SetFont('stsongstdlight', '', 16, '', true);
+        $this->pdf->Cell(90, 15, '     客户名称:张三', '0', 0, 'L');
+        $this->pdf->Cell(90, 15, '日期:   2022年12月15日     ', '0', 1, 'R');
+
+        $h = 15;
+        // 绘表  表头
+        $this->pdf->Cell(40, $h, '规格及名称', '1', 0, 'C');
+        $this->pdf->Cell(15, $h, '单位', '1', 0, 'C');
+        $this->pdf->Cell(20, $h, '数量', '1', 0, 'C');
+        $this->pdf->Cell(25, $h, '单价', '1', 0, 'C');
+        $this->pdf->Cell(45, $h, '金额', '1', 0, 'C');
+        $this->pdf->Cell(35, $h, '备注', '1', 1, 'C');
+
+        $data = [
+            ['name'=>'项目一项目一项目一项目一项目一项目一项目一项目一项目一项目一项目一项目一项目一项目一项目一项目一项目一项目一项目一','unit'=>'件','num'=>13,'price'=>55.00,'money'=>'715.00','remark'=>''],
+            ['name'=>'项目二','unit'=>'件','num'=>13,'price'=>54.00,'money'=>'702.00','remark'=>''],
+            ['name'=>'项目三','unit'=>'件','num'=>19,'price'=>54.00,'money'=>'1026.00','remark'=>''],
+            ['name'=>'项目四','unit'=>'件','num'=>24,'price'=>54.00,'money'=>'1296.00','remark'=>''],
+        ];
+        // 内容
+        foreach ($data as $item) {
+            $this->pdf->Cell(40, $h, $item['name'], '1', 0, 'C');
+            $this->pdf->Cell(15, $h, $item['unit'], '1', 0, 'C');
+            $this->pdf->Cell(20, $h, $item['num'], '1', 0, 'C');
+            $this->pdf->Cell(25, $h, $item['price'], '1', 0, 'C');
+            $this->pdf->Cell(45, $h, $item['money'], '1', 0, 'C');
+            $this->pdf->Cell(35, $h, $item['remark'], '1', 1, 'C');
+        }
+        $total = sprintf('%.2F', array_sum(array_column($data, 'money')));
+        $this->pdf->Cell(100, $h, '合计金额:', 'LTB', 0, 'L');
+        $this->pdf->Cell(45, $h, $total, 'TBR', 0, 'R');
+        $this->pdf->Cell(35, $h, '', '1', 0, 'C');
+
+        $this->pdf->Output($fileName, 'F');
+
+    }
+
+    public function exportPdf($fileName)
+    {
+        $this->setPdfAttr();
+//        $this->pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
+
+        $this->pdf->SetCreator(PDF_CREATOR);
+        $this->pdf->SetAuthor('RoyalsZch');
+        $this->pdf->SetTitle('123');
+        $this->pdf->SetSubject('123pdf');
+        $this->pdf->SetKeywords('TCPDF, PDF, example, test, guide');
+
+// set default header data
+        $this->pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING, array(0,64,255), array(0,64,128));
+        $this->pdf->setFooterData(array(0, 64, 0), array(0, 64, 128));
+
+// set header and footer fonts
+        $this->pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
+        $this->pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
+
+// set default monospaced font
+        $this->pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
+
+// set margins
+        $this->pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
+        $this->pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
+        $this->pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
+
+// set auto page breaks
+        $this->pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
+
+// set image scale factor
+        $this->pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
+
+        $this->pdf->SetFont('stsongstdlight', '', 14, '', true);
+
+//        $this->pdf->Output('pdf'.'.pdf', 'D');
+        //        add a page
+        $this->pdf->AddPage();
+
+// 随便写HTML
+        $htmlUrl=app()->getRootPath() . 'public/upload/1.html';
+
+        $html=file_get_contents($htmlUrl);
+// output the HTML content
+        $this->pdf->writeHTML($html, true, false, true, false, '');
+//        $this->pdf->Image('https://gvrboxwit.obs.cn-east-2.myhuaweicloud.com:443/web/202303/202303301615200163657.png', 15, 140, 75, 113, 'JPG', 'http://www.tcpdf.org', '', true, 150, '', false, false, 1, false, false, false);
+
+// reset pointer to the last page
+        $this->pdf->lastPage();
+        //D是下载,I是在线写入
+        $this->pdf->Output($fileName, 'F');
+
+    }
+
+
     /**
      * 类型数据
      *

+ 208 - 61
application/common/service/ApproveInfoService.php

@@ -44,7 +44,7 @@ class ApproveInfoService
 
         // 5=出差申请,6=请假申请,7=用车申请 申请人信息 提交人和申请人不是同一人
         if (in_array($module, [CommonConstant::MODULE_5, CommonConstant::MODULE_6, CommonConstant::MODULE_7])) {
-            if($userid != $params['apply_user_id']){
+            if ($userid != $params['apply_user_id']) {
                 $apply_user = User::field('userid,department')
                     ->where('userid', $params['apply_user_id'])
                     ->find();
@@ -130,7 +130,7 @@ class ApproveInfoService
                 // 编辑审批申请
                 if ($module == CommonConstant::MODULE_9) {
                     // 9=合同呈批 不编辑合同编号
-                    unset($data['reason'],$data['type']);
+                    unset($data['reason'], $data['type']);
                 }
                 unset($data['order_no']);
                 $data['create_at'] = date('Y-m-d H:i:s');
@@ -152,7 +152,7 @@ class ApproveInfoService
                 self::create_approve_copy($copy_user, $info_id, 'create');
             }
 
-            user_log('approve',json_encode($result,JSON_UNESCAPED_UNICODE));
+            user_log('approve', json_encode($result, JSON_UNESCAPED_UNICODE));
             Db::commit();
         } catch (Exception $e) {
             Db::rollback();
@@ -162,16 +162,16 @@ class ApproveInfoService
 
         // 4=领用申请 增加冻结库存
         if ($module == CommonConstant::MODULE_4) {
-            list($goodsStockSave,$goodsStockLog,$redisStock) = self::composition_data($result['other']['data'],CommonConstant::MODULE_4,CommonConstant::STATUS_2);
+            list($goodsStockSave, $goodsStockLog, $redisStock) = self::composition_data($result['other']['data'], CommonConstant::MODULE_4, CommonConstant::STATUS_2);
             if ($goodsStockSave) {
                 // 批量更新商品库存
                 (new GoodsStock)->saveAll($goodsStockSave);
             }
-            if($redisStock){
+            if ($redisStock) {
                 // 库存缓存记录
                 $redis = new Redis(config('redis.'));
-                foreach ($redisStock as $key=>$val){
-                    $redis->inc($val['id'], $val['stock']);
+                foreach ($redisStock as $key => $value) {
+                    $redis->inc($value['id'], $value['stock']);
                 }
             }
         }
@@ -182,7 +182,7 @@ class ApproveInfoService
             $info->save(['reason' => $contract_no]);
             $models = CommonConstant::get_module_model_list();
             $model = $models[$module];
-            $model::where('id',$result['module_id'])->update(['reason' => $contract_no]);
+            $model::where('id', $result['module_id'])->update(['reason' => $contract_no]);
         }
 
         return true;
@@ -195,7 +195,7 @@ class ApproveInfoService
      * @param array $params
      * @param integer $info_id 申请ID
      * @param mixed $info 申请信息
-     * @param string $type 类型:create=申请,update=重新发起
+     * @param string $type 类型:create=申请,update=重新发起,edit:审批人修改 只有module=4才传edit
      * @return array {"module_id":"3","module_info":{"info_id":"97","reason":"联想显示屏","document":"https:\/\/dingding.hdlkeji.com\/upload\/20240105\/202401051706366597c69c8800d.jpeg","remark":"领用电脑显示屏"},"other":{"total_amount":"0.00","data":[{"info_id":"97","goods_id":50,"goods_category_first":49,"goods_category_id":50,"goods_no":"jx105","goods_name":"联想 S22E","goods_brand":"联想","total_price":"0.00","goods_stock":[{"id":98,"goods_id":50,"name":"S22E","price":0,"stock":"10"}]}]}}
      **/
     public static function create_module($module, $params, $info_id, $info, $type)
@@ -206,7 +206,7 @@ class ApproveInfoService
                 // 添加申购物品
                 $total_amount = 0;
                 if ($params['type'] == ApplyConstant::TYPE_1) {
-                    $other = self::create_goods($info_id, $module, $params['apply_goods'], $type);
+                    $other = self::create_goods($module, $params['apply_goods'], $info_id, $info, $type);
                     $total_amount = $other['total_amount'];
                 }
 
@@ -231,7 +231,7 @@ class ApproveInfoService
                 break;
             case CommonConstant::MODULE_3:
                 // 添加入库物品
-                $other = self::create_goods($info_id, $module, $params['stock_goods'], $type);
+                $other = self::create_goods($module, $params['stock_goods'], $info_id, $info, $type);
                 $total_amount = $other['total_amount'];
 
                 $data['info_id'] = $info_id;
@@ -242,7 +242,7 @@ class ApproveInfoService
                 break;
             case CommonConstant::MODULE_4:
                 // 添加领用物品
-                $other = self::create_goods($info_id, $module, $params['use_goods'], $type);
+                $other = self::create_goods($module, $params['use_goods'], $info_id, $info, $type);
 
                 $data['info_id'] = $info_id;
                 $data['reason'] = $params['reason'];
@@ -251,7 +251,7 @@ class ApproveInfoService
                 break;
             case CommonConstant::MODULE_5:
                 // 添加同行人员
-                $other = self::create_peer_user($info_id, $params['peer_user'], $type);
+                $other = self::create_peer_user($module, $params['peer_user'], $info_id, $type);
 
                 $data['info_id'] = $info_id;
                 $data['reason'] = $params['reason'];
@@ -303,8 +303,8 @@ class ApproveInfoService
                 $data['legal_opinion'] = $params['legal_opinion'];
                 $data['document'] = $params['document'];
                 $data['remark'] = $params['remark'];
-                if ($type == 'update') {
-                    unset($data['reason'],$data['type']);
+                if ($type != 'create') {
+                    unset($data['reason'], $data['type']);
                 }
                 break;
             case CommonConstant::MODULE_10:
@@ -330,16 +330,16 @@ class ApproveInfoService
                 $data['serial_number'] = $params['serial_number'];
                 break;
         }
-        if ($type == 'update') {
-            $info->module_info->save($data);
-            $module_id = $info->module_info->id;
-            $module_info = $info->module_info;
-        } else {
+        if ($type == 'create') {
             $models = CommonConstant::get_module_model_list();
             $model = $models[$module];
             $module_result = $model::create($data);
             $module_id = $module_result->id;
             $module_info = $data;
+        } else {
+            $info->module_info->save($data);
+            $module_id = $info->module_info->id;
+            $module_info = $info->module_info;
         }
         return compact("module_id", "module_info", "other");
     }
@@ -347,13 +347,14 @@ class ApproveInfoService
     /**
      * 添加申购商品/入库商品/领用商品
      *
-     * @param integer $info_id 申请ID
      * @param integer $module 模块类型
      * @param array $params 数据
-     * @param string $type 类型:create=申请,update=重新发起
+     * @param integer $info_id 申请ID
+     * @param mixed $info 申请信息
+     * @param string $type 类型:create=申请,update=重新发起,edit:审批人修改
      * @return array {"total_amount":"10","data":[{"info_id":"97","goods_id":50,"goods_category_first":49,"goods_category_id":50,"goods_no":"jx105","goods_name":"联想 S22E","goods_brand":"联想","total_price":"0.00","goods_stock":[{"id":98,"goods_id":50,"name":"S22E","price":0,"stock":"10"}]}]}
      **/
-    public static function create_goods($info_id, $module, $params, $type)
+    public static function create_goods($module, $params, $info_id, $info, $type)
     {
         if (!$params) {
             return [];
@@ -367,21 +368,6 @@ class ApproveInfoService
         $data = [];
         $total_amount = 0;
 
-        switch ($module) {
-            case CommonConstant::MODULE_1:
-                $model = ApproveApplyGoods::class;
-                break;
-            case CommonConstant::MODULE_3:
-                $model = ApproveStockGoods::class;
-                break;
-            case CommonConstant::MODULE_4:
-                $model = ApproveUseGoods::class;
-                break;
-        }
-        if ($type == 'update') {
-            $model::where('info_id', $info_id)->delete();
-        }
-
         foreach ($params as $value) {
             if ($value['flag'] == '2') {
                 // 批量导入
@@ -391,13 +377,170 @@ class ApproveInfoService
                 // 商品库选择
                 $goods_ids[$value['goods_id']] = $value;
             }
-            if($module == CommonConstant::MODULE_4 && $value['flag'] == '1'){
+            if ($module == CommonConstant::MODULE_4 && $value['flag'] == '1') {
                 // 商品库选择 TODO 这里修复 前端导入领用模块商品后,所返回的商品是过滤后的flag=3;然后,更改操作,对商品进行了规格库存修改,导致了flag=1
                 $value['flag'] = '3';
                 $goods_ids[$value['goods_id']] = $value;
             }
         }
 
+        switch ($module) {
+            case CommonConstant::MODULE_1:
+                $model = ApproveApplyGoods::class;
+                break;
+            case CommonConstant::MODULE_3:
+                $model = ApproveStockGoods::class;
+                break;
+            case CommonConstant::MODULE_4:
+                $model = ApproveUseGoods::class;
+                if($type == 'edit'){
+                    $old_goods_data = [];
+                    $old_goods_freeze_stock_data = []; // 旧数据的冻结库存
+                    foreach ($info['data'] as $key=>$val){
+                        $old_goods_data[$val['goods_id']] = $val;
+                        $goods_stock = $val['goods_stock_text'];
+                        foreach ($goods_stock as $k => $v) {
+                            $old_goods_freeze_stock_data[$v['id']] = [
+                                'id'=>$v['id'],
+                                'stock'=>$v['stock'],
+                            ];
+                        }
+                    }
+
+                    $goods_list = Goods::field('status,is_deleted,create_at', true)
+                        ->where('id', 'in', array_keys($goods_ids))
+                        ->where('is_deleted', CommonConstant::IS_DELETED_0)
+                        ->with([
+                            'goodsStock',
+                        ])
+                        ->select();
+                    $goods_object = $goods_list ? array_column($goods_list->toArray(), null, 'id') : [];
+                    $error_data = '';
+                    $apply_goods_data = [];
+                    $add_data = [];
+                    $del_ids = [];
+                    $goodsStockSave = [];
+                    $redisStock = [];
+                    foreach ($goods_ids as $key => $value) {
+                        if (array_key_exists($value['goods_id'], $goods_object)) {
+                            // 商品库里有该商品
+                            $goods_info = $goods_object[$value['goods_id']];
+                            $goods_stock_object = array_column($goods_info['goods_stock'], null, 'id');
+                            $goods_stock_data = [];
+                            $total_price = 0;
+                            foreach ($value['goods_stock'] as $val) {
+                                if (array_key_exists($val['id'], $goods_stock_object)) {
+                                    // 商品库里有该商品规格
+                                    $goods_stock_info = $goods_stock_object[$val['id']];
+                                    $total_stock = $goods_stock_info['stock'];
+                                    $stock = isset($val['stock']) && $val['stock'] > 0 ? $val['stock'] : 0;
+                                    $price = isset($val['price']) && $val['price'] > 0 ? $val['price'] : 0;
+                                    $freeze_stock = array_key_exists($val['id'],$old_goods_freeze_stock_data) ? $old_goods_freeze_stock_data[$val['id']]['stock'] : 0;
+                                    if ($stock > ($total_stock + $freeze_stock)) {
+                                        // 商品规格库存不足
+                                        $error_data .= $value['goods_name'] . '-' . $val['name'] . '的库存不足' . '、';
+                                    }
+                                    $total_price = bcadd($total_price, $stock * $price, 2);
+                                    $goods_stock_data[] = [
+                                        'id' => $val['id'],
+                                        'goods_id' => $goods_info['id'],
+                                        'name' => $val['name'],
+                                        'price' => $price,
+                                        'stock' => $stock,
+                                    ];
+
+                                    if($freeze_stock > 0){
+                                        if($stock>$freeze_stock){
+                                            // 扣除剩余库存 增加冻结库存
+                                            $save_stock = $stock-$freeze_stock;
+                                            $goodsStockSave[] = [
+                                                'id'=>$val['id'],
+                                                'stock'=>['dec',$save_stock],
+                                                'freeze_stock'=>['inc',$save_stock],
+                                            ];
+                                            $redisStock[] = [
+                                                'id' => 'dingtalk_stock_' . $info_id . '_' . $value['goods_id'] . '_' . $val['id'],
+                                                'exp'=> 'inc',
+                                                'stock' => $save_stock,
+                                            ];
+                                        }
+                                        if($stock<$freeze_stock){
+                                            // 增加剩余库存 扣除冻结库存
+                                            $save_stock = $freeze_stock - $stock;
+                                            $goodsStockSave[] = [
+                                                'id'=>$val['id'],
+                                                'stock'=>['inc',$save_stock],
+                                                'freeze_stock'=>['dec',$save_stock],
+                                            ];
+                                            $redisStock[] = [
+                                                'id' => 'dingtalk_stock_' . $info_id . '_' . $value['goods_id'] . '_' . $val['id'],
+                                                'exp'=> 'dec',
+                                                'stock' => $save_stock,
+                                            ];
+                                        }
+                                    }
+                                } else {
+                                    // 商品库里没有该商品规格
+                                    $error_data .= $value['goods_name'] . '-' . $val['name'] . '规格商品库不存在、';
+                                }
+                            }
+
+                            $total_amount = bcadd($total_amount, $total_price, 2);
+                            $goods_data = [
+                                'info_id' => $info_id,
+                                'goods_id' => $goods_info['id'],
+                                'goods_category_first' => $goods_info['goods_category_first'],
+                                'goods_category_id' => $goods_info['goods_category_id'],
+                                'goods_no' => $goods_info['goods_no'],
+                                'goods_name' => $goods_info['goods_name'],
+                                'goods_brand' => $goods_info['goods_brand'],
+                                'total_price' => $total_price,
+                                'goods_stock' => $goods_stock_data,
+                            ];
+                            $data[] = $goods_data;
+                            $goods_data['goods_stock'] = json_encode($goods_stock_data, JSON_UNESCAPED_UNICODE);
+                            if(array_key_exists($value['goods_id'],$old_goods_data)){
+                                // 修改
+                                $apply_goods_data[$value['goods_id']] = $goods_data;
+                            } else{
+                                // 添加
+                                $add_data[] = $goods_data;
+                            }
+                        } else {
+                            // 商品库里没有该商品
+                            $error_data .= $value['goods_name'] . '商品库不存在、';
+                        }
+                    }
+                    if ($error_data) {
+                        // 商品库选择的商品 商品库选择的商品的规格 在商品库没有匹配到 返回错误提示
+                        except($error_data);
+                    }
+
+                    foreach ($info['data'] as $index){
+                        if (array_key_exists($index['goods_id'], $apply_goods_data)) {
+                            // 更新
+                            $save_data = $apply_goods_data[$index['goods_id']];
+                            $index->save($save_data);
+                        } else {
+                            // 删除
+                            $del_ids[] = $index['id'];
+                        }
+                    }
+                    if ($add_data) {
+                        $model::insertAll($add_data);
+                    }
+                    if ($del_ids) {
+                        $model::where(['id' => ['IN', $del_ids]])->delete();
+                    }
+                }
+                return compact("total_amount", "data","goodsStockSave","redisStock");
+                break;
+        }
+
+        if ($type == 'update') {
+            $model::where('info_id', $info_id)->delete();
+        }
+
         // 商品库选择
         if ($goods_ids) {
             $goods_list = Goods::field('status,is_deleted,create_at', true)
@@ -426,7 +569,7 @@ class ApproveInfoService
                             $price = isset($val['price']) && $val['price'] > 0 ? $val['price'] : 0;
                             if ($stock > $total_stock) {
                                 // 商品规格库存不足
-                                $error_data .= $value['goods_name'] . '-' . $val['name'] . '的库存不足'. '、';
+                                $error_data .= $value['goods_name'] . '-' . $val['name'] . '的库存不足' . '、';
                             }
                             $total_price = bcadd($total_price, $stock * $price, 2);
                             $goods_stock_data[] = [
@@ -624,11 +767,12 @@ class ApproveInfoService
     /**
      * 添加同行人员
      *
-     * @param integer $info_id 申请ID
+     * @param integer $module 模块类型
      * @param array $params 同行人员数据
+     * @param integer $info_id 申请ID
      * @param string $type 类型:create=申请,update=重新发起
      **/
-    public static function create_peer_user($info_id, $params, $type)
+    public static function create_peer_user($module, $params, $info_id, $type)
     {
         if ($type == 'update') {
             ApproveEvectionPeerUser::where('info_id', $info_id)->delete();
@@ -664,12 +808,12 @@ class ApproveInfoService
      * @param string $type 类型:create=申请,update=重新发起
      * @param string $userid 发起人ID
      **/
-    public static function create_approve($approve_user,  $info_id, $type,$userid)
+    public static function create_approve($approve_user, $info_id, $type, $userid)
     {
         if ($type == 'update') {
             // 审批全部改为历史记录
-            Approve::where('info_id', $info_id)->where('status','in',[CommonConstant::STATUS_3,CommonConstant::STATUS_4])->update(['state' => CommonConstant::IS_WHO_1]);
-            Approve::where('info_id', $info_id)->where('status','in',[CommonConstant::STATUS_1,CommonConstant::STATUS_2])->update(['state' => CommonConstant::IS_WHO_0]);
+            Approve::where('info_id', $info_id)->where('status', 'in', [CommonConstant::STATUS_3, CommonConstant::STATUS_4])->update(['state' => CommonConstant::IS_WHO_1]);
+            Approve::where('info_id', $info_id)->where('status', 'in', [CommonConstant::STATUS_1, CommonConstant::STATUS_2])->update(['state' => CommonConstant::IS_WHO_0]);
         }
 
         $approve_data = [];
@@ -711,7 +855,8 @@ class ApproveInfoService
      * @param integer $info_id 申请ID
      * @param string $type 类型:create=申请,update=重新发起
      **/
-    public static function create_approve_copy($copy_user,$info_id, $type){
+    public static function create_approve_copy($copy_user, $info_id, $type)
+    {
         if ($type == 'update') {
             // 删除掉抄送
             ApproveCopy::where('info_id', $info_id)->delete();
@@ -740,10 +885,11 @@ class ApproveInfoService
      * 入库商品/领用商品组成数据
      *
      * @param mixed $goods 商品
-     * @param integer $module 模块
+     * @param integer $module 模块类型
      * @param integer $status 状态:2=审批中,3=审批同意,4=审批驳回
      **/
-    public static function composition_data($goods,$module,$status){
+    public static function composition_data($goods, $module, $status)
+    {
         $goodsStockSave = [];
         $goodsStockLog = [];
         $redisStock = [];
@@ -752,15 +898,15 @@ class ApproveInfoService
         foreach ($goods as $key => $val) {
             $goods_stock = $status == CommonConstant::STATUS_2 ? $val['goods_stock'] : $val['goods_stock_text'];
             foreach ($goods_stock as $k => $v) {
-                if($module == CommonConstant::MODULE_3){
+                if ($module == CommonConstant::MODULE_3) {
                     // 增加剩余库存
                     $goodsStockSave[] = [
                         'id' => $v['id'],
                         'stock' => ['inc', $v['stock']],
                     ];
                 }
-                if($module == CommonConstant::MODULE_4){
-                    if($status == CommonConstant::STATUS_2){
+                if ($module == CommonConstant::MODULE_4) {
+                    if ($status == CommonConstant::STATUS_2) {
                         // 扣除剩余库存 增加冻结库存
                         $goodsStockSave[] = [
                             'id' => $v['id'],
@@ -768,7 +914,7 @@ class ApproveInfoService
                             'freeze_stock' => ['inc', $v['stock']],
                         ];
                     }
-                    if($status == CommonConstant::STATUS_3){
+                    if ($status == CommonConstant::STATUS_3) {
                         // 扣除冻结库存
                         $goodsStockSave[] = [
                             'id' => $v['id'],
@@ -776,8 +922,8 @@ class ApproveInfoService
                         ];
                         $type = 1;
                     }
-                    if($status == CommonConstant::STATUS_4){
-                        // 扣除冻结库存 增加剩余库存
+                    if ($status == CommonConstant::STATUS_4) {
+                        // 增加剩余库存 扣除冻结库存
                         $goodsStockSave[] = [
                             'id' => $v['id'],
                             'stock' => ['inc', $v['stock']],
@@ -785,11 +931,11 @@ class ApproveInfoService
                         ];
                     }
                     $redisStock[] = [
-                        'id'=>'dingtalk_stock_'.$val['info_id'].'_'.$v['goods_id'].'_'.$v['id'],
-                        'stock'=>$v['stock'],
+                        'id' => 'dingtalk_stock_' . $val['info_id'] . '_' . $v['goods_id'] . '_' . $v['id'],
+                        'stock' => $v['stock'],
                     ];
                 }
-                if($status == CommonConstant::STATUS_3) {
+                if ($status == CommonConstant::STATUS_3) {
                     $goodsStockLog[] = [
                         'type' => $type,
                         'info_id' => $val['info_id'],
@@ -823,7 +969,7 @@ class ApproveInfoService
      * @param integer $length 查询数量
      * @param mixed $user 用户信息
      **/
-    public static function get_list($group, $module, $status, $search, $start_time, $end_time,$offset, $length, $user)
+    public static function get_list($group, $module, $status, $search, $start_time, $end_time, $offset, $length, $user)
     {
         if ($group == 'list') {
             if (!array_key_exists($module, CommonConstant::get_module_list())) {
@@ -930,7 +1076,7 @@ class ApproveInfoService
                 ];
                 $apply_user = $create_user;
                 if (in_array($module, [CommonConstant::MODULE_5, CommonConstant::MODULE_6, CommonConstant::MODULE_7])) {
-                    if($user['userid'] == $info['user_id']){
+                    if ($user['userid'] == $info['user_id']) {
                         // 当前是提交人
                         if ($info['user_id'] != $info['apply_user_id']) {
                             $apply_user_info = User::field('id,userid,name,avatar')
@@ -944,7 +1090,7 @@ class ApproveInfoService
                             ];
                         }
                     }
-                    if($user['userid'] == $info['apply_user_id']){
+                    if ($user['userid'] == $info['apply_user_id']) {
                         //  当前是申请人
                         if ($info['user_id'] != $info['apply_user_id']) {
                             $apply_user_info = User::field('id,userid,name,avatar')
@@ -1318,7 +1464,8 @@ class ApproveInfoService
     /**
      * 下载文件
      **/
-    public static function download($id){
+    public static function download($id)
+    {
 
     }
 

+ 22 - 7
application/common/service/ApproveService.php

@@ -423,7 +423,7 @@ class ApproveService
                 if (!$info->module_info) {
                     except(CommonConstant::get_module_list()[$params['module']] . '记录不存在或已删除');
                 }
-                $info = ApproveInfoService::get_item($info, 'edit');
+                $info = ApproveInfoService::get_item($info, $type);
 
                 self::edit($approve, $info, $params);
                 break;
@@ -567,8 +567,8 @@ class ApproveService
             if ($redisStock) {
                 // 库存缓存记录
                 $redis = new Redis(config('redis.'));
-                foreach ($redisStock as $key => $val) {
-                    $redis->dec($val['id'], $val['stock']);
+                foreach ($redisStock as $key => $value) {
+                    $redis->dec($value['id'], $value['stock']);
                 }
             }
         }
@@ -587,7 +587,6 @@ class ApproveService
     {
         $module = $info->module;
         $before = $info->toArray();
-
         $copy_user = $params['copy_user'] ? explode(',', $params['copy_user']) : [];
         $data = [
             'reason' => $params['reason'],
@@ -601,7 +600,7 @@ class ApproveService
         Db::startTrans();
         try {
             // 编辑对应模块
-            $result = ApproveInfoService::create_module($module, $params, $info->id, $info, 'update');
+            $result = ApproveInfoService::create_module($module, $params, $info->id, $info, $module == CommonConstant::MODULE_4 ? 'edit' : 'update');
 
             // 编辑抄送人
             ApproveInfoService::create_approve_copy($copy_user, $info->id, 'update');
@@ -620,9 +619,25 @@ class ApproveService
             except('出现错误:' . $e->getMessage(), 2, $e);
         }
 
-        // 4=领用申请 TODO 领领用商品库存扣除重新计算
+        // 4=领用申请 领用商品库存扣除重新计算
         if ($module == CommonConstant::MODULE_4) {
-
+            list($goodsStockSave, $redisStock) = [$result['other']['goodsStockSave'],$result['other']['redisStock']];
+            if ($goodsStockSave) {
+                // 批量更新商品库存
+                (new GoodsStock)->saveAll($goodsStockSave);
+            }
+            if ($redisStock) {
+                // 库存缓存记录
+                $redis = new Redis(config('redis.'));
+                foreach ($redisStock as $key => $value) {
+                    if($value['exp'] == 'inc'){
+                        $redis->inc($value['id'], $value['stock']);
+                    }
+                    if($value['exp'] == 'dec'){
+                        $redis->dec($value['id'], $value['stock']);
+                    }
+                }
+            }
         }
         return true;
     }