wugg 6 ay önce
ebeveyn
işleme
6d8a7a70bc

+ 1 - 0
app/admin/controller/Resignation.php

@@ -7,6 +7,7 @@ namespace app\admin\controller;
 use think\App;
 use app\admin\model\DataGroup;
 use think\facade\Validate;
+//离职交接
 class Resignation extends Base{
     public function __construct(App $app) {
         parent::__construct($app);

+ 42 - 1
app/common.php

@@ -111,6 +111,47 @@ if(!function_exists('UploadImg')){
     } catch (\think\exception\ValidateException $e) {
             throw new \think\Exception($e->getMessage());
     }
-    }
+  }
+}
+
+if(!function_exists('validate_invoice_info')){
+    function validate_invoice_info($data,&$return){
+        $return=["code"=>0,"校验通过"];
+        if (!isset($data['invoice_type'])||$data['invoice_type']==''){
+          $return['code']=1004;
+          $return['message']="发票类型不能为空";
+          return false;
+        }
 
+        if (in_array($data['invoice_type'],['fully_digitalized_special_electronic','fully_digitalized_normal_electronic'])){
+            if (!isset($data['invoice_total'])||$data['invoice_total']==''){
+                $return['code']=1004;
+                $return['message']='发票税前金额不能为空';
+                return false;
+            }
+        }else{
+             if (!isset($data['invoice_code'])||$data['invoice_code']==''){
+              $return['code']=1004;
+              $return['message']='发票代码不能为空';
+              return false;
+            }
+            if (!isset($data['invoice_subtotal'])||$data['invoice_subtotal']==''){
+                $return['code']=1004;
+                $return['message']='发票税后金额不能为空';
+                return false;
+            }
+        }
+      if (!isset($data['invoice_number'])||$data['invoice_number']==''){
+            $return['code']=1004;
+            $return['message']='发票号码不能为空';
+            return false;
+        }
+        if(in_array($data['invoice_type'],['normal','roll','toll','electronic','fully_digitalized_normal_electronic','fully_digitalized_special_electronic'])){
+            if(!isset($item['checkNumber'])||$item['checkNumber']==''){
+                $return['code']=1004;
+                $return['message']='校验码不能为空';
+                return false;
+            }
+		}
+    }
 }

+ 115 - 0
app/cxinv/controller/Invoice.php

@@ -0,0 +1,115 @@
+<?php
+
+
+namespace app\cxinv\controller;
+
+
+use app\cxinv\model\InvoiceOrder;
+use app\cxinv\model\InvoiceItem;
+use think\App;
+use think\facade\Validate;
+class Invoice extends Base{
+    public function __construct(App $app) {
+        parent::__construct($app);
+        $this->model = new \app\cxinv\model\Invoice();
+    }
+    public function List(){
+        $param= $this->request->param(["start"=>"","end"=>"","supplierNo"=>"","companyNo"=>"","status"=>"",
+        "invoice_number"=>"","invoice_type"=>"","page"=>1,"size"=>15,"apply_id"=>""],"post","trim");
+        $where=[];
+        if($param['start']!=="") $where[]=["createTime",">=",startTime($param['start'])];
+        if($param['end']!=="") $where[]=["createTime","<=",endTime($param['end'])];
+        if($param['supplierNo']!=="") $where[]=["supplierNo","like","%".$param['supplierNo']."%"];
+        if($param['companyNo']!=="") $where[]=["companyNo","like","%".$param['companyNo']."%"];
+        if($param['status']!=="") $where[]=["status","=",$param['status']];
+        if($param['invoice_number']!=="") $where[]=["invoice_number","like","%".$param['invoice_number']."%"];
+        if($param['invoice_type']!=="") $where[]=["invoice_type","=",$param['invoice_type']];
+        if($param['apply_id']!=="") $where[]=["apply_id","=",$param['apply_id']];
+        $list=$this->model->where($where)->order("id desc")->paginate(["page"=>$param['page'],"list_rows"=>$param['size']]);
+        return success("获取成功",["list"=>$list->items(),"count"=>$list->total()]);
+    }
+
+    public function create(){
+        $param= $this->request->param(["list"=>[]],"post","trim");
+        if (!is_array($param['list'])) return error("请传入正确参数");
+        $valid = Validate::rule([
+            "invoice_code|发票代码"=>"require|max:255",
+            "invoice_number|发票号码"=>"require|max:255",
+            "invoice_type|发票类型"=>"require|in:".explode(",",implode(",",array_keys(\app\cxinv\model\Invoice::$invoiceType))),
+            "invoice_total|发票税前金额"=>"float",
+            "open_date|开票日期"=>"require|date|dateFormat:Y-m-d",
+            "invoice_subtotal|发票税后金额"=>"float",
+            "check_code|校验码"=>"max:255"
+            ]);
+        foreach ($param['list'] as $k=>$v){
+            if(!$valid->check($v)) return error($valid->getError());
+            validate_invoice_info($v,$return);
+            if($return['code']!=0) return error($v['invoice_number'].":".$return['message']);
+            $param['list'][$k]['InvCode']=makeNo("FP",str_pad($k,4,"0",STR_PAD_RIGHT));
+            $param['list'][$k]['apply_id']=$this->uid;
+            $param['list'][$k]['apply_name']=$this->uname;
+        }
+        $this->model->saveAll($param['list']);
+        return success("添加成功");
+    }
+    //0待验证1待关联订单2待买方公司审核3待买方公司认证4 认证完成 5 发票取消 6 买方审核驳回 7 认证失败 8 验票失败 9 退票成功
+    public function status(){
+        $param= $this->request->param(["InvCode"=>"","status"=>"","remark"=>"",'ItemRemark'=>[]],"post","trim");
+        $valide=Validate::rule([
+            "InvCode|回票编号"=>"require|max:255",
+            "status|状态"=>"require|in:3,4,5,6,7,8"
+        ]);
+        if(!$valide->check($param)) return error($valide->getError());
+        $info=$this->model->where("InvCode",$param['InvCode'])->findOrEmpty();
+        if($info->isEmpty()) return error("回票编号不存在");
+        if($param['status']==3) $info->check_time=date('Y-m-d H:i:s');
+        if(in_array($info['invoice_type'],['normal','electronic','toll','roll']) && $param['status']==3){
+          $param['status']=4; //普票无需认证
+        }
+        $info->status=$param['status'];
+        $info->remark=$param['remark'];
+        $this->model->startTrans();
+        try{
+            $save=$info->save();
+            if(!$save) throw new \Exception("修改失败");
+            if($param['status']==3){
+                if (!empty($param['ItemRemark'])){
+                     (new InvoiceOrder)->saveAll($param['ItemRemark']);
+                    };
+            }
+             if(in_array($param['status'],[6,7])){
+                    InvoiceItem::rmInvoice($param['hpNo']);
+              }
+            $this->model->commit();
+        }catch (\Exception $e){
+            $this->model->rollback();
+            return error($e->getMessage());
+        }
+        return success("修改成功");
+    }
+
+    public function delete(){
+        $param= $this->request->param(["InvCode"=>""],"post","trim");
+        $valide=Validate::rule([
+            "InvCode|回票编号"=>"require|max:255"
+        ]);
+        if(!$valide->check($param)) return error($valide->getError());
+        $info=$this->model->where("InvCode",$param['InvCode'])->findOrEmpty();
+        if($info->isEmpty()) return error("回票编号不存在");
+        if($info->status!=3) return error("回票状态不允许删除");
+        $info->delete();
+       return success("删除成功");
+    }
+
+    public function info(){
+        $param= $this->request->param(["InvCode"=>""],"post","trim");
+        $valide=Validate::rule([
+            "InvCode|回票编号"=>"require|max:255"
+        ]);
+        if(!$valide->check($param)) return error($valide->getError());
+        $info=$this->model->where("InvCode",$param['InvCode'])->findOrEmpty();
+        if($info->isEmpty()) return error("回票编号不存在");
+        $info['items'] = InvoiceItem::where(['invoiceCode'=>$param['InvCode']])->select();
+        return success("获取成功",$info);
+    }
+}

