wugg 6 months ago
parent
commit
dce834f434

+ 160 - 3
app/cxinv/controller/Invoice.php

@@ -6,7 +6,7 @@ namespace app\cxinv\controller;
 
 use app\cxinv\model\InvoiceOrder;
 use app\cxinv\model\InvoiceItem;
-use think\App;
+use app\cxinv\model\PayReturn;use app\cxinv\model\RoleAction;use app\user\model\AccountCompany;use app\user\model\Business;use app\user\model\Headquarters;use think\App;
 use think\facade\Validate;
 class Invoice extends Base{
     public function __construct(App $app) {
@@ -52,6 +52,54 @@ class Invoice extends Base{
         $this->model->saveAll($param['list']);
         return success("添加成功");
     }
+    public function save(){
+        $param= $this->request->param([
+            "InvCode"=>"",
+            "invoice_code"=>"",
+            "invoice_number"=>"",
+            "invoice_type"=>"",
+            "invoice_total"=>"",
+            "open_date"=>"",
+            "invoice_subtotal"=>"",
+            "check_code"=>"",
+            "companyNo"=>"",
+            "status"=>0,
+            "supplierNo"=>""],"post","trim");
+        $valide=Validate::rule([
+            "id|回票编号id"=>"require|max:255",
+            "invoice_code|发票代码"=>"requireIf:status,0|max:255",
+            "invoice_number|发票号码"=>"requireIf:status,0|max:255",
+            "invoice_type|发票类型"=>"requireIf:status,0|in:".explode(",",implode(",",array_keys(\app\cxinv\model\Invoice::$invoiceType))),
+            "invoice_total|发票税前金额"=>"float",
+            "open_date|开票日期"=>"requireIf:status,0|date|dateFormat:Y-m-d",
+            "invoice_subtotal|发票税后金额"=>"float",
+            "check_code|校验码"=>"max:255",
+            "companyNo|业务公司"=>"requireIf:status,1|max:255",
+            "supplierNo|供应商公司"=>"requireIf:status,1|max:255"
+        ]);
+        $invoice=$this->model->where("InvCode",$param['InvCode'])->findOrEmpty();
+        if($invoice->isEmpty()) return error("回票编号不存在");
+        $param['status'] = $invoice->status;
+        if(!$valide->check($param)) return error($valide->getError());
+        if ($invoice->status>1) return error("回票已关联订单,无法修改");
+        if ($param['status']==0){
+            $invoice->invoice_code=$param['invoice_code'];
+            $invoice->invoice_number=$param['invoice_number'];
+            $invoice->invoice_type=$param['invoice_type'];
+            $invoice->invoice_total=$param['invoice_total'];
+            $invoice->open_date=$param['open_date'];
+            $invoice->invoice_subtotal=$param['invoice_subtotal'];
+            $invoice->check_code=$param['check_code'];
+        }
+        if($param['status']==1){
+            $invoice->companyNo=$param['companyNo'];
+            $invoice->companyName=Business::where("companyNo",$param['companyNo'])->value("company","");
+            $invoice->supplierNo=$param['supplierNo'];
+            $invoice->supplierName=Headquarters::where("code",$param['supplierNo'])->value("name","");
+        }
+        $invoice->save();
+        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");
@@ -107,9 +155,118 @@ class Invoice extends Base{
             "InvCode|回票编号"=>"require|max:255"
         ]);
         if(!$valide->check($param)) return error($valide->getError());
-        $info=$this->model->where("InvCode",$param['InvCode'])->findOrEmpty();
+        $info=$this->model->with(["items"])->where("InvCode",$param['InvCode'])->findOrEmpty();
         if($info->isEmpty()) return error("回票编号不存在");
-        $info['items'] = InvoiceItem::where(['invoiceCode'=>$param['InvCode']])->select();
         return success("获取成功",$info);
     }
+
+    public function Back(){
+         $param= $this->request->param(["InvCode"=>"","reason"=>""],"post","trim");
+         $valide=Validate::rule([
+             "InvCode|回票编号"=>"require|max:255",
+             "reason|备注"=>"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 ($this->level == 2) {
+		    //判断是否开通供应商账号
+		    $rebool= AccountCompany::SupplierHasAcount($info->supplierNo);
+		    if ($rebool) return error( '该供应商已经开通账号,不允许当前账号操作');
+	    }
+        if ($info->status!=4) return error("回票信息流程未完成");
+        $isr = PayReturn::where(['orderCode'=>$param['InvCode'],'status'=>[1,2],'is_del'=>0])->findOrEmpty();
+        if (!$isr->isEmpty()) return error("该订单已申请退票,不允许重复申请");
+        $returnCode =makeNo('RP');
+		$data = [
+			'returnCode'=>$returnCode,
+			'returnType'=>3,
+			'payNo'=>$param['InvCode'],
+			'orderCode'=>$param['hpNo'],
+			'reason'=>$param['reason'],
+			'returnImg'=>'',
+			'remark'=>'',
+			'status'=>1,
+			'apply_id'=>$this->uid,
+			'apply_name'=>$this->uname,
+			'is_del'=>0,
+			'addtime'=>date('Y-m-d H:i:s'),
+			'updatetime'=>date('Y-m-d H:i:s'),
+		];
+		$ce= PayReturn::create($data);
+		if (!$ce) return error("申请退票创建失败");
+		return success("申请退票创建成功");
+    }
+    public function BackList(){
+      	$param =$this->request->only(['relaComNo'=>'','companyNo'=>'','supplierNo'=>'','start'=>'','end'=>'','returnCode'=>'',
+		'status'=>'','InvCode'=>'','page'=>1,'size'=>15],'post','trim');
+      	$condition=[['a.is_del','=',0],['a.returnType','=',3]];
+      	$check = RoleAction::checkRole($this->roleid,[132,130]);
+      	if($check) $condition[]=['a.apply_id','=',$this->uid];
+      	if($param['relaComNo']!='') $condition[]=['b.companyNo|b.supplierNo','=',$param['relaComNo']];
+		if($param['companyNo']!='') $condition[]=['b.companyNo','=',$param['companyNo']];
+		if($param['supplierNo']!='') $condition[]=['b.supplierNo','=',$param['supplierNo']];
+		if($param['start']!='') $condition[]=['a.addtime','>=',date('Y-m-d H:i:s',strtotime($param['start']))];
+		if($param['end']!='') $condition[]=['a.addtime','<=',date('Y-m-d 23:59:59',strtotime($param['end']))];
+		if($param['status']!='') $condition[]=['a.status','=',$param['status']];
+		if($param['InvCode']!='') $condition[]=['b.InvCode','=',$param['InvCode']];
+		if($param['returnCode']!='') $condition[]=['a.returnCode','=',$param['returnCode']];
+		$list= PayReturn::alias('a')
+		->join('invoice b','a.orderCode=b.InvCode','left')
+		->where($condition)
+		->field('a.*,b.InvCode,b.supplierNo,b.supplierName,b.companyNo,b.companyName,b.invoice_total,b.invoice_subtotal,b.open_date,b.invoice_code,b.invoice_number')
+		->order('a.id desc')
+		->paginate(["list_row"=>$param['size'],"page"=>$param['page']]);
+		foreach ($list as $k=>&$v){
+            $v['has_account'] = AccountCompany::SupplierHasAcount($v['supplierNo']);
+		}
+        return success("获取成功",["list"=>$list->items(),"count"=>$list->total()]);
+    }
+
+    public function BackInfo(){
+        $param =$this->request->only(['returnCode'=>''],'post','trim');
+        $valide=Validate::rule([
+				'returnCode|退票申请编号'=>'require|max:255',
+			]);
+        if(!$valide->check($param))return error($valide->getError());
+        $info= PayReturn::where(['returnCode'=>$param['returnCode'],"returnType"=>3,'is_del'=>0])->findOrEmpty();
+        if($info->isEmpty()) return error("退票申请编号不存在");
+        $info['invoice'] = $this->model->with(["items"])->where(["InvCode"=>$info->orderCode])->findOrEmpty();
+        return success("获取成功",$info);
+    }
+
+    public function BackStatus(){
+      $param =$this->request->only(['returnCode'=>'','status'=>'','remark'=>'','returnImg'=>''],'post','trim');
+      $valide=Validate::rule([
+				'returnCode|退票申请编号'=>'require|max:255',
+				'status|状态'=>'require|number|in:1,2,3',
+			]);
+      if(!$valide->check($param))return error($valide->getError());
+      $info= PayReturn::where(['returnCode'=>$param['returnCode'],"returnType"=>3,'is_del'=>0])->findOrEmpty();
+      if($info->isEmpty()) return error("退票申请编号不存在");
+      $invoice = $this->model->where(['InvCode'=>$info['orderCode'],'is_del'=>0])->findOrEmpty();
+      if($invoice->isEmpty()) return error("发票信息不存在");
+      if($invoice->status!=4) return error("发票申请状态不允许退票");
+      $info->status=2;
+      $info->remark=$param['remark'];
+      $info->returnImg=$param['returnImg'];
+      $info->updatetime=date('Y-m-d H:i:s');
+      $this->model->startTrans();
+      try{
+          $up=$info->save();
+          if(!$up) throw new \Exception("审批失败");
+          if($param['status']==2){
+              $invoice->status=9;
+              $invoice->updatetime=date('Y-m-d H:i:s');
+              $up2=$invoice->save();
+              if(!$up2) throw new \Exception("审批失败");
+          }
+          $this->model->commit();
+      }catch (\Exception $e){
+          $this->model->rollback();
+          return error("审批失败");
+      }
+       return success('审批成功');
+    }
+
 }

+ 11 - 11
app/cxinv/controller/InvoiceItem.php

@@ -11,8 +11,8 @@ use think\App;
 use think\facade\Validate;
 class InvoiceItem extends Base{
     public function __construct(App $app) {
-     #  $this->novalidate = ["*"];
         parent::__construct($app);
+        $this->model = new \app\cxinv\model\InvoiceItem();
     }
     //查询
     public function cgdListByPayNo(){
@@ -70,7 +70,7 @@ class InvoiceItem extends Base{
             'total_amount|总金额' => 'require|float|gt:0',
             'remark|备注' => 'max:255',
         ]);
-        $item = \app\admin\model\InvoiceItem::where(['id'=>$param["itemId"]])->findOrEmpty();
+        $item = $this->model->where(['id'=>$param["itemId"]])->findOrEmpty();
         if($item->isEmpty()) return  error("发票明细不存在");
         $save=[];
         $amount = $item['balance_amount'];
@@ -124,7 +124,7 @@ class InvoiceItem extends Base{
         $item->startTrans();
         try{
 
-            $res=(new \app\admin\model\InvoiceOrder)->saveAll($save);
+            $res=(new InvoiceOrder)->saveAll($save);
             if($res){
                 $item->balance_amount = $amount;
                 $item->status = $amount>0?2:1; //已关联数据 $amont=0 2 还有余额则为1
@@ -144,15 +144,15 @@ class InvoiceItem extends Base{
             'id|发票明细对应id' => 'require|number|gt:0',
         ]);
         if(!$valid->check($param)) return  error($valid->getError());
-        $info = \app\admin\model\InvoiceOrder::where(['id'=>$param["id"]])->findOrEmpty();
+        $info = InvoiceOrder::where(['id'=>$param["id"]])->findOrEmpty();
         if($info->isEmpty()) return  error("发票明细对应关系不存在");
-        $item = \app\admin\model\InvoiceItem::where(['id'=>$info['itemId']])->findOrEmpty();
+        $item =  $this->model->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();
+                $count = 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();
@@ -173,9 +173,9 @@ class InvoiceItem extends Base{
             'remark|备注' => 'require|max:255',
         ]);
         if(!$valid->check($param)) return  error($valid->getError());
-        $info = \app\admin\model\InvoiceOrder::where(['id'=>$param['id']])->findOrEmpty();
+        $info = InvoiceOrder::where(['id'=>$param['id']])->findOrEmpty();
         if($info->isEmpty()) return  error('发票明细对应关系不存在');
-        $item = \app\admin\model\InvoiceItem::where(['id'=>$info['itemId']])->findOrEmpty();
+        $item =  $this->model->where(['id'=>$info['itemId']])->findOrEmpty();
         if($item->isEmpty()) return  error('发票明细不存在');
         $info->startTrans();
         try{
@@ -196,7 +196,7 @@ class InvoiceItem extends Base{
         $where=[];
         if($param["code"]!=="") $where[]=["invoiceCode","=",$param["code"]];
         if($param["status"]!=="") $where[]=["status","=",$param["status"]];
-        $list= \app\admin\model\InvoiceItem::with(["OrderInfo"])
+        $list=  $this->model->with(["OrderInfo"])
             ->where($where)
             ->limit($param["size"])
             ->select();
@@ -218,7 +218,7 @@ class InvoiceItem extends Base{
             '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");
+        $itemArr=  $this->model->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){
@@ -279,7 +279,7 @@ class InvoiceItem extends Base{
                 'apply_name'=>$this->uname
             ];
         }
-         $orderItemModel = new \app\admin\model\InvoiceItem();
+         $orderItemModel = new \app\cxinv\model\InvoiceItem();
         $orderItemModel->startTrans();
         try{
            $num=$orderItemModel->saveAll(array_values($itemArr));

+ 309 - 3
app/cxinv/controller/Payment.php

@@ -4,13 +4,12 @@
 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;
+use app\cxinv\model\CgdInfo;use app\cxinv\model\FhdChild;use app\cxinv\model\InvoicePay;use app\cxinv\model\InvoicePool;use app\cxinv\model\OrderCategory;use app\cxinv\model\Pay;use app\cxinv\model\PayInfo;use app\cxinv\model\RoleAction;use app\cxinv\model\TagLog;use app\cxinv\model\Track;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"]);
@@ -75,6 +74,313 @@ class Payment extends Base{
             $this->model->rollback();
             return error($e->getMessage());
         }
+         event("report_code",["type"=>"add","key"=>"payNo","value"=>$payNo,"main"=>['key'=>'cgdNo','value'=>array_column($payinfo,'cgdNo')]]);
          return success('创建付款单成功');
     }
-}
+    public function list(){
+        $params = $this->request->param(['page'=>1,'size'=>20,'startTime'=>'',"endTime"=>"","supplierNo"=>"",
+        "supplierName"=>"","pay_status"=>"","inv_status"=>"","tag_id"=>"","status"=>"",'companyNo'=>'','pay_type'=>'',
+        'companyName'=>'','is_comon'=>'',"relaComNo"=>""],"post","trim");
+        $where=[['is_del','=',0],['pay_type','=',$params['pay_type']??1]];
+        $check = RoleAction::checkRole($this->roleid, [77,117]);
+        if ($check) $where[]=['apply_id','=',$this->uid];
+       if ($params['startTime']!=="") $where[]=['addtime','>=',startTime($params['startTime'])];
+       if ($params['endTime']!=="") $where[]=['addtime','<=',endTime($params['endTime'])];
+       if ($params['supplierNo']!=="") $where[]=['supplierNo','like','%'.$params['supplierNo'].'%'];
+       if ($params['supplierName']!=="") $where[]=['supplierName','like','%'.$params['supplierName'].'%'];
+       if ($params['pay_status']!==""){
+           if($params['pay_status']==0)$where[]=['pay_status','<>',3];
+           else $where[]=['pay_status','=',$params['pay_status']];
+       }
+       if ($params['inv_status']!==""){
+           if($params['inv_status']==0)$where[]=['inv_status','<>',3];
+             else $where[]=['inv_status','=',$params['inv_status']];
+       }
+       if ($params['status']!=="") $where[]=['status','=',$params['status']];
+       if ($params['tag_id']!=="") {
+           $conditions_map = [
+               1 => ['inv_tag', '=', 1],
+               2 => ['pay_tag', '=', 1],
+               3 => ["pay_tag|inv_tag", '=', 1],
+               4 => ['pay_tag&inv_tag', '=', 1],
+           ];
+          $where[]=$conditions_map[$params['tag_id']];
+       }
+       if ($params['companyNo']!=="") $where[]=['companyNo','=',$params['companyNo']];
+       if ($params['companyName']!=="") $where[]=['companyName','like','%'.$params['companyName'].'%'];
+       if ($params['is_comon']!=="") $where[]=['is_comon','=',$params['is_comon']];
+       if($params['relaComNo']!=="") $where[]=['companyNo|supplierNo','=',$params['relaComNo']];
+       $list = $this->model->where($where)->order("id desc")->paginate(["list_rows"=>$params['size'],"page"=>$params['page']]);
+
+       foreach ($list as $k=>&$v){
+            $v['orderNum'] = PayInfo::where([['payNo','=',$v['payNo']],['is_del','=',0],['status','=',1]])->count();
+            $v['inv_tag_name']='';
+            $v['pay_tag_name']='';
+            $v['pay_tag_img']='';
+            $v['inv_tag_id']='0';
+            $v['pay_tag_id']='0';
+            $v['pay_tag_remark']='';
+            $v['inv_tag_img']='';
+            $v['inv_tag_remark']='';
+            if($v['inv_tag']==1 || $v['pay_tag']==1){
+                $tag = TagLog::alias("a")
+                ->leftJoin("order_tag b", "a.tag_id=b.id")
+                ->where(['code'=>$v['payNo'],'a.status'=>[1,2]])
+                ->order("a.id desc")
+                ->column('a.id,b.tag_name,a.tag_img,a.tag_remark','b.type');
+                if($tag['inv_tag']==1){
+                    $v['inv_tag_name']=$tag['2']['tag_name']??"";
+                    $v['inv_tag_img']=$tag['2']['tag_img']??'';
+                    $v['inv_tag_remark']=$tag['2']['tag_remark']??'';
+                    $v['inv_tag_id']=$tag['2']['id']??'';
+                }
+                if($tag['pay_tag']==1){
+                    $v['pay_tag_name']=$tag['1']['tag_name']??'';
+                    $v['pay_tag_img']=$tag['1']['tag_img']??'';
+                    $v['pay_tag_remark']=$tag['1']['tag_remark']??'';
+                    $v['pay_tag_id']=$tag['1']['id']??'';
+                }
+            }
+            $v['has_account'] = AccountCompany::SupplierHasAcount($v['supplierNo']);
+       }
+
+       return success("获取成功",["list"=>$list->items(),"count"=>$list->total()]);
+    }
+    public function save(){
+        $params = $this->request->param(["cids"=>[],"payNo"=>""],"post","trim");
+        $valid=Validate::rule(["cids|采购单集合数据"=>"require|array","payNo|对账单编号"=>"require|max:255"]);
+        if(!$valid->check($params)) return error($valid->getError());
+        $pay = $this->model->where(['payNo'=>$params['payNo']])->findOrEmpty();
+        if($pay->isEmpty()) return error("对账单不存在");
+        if($pay['status']!=1) return error("对账单已提交审核");
+        $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('采购单数据商品进项类目不存在');
+        $payCgd = PayInfo::where([['payNo','=',$params['payNo']],['is_del','=',0]])->column("cgdNo");
+        if (!empty($payCgd)){
+            $add = array_diff($cgdlist->column('sequenceNo'),$payCgd);
+            $remove = array_diff($payCgd,$cgdlist->column('sequenceNo'));
+        }
+        $payinfo = [];
+        $totalPrice='0';
+        foreach ($cgdlist as $k=>$v){
+           if(!empty($add)&& in_array($v['sequenceNo'],$add)){
+                $temp= [
+                    'cgdNo'=>$v['sequenceNo'],
+                    'total_fee'=>$v['totalPrice'],
+                    'wapy_fee'=>$v['totalPrice'],
+                    'winv_fee'=>$v['totalPrice'],
+                    'payNo'=>$params['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=[
+                'total_fee'=>$totalPrice,
+                '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,
+                'ainv_fee'=>$totalPrice,
+            ];
+
+        $this->model->startTrans();
+        try{
+            $paySave=$pay->save($paydata);
+            if($paySave==false) throw new \Exception("对账单保存失败");
+            if(!empty($payinfo)){
+                $payinfoSave = (new \app\cxinv\model\PayInfo)->saveAll($payinfo);
+                if($payinfoSave==false) throw new \Exception("对账单明细保存失败");
+                $up = CgdInfo::where([['sequenceNo','in',$add],['status','=',0]])->save(['status'=>1, 'updatetime'=>date('Y-m-d H:i:s')]);
+                if($up==false) throw new \Exception("采购单状态修改失败");
+            }
+            if (!empty($remove)){
+                $payRemove = PayInfo::where([['cgdNo','in',$remove],['payNo','=',$params['payNo']]])->save(['is_del'=>1, 'updatetime'=>date('Y-m-d H:i:s')]);
+                if($payRemove==false) throw new \Exception("对账单明细删除失败");
+                $up = CgdInfo::where([['sequenceNo','in',$remove],['status','=',1]])->save(['status'=>0, 'updatetime'=>date('Y-m-d H:i:s')]);
+                if($up==false) throw new \Exception("采购单状态修改失败");
+            }
+            $this->model->commit();
+             event('report_code',['type'=>'add','key'=>'payNo','value'=>$params['payNo'],'main'=>['key'=>'cgdNo','value'=>$add]]);
+             event('report_code',['type'=>'sub','key'=>'payNo','value'=>$params['payNo'],'main'=>['key'=>'cgdNo','value'=>$remove]]);
+        }catch (\Exception $exception){
+            $this->model->rollback();
+            return error($exception->getMessage());
+        }
+          return success('保存成功');
+   }
+    public function status(){
+     $params = $this->request->param(["payNo"=>"","status"=>"","remark"=>""],"post","trim");
+     $valid = Validate::rule(["payNo|对账申请编号"=>"require|max:255","status|状态"=>"require|in:1,2,3,4","remark|备注"=>"max:255"]);
+     if(!$valid->check($params)) return error($valid->getError());
+     $pay = $this->model->where(['payNo'=>$params['payNo'],"is_del"=>0])->findOrEmpty();
+     if($pay->isEmpty()) return error("对账单不存在");
+     if($params["status"]==4){
+         if($pay['inv_tag']==1)return error('存在回票标签未解除');
+         if($pay['pay_tag']==1)return error('存在付款标签未解除');
+         if($pay->pay_status!=1)return error("对账单存在未解除的付款金额");
+         if($pay->inv_status!=1) return error("对账单存在未解除的开票金额");
+         if($pay->is_comon==1){
+            	$invoceAr=InvoicePay::where(['payNo'=>$params['payNo']])->column('invNo');
+       	    	if(!empty($invoceAr)){
+       	    		$ist= InvoicePool::where([['invNo','in',$invoceAr],['status','in',[0,1,2,3,4]]])->select()
+       	    		->isEmpty();
+       	    		if($ist==false)return error('通用订单存在开票申请未解除');
+       	    	}
+         }
+     }
+     $this->model->startTrans();
+     try{
+         $pay->status=$params["status"];
+         $pay->remark=$params["remark"];
+         $pay->updatetime=date("Y-m-d H:i:s");
+         $paySave=$pay->save();
+         if($paySave==false) throw new \Exception("对账单状态修改失败");
+         if($params["status"]==4||$params["status"]==3){
+             $cgdNo= PayInfo::where(['payNo'=>$params['payNo'],'is_del'=>0,"status"=>1])->column('cgdNo');
+             if(!empty($cgdNo)){
+                 if($params["pay_type"]==1){
+                     $up = CgdInfo::where([['sequenceNo','in',$cgdNo],['status','=',1]])->save(['status'=>0, 'updatetime'=>date('Y-m-d H:i:s')]);
+                     if($up==false) throw new \Exception("采购单状态修改失败");
+                 }
+                 else {
+                     $up = Track::where([['TrackCode','in',$cgdNo],['status','=',1]])->save(['status'=>0, 'updatetime'=>date('Y-m-d H:i:s')]);
+                      if($up==false) throw new \Exception('物流单状态修改失败');
+                 }
+             }
+             $payRemove = PayInfo::where([['payNo'=>$params['payNo'],'status'=>1,'is_del'=>0]])->save(['status'=>0, 'updatetime'=>date('Y-m-d H:i:s')]);
+             if($payRemove==false) throw new \Exception("对账单明细删除失败");
+         }
+         $this->model->commit();
+         event('report_code',['type'=>'sub','key'=>'payNo','value'=>$params['payNo']]);
+         if(($params['status']==3 || $params['status']==4)&&$pay['is_comon']==1){
+           event('comonOrder',['payNo'=>$params['payNo'],'type'=>'check']);
+        }
+     }catch (\Exception $exception){
+         $this->model->rollback();
+         return error($exception->getMessage());
+     }
+        return success('保存成功');
+    }
+    public function delete(){
+        $params = $this->request->param(["payNo"=>""],"post","trim");
+        $valid = Validate::rule(["payNo|对账单编号"=>"require|max:255"]);
+        if(!$valid->check($params)) return error($valid->getError());
+        $pay = $this->model->where(['payNo'=>$params['payNo'],"is_del"=>0])->findOrEmpty();
+        if($pay->isEmpty()) return error("对账单不存在");
+        if($pay->status!=1)return error('对账单当前状态不可删除');
+         if($this->level==2){
+            $isBool = AccountCompany::SupplierHasAcount($pay->supplierNo);
+            if ($isBool) return error('该供应商已经开通账号,不允许当前账号操作');
+        }
+         $payinfo = PayInfo::where(['payNo'=>$params['payNo'],"status"=>1,'is_del'=>0])->select();
+         if($payinfo->isEmpty()) return error('该对账单没有明细');
+        $this->model->startTrans();
+         try{
+             $pay->is_del=1;
+             $pay->updatetime=date("Y-m-d H:i:s");
+             $paySave=$pay->save();
+             if($paySave==false) throw new \Exception("对账单删除失败");
+             $payRemove = PayInfo::where([['payNo'=>$params['payNo'],"status"=>1,'is_del'=>0]])->save(["is_del"=>1, 'updatetime'=>date('Y-m-d H:i:s')]);
+             if($payRemove==false) throw new \Exception("对账单明细删除失败");
+             if ($pay->pay_type==1){
+                 $cgdNo=$payinfo->column('cgdNo');
+                 if(!empty($cgdNo)){
+                     $up = CgdInfo::where([['sequenceNo','in',$cgdNo],['status','=',1]])->save(['status'=>0, 'updatetime'=>date('Y-m-d H:i:s')]);
+                    if($up==false) throw new \Exception( "采购单状态修改失败");
+                 }else{
+                     $up = Track::where([['TrackCode','in',$cgdNo],['status','=',1]])->save(['status'=>0, 'updatetime'=>date('Y-m-d H:i:s')]);
+                     if($up==false) throw new \Exception('物流单状态修改失败');
+                 }
+             }
+             $this->model->commit();
+             event('report_code',['type'=>'sub','key'=>'payNo','value'=>$params['payNo']]);
+         }catch (\Exception $exception){
+             $this->model->rollback();
+             return error($exception->getMessage());
+         }
+         return success('删除成功');
+    }
+    public function info(){
+        $params = $this->request->param(["payNo"=>""],"post","trim");
+        $valid = Validate::rule(["payNo|对账单编号"=>"require|max:255"]);
+        if(!$valid->check($params)) return error($valid->getError());
+        $pay = $this->model->where(['payNo'=>$params['payNo'],"is_del"=>0])->findOrEmpty();
+        if($pay->isEmpty()) return error("对账单不存在");
+        $payinfo= PayInfo::where(['payNo'=>$params['payNo'],"is_del"=>0,"status"=>1])->select();
+        if($payinfo->isEmpty()) return error("对账单明细不存在");
+        $cgdNo = $payinfo->column('cgdNo');
+        if($pay->pay_type==1){
+            $cgdInfo = CgdInfo::where(['sequenceNo'=>['in',$cgdNo],'is_del'=>0,'status'=>1])->select();
+            if(!$cgdInfo->isEmpty()){
+                $cgdInfo = $cgdInfo->toArray();
+                foreach ($cgdInfo as $key=>&$value){
+                   $value['orderTax'] = OrderCategory::where(['code'=>$value['sequenceNo'],'spuCode'=>$value['goodNo']])
+                    ->field(['cat_code', 'cat_name', 'merge_code', 'short_name', 'tax', 'inv_good_name'])->findOrEmpty();
+                    $value['catInfo'] = json_decode($value['catInfo'],true);
+                    $value['goodNum'] =$value['goodNum']- $value['thNum'];
+                    $value['sendNum'] =$value['sendNum']- $value['thNum'];
+                    if($payinfo['is_comon']==1){
+                        $value['qrdCode'] = (new \app\cxinv\model\ComonOrder())->where(['cgdNo'=>$value['sequenceNo']])->value('orderCode','');
+                    }
+                }
+            }
+
+        }else{
+           $cgdInfo = Track::where(['TrackCode'=>['in',$cgdNo],'is_del'=>0,'status'=>1])->select();
+           if(!$cgdInfo->isEmpty()){
+                $fhds = FhdChild::where(['outChildCode'=>$cgdInfo->column("outChildCode")])->column("outCode,good_name,spuCode,post_name,post_code","outChildCode");
+               $cgdInfo = $cgdInfo->toArray();
+               foreach ($cgdInfo as $key=>&$value){
+                if(!isset($fhds[$value['outChildCode']]))$fhds[$value['outChildCode']]=["outCode"=>"","good_name"=>"","spuCode"=>"","post_name"=>"","post_code"=>""];
+                $value = array_merge($value,$fhds[$value['outChildCode']]);
+               }
+           }
+        }
+        $pay['pay_type']=Supplier::where(['code'=>$pay['supplierNo']])->value("pay_method",'');
+        $pay['inv_tag_name']='';
+        $pay['pay_tag_name']='';
+        $pay['pay_tag_img']='';
+        $pay['inv_tag_id']='0';
+        $pay['pay_tag_id']='0';
+        $pay['pay_tag_remark']='';
+        $pay['inv_tag_img']='';
+        $pay['inv_tag_remark']='';
+        if($pay['inv_tag']==1 || $pay['pay_tag']==1){
+            $tag = TagLog::alias('a')
+            ->leftJoin('order_tag b', 'a.tag_id=b.id')
+            ->where(['code'=>$pay['payNo'],'a.status'=>[1,2]])
+            ->order('a.id desc')
+            ->column('a.id,b.tag_name,a.tag_img,a.tag_remark','b.type');
+            if($tag['inv_tag']==1){
+                $pay['inv_tag_name']=$tag['2']['tag_name']??'';
+                $pay['inv_tag_img']=$tag['2']['tag_img']??'';
+                $pay['inv_tag_remark']=$tag['2']['tag_remark']??'';
+                $pay['inv_tag_id']=$tag['2']['id']??'';
+            }
+            if($tag['pay_tag']==1){
+                $pay['pay_tag_name']=$tag['1']['tag_name']??'';
+                $pay['pay_tag_img']=$tag['1']['tag_img']??'';
+                $pay['pay_tag_remark']=$tag['1']['tag_remark']??'';
+                $pay['pay_tag_id']=$tag['1']['id']??'';
+            }
+        }
+       $pay['cgdlist']= $cgdInfo;
+        return success("获取成功",$pay);
+    }
+ }

+ 337 - 0
app/cxinv/controller/Stage.php

@@ -0,0 +1,337 @@
+<?php
+
+
+namespace app\cxinv\controller;
+
+
+use app\cxinv\model\Pay;
+use app\cxinv\model\PayInfo;
+use app\cxinv\model\PayPayment;
+use app\cxinv\model\PayReturn;
+use app\cxinv\model\RoleAction;
+use app\user\model\AccountCompany;
+use think\App;
+use think\facade\Validate;
+class Stage extends Base{
+    public function __construct(App $app) {
+        parent::__construct($app);
+        $this->model =new PayPayment();
+    }
+
+    public function create(){
+        $params = $this->request->param(["payNo"=>"","cgdNos"=>[]],"post","trim");
+        $valid = Validate::rule([
+            "payNo|对账单申请编号"=>"require|max:255",
+            "cgdNos|对账单付款申请明细"=>"require|array"
+            ]);
+        if (!$valid->check($params)) return error($valid->getError());
+        $pay = Pay::where(["payNo"=>$params["payNo"],"is_del"=>0])->findOrEmpty();
+        if ($pay->isEmpty()) return error("对账单申请不存在");
+        if($pay->status!=2) return error("对账单申请状态不正确");
+        $cgdInfo= PayInfo::where(['payNo'=>$params['payNo'],'is_del'=>0,'status'=>1])->select();
+        if($cgdInfo->isEmpty()) return error("对账单付款申请明细不存在");
+        $cgdNos = $cgdInfo->column("cgdNo");
+        $dzNo= makeNo("DZ");
+        $val= Validate::rule([
+            "sequenceNo|采购单号"=>"require|max:255",
+            "rela_fee|关联付款金额"=>"require|float"]);
+        $total_fee=0;
+        $relaData=[];
+        foreach ($params["cgdNos"] as $v){
+            if(!$val->check($v)) return error($val->getError());
+            if(!in_array($v["sequenceNo"],$cgdNos)) return error("{$v["sequenceNo"]}采购单号不在当前对账单中");
+            $relaData[]=[
+                "dzNo"=>$dzNo,
+                "payNo"=>$params["payNo"],
+                "cgdNo"=>$v["sequenceNo"],
+                "rela_fee"=>$v["rela_fee"]
+            ];
+            $total_fee+=$v["rela_fee"];
+        }
+        $ment =[
+                'payNo'=>$params['payNo'],
+                'dzNo'=>$dzNo,
+                'apply_id'=>$this->uid,
+                'apply_name'=>$this->uname,
+                'pay_fee'=>$total_fee,
+                'return_img'=>'',
+                'status'=>1,
+                'addtime'=>date('Y-m-d H:i:s'),
+                'updatetime'=>date('Y-m-d H:i:s')
+            ];
+        if($total_fee>$pay->wpay_fee) return error("对账单未付金额不足");
+        if($total_fee <=0) return error("付款金额不正确");
+        $this->model->startTrans();
+        try{
+            $cerste= $this->model->create($ment);
+            if($cerste->isEmpty()) throw new \Exception("创建付款申请失败");
+            $relaSte= (new \app\cxinv\model\PaymentOrder)->saveAll($relaData);
+            if(!$relaSte) throw new \Exception("创建付款申请明细失败");
+            $pay->wpay_fee=$pay->wpay_fee-$total_fee;
+            $pay->pay_fee = $pay->pay_fee+$total_fee;
+            $paySte=$pay->save();
+            if(!$paySte) throw new \Exception("更新付款申请失败");
+            $this->model->commit();
+            event('report_code',['type'=>'add','key'=>'dzNo','value'=>$dzNo,
+            'main'=>['key'=>'cgdNo','value'=>array_column($params['cgdNos'],"sequenceNo")]]);
+        }catch (\Exception $e){
+            $this->model->rollback();
+            return error($e->getMessage());
+        }
+        return success('创建付款申请成功');
+    }
+
+    public function list(){
+       $params= $this->request->param(["startTime"=>"","endTime"=>"","payNo"=>"","supplierNo"=>"","supplierName"=>"",
+       "companyNo"=>"","apply_name"=>"","status"=>"","dzNo"=>"","relaComNo"=>"","is_comon"=>"",'pay_type'=>'',"page"=>1,
+       "size"=>20],"post","trim");
+       $where=[['a.is_del','=',0],['pay_type','=',$params['pay_type']??1]];
+       $check = RoleAction::checkRole($this->roleid, [77,117]);
+       if ($check) $where[]=['apply_id','=',$this->uid];
+       if ($params['startTime']!=='') $where[]=['addtime','>=',startTime($params['startTime'])];
+       if ($params['endTime']!=='') $where[]=['addtime','<=',endTime($params['endTime'])];
+       if ($params['supplierNo']!=='') $where[]=['supplierNo','like','%'.$params['supplierNo'].'%'];
+       if ($params['supplierName']!=='') $where[]=['supplierName','like','%'.$params['supplierName'].'%'];
+       if ($params['companyNo']!=='') $where[]=['companyNo','like','%'.$params['companyNo'].'%'];
+       if ($params['apply_name']!=='') $where[]=['apply_name','like','%'.$params['apply_name'].'%'];
+       if ($params['status']!=='') $where[]=['status','=',$params['status']];
+       if ($params['dzNo']!=='') $where[]=['dzNo','like','%'.$params['dzNo'].'%'];
+       if ($params['payNo']!=='') $where[]=['payNo','like','%'.$params['payNo'].'%'];
+       if ($params['relaComNo']!=='') $where[]=['companyNo|supplierNo','like','%'.$params['relaComNo'].'%'];
+       if ($params['is_comon']!=='') $where[]=['is_comon','=',$params['is_comon']];
+       $list = $this->model->alias("a")
+       ->leftJoin("pay b","`a`.`payNo` = `b`.`payNo` AND  b.is_del = 0 ")
+       ->where($where)
+       ->field("`b`.`id` AS `id`,
+                           `a`.`payNo` AS `payNo`,
+                           `a`.`supplierNo`,
+                           `a`.`supplierName`,
+                           `a`.`apay_fee` ,
+                           `a`.`total_fee` AS `total_fee`,
+                           `b`.`apply_name`,
+                           `b`.`apply_id`,
+                           `a`.`is_comon`,
+                           `a`.`winv_fee` ,
+                           `a`.`ainv_fee` ,
+                           `a`.`wpay_fee` ,
+                           `a`.`pay_status` ,
+                           `a`.`inv_status` ,
+                           `b`.`pay_fee` AS `dpay_fee`,
+                           `b`.`return_img`,
+                           `b`.`return_time`,
+                           `b`.`status` AS `dstatus`,
+                           `a`.`status`,
+                           `a`.`remark` AS `remark`,
+                           `b`.`addtime` ,
+                           `a`.`companyNo` ,
+                           `a`.`companyName` ,
+                           `b`.`dzNo` AS `dzNo`")
+                           ->order("a.id DESC")
+                          ->paginate(['list_rows'=>$params['size'],'page'=>$params['page']]);
+        foreach ($list as $k=>&$v){
+            $v['orderNum'] = PayInfo::where([['payNo','=',$v['payNo']],['is_del','=',0],['status','=',1]])->count();
+            $v['has_account'] = AccountCompany::SupplierHasAcount($v['supplierNo']);
+       }
+       return success('获取成功',['list'=>$list->items(),'count'=>$list->total()]);
+    }
+
+    public function status(){
+        $params=$this->request->param(["dzNo"=>"","status"=>"","remark"=>"","return_image"=>"","return_time"=>""],"post","trim");
+        $valid =Validate::rule([
+            "dzNo|付款申请编号"=>"require|max:255",
+            "status|审核状态"=>"require|number|in:1,2,3,4,5,6,7",
+            "remark|备注"=>"max:255",
+            "return_image|回执图片"=>"requireIf:status=4|max:255",
+            "return_time|回执时间"=>"requireIf:status=4|date"
+        ]);
+        if(!$valid->check($params)) return error($valid->getError());
+        $stage = $this->model->where([['dzNo','=',$params['dzNo']],['is_del','=',0]])->findOrEmpty();
+        if($stage->isEmpty()) return error("付款申请不存在");
+        $pay = Pay::where([['payNo','=',$stage['payNo']],['is_del','=',0]])->findOrEmpty();
+        if($pay->isEmpty()) return error("对账申请单不存在");
+        if($pay->status!=2) return error("对账单状态不正确");
+        if($pay->pay_fee<$stage['pay_fee']) return error("对账付款申请金额有误,请确认对账申请金额");
+        $this->model->startTrans();
+        try{
+            $stage->status=$params['status'];
+            $stage->remark=$params['remark'];
+            if($params['status']==4){
+                    $stage->return_img=$params['return_image'];
+                    $stage->return_time=$params['return_time'];
+            }
+
+            $stageSte=$stage->save();
+            if(!$stageSte) throw new \Exception("更新付款申请状态失败");
+            $this->model->commit();
+        }catch (\Exception $e){
+            $this->model->rollback();
+            return error($e->getMessage());
+        }
+          return success('更新付款申请状态成功');
+    }
+    public function delete(){
+        $dzNo=$this->request->param("dzNo","post","trim");
+        $valid =Validate::rule([
+            "dzNo|付款申请编号"=>"require|max:255"
+        ]);
+        if(!$valid->check(['dzNo'=>$dzNo])) return error($valid->getError());
+        $stage = $this->model->where([['dzNo','=',$dzNo],['is_del','=',0]])->findOrEmpty();
+        if($stage->isEmpty()) return error("付款申请不存在");
+        $pay = Pay::where([['payNo','=',$stage['payNo']],['is_del','=',0]])->findOrEmpty();
+        if($pay->isEmpty()) return error("对账申请单不存在");
+        if($stage->status==4) return error("已回执的付款申请不能删除");
+        $this->model->startTrans();
+        try{
+            $stage->status=8;
+            $stage->is_del=1;
+            $stageSte=$stage->save();
+            if(!$stageSte) throw new \Exception("删除付款申请失败");
+            $this->model->commit();
+        }catch (\Exception $e){
+            $this->model->rollback();
+            return error($e->getMessage());
+        }
+        return success('删除付款申请成功');
+    }
+    public function info(){
+        $dzNo=$this->request->param("dzNo","post","trim");
+        $valid =Validate::rule([
+            "dzNo|付款申请编号"=>"require|max:255"
+        ]);
+        if(!$valid->check(['dzNo'=>$dzNo])) return error($valid->getError());
+        $stage = $this->model->where([['dzNo','=',$dzNo],['is_del','=',0]])->findOrEmpty();
+        if($stage->isEmpty()) return error("付款申请不存在");
+        $pay = Pay::where([['payNo','=',$stage['payNo']],['is_del','=',0]])->findOrEmpty();
+        if($pay->isEmpty()) return error("对账申请单不存在");
+        $stage['pay_apply_id'] = $pay['apply_id']??'';
+        $stage['pay_apply_name'] = $pay['apply_name']??'';
+        $stage['supplierNo'] = $pay['supplierNo']??'';
+        $stage['supplierName'] = $pay['supplierName']??'';
+        $stage['companyNo'] = $pay['companyNo']??'';
+        $stage['companyName'] = $pay['companyName']??'';
+        $stage['total_fee'] = $pay['total_fee']??'';
+        return success('获取成功',$stage);
+    }
+    public function Back(){
+        $params=$this->request->param(["dzNo"=>"","reason"=>"","is_del"=>0],"post","trim");
+        $valid =Validate::rule([
+            "dzNo|付款申请编号"=>"require|max:255",
+            "reason|退款原因"=>"require|max:255"
+        ]);
+        if(!$valid->check($params)) return error($valid->getError());
+        $stage = $this->model->where([['dzNo','=',$params['dzNo']],['is_del','=',0]])->findOrEmpty();
+        if($stage->isEmpty()) return error("付款申请不存在");
+        if($stage->status!=4) return error("付款申请状态不正确");
+        $pay = Pay::where([['payNo','=',$stage['payNo']],['is_del','=',0]])->findOrEmpty();
+        if($pay->isEmpty()) return error("对账申请单不存在");
+        if($this->level==2 && $pay->is_comon==0){
+            $boolen= AccountCompany::SupplierHasAcount($pay->supplierNo);
+            if($boolen) return error("该供应商已经开通账号,不允许当前账号操作");
+        }
+        $isR=PayReturn::where(['orderCode'=>$param['dzNo'],'status'=>[1,2],'is_del'=>0])->findOrEmpty();
+		if(!$isR->isEmpty())return error_show(1004,'付款信息退款流程已存在');
+        $reCode= makeNo("RP");
+        $data = [
+			'returnCode'=>$reCode,
+			'returnType'=>2,
+			'payNo'=>$stage['payNo'],
+			'orderCode'=>$stage['dzNo'],
+			'reason'=>$params['reason'],
+			'returnImg'=>'',
+			'remark'=>'',
+			'status'=>1,
+			'apply_id'=>$this->uid,
+			'apply_name'=>$this->uname,
+			'is_del'=>0,
+			'addtime'=>date('Y-m-d H:i:s'),
+			'updatetime'=>date('Y-m-d H:i:s'),
+		];
+        $this->model->startTrans();
+        try{
+            $create= PayReturn::create($data);
+            if(!$create) throw new \Exception("退款申请创建失败");
+            $this->model->commit();
+        }catch (\Exception $e){
+            $this->model->rollback();
+            return error($e->getMessage());
+        }
+        return success('退款款申请创建成功');
+    }
+
+    public function BackList(){
+       $param =$this->request->only(['relaComNo'=>'','companyNo'=>'','supplierNo'=>'','start'=>'','end'=>'','returnCode'=>'','payNo'=>'',
+		'status'=>'','dzNo'=>'','pay_type'=>'','is_comon'=>'','page'=>1,'size'=>15],'post','trim');
+		$condition=[['a.is_del','=',0],['a.returnType','=',2],['pay_type','=',$param['pay_type']?:1]];
+		$check = RoleAction::checkRole($this->roleid,[131,129]);
+		if($check) $condition[]=['a.apply_id','=',$this->uid];
+		if($param['relaComNo']!='') $condition[]=['b.companyNo|b.supplierNo','=',$param['relaComNo']];
+		if($param['companyNo']!='') $condition[]=['b.companyNo','=',$param['companyNo']];
+		if($param['supplierNo']!='') $condition[]=['b.supplierNo','=',$param['supplierNo']];
+		if($param['start']!='') $condition[]=['a.addtime','>=',date('Y-m-d H:i:s',strtotime($param['start']))];
+		if($param['end']!='') $condition[]=['a.addtime','<=',date('Y-m-d 23:59:59',strtotime($param['end']))];
+		if($param['status']!='') $condition[]=['a.status','=',$param['status']];
+		if($param['dzNo']!='') $condition[]=['a.orderCode','like',"%{$param['dzNo']}%"];
+		if($param['returnCode']!='') $condition[]=['a.returnCode','like',"%{$param['returnCode']}%"];
+		if($param['payNo']!='') $condition[]=['a.payNo','like',"%{$param['payNo']}%"];
+		if(isset($param['is_comon'])&&$param['is_comon']!=='') $condition []=['is_comon','=',$param['is_comon']];
+		$list = PayReturn::alias('a')
+		->leftJoin('pay b','a.payNo=b.payNo and b.is_del=0')
+		->leftJoin('pay_payment c','c.dzNo=a.orderCode and c.is_del=0')
+		->where($condition)
+		->field('a.*,b.supplierNo,b.is_comon,b.supplierName,b.companyNo,b.companyName,b.total_fee,b.apay_fee,b.wpay_fee,b.pay_fee,c.pay_fee pay_pay_fee')
+		->order('a.id desc')
+		->paginate(["list_rows"=>$param['size'],"page"=>$param['page']]);
+		foreach ($list->items() as $key => &$value){
+		    $value['has_account'] = AccountCompany::SupplierHasAcount($value['supplierNo']);
+		}
+        return success("获取成功",["list"=>$list->items(),"count"=>$list->total()]);
+    }
+    public function BackStatus(){
+        $params = $this->request->param(["returnCode"=>"","status"=>"","remark"=>"","returnImg"=>""],"post","trim");
+        $valid =Validate::rule([
+            "returnCode|退款单号"=>"require|max:255",
+            "status|退款状态"=>"require|in:2,3",
+            "remark|备注"=>"requireIf:status,3|max:255",
+            "returnImg|退款凭证"=>"max:255"
+        ]);
+        if(!$valid->check($params)) return error($valid->getError());
+        $return = PayReturn::where([['returnCode','=',$params['returnCode']],['is_del','=',0]])->findOrEmpty();
+        if($return->isEmpty()) return error("退款申请不存在");
+        $return->status=$params['status'];
+        $return->remark=$params['remark'];
+        $return->returnImg=$params['returnImg'];
+        $this->model->startTrans();
+        try{
+            $returnSte=$return->save();
+            if(!$returnSte) throw new \Exception("退款申请状态修改失败");
+            if($params['status']==2){
+                $stage = $this->model->where([['dzNo','=',$return['orderCode']],['is_del','=',0]])->findOrEmpty();
+                if($stage->isEmpty()) throw new \Exception("付款申请不存在");
+                $stage->status=5;
+                $stageSte=$stage->save();
+                if(!$stageSte) throw new \Exception("付款申请状态修改失败");
+            }
+            $this->model->commit();
+        }catch (\Exception $e){
+            $this->model->rollback();
+            return error($e->getMessage());
+        }
+        return  success("退款申请状态修改成功");
+    }
+
+    public function BackDetail(){
+        $param = $this->request->only(['returnCode'=>''],'post','trim');
+    	$valide=Validate::rule([
+				'returnCode|退票申请编号'=>'require|max:255',
+			]);
+		if($valide->check($param)==false)return error($valide->getError());
+		$detail=PayReturn::alias('a')
+		->leftJoin('pay b','a.payNo=b.payNo and b.is_del=0')
+		->leftJoin('pay_payment c','a.orderCode=c.dzNo')
+		->where(['returnCode'=>$param['returnCode']])
+		->field('a.*,b.supplierNo,b.supplierName,b.companyNo,b.companyName,b.total_fee,b.apay_fee,b.wpay_fee,b.pay_fee,c.pay_fee pay_pay_fee')
+		->findOrEmpty();
+		if($detail->isEmpty())return error("退票申请不存在");
+		return success("获取成功",$detail);
+    }
+}

+ 355 - 0
app/cxinv/listener/ComonQrd.php

@@ -0,0 +1,355 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\cxinv\listener;
+
+use app\cxinv\model\Assoc;
+use app\cxinv\model\InvoiceInfo;
+use app\cxinv\model\InvoicePay;
+use app\cxinv\model\InvoicePool;
+use app\cxinv\model\InvoiceTicket;
+use app\cxinv\model\Pay;
+use app\cxinv\model\PayInfo;
+use app\cxinv\model\PayInvoice;
+use app\cxinv\model\QrdInfo;
+use app\cxinv\model\TagLog;
+use think\helper\Str;
+class ComonQrd
+{
+    /**
+     * 事件监听处理
+     * @return mixed
+     */
+    public function handle($event)
+    {
+        if($event['type']=='pay')$this->payComon($event);
+		if($event['type']=='repay')$this->repayComon($event);
+		if($event['type']=='inv'){
+		    $this->invComon($event);
+		    $this->InvToPay($event);
+		}
+		if($event['type']=='rinv'){
+		    $this->returnInv($event);
+		    $this->InvToPay($event,false);
+		}
+		if($event['type']=='check')$this->checkPay($event);
+    }
+    
+    public function InvToPay($data,$bool=True){
+                $invinfo =InvoicePool::with(["poolInfo"])->where(['invNo'=>$data['invNo']])->findOrEmpty();
+            	if($invinfo->isEmpty())return;
+            	if($invinfo->buyer_code !=='911100006337468570')return;
+            	if($bool){
+            		if($invinfo->status!=4 ||$invinfo->is_comon!=1 )return;
+            		$assoc_status=2;
+            	}else{
+            		$assoc_status=3;
+            		if(in_array($invinfo->status,[5,6,7,8,9])||$invinfo->is_comon!=1 )return;
+            	}
+
+            	$assoc = Assoc::where(["viceCode"=>$data['invNo'],"status"=>$assoc_status,"is_del"=>0,"type"=>1])->select();
+            	if($assoc->isEmpty()) return;
+            	$orderArr = QrdInfo::whereIn("sequenceNo",array_column($assoc->toArray(),"orderCode"))->select();
+            	if($orderArr->isEmpty())return;
+            	$payArr=array_column($assoc->toArray(),"cancel_fee","orderCode");
+            	$tag=[];
+    	        $qrdSave=[];
+            	foreach ($orderArr as $item){
+            		if(!isset($payArr[$item->sequenceNo]))continue;
+		           $tag_temp=[
+		                'code'=>$item->sequenceNo,
+		                'tag_id'=>107,//开票申请同步QR
+		                'creater'=>'system',
+		                'createrid'=>0,
+		                'tag_fee'=>0,
+		                'tag_img'=>'',
+		                "tag_code"=>$data['invNo'],
+		                'status'=>$bool?1:0
+		                ];
+		            $qrd=[
+		                'id'=>$item->id,
+			            'wpay_fee'=>$item->wpay_fee,
+			            'pay_status'=>$item->pay_status,
+			            'pay_tag_fee'=>$item->pay_tag_fee,
+			            'pay_tag' => 1
+			            ];
+		            if($bool){
+		            	if($item->wpay_fee>$payArr[$item->sequenceNo]){
+		            		$tag_temp['tag_fee']= $payArr[$item->sequenceNo];
+		            		$qrd['pay_tag_fee'] =$item->pay_tag_fee+$payArr[$item->sequenceNo];
+		            		$qrd['wpay_fee'] = $item->wpay_fee-$payArr[$item->sequenceNo];
+		            		$qrd['pay_status'] = ($qrd['wpay_fee']==0 &&$item->pay_fee==0) ? 3:($qrd['apay_fee']==0?1:2);
+		            	}else{
+		            		$tag_temp['tag_fee'] =$item->wpay_fee;
+		            		$qrd['pay_tag_fee'] =$item->pay_tag_fee+ $item->wpay_fee;
+		            		$qrd['wpay_fee'] = 0;
+		            		$qrd['pay_status'] = ($qrd['wpay_fee']==0 &&$item->pay_fee==0) ? 3:($qrd['apay_fee']==0?1:2);
+		            	}
+		            }else{
+                        $tag_temp['tag_fee']= $payArr[$item->sequenceNo];
+                        $tag_fee = ($item->pay_tag_fee>$payArr[$item->sequenceNo])?$payArr[$item->sequenceNo]:$item->pay_tag_fee;
+                        $qrd['pay_tag_fee']=$item->pay_tag_fee-$tag_fee;
+                        $qrd['wpay_fee'] = $item->wpay_fee+$tag_fee;
+                        $qrd['pay_status'] = ($qrd['wpay_fee']==0  &&$item->pay_fee==0) ? 3:($qrd['apay_fee']==0?2:1);
+		            }
+		            $qrdSave[]=$qrd;
+		            $tag[]=$tag_temp;
+            	};
+            	(new \app\admin\model\QrdInfo)->saveAll($qrdSave);
+            	(new \app\admin\model\TagLog)->saveAll($tag);
+    }
+    
+    public function payComon($data){
+    	$payinfo = Pay::where("payNo",$data['payNo'])->findOrEmpty();
+    	if($payinfo->isEmpty()) return;
+    	if($payinfo->is_comon!=1)return;
+    	if(!in_array($payinfo->status,[1,2]))return;
+    	$qrdNo = PayInfo::alias("a")->leftJoin("ComonOrder b","a.cgdNo=b.cgdNo")
+    	->where(["payNo"=>$data['payNo'],"is_del"=>0,"a.status"=>1])->column("orderCode");
+    	$qrdinfo = QrdInfo::where([["sequenceNo","in",$qrdNo],["wpay_fee",">",0]])->select();
+    	if($qrdinfo->isEmpty())return;
+    	$this->CheckComonOrder($payinfo);
+    	$tagInfo = TagLog::where(["code"=>$qrdNo,"tag_id"=>108,"status"=>1])->column("id,code,tag_id,creater,createrid,tag_fee,tag_img,status","code");
+    	$tag=[];
+    	$qrdSave=[];
+        $payfee=$data['pay_fee'];
+    	foreach ($qrdinfo as $item){
+    	    if(isset($tagInfo[$item->sequenceNo])){
+    	        $tag_temp = $tagInfo[$item->sequenceNo];
+    	    }else{
+    	        $tag_temp=[
+    	            "id"=>null,
+                    'code'=>$item->sequenceNo,
+                    'tag_id'=>108,//对账付款同步至QR
+                    'creater'=>'system',
+                    'createrid'=>0,
+                    'tag_fee'=>0,
+                    'tag_img'=>'',
+                    'status'=>1
+    			];
+    	    }
+    		$qrd=[
+    			"id"=>$item->id,
+	            "wpay_fee"=>$item->wpay_fee,
+	            "pay_status"=>$item->pay_status,
+	            "pay_tag_fee"=>0,
+	            "pay_tag" => 1
+	            ];
+    		if($item->wpay_fee>=$payfee){
+    			$tag_temp['tag_fee'] += $payfee;
+    			$qrd['pay_tag_fee'] = $item->pay_tag_fee+$payfee;
+    			$qrd['wpay_fee'] = ($item->wpay_fee>=$payfee)? $item->wpay_fee-$payfee:0;
+    			$qrd['pay_status'] = ($qrd['wpay_fee']==0 &&$item->pay_fee==0) ? 3:($item->apay_fee==0?1:2);
+    			$payfee=0;
+    		}else{
+    			$payfee=$payfee-$item->wpay_fee;
+    			$tag_temp['tag_fee'] +=$item->wpay_fee;
+    			$qrd['pay_tag_fee'] = $item->pay_tag_fee+$item->wpay_fee;
+    			$qrd['wpay_fee'] = 0;
+    			$qrd['pay_status'] = ($qrd['wpay_fee']==0 &&$item->pay_fee==0) ? 3:($item->apay_fee==0?1:2);
+    		}
+    		$qrdSave[]=$qrd;
+    		$tag[]=$tag_temp;
+    		if($payfee==0) break;
+    	}
+    	(new \app\admin\model\QrdInfo)->saveAll($qrdSave);
+    	(new \app\admin\model\TagLog)->saveAll($tag);
+    }
+    public function repayComon($data)
+    {
+        $payinfo = Pay::where('payNo', $data['payNo'])->findOrEmpty();
+        if ($payinfo->isEmpty()) return;
+        if ($payinfo->is_comon != 1) return;
+        if (!in_array($payinfo->status, [1, 2])) return;
+        $qrdNo   = PayInfo::alias('a')->leftJoin('ComonOrder b', 'a.cgdNo=b.cgdNo')->where(['payNo' => $data['payNo'], 'is_del' => 0, 'a.status' => 1])->column('orderCode');
+        $qrdinfo = QrdInfo::where([['sequenceNo', 'in', $qrdNo], ['pay_tag_fee', '>', 0], ['pay_tag', '=', 1]])
+            ->select();
+        if ($qrdinfo->isEmpty()) return;
+        $this->CheckComonOrder($payinfo);
+        $tagInfo = TagLog::where(['code'=>$qrdNo,'tag_id'=>108,'status'=>1])->column('id,code,tag_id,creater,createrid,tag_fee,tag_img,status','code');
+
+        $qrdSave =$tagsave =$del= [];
+         $payfee=$data['pay_fee'];
+        foreach ($qrdinfo as $item) {
+            if(!isset($tagInfo[$item->sequenceNo]))continue;
+            $tag_temp = $tagInfo[$item->sequenceNo];
+             $qrd = [
+                'id'          => $item->id,
+                'wpay_fee'    => $item->wpay_fee,
+                'pay_status'  => $item->pay_status,
+                'pay_tag_fee' => 0,
+                'pay_tag'     => 1
+            ];
+
+            if ($item->pay_tag_fee >=$payfee) {
+                $tag_temp['tag_fee']-= $payfee;
+                $qrd['pay_tag_fee']  = $item->pay_tag_fee-$payfee;
+                $qrd['pay_tag']  =$qrd['pay_tag_fee']>0?1:0;
+                $qrd['wpay_fee']     = $item->wpay_fee + $payfee;
+                $qrd['pay_status']   = ($qrd['wpay_fee'] == 0 && $item->pay_fee == 0) ? 3 : ($item->apay_fee == 0 ? 1 : 2);
+            } else {
+                $tag_temp['tag_fee']-= $item->pay_tag_fee;
+                $qrd['pay_tag_fee']  = 0;
+                $qrd['pay_tag']  = 0;
+                $qrd['wpay_fee']     = $item->wpay_fee +  $item->pay_tag_fee;
+                $qrd['pay_status']   = ($qrd['wpay_fee'] == 0 && $item->pay_fee == 0) ? 3 : ($item->apay_fee== 0 ? 1 : 2);
+            }
+            $qrdSave[] = $qrd;
+            if($tag_temp['tag_fee']<=0)$del[]=$tag_temp['id'];
+            else $tagsave[]=$tag_temp;
+        }
+        (new \app\admin\model\QrdInfo)->saveAll($qrdSave);
+        if(!empty($del))(new \app\admin\model\TagLog)->whereIn("id",$del)->delete();
+        if(!empty($tagsave))(new \app\admin\model\TagLog)->saveAll($tagsave);
+
+    }
+    public function returnInv($data){
+            $invinfo =InvoicePool::where(['invNo'=>$data['invNo'],"status"=>[5,6,7,8,9]])->findOrEmpty();
+        	if($invinfo->isEmpty())return;
+        	if($invinfo->is_comon!=1 )return;
+        	$invpay =InvoicePay::where(['invNo'=>$data['invNo']])->findOrEmpty();
+        	if($invpay->isEmpty())return;
+        	if($invpay->status!=1 )return;
+        	$payinfo = Pay::where('payNo',$invpay['payNo'])->findOrEmpty();
+        	if($payinfo->isEmpty()) return;
+        	if($payinfo->is_comon!=1)return;
+        	$payinvoice = PayInvoice::where(["hpNo"=>$invpay->hpNo,"status"=>4])->findOrEmpty();
+        	if($payinvoice->isEmpty())return;
+        	$payinvoice->status=10;
+        	$payinvoice->save();
+          $payinfo->winv_fee = $payinfo->winv_fee+$payinvoice->inv_fee;
+          $payinfo->ainv_fee = $payinfo->ainv_fee-$payinvoice->inv_fee;
+          $payinfo->inv_status = ($payinfo->winv_fee==0 &&$payinfo->inv_fee==0)?3:($payinfo->ainv_fee==0?2:1);
+          $this->CheckComonOrder($payinfo);
+          $payinfo->save();
+          $invpay->status =2;
+          $invpay->save();
+    }
+
+     protected function checkPay($data){
+    	$payinfo = Pay::where('payNo',$data['payNo'])->findOrEmpty();
+    	if($payinfo->isEmpty()) return;
+    	if($payinfo->is_comon!=1)return;
+    	$this->CheckComonOrder($payinfo);
+
+    }
+
+    public function CheckComonOrder($payinfo){
+    	if($payinfo->status==3||$payinfo->status==4 ){
+	        PayInfo::alias('a')
+	        ->leftJoin('ComonOrder b','a.cgdNo=b.cgdNo')
+	            ->where(['payNo'=>$payinfo->payNo,'is_del'=>0,'a.status'=>0])
+	            ->update(['b.status'=>0]);
+    	}else{
+    		if($payinfo->inv_status==3 &&$payinfo->pay_status==3){
+	            PayInfo::alias('a')
+	            ->leftJoin('ComonOrder b','a.cgdNo=b.cgdNo')
+	            ->where(['payNo'=>$payinfo->payNo,'is_del'=>0,'a.status'=>1])
+	            ->update(["b.status"=>2]);
+		        }elseif($payinfo->inv_status!=3|| $payinfo->pay_status!=3){
+		            PayInfo::alias('a')
+		            ->leftJoin('ComonOrder b','a.cgdNo=b.cgdNo')
+		            ->where(['payNo'=>$payinfo->payNo,'is_del'=>0,'a.status'=>1])
+		            ->update(['b.status'=>1]);
+		        }
+    		}
+    }
+    
+   //新开票完成 创建对应的标签;
+
+    protected function invComon($data){
+    	$invinfo =InvoicePool::where(['invNo'=>$data['invNo']])->findOrEmpty();
+    	if($invinfo->isEmpty())return;
+    	if($invinfo->status!=4 ||$invinfo->is_comon!=1 )return;
+    	$invpay =InvoicePay::where(['invNo'=>$data['invNo']])->findOrEmpty();
+    	if($invpay->isEmpty())return;
+    	if($invpay->status!=0 )return;
+    	$payinfo = Pay::where('payNo',$invpay['payNo'])->findOrEmpty();
+    	if($payinfo->isEmpty()) return;
+    	if($payinfo->is_comon!=1)return;
+    	if(!in_array($payinfo->status,[1,2]))return;
+    	$ticket =InvoiceTicket::where(["invNo"=>$data['invNo'],"type"=>0])->findOrEmpty();
+    	if($ticket->isEmpty())return;
+    	$pay_fee=0;
+    	if($payinfo->winv_fee >=$invinfo->inv_value){
+    	  $pay_fee = $invinfo->inv_value;
+    	}else{
+    	   $pay_fee = $payinfo->winv_fee;
+    	}
+    	$payinvoice = [
+    		"payNo"=>$invpay['payNo'],
+    		"hpNo"=>makeNo("hp"),
+    		"apply_id"=>0,
+    		"apply_name"=>"system",
+    		"invType"=>$invinfo->open_type==3?1:3,
+    		"invoiceType"=>$invinfo->inv_type,
+    		"inv_fee"=>$pay_fee,
+    		"inv_subtotal_amount"=>$ticket->inv_subtotal,
+    		"inv_amount"=>$ticket->inv_total,
+    		"invStatus"=>1,
+    		"status"=>4,
+    		"check_time"=>date("Y-m-d H:i:s"),
+    		"open_time"=>$ticket->open_date,
+    		"invoiceNumber"=>$ticket->inv_number,
+    		"seller_check"=>1,
+    		"buyer_check"=>1,
+    		"invoiceCode"=>$ticket->inv_code,
+    		"checkNumber"=>$ticket->check_code,
+    		"checkApi"=>$data['checkApi']??0
+    		];
+    	$payinfo->winv_fee = $payinfo->winv_fee-$pay_fee;
+    	$payinfo->ainv_fee = $payinfo->ainv_fee+$pay_fee;
+    	$payinfo->inv_status = ($payinfo->winv_fee==0 &&$payinfo->inv_fee==0)?3:($payinfo->ainv_fee==0?1:2);
+    	$this->CheckComonOrder($payinfo);
+    	$payinfo->save();
+    	PayInvoice::create($payinvoice);
+    	if(!empty($ticket->item)){
+    	    		$itemArr=[];
+    	    		foreach ($ticket->item as $item){
+    	    		    $temp=[];
+    	    		    $temp['name']=$item['XMMC'];
+    	    		    $temp['unit']=$item['DW'];
+    	    		    $temp['quantity']=$item['SPSL'];
+    	    		    $temp['unit_price']=$item['DJ'];
+    	    		    $temp['amount']=$item['JE'];
+    	    		    $temp['tax']=$item['SE'];
+    	    		    $temp['tax_rate']= Str::contains($item['SL'],"%")?$item['SL']:strval($item['SL']*100)."%" ;
+    				    $itemArr[]=$temp;
+    			    }
+    	}
+    		    $info=[
+    			    'payNo'          =>$invpay['payNo'] ,
+    			    'hpNo'           =>$payinvoice['hpNo'] ,
+    			    'type'           =>$invinfo['inv_type'] ,
+    			    'number'         =>$ticket->inv_number ,
+    			    'code'           =>$ticket->inv_code ,
+    			    'check_code'     =>$ticket->check_code ,
+    			    'issue_date'     =>date('Ymd' ,strtotime($ticket->open_date)) ,
+    			    'buyer_name'     =>$ticket->buyer_title ,
+    			    'buyer_id'       =>$ticket->buyer_id ,
+    			    'buyer_address'  =>$ticket->buyer_addr . $ticket->buyer_mobile ,
+    			    'buyer_bank'     =>$ticket->buyer_bank . $ticket->buyer_bankNo ,
+    			    'seller_name'    =>$ticket->seller_title ,
+    			    'seller_id'      =>$ticket->seller_id ,
+    			    'seller_address' =>$ticket->seller_addr . $ticket->seller_mobile ,
+    			    'seller_bank'    =>$ticket->seller_bank . $ticket->seller_bankNo ,
+    			    'subtotal_amount'=>$ticket->inv_subtotal ,
+    			    'subtotal_tax'   =>$ticket->tax_fee ,
+    			    'total'          =>$ticket->inv_total ,
+    			    'item_list'      =>$itemArr,
+    			    'receiver'       =>$ticket->reciver ,
+    			    'issuer'         =>$ticket->issuer ,
+    			    'reviewer'       =>$ticket->reviewer ,
+    			    'change_field'   =>'' ,
+    			    "status"=>1,
+    		    ];
+    	        InvoiceInfo::create($info);
+//    	        $invoiceItem = InvoiceItem::where(["invoiceCode"=>$data['invNo'],"status"=>[1,2]])->select();
+//    	        if(!$invoiceItem->isEmpty()){
+//    	            InvoiceItem::CopyItem($data['invNo'],$payinvoice['hpNo']);
+//    	        }
+    		    $invpay->hpNo = $payinvoice['hpNo'];
+    		    $invpay->status =1;
+    		    $invpay->save();
+    }
+}

+ 45 - 0
app/cxinv/listener/Report.php

@@ -0,0 +1,45 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\cxinv\listener;
+
+class ReportCode
+{
+    protected $model;
+    /**
+     * 事件监听处理
+     *
+     * @return mixed
+     */
+    public function handle($event)
+    {
+        $this->model = new \app\cxinv\model\ReportCode();
+        if($event['type']=='add'){
+
+            $this->addField($event['param']);
+        }
+        if ($event['type']=='sub'){
+            $this->subField($event['param']);
+        }
+    }
+
+    private function subField($param){
+        if(is_string($param['value'])){
+            $this->model->whereFindInSet($param['key'],$param['value'])->select()->each(function($item)use($param){
+                $item->rmField($param['key'],$item[$param['key']]);
+            });
+        }
+        if(is_array($param['value'])){
+           foreach ($param['value'] as $v){
+              $this->model->whereFindInSet($param['key'],$v)->select()->each(function($item)use($param){
+                              $item->rmField($param['key'],$item[$param['key']]);
+                          });
+           }
+        }
+    }
+
+    private function addField($param){
+        $info= $this->model->where([$param['main']['key']=>$param['main']['value']])->find()->setField($param['key'],$param['value']);
+        $this->model->save();
+    }
+}

+ 2 - 0
app/cxinv/model/CgdInfo.php

@@ -87,4 +87,6 @@ class CgdInfo extends Base
         'cgd_apply_id'  =>'int',//竞单人
         'cgd_apply_name'  =>'varchar',//竞单人
        ];
+    protected $updateTime = 'updatetime';
+    protected $createTime = 'addtime';
 }

+ 8 - 1
app/cxinv/model/Invoice.php

@@ -22,7 +22,10 @@ class Invoice extends Base{
 		             "fully_digitalized_special_electronic"=>"全电专用发票",
 		             "fully_digitalized_normal_electronic"=>"全电普通发票",
                     ];
-
+    //0待验证1待关联订单2待买方公司审核3待买方公司认证4 认证完成 5 发票取消 6 买方审核驳回 7 认证失败 8 验票失败 9 退票成功
+    public function Items(){
+        return $this->hasMany(InvoiceItem::class,'invoiceCode','InvCode');
+    }
     public static function onAfterWrite(Model $model) : void{
          $change = $model->getChangedData();
          if (isset($change['status'])){
@@ -52,6 +55,10 @@ class Invoice extends Base{
                     }
                  }
              }
+
+             if($change['status']==9){
+                  InvoiceItem::refund($model->InvCode);
+             }
          }
     }
 }

+ 12 - 2
app/cxinv/model/InvoiceItem.php

@@ -57,7 +57,7 @@ class InvoiceItem extends Base{
                 }
         }
     }