+ 297 - 0
app/cxinv/controller/InvoiceItem.php

@@ -0,0 +1,297 @@
+<?php
+
+
+namespace app\cxinv\controller;
+
+use app\cxinv\model\InvoiceGood;
+use app\cxinv\model\InvoiceOrder;
+use app\cxinv\model\OrderCategory;
+use app\cxinv\model\PayInfo;
+use think\App;
+use think\facade\Validate;
+class InvoiceItem extends Base{
+    public function __construct(App $app) {
+     #  $this->novalidate = ["*"];
+        parent::__construct($app);
+    }
+    //查询
+    public function cgdListByPayNo(){
+        $param = $this->request->param(["payNo"=>"","merge_code"=>"","inv_good_name"=>"",'good_name'=>''],"post","trim");
+        $where=[["a.status","=",1],["a.is_del","=",0]];
+        if($param["payNo"]!=="") $where[]=["a.payNo","=",$param["payNo"]];
+        if($param["merge_code"]!=="") $where[]=["c.merge_code","like","%{$param['merge_code']}%"];
+        if($param["inv_good_name"]!=="") $where[]=["c.inv_good_name","like","%{$param["inv_good_name"]}%"];
+        if($param["good_name"]!=="") $where[]=["b.goodName","like","%{$param["good_name"]}%"];
+        $list = PayInfo::alias('a')
+                ->join('cgd_info b','a.cgdNo=b.sequenceNo',"left")
+                ->join('order_category c','b.sequenceNo=c.code and b.goodNo=c.spuCode and c.order_type=2',"left")
+                ->where($where)
+                ->field("b.sequenceNo,b.goodNo,b.goodName,(b.goodNum-thNum) as goodNum,b.goodPrice,b.totalPrice,
+                c.merge_code,c.cat_code,c.cat_name,c.short_name,c.tax,c.inv_good_name")
+                ->select();
+        $list->each(function (&$item){
+            $item['balance_amount']= bcsub($item['totalPrice'],InvoiceOrder::getInvoiceOrderTotalFee($item['sequenceNo']),2);
+        });
+         return  success('获取成功',$list);
+    }
+    //查询
+    public function qrdListByInvNo(){
+        $param = $this->request->param(["invNo"=>"","merge_code"=>"","inv_good_name"=>""],"post","trim");
+        $where=[["a.goodNum",">",0],["a.is_del","=",0]];
+        if($param["invNo"]!=="") $where[]=["a.invNo","=",$param["invNo"]];
+        if($param["merge_code"]!=="") $where[]=["c.merge_code","=",$param["merge_code"]];
+        if($param["inv_good_name"]!=="") $where[]=["c.inv_good_name","like","%{$param["inv_good_name"]}%"];
+        $list= InvoiceGood::alias('a')
+                ->join('qrd_info b','a.orderCode=b.sequenceNo','left')
+                ->join('order_category c','b.sequenceNo=c.code and b.goodNo=c.spuCode and  c.order_type=1','left')
+                ->where($where)
+                ->field("b.sequenceNo,b.goodNo,b.goodName,a.goodNum,a.goodPrice,a.totalPrice,
+                                c.merge_code,c.cat_code,c.cat_name,c.short_name,c.tax,c.inv_good_name")
+            ->select();
+          $list->each(function (&$item){
+            $item['balance_amount']= bcsub($item['totalPrice'],InvoiceOrder::getInvoiceOrderTotalFee($item['sequenceNo']),2);
+        });
+         return  success('获取成功',$list);
+    }
+    //添加发票明细对应关系
+    public function create(){
+        $param = $this->request->param(["itemId"=>"","orderArr"=>[]],"post","trim");
+        $valid=Validate::rule([
+            'itemId|发票明细id' => 'require|number|gt:0',
+            'orderArr|订单信息' => 'require|array',
+        ]);
+        if(!$valid->check($param)) return  error($valid->getError());
+        $valids=Validate::rule([
+            'code|订单号' => 'require|max:255',
+            'spuCode|商品编码' => 'require|max:255',
+            'good_name|商品名称' => 'require|max:255',
+            'num|数量' => 'require|float|gt:0',
+            'good_price|商品价格' => 'require|float|gt:0',
+            'total_amount|总金额' => 'require|float|gt:0',
+            'remark|备注' => 'max:255',
+        ]);
+        $item = \app\admin\model\InvoiceItem::where(['id'=>$param["itemId"]])->findOrEmpty();
+        if($item->isEmpty()) return  error("发票明细不存在");
+        $save=[];
+        $amount = $item['balance_amount'];
+        foreach ($param["orderArr"] as $k=>$v){
+            if(!$valids->check($v)) return  error($valids->getError());
+            $taxInfo = OrderCategory::where(['code'=>$v['code'],'spuCode'=>$v['spuCode']])->findOrEmpty();
+            if($taxInfo->isEmpty()) return  error("商品编码{$v['spuCode']}税目信息不存在");
+            $balance="0";
+            if($amount<$v['total_amount']){
+                $balance = bcsub($v['total_amount'],$amount,2);
+                $amount="0";
+            }else{
+                $balance = "0";
+                $amount = bcsub($amount,$v['total_amount'],2);
+            }
+            $diff=[];
+            $tax_diff=1;
+            $cat_diff=1;
+            if(str_replace("%","",$item['tax'])!=$taxInfo['tax']){
+                $diff["tax"] = [
+                    "inv_tax"=>str_replace('%','',$item['tax']),
+                    "order_tax"=>$taxInfo['tax'],
+                ];
+                $tax_diff=2;
+            }
+            if($item['cat_code']!=$taxInfo['merge_code']){
+                $diff["cat_code"] = [
+                    "inv_cat_code"=>$item['cat_code'],
+                    "order_cat_code"=>$taxInfo['merge_code'],
+                ];
+                $cat_diff=2;
+            }
+            $save[]=[
+                "itemId"=>$param["itemId"],
+                "code"=>$v["code"],
+                "spuCode"=>$v["spuCode"],
+                "good_name"=>$v['good_name'],
+                "num"=>$v["num"],
+                "good_price"=>$v["good_price"],
+                "total_amount"=>$v["total_amount"],
+                "tax_diff"=> $tax_diff,
+                "cat_diff"=>$cat_diff,
+                "balance_amount"=>$balance,
+                "diff_info"=>$diff,
+                "status"=>$balance>0?2:1,
+                "remark"=>$v["remark"],
+                "apply_id"=>$this->uid,
+                "apply_name"=>$this->uname
+            ];
+        }
+        $item->startTrans();
+        try{
+
+            $res=(new \app\admin\model\InvoiceOrder)->saveAll($save);
+            if($res){
+                $item->balance_amount = $amount;
+                $item->status = $amount>0?2:1; //已关联数据 $amont=0 2 还有余额则为1
+                $item->save();
+            }else throw new \Exception("添加失败");
+            $item->commit();
+        }catch (\Exception $e){
+            $item->rollback();
+             return  error($e->getMessage());
+       }
+        return  success('添加成功');
+    }
+    //删除发票明细对应关系
+    public function delete(){
+        $param = $this->request->param(["id"=>""],"post","trim");
+        $valid=Validate::rule([
+            'id|发票明细对应id' => 'require|number|gt:0',
+        ]);
+        if(!$valid->check($param)) return  error($valid->getError());
+        $info = \app\admin\model\InvoiceOrder::where(['id'=>$param["id"]])->findOrEmpty();
+        if($info->isEmpty()) return  error("发票明细对应关系不存在");
+        $item = \app\admin\model\InvoiceItem::where(['id'=>$info['itemId']])->findOrEmpty();
+        if($item->isEmpty()) return  error("发票明细不存在");
+        InvoiceOrder::startTrans();
+        try{
+            $res = $info->delete();
+            if($res){
+                $count = \app\admin\model\InvoiceOrder::where(['itemId'=>$info['itemId']])->count();
+                $item->balance_amount = bcadd($item['balance_amount'],bcsub($info['total_amount'],$info['balance_amount'],2),2);
+                $item->status = ($count==0) ? 0 : ($item->balance_amount==$item->total_amount?0:($item->balance_amount>0?2:1));
+                $item->save();
+            }else throw new \Exception("删除失败");
+            InvoiceOrder::commit();
+        }catch (\Exception $e){
+            InvoiceOrder::rollback();
+             return  error($e->getMessage());
+        }
+         return  success('删除成功');
+
+    }
+
+    public function addRemark(){
+        $param = $this->request->param(['id'=>''],'post','trim');
+        $valid=Validate::rule([
+            'id|发票明细对应id' => 'require|number|gt:0',
+            'remark|备注' => 'require|max:255',
+        ]);
+        if(!$valid->check($param)) return  error($valid->getError());
+        $info = \app\admin\model\InvoiceOrder::where(['id'=>$param['id']])->findOrEmpty();
+        if($info->isEmpty()) return  error('发票明细对应关系不存在');
+        $item = \app\admin\model\InvoiceItem::where(['id'=>$info['itemId']])->findOrEmpty();
+        if($item->isEmpty()) return  error('发票明细不存在');
+        $info->startTrans();
+        try{
+            $info->remark = $param['remark'] ?? '';
+            $res = $info->save();
+            if($res==false)throw new \Exception('备注添加失败');
+            $info->commit();
+        }catch (\Exception $e){
+            $info->rollback();
+            return  error($e->getMessage());
+        }
+         return  success('备注添加成功');
+
+    }
+
+    public function getListByCode(){
+        $param=$this->request->param(["code"=>"","status"=>"","size"=>100]);
+        $where=[];
+        if($param["code"]!=="") $where[]=["invoiceCode","=",$param["code"]];
+        if($param["status"]!=="") $where[]=["status","=",$param["status"]];
+        $list= \app\admin\model\InvoiceItem::with(["OrderInfo"])
+            ->where($where)
+            ->limit($param["size"])
+            ->select();
+         return  success('获取成功',$list);
+    }
+
+    public function importOrder(){
+        $param=$this->request->param([ "order_type"=>"","list"=>[]],"post","trim");
+        $valid = Validate::rule([
+            'order_type|订单类型' => 'require|in:1,2',
+            'list|发票明细' => 'require|array',
+        ]);
+        if(!$valid->check($param)) return  error($valid->getError());
+        $listValid = Validate::rule([
+            "itemId|发票明细ID"=>'require|number|gt:0',
+            'code|订单编码' => 'require|max:20',
+            'num|数量' => 'float|egt:0',
+            'good_price|商品价格' => 'float|egt:0',
+            'total_amount|总金额' => 'require|float|gt:0',
+            'remark|备注' =>'max:255',
+        ]);
+        $itemArr= \app\admin\model\InvoiceItem::whereIn('id',array_column($param['list'],"itemId"))->column("id,invoiceCode,order_type,balance_amount,cat_code,tax","id");
+        $orderInfo=[];
+        $orderItem=[];
+        foreach($param["list"] as $v){
+            if(!$listValid->check($v)) return  error($listValid->getError());
+            if(!isset($itemArr[$v['itemId']])) return  error("发票明细不存在");
+            if(!isset($orderInfo[$itemArr[$v['itemId']]['invoiceCode'].$v["code"]])){
+                  $orderInfo[$itemArr[$v['itemId']]['invoiceCode'].$v['code']]= \app\admin\model\InvoiceOrder::getOrderInfo( $itemArr[$v['itemId']]['invoiceCode'],$v['code'],$param['order_type']);
+            }
+
+             if($orderInfo[$itemArr[$v['itemId']]['invoiceCode'].$v['code']]->isEmpty()) return  error("发票{$itemArr[$v['itemId']]['invoiceCode']}关联订单{$v['code']}信息不存在");
+            if($orderInfo[$itemArr[$v['itemId']]['invoiceCode'].$v['code']]['balance_amount']<$v['total_amount']) return  error("{$v["code"]}订单金额不足");
+            if($itemArr[$v['itemId']]['balance_amount']<=0) return  error("发票明细ID {$v["itemId"]} 可关联金额不足");
+            if($orderInfo[$itemArr[$v['itemId']]['invoiceCode'].$v['code']]['merge_code']=="") return  error("{$v["code"]}订单税目信息不存在");
+             if($itemArr[$v['itemId']]['balance_amount']<$v['total_amount']){
+                $balance = bcsub($v['total_amount'],$itemArr[$v['itemId']]['balance_amount'],2);
+                $itemArr[$v['itemId']]['balance_amount']='0';
+            }else{
+                $balance = '0';
+                $itemArr[$v['itemId']]['balance_amount'] = bcsub($itemArr[$v['itemId']]['balance_amount'],$v['total_amount'],2);
+            }
+            $orderInfo[$itemArr[$v['itemId']]['invoiceCode'].$v['code']]['balance_amount'] =
+            bcsub($orderInfo[$itemArr[$v['itemId']]['invoiceCode'].$v['code']]['balance_amount'],bcsub($v['total_amount'],$balance,2),2);
+            $tax = $orderInfo[$itemArr[$v['itemId']]['invoiceCode'].$v['code']]['tax'];
+            $merge_code = $orderInfo[$itemArr[$v['itemId']]['invoiceCode'].$v['code']]['merge_code'];
+            $diff=[];
+            $tax_diff=1;
+            $cat_diff=1;
+            if(str_replace('%','',$itemArr[$v['itemId']]['tax'])!=$tax ){
+                $diff['tax'] = [
+                    'inv_tax'=>str_replace('%','',$itemArr[$v['itemId']]['tax']),
+                    'order_tax'=>$tax ,
+                ];
+                $tax_diff=2;
+            }
+            if($itemArr[$v['itemId']]['cat_code']!=$merge_code){
+                $diff['cat_code'] = [
+                    'inv_cat_code'=>$itemArr[$v['itemId']]['cat_code'],
+                    'order_cat_code'=>$merge_code,
+                ];
+                $cat_diff=2;
+            }
+            $itemArr[$v['itemId']]['status'] = ($itemArr[$v['itemId']]['balance_amount']>0?2:1);
+            $orderItem[]=[
+                'itemId'=>$v['itemId'],
+                'code'=>$v['code'],
+                'spuCode'=>$orderInfo[$itemArr[$v['itemId']]['invoiceCode'].$v['code']]['goodNo'],
+                'good_name'=>$orderInfo[$itemArr[$v['itemId']]['invoiceCode'].$v['code']]['goodName'],
+                'num'=>$v['num']??0,
+                'good_price'=>$v['good_price']??0,
+                'total_amount'=>$v['total_amount'],
+                'tax_diff'=> $tax_diff,
+                'cat_diff'=>$cat_diff,
+                'balance_amount'=>$balance,
+                'diff_info'=>$diff,
+                'status'=>$balance>0?2:1,
+                'remark'=>$v['remark'],
+                'apply_id'=>$this->uid,
+                'apply_name'=>$this->uname
+            ];
+        }
+         $orderItemModel = new \app\admin\model\InvoiceItem();
+        $orderItemModel->startTrans();
+        try{
+           $num=$orderItemModel->saveAll(array_values($itemArr));
+            if(count($num)>0){
+                (new InvoiceOrder())->saveAll($orderItem);
+            }else throw new \Exception("导入失败");
+        }catch (\Exception $e){
+            $orderItemModel->rollback();
+             return  error($e->getMessage());
+        }
+        $orderItemModel->commit();
+         return  success("导入成功");
+    }
+
+}

+ 80 - 0
app/cxinv/controller/Payment.php

@@ -0,0 +1,80 @@
+<?php
+
+
+namespace app\cxinv\controller;
+
+
+use app\cxinv\model\CgdInfo;use app\cxinv\model\OrderCategory;use app\cxinv\model\Pay;use app\cxinv\model\PayInfo;use app\user\model\AccountCompany;use app\user\model\Business;use app\user\model\Supplier;use think\App;use think\facade\Validate;
+class Payment extends Base{
+    public function __construct(App $app) {
+        parent::__construct($app);
+        $this->model = new Pay();
+    }
+
+    public function create(){
+        $params = $this->request->param(['cids'=>[]],"post","trim");
+        $valid=Validate::rule(["cids|采购单id集合"=>"require|array"]);
+        if ($valid->check($params)===false) return error($valid->getError());
+        $cgdlist = CgdInfo::whereIn("id",$params['cids'])
+        ->field("sequenceNo,supplierNo,totalPrice,companyNo")->select();
+        if($cgdlist->isEmpty())return error("采购单数据不能为空");
+        $supplier =array_unique($cgdlist->column('supplierNo')) ;
+        $company = array_unique($cgdlist->column("companyNo"));
+        if (count($supplier)>1) return error("采购单数据供应商不一致");
+        if (count($company)>1) return error("采购单数据业务公司不一致");
+        if($this->level==2){
+            $isBool = AccountCompany::SupplierHasAcount($supplier[0]);
+            if ($isBool) return error('该供应商已经开通账号,不允许当前账号操作');
+        }
+        $orderCate = OrderCategory::where(['code'=>$cgdlist->column('sequenceNo')])->column("*","code");
+        if(empty($orderCate)) return error("采购单数据商品进项类目不存在");
+        $payNo=makeNo("PAY");
+        $payinfo = [];
+        $totalPrice='0';
+        foreach ($cgdlist as $k=>$v){
+            $temp= [
+                "cgdNo"=>$v['sequenceNo'],
+                "total_fee"=>$v['totalPrice'],
+                "wapy_fee"=>$v['totalPrice'],
+                "winv_fee"=>$v['totalPrice'],
+                "payNo"=>$payNo
+                ];
+            if (!isset($orderCate[$v['sequenceNo']])) return error("采购单{$v['sequenceNo']}数据商品进项类目不存在");
+            if($v['status']==1) return error("采购单{$v['sequenceNo']}数据已付款");
+            if($v['status']==2) return error("采购单{$v['sequenceNo']}数据不结算");
+            $payinfo[]=$temp;
+            $totalPrice+=$v['totalPrice'];
+        }
+        $paydata=[
+                'payNo'=>$payNo,
+                'apply_id'=>$this->uid,
+                'apply_name'=>$this->uname,
+                'total_fee'=>$totalPrice,
+                'is_comon'=>0,
+                'supplierNo'=>$supplier[0],
+                'supplierName'=>Supplier::where('code',$supplier[0])->value("name",''),
+                'companyNo'=>$company[0],
+                'companyName'=>Business::where("companyNo",$company[0])->value("company",""),
+                'wpay_fee'=>$totalPrice,
+                'apay_fee'=>0,
+                'ainv_fee'=>$totalPrice,
+                'winv_fee'=>0,
+                'remark'=>'',
+                'status'=>1,
+            ];
+        $this->model->startTrans();
+        try{
+            $pay=$this->model->save($paydata);
+            if(!$pay) throw new \Exception("创建付款单失败");
+            $paysace =(new PayInfo())->saveAll($payinfo);
+            if(!$paysace) throw new \Exception("创建付款单详情失败");
+            $up= CgdInfo::whereIn("sequenceNo",array_column($payinfo,"cgdNo"))->update(['status'=>1]);
+            if(!$up) throw new \Exception("更新采购单状态失败");
+            $this->model->commit();
+        }catch (\Exception $e){
+            $this->model->rollback();
+            return error($e->getMessage());
+        }
+         return success('创建付款单成功');
+    }
+}

+ 57 - 0
app/cxinv/model/Invoice.php

@@ -0,0 +1,57 @@
+<?php
+
+
+namespace app\cxinv\model;
+
+
+use think\Model;use think\model\concern\SoftDelete;
+class Invoice extends Base{
+    use SoftDelete;
+    protected $createTime="createTime";
+    protected $updateTime="updateTime";
+    protected $deleteTime="delete_time";
+
+    public static $invoiceType=[
+		            "special"=>"增值税专用发票",
+		             "normal"=>"增值税普通发票",
+		             "roll"=>"增值税普通发票(卷式)",
+		             "special_electronic"=>"增值税电子专用发票",
+		             "electronic"=>"增值税电子普通发票",
+		             "blockchain_electronic"=>"区块链电子发票",
+		             "toll"=>"增值税电子普通发票(通行费)",
+		             "fully_digitalized_special_electronic"=>"全电专用发票",
+		             "fully_digitalized_normal_electronic"=>"全电普通发票",
+                    ];
+
+    public static function onAfterWrite(Model $model) : void{
+         $change = $model->getChangedData();
+         if (isset($change['status'])){
+             if($change['status']==4){
+                $itemid= InvoiceItem::where(['invoiceCode'=>$model->InvCode,'status'=>[1,2]])->column("id");
+                 if(!empty($itemid)){
+                    $invo= InvoiceOrder::whereIn('itemId',$itemid)->where(['status'=>[1,2]])->column("code,balance_amount,total_amount");
+                    if(!empty($invo)){
+                        foreach ($invo as $key=>$val){
+                            $cgdinfo = CgdInfo::where(['sequenceNo'=>$val['code']])->findOrEmpty();
+                             if(!$cgdinfo->isEmpty()){
+                                 $cgdinfo->ainv_fee = bcadd($cgdinfo->winv_fee,bcsub($val['total_amount'],$val['balance_amount'],2),2);
+                                 $cgdinfo->inv_status = $cgdinfo->winv_fee==0 && $cgdinfo->ainv_fee==$cgdinfo->totalPrice ?3:2;
+                                 $cgdinfo->save();
+                             }
+                             $payinfo = PayInfo::where(['cgdNo'=>$val['code'],'status'=>1,'is_del'=>0])->findOrEmpty();
+                             if(!$payinfo->isEmpty()){
+                               $pay= Pay::where(['payNo'=>$payinfo->payNo,'status'=>2])->findOrEmpty();
+                               if(!$pay->isEmpty()){
+                                   $pay->inv_fee=bcsub($pay->winv_fee,bcsub($val['total_amount'],$val['balance_amount'],2),2);
+                                   $pay->ainv_fee = bcadd($pay->inv_fee,bcsub($val['total_amount'],$val['balance_amount'],2),2);
+                                   $pay->inv_status = $pay->winv_fee==0 && $pay->inv_fee==0?3:2;
+                                   $pay->save();
+                               }
+                             }
+                        }
+                    }
+                 }
+             }
+         }
+    }
+}

+ 2 - 13
app/cxinv/model/InvoiceInfo.php

@@ -8,24 +8,13 @@ class InvoiceInfo extends Base
         'id'  =>'bigint',//
         'hpNo'  =>'varchar',//回票编号
         'payNo'  =>'varchar',//对账编号
-        'type'  =>'varchar',//special: 增值税专用发票
-
-normal: 增值税普通发票
-
-electronic: 增值税电子普通发票
-
-special_electronic:增值税电子专用发票
-
-toll:增值税电子普通发票(通行费)
-
-roll:增值税普通发票(卷票)
+        'type'  =>'varchar',//special: 增值税专用发票normal: 增值税普通发票electronic: 增值税电子普通发票special_electronic:增值税电子专用发票toll:增值税电子普通发票(通行费)roll:增值税普通发票(卷票)
         'title'  =>'varchar',//增值税发票title
         'serial_number'  =>'varchar',//发票联次
         'attribution'  =>'varchar',//发票归属地
         'supervision_seal'  =>'varchar',//发票监制章
         'number'  =>'varchar',//发票号码。
-        'code'  =>'varchar',//	
-发票代码
+        'code'  =>'varchar',//	发票代码
         'check_code'  =>'varchar',//发票校验码
         'print_code'  =>'varchar',//机打代码
         'machine_number'  =>'varchar',//机器编号

+ 94 - 0
app/cxinv/model/InvoiceItem.php

@@ -0,0 +1,94 @@
+<?php
+
+
+namespace app\cxinv\model;
+
+
+use think\facade\Log;
+use think\model\concern\SoftDelete;
+class InvoiceItem extends Base{
+    use SoftDelete;
+    protected $createTime="createTime";
+    protected $updateTime="updateTime";
+    protected $autoWriteTimestamp=true;
+    protected $deleteTime="delete_time";
+
+    public function OrderInfo(){
+        return $this->hasMany(InvoiceOrder::class,"itemId","id")->whereIn('status', [1, 2]);
+    }
+
+    public static function getNumAttr($val){
+        return  strval(floatval($val));
+    }
+
+    public static function setNumAttr($val){
+        return  floatval($val);
+    }
+    public static function onAfterUpdate($model){
+        $code=$model->invoiceCode;
+        $orderType=$model->order_type;
+        $change = $model->getChangedData();
+        Log::info("修改发票明细状态:".json_encode($change,JSON_UNESCAPED_UNICODE));
+        Log::info("跟后数据:".json_encode($model->toArray(),JSON_UNESCAPED_UNICODE));
+        if(isset($change['status'])&&in_array($change["status"],[0,1,2])){
+             Log::info('跟后数据:'.json_encode($model->toArray(),JSON_UNESCAPED_UNICODE));
+             $num = self::where(['invoiceCode'=>$code,'order_type'=>$orderType,'status'=>0])->count();
+//                if($orderType==1){
+//                      $info= InvoicePool::where(['invNo'=>$code,'is_del'=>0])->findOrEmpty();
+//                      if(!$info->isEmpty()){
+//                          if($num==0 && $info->status==10){
+//                               $info->status=11;
+//                          }
+//                          if($num>0 && $info->status==11){
+//                              $info->status=10;
+//                          }
+//                          $info->save();
+//                      }
+//                }
+                if($orderType==2){
+                    $info= Invoice::where(['InvCode'=>$code,"status"=>1])->findOrEmpty();
+                     Log::info('跟后数据:'.json_encode( $info->toArray(),JSON_UNESCAPED_UNICODE));
+                    if(!$info->isEmpty()){
+                        if ($num==0){
+                              $info->status=2;
+                              $info->save();
+                        }
+                    }
+                }
+        }
+    }
+
+    public static function rmInvoice($code,$orderType=2){
+        $items = self::where(['invoiceCode'=>$code,'order_type'=>$orderType])->select();
+       if(!empty($items)){
+            $orderItems=InvoiceOrder::whereIn('itemId',$items->column('id'))->select();
+            if(!empty($orderItems)){
+               InvoiceOrder::whereIn('itemId',$items->column('id'))->save(["status"=>3]);
+            }
+            self::where(['invoiceCode'=>$code,'order_type'=>$orderType])->save(["status"=>3]);
+       }
+    }
+
+    public static function CopyItem($invNo,$hpNo){
+        $info = self::where(['invoiceCode'=>$invNo,'order_type'=>1])->select();
+        if(!$info->isEmpty()){
+            foreach($info as $item){
+                $temp = $item->toArray();
+                $temp['invoiceCode']=$hpNo;
+                $temp['order_type']=2;
+                unset($temp['id']);
+               $up = self::create($temp);
+               if($up->id>0){
+                   $orders = InvoiceOrder::where(['itemId'=>$item->id,"status"=>[1,2]])->select();
+                   if(!$orders->isEmpty()){
+                      InvoiceOrder::create(array_map(function ($items)use ($up){
+                          $items['itemId']=$up->id;
+                          unset($items['id']);
+                          return $items;
+                      },$orders->toArray()));
+                   }
+               }
+            }
+        }
+    }
+}

+ 135 - 0
app/cxinv/model/InvoiceOrder.php

@@ -0,0 +1,135 @@
+<?php
+
+
+namespace app\cxinv\model;
+
+
+use think\facade\Log;
+use think\model\concern\SoftDelete;
+class InvoiceOrder extends Base{
+
+    use SoftDelete;
+    protected $createTime='createTime';
+    protected $updateTime='updateTime';
+    protected $autoWriteTimestamp=true;
+    protected $deleteTime='delete_time';
+    protected $append=["merge_code","short_name","cat_code","cat_name","tax","inv_good_name"];
+    public function ItemInfo(){
+        return $this->hasOne('InvoiceItem','itemId','id');
+    }
+    public static function getInvoiceOrderTotalFee($code){
+        $banance =  (new InvoiceOrder)->where(['code'=>$code,'status'=>[1,2]])->field('sum(ifnull(total_amount-balance_amount,0)) as total_amount')->find();
+        return $banance['total_amount']??"0";
+    }
+
+    public function getMergeCodeAttr($value,$data){
+        return OrderCategory::where(['code'=>$data['code'],'spuCode'=>$data['spuCode']])->value("merge_code","");
+    }
+    public function getShortNameAttr($value,$data){
+        return OrderCategory::where(['code'=>$data['code'],'spuCode'=>$data['spuCode']])->value("short_name","");
+    }
+    public function getCatCodeAttr($value,$data){
+        return OrderCategory::where(['code'=>$data['code'],'spuCode'=>$data['spuCode']])->value("cat_code","");
+    }
+    public function getCatNameAttr($value,$data){
+        return OrderCategory::where(['code'=>$data['code'],'spuCode'=>$data['spuCode']])->value("cat_name","");
+    }
+
+    public function getTaxAttr($value,$data){
+        return OrderCategory::where(['code'=>$data['code'],'spuCode'=>$data['spuCode']])->value("tax","");
+    }
+    public function getInvGoodNameAttr($value,$data){
+        return OrderCategory::where(['code'=>$data['code'],'spuCode'=>$data['spuCode']])->value("inv_good_name","");
+    }
+     public static function getNumAttr($val){
+        return  strval(floatval($val));
+    }
+
+    public static function setDiffInfoAttr($val){
+        return  json_encode($val,JSON_UNESCAPED_UNICODE);
+    }
+    public static function getDiffInfoAttr($val){
+        return  json_decode($val,true);
+    }
+
+    public static function getOrderInfo($code,$orderCode,$type){
+       if($type==1){
+           $info=InvoiceGood::alias('a')
+                ->join('qrd_info b','a.orderCode=b.sequenceNo','left')
+                ->join('order_category c','b.sequenceNo=c.code and b.goodNo=c.spuCode and  c.order_type=1','left')
+                ->where(["invNo"=>$code,"a.orderCode"=>$orderCode])
+                ->where([['a.goodNum','>',0],['a.is_del','=',0]])
+                ->field('b.sequenceNo,b.goodNo,b.goodName,a.goodNum,a.goodPrice,a.totalPrice,c.merge_code,c.cat_code,c.cat_name,c.short_name,c.tax,c.inv_good_name')
+                ->findOrEmpty();
+          } else{
+           $payNo = PayInvoice::where(['hpNo'=>$code])->value("payNo","");
+           $info = PayInfo::alias('a')
+                ->join('cgd_info b','a.cgdNo=b.sequenceNo','left')
+                ->join('order_category c','b.sequenceNo=c.code and b.goodNo=c.spuCode and c.order_type=2','left')
+                ->where([['a.status','=',1],['a.is_del','=',0],['a.payNo',"=",$payNo ],['a.cgdNo',"=",$orderCode]])
+                ->field('b.sequenceNo,b.goodNo,b.goodName,(b.goodNum-thNum) as goodNum,b.goodPrice,b.totalPrice,
+                c.merge_code,c.cat_code,c.cat_name,c.short_name,c.tax,c.inv_good_name')
+                ->findOrEmpty();
+        }
+       if(!$info->isEmpty())$info['balance_amount']= bcsub($info['totalPrice'],InvoiceOrder::getInvoiceOrderTotalFee($info['sequenceNo']),2);
+       return $info;
+    }
+
+    //回票流程结束未认证 状态3  退票认证结束 状态4
+    public static function onAfterWrite($model){
+      $id= $model->id;
+      $info = InvoiceOrder::where(['id'=>$id])->findOrEmpty();
+      if(!$info->isEmpty())return ;
+      if(in_array($info->status,[1,2])){
+         $cgdinfo = CgdInfo::where(['sequenceNo'=>$info->code])->findOrEmpty();
+         if(!$cgdinfo->isEmpty()){
+             $cgdinfo->winv_fee = bcsub($cgdinfo->winv_fee,bcsub($info->total_amount,$info->balance_amount,2),2);
+             $cgdinfo->save();
+         }
+         $payinfo = PayInfo::where(["cgdNo"=>$info->code,"status"=>1,"is_del"=>0])->findOrEmpty();
+         if(!$payinfo->isEmpty()){
+           $pay= Pay::where(['payNo'=>$payinfo->payNo,"status"=>2])->findOrEmpty();
+           if(!$pay->isEmpty()){
+               $pay->winv_fee=bcsub($pay->winv_fee,bcsub($info->total_amount,$info->balance_amount,2),2);
+               $pay->inv_fee = bcadd($pay->inv_fee,bcsub($info->total_amount,$info->balance_amount,2),2);
+               $pay->save();
+           }
+         }
+      }
+      if($info->status==3){
+          $cgdinfo = CgdInfo::where(['sequenceNo'=>$info->code])->findOrEmpty();
+                    if(!$cgdinfo->isEmpty()){
+                        $cgdinfo->winv_fee = bcadd($cgdinfo->winv_fee,bcsub($info->total_amount,$info->balance_amount,2),2);
+                        $cgdinfo->save();
+                    }
+                   $payinfo = PayInfo::where(['cgdNo'=>$info->code,'status'=>1,'is_del'=>0])->findOrEmpty();
+                   if(!$payinfo->isEmpty()){
+                     $pay= Pay::where(['payNo'=>$payinfo->payNo,'status'=>2])->findOrEmpty();
+                     if(!$pay->isEmpty()){
+                         $pay->winv_fee=bcadd($pay->winv_fee,bcsub($info->total_amount,$info->balance_amount,2),2);
+                         $pay->inv_fee = bcsub($pay->inv_fee,bcsub($info->total_amount,$info->balance_amount,2),2);
+                         $pay->save();
+                     }
+                   }
+      }
+      if($info->status==4){
+          $cgdinfo = CgdInfo::where(['sequenceNo'=>$info->code])->findOrEmpty();
+          if(!$cgdinfo->isEmpty()){
+              $cgdinfo->winv_fee = bcadd($cgdinfo->winv_fee,bcsub($info->total_amount,$info->balance_amount,2),2);
+              $cgdinfo->ainv_fee = bcsub($cgdinfo->ainv_fee,bcsub($info->total_amount,$info->balance_amount,2),2);
+              $cgdinfo->inv_status = $cgdinfo->winv_fee >0 && $cgdinfo->ainv_fee==0?1:2;
+              $cgdinfo->save();
+          }
+         $payinfo = PayInfo::where(['cgdNo'=>$info->code,'status'=>1,'is_del'=>0])->findOrEmpty();
+         if(!$payinfo->isEmpty()){
+           $pay= Pay::where(['payNo'=>$payinfo->payNo,'status'=>2])->findOrEmpty();
+           if(!$pay->isEmpty()){
+               $pay->winv_fee=bcadd($pay->winv_fee,bcsub($info->total_amount,$info->balance_amount,2),2);
+               $pay->ainv_fee = bcsub($pay->ainv_fee,bcsub($info->total_amount,$info->balance_amount,2),2);
+               $pay->inv_status = $pay->winv_fee >0 && $pay->ainv_fee==0?1:2;
+               $pay->save();
+           }
+         }
+      }
+    }
+}

+ 8 - 8
app/cxinv/model/InvoicePool.php

@@ -13,14 +13,14 @@ class InvoicePool extends Base
         'apply_id'  =>'bigint',//申请人id
         'apply_name'  =>'varchar',//申请人名称
         'inv_type'  =>'varchar',//发票类型 
-"special"=>"增值税专用发票",
-        "normal"=>"增值税普通发票",
-        "roll"=>"增值税普通发票(卷式)",
-        "special_electronic"=>"增值税电子专用发票",
-        "electronic"=>"增值税电子普通发票",
-        "toll"=>"增值税电子普通发票(通行费)",
-        "fully_digitalized_special_electronic"=>"全电专用发票",
-        "fully_digitalized_normal_electronic"=>"全电普通发票",
+//        "special"=>"增值税专用发票",
+//        "normal"=>"增值税普通发票",
+//        "roll"=>"增值税普通发票(卷式)",
+//        "special_electronic"=>"增值税电子专用发票",
+//        "electronic"=>"增值税电子普通发票",
+//        "toll"=>"增值税电子普通发票(通行费)",
+//        "fully_digitalized_special_electronic"=>"全电专用发票",
+//        "fully_digitalized_normal_electronic"=>"全电普通发票",
         'open_type'  =>'tinyint',//开票类型 1金税开票 2金税线下 3纯线下
         'company_type'  =>'varchar',//买方账户类型01 企业,02 机关事业单位,03 个人, 04 其他
         'platform_type'  =>'tinyint',//0 无属性 1 ToB 2 ToC

+ 1 - 11
app/cxinv/model/PayInvoice.php

@@ -11,17 +11,7 @@ class PayInvoice extends Base
         'apply_id'  =>'int',//申请人id
         'apply_name'  =>'varchar',//申请人名称
         'invType'  =>'tinyint',//发票申请类型 1 手工添加 2 ocr识别 3 金税扫描
-        'invoiceType'  =>'varchar',//发票类型 special: 增值税专用发票
-
-normal: 增值税普通发票
-
-electronic: 增值税电子普通发票
-
-special_electronic: 增值税电子专用发票
-
-toll: 增值税电子普通发票(通行费)
-
-roll: 增值税普通发票(卷票),fully_digitalized_special_electronic:全电专用发票, fully_digitalized_normal_electronic:全电专用发票
+        'invoiceType'  =>'varchar',//发票类型 special: 增值税专用发票normal: 增值税普通发票electronic: 增值税电子普通发票special_electronic: 增值税电子专用发票toll: 增值税电子普通发票(通行费)roll: 增值税普通发票(卷票),fully_digitalized_special_electronic:全电专用发票, fully_digitalized_normal_electronic:全电专用发票
         'invName'  =>'varchar',//
         'inv_img'  =>'varchar',//发票图片
         'inv_fee'  =>'decimal',//回票金额

+ 9 - 0
app/user/model/AccountCompany.php

@@ -24,4 +24,13 @@ class AccountCompany extends Base
     public function accountInfo(){
     	return $this->belongsTo(Account::class,"account_id","id")->bind(['nickname','user_mobile','mobile','openId','depart_name','itemid','depart_link','position',"username"]);
     }
+
+    public static function SupplierHasAcount($code){
+    	$isRela=self::where(['companyCode'=>$code,'status'=>1,'is_del'=>0])->select();
+    	if ($isRela->isEmpty()) return false;
+    	$account_id = $isRela->column("account_id");
+    	$info = Account::whereIn("id",$account_id)->where(["status"=>1,"level"=>3])->select();
+    	return !$info->isEmpty();
+
+    }
 }