-
+    //流程结束
     public static function rmInvoice($code,$orderType=2){
         $items = self::where(['invoiceCode'=>$code,'order_type'=>$orderType])->select();
        if(!empty($items)){
@@ -68,7 +68,17 @@ class InvoiceItem extends Base{
             self::where(['invoiceCode'=>$code,'order_type'=>$orderType])->save(["status"=>3]);
        }
     }
-
+    //退票申请
+    public static function refund($invNo){
+        $info = self::where(['invoiceCode'=>$invNo,'order_type'=>2])->select();
+        if(!$info->isEmpty()){
+            $orderItems=InvoiceOrder::whereIn('itemId',$info->column('id'))->where(["status"=>[1,2]])->select();
+            if(!$orderItems->isEmpty()){
+                InvoiceOrder::whereIn('itemId',$info->column('id'))->where(['status'=>[1,2]])->save(["status"=>4]);
+            }
+            self::where(['invoiceCode'=>$invNo,'order_type'=>2])->save(["status"=>3]);
+        }
+    }
     public static function CopyItem($invNo,$hpNo){
         $info = self::where(['invoiceCode'=>$invNo,'order_type'=>1])->select();
         if(!$info->isEmpty()){

+ 2 - 2
app/cxinv/model/InvoiceOrder.php

@@ -117,7 +117,7 @@ class InvoiceOrder extends Base{
           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->inv_status = $cgdinfo->ainv_fee==0?1:2;
               $cgdinfo->save();
           }
          $payinfo = PayInfo::where(['cgdNo'=>$info->code,'status'=>1,'is_del'=>0])->findOrEmpty();
@@ -126,7 +126,7 @@ class InvoiceOrder extends Base{
            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->inv_status = $pay->ainv_fee==0?1:2;
                $pay->save();
            }
          }

+ 52 - 2
app/cxinv/model/PayPayment.php

@@ -1,7 +1,7 @@
 <?php
 namespace app\cxinv\model;
 
-class PayPayment extends Base
+use think\Model;class PayPayment extends Base
 {
 //设置字段信息
     protected $schema = [
@@ -14,10 +14,60 @@ class PayPayment extends Base
         'return_img'  =>'text',//付款回执
         'return_time'  =>'varchar',//付款回执时间
         'tag_id'  =>'int',//标签id
-        'status'  =>'tinyint',//审核状态 0 待发起流程1 待业务审核 2待财务审核 3 待付款回执 4付款完成 5 业务驳回 6财务驳回
+        'status'  =>'tinyint',//审核状态 0 待发起流程1 待业务审核 2待财务审核 3 待付款回执 4付款完成 5 付款已退 6业务驳回 7 财务驳回 8 已作废
         'remark'  =>'varchar',//
         'is_del'  =>'tinyint',//
         'addtime'  =>'datetime',//
         'updatetime'  =>'datetime',//
        ];
+
+    protected $createTime='addtime';
+    protected $updateTime="updatetime";
+
+    public static function onAfterUpdate(Model $model) : void{
+        $changed = $model->getChangedData();
+        $dzNo = $model['dzNo'];
+        if(isset($changed['status'])){
+             $pay = Pay::where(['payNo'=>$model['payNo'],"is_del"=>0,"status"=>2])->findOrEmpty();
+             if($pay->isEmpty()) return;
+             $stageOrder = PaymentOrder::where(['dzNo'=>$dzNo,"is_del"=>0])->select();
+          switch ($changed['status']){
+              case 4:
+                  $pay->apay_fee = $pay->apay_fee+$model['pay_fee'];
+                  $pay->pay_fee = $pay->pay_fee-$model['pay_fee'];
+                  $pay->pay_status= $pay->wpay_fee==0 &&  $pay->pay_fee ==0 ? 3:2;
+                  $pay->save();
+                  if($stageOrder->isEmpty()==false){
+                      PaymentOrder::where(['dzNo'=>$dzNo,"status"=>0,'is_del'=>0])->save(["status"=>1]);
+                  }
+                  event('comonOrder',['payNo'=>$model['payNo'],'pay_fee'=>$model['pay_fee'],'type'=>'pay']);
+                  break;
+              case 5:
+                  $pay->apay_fee = $pay->apay_fee-$model['pay_fee'];
+                  $pay->wpay_fee = $pay->wpay_fee+$model['pay_fee'];
+                  $pay->pay_status= $pay->apay_fee==0 ? 1:2;
+                  $pay->save();
+                  if($stageOrder->isEmpty()==false){
+                      PaymentOrder::where(['dzNo'=>$dzNo,'status'=>1,'is_del'=>0])->save(['status'=>2]);
+                  }
+                  event('comonOrder',['payNo'=>$model['payNo'],'pay_fee'=>$model['pay_fee'],'type'=>'repay']);
+                  event('report_code',['type'=>'sub','key'=>'dzNo','value'=>$model['dzNo']]);
+                  break;
+              case 6:
+              case 7:
+              case 8:
+                  $pay->wpay_fee = $pay->wpay_fee+$model['pay_fee'];
+                  $pay->pay_fee = $pay->pay_fee-$model['pay_fee'];
+                  $pay->pay_status= $pay->apay_fee==0 ? 1:2;
+                  $pay->save();
+                  if($stageOrder->isEmpty()==false){
+                      PaymentOrder::where(['dzNo'=>$dzNo,'status'=>0,'is_del'=>0])->save(['status'=>3]);
+                  }
+                  event("report_code",["type"=>"sub","key"=>"dzNo","value"=>$model['dzNo']]);
+                  break;
+              default:
+                  break;
+          }
+        }
+    }
 }

+ 59 - 0
app/cxinv/model/PaymentOrder.php

@@ -0,0 +1,59 @@
+<?php
+
+
+namespace app\cxinv\model;
+
+
+use think\Model;use think\model\concern\SoftDelete;
+class PaymentOrder extends Base{
+    use SoftDelete;
+    protected $createTime='createTime';
+    protected $updateTime='updateTime';
+    protected $deleteTime='delete_time';
+    //CREATE TABLE `cfp_payment_order` (
+    //  `id` int(11) NOT NULL AUTO_INCREMENT,
+    //  `dzNo` varchar(255) NOT NULL COMMENT '对账付款申请编号',
+    //  `cgdNo` varchar(255) NOT NULL COMMENT '关联采购单编号',
+    //  `rela_fee` decimal(18,2) NOT NULL COMMENT '关联金额',
+    //  `status` tinyint(3) NOT NULL COMMENT '状态 0 关联中 1 已付款 2 解除付款 3 取消付款',
+    //  `createTime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
+    //  `updateTime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
+    //  `delete_time` datetime DEFAULT NULL,
+    //  PRIMARY KEY (`id`)
+    //) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='付款申请关联订单数据';
+    protected $schema=[
+        'id'=>'int',
+        'dzNo'=>'string',
+        'cgdNo'=>'string',
+        'rela_fee'=>'decimal',
+        'status'=>'tinyint',
+        'createTime'=>'datetime',
+        'updateTime'=>'datetime',
+        'delete_time'=>'datetime'
+    ];
+        //状态 0 关联中 1 已付款 2 解除付款 3 取消付款',
+    public static function onAfterWrite(Model $model) : void{
+         $cgdNo = $model->cgdNo;
+         $status = $model->status;
+         $cgdinfo = CgdInfo::where(["sequenceNo"=>$cgdNo,"is_del"=>0,"status"=>1])->findOrEmpty();
+         if($cgdinfo->isEmpty()) return;
+         switch ($status){
+             case 0:
+                 $cgdinfo->wpay_fee= $cgdinfo->wpay_fee-$model->rela_fee;
+                 break;
+             case 1:
+                 $cgdinfo->apay_fee= $cgdinfo->apay_fee+$model->rela_fee;
+                 break;
+             case 2:
+                 $cgdinfo->apay_fee= $cgdinfo->apay_fee-$model->rela_fee;
+                 $cgdinfo->wpay_fee= $cgdinfo->wpay_fee+$model->rela_fee;
+                 break;
+             case 3:
+                $cgdinfo->wpay_fee= $cgdinfo->wpay_fee+$model->rela_fee;
+                break;
+                default:
+                 return;
+         }
+         $cgdinfo->save();
+    }
+}

+ 24 - 0
app/cxinv/model/ReportCode.php

@@ -27,4 +27,28 @@ class ReportCode extends Base
         'returnInv'  =>'varchar',//销售单退票申请编号
         'returnTrad'  =>'varchar',//销售单退款申请编号
        ];
+    public function setField($filed,$vale){
+        $arr= explode(',',$this->$filed);
+       if(!in_array($vale,$arr)) $this->$filed == '' ? $this->$filed =$vale : $this->$filed .=','.$vale;
+    }
+    public function rmField($filed,$vale){
+          $arr= explode(',',$this->$filed);
+          if(is_array($vale)){
+              foreach ($vale as $v){
+                  if(in_array($v,$arr)){
+                      $key = array_search($v,$arr);
+                      unset($arr[$key]);
+                  }
+              }
+          }else{
+              if(in_array($vale,$arr)){
+                  $key = array_search($vale,$arr);
+                  unset($arr[$key]);
+              }
+          }
+         $this->$filed=implode(',',$arr);
+    }
+    public function __destruct(){
+      $this->save();
+    }
 }

+ 8 - 0
app/cxinv/model/RoleAction.php

@@ -39,4 +39,12 @@ class RoleAction extends Base
         public function SetPrivateDataAttr($v){
               return json_encode($v,JSON_UNESCAPED_UNICODE);
         }
+
+    public static function checkRole($roleid,$actionid){
+        $info = self::where([['role_id',"in",$roleid],["status","=",1]])->findOrEmpty();
+        if ($info->isEmpty()) return false;
+        $provate_data = $info->private_data;
+        if(is_array($actionid))return empty(array_intersect($actionid,$provate_data))==false;
+        if(is_string($actionid)||is_int($actionid)) return in_array($actionid,$provate_data);
+    }
 }

+ 1 - 0
app/event.php

@@ -16,6 +16,7 @@ return [
         "PlatCat"=>[app\admin\listener\PlatCat::class],
         "copyCompany"=>[\app\listener\CopyCompany::class],
         "updateSupplierGood"=>[app\admin\listener\updateSupplierGood::class],
+        "report_code"=>[app\cxinv\listener\ReportCode::class]
     ],
 
     'subscribe' => [