wugg 1 year ago
parent
commit
81b0c44885

+ 24 - 24
app/admin/command/GenerrateInvoice.php

@@ -23,18 +23,22 @@ class GenerrateInvoice extends Command
 
     protected function execute(Input $input, Output $output)
     {
+    	$generrateinvoice= Cache::store("redis")->get("generrateinvoice");
+	    if($generrateinvoice==0) Cache::store("redis")->set("generrateinvoiceo",1,180);
+	  	    Db::startTrans();
         // 指令输出
         try {
-        	 $generrateinvoice= Cache::store("redis")->get("generrateinvoice");
-        	 if($generrateinvoice==0) Cache::store("redis")->set("generrateinvoiceo",1,180);
-			$data =$this->GetAll();
-			if(empty($data)){
-				return '暂无数据处理';
-			}
-			$seller_code =$this->isTicket();
-			$fail=[];
-			$interface =[];
+        	$data =$this->GetAll();
+		    if(empty($data)){
+		    	Db::rollback();
+			    return '';
+		    }
+		    $date=date("Y-m-d H:i:s");
+		    $seller_code =$this->isTicket();
+		    $fail=[];
+		    $interface =[];
 			foreach ($data as $value){
+				$invNo=$value['invNo'];
 				if(!in_array($value['XHFSBH'],$seller_code)){
 					Db::name("invoice_interface")->where(['invNo'=>$value['invNo']])->update(["status"=>3,"remark"=>"不支持金税","updatetime"=>date("Y-m-d H:i:s")]);
 					$fail[]=$value['invNo'];
@@ -53,31 +57,26 @@ class GenerrateInvoice extends Command
 				unset($value['KPFS']);
 				unset($value['FPLXDM']);
 				unset($value['DDQQPCH']);
-//				unset($value['YFPDM']);
-//				unset($value['YFPHM']);
-//				unset($value['YFPLX']);
-//				unset($value['YFPKPRQ']);
-//				unset($value['CHYY']);
-//				unset($value['TSCHBZ']);
-//				unset($value['BZ']);
-//				unset($value['GMFSJH']);
-//				unset($value['GMFBM']);
 				$temp["DDMXXX"]=$value['DDMXXX'];
 				unset($value['DDMXXX']);
 				$temp["DDTXX"]=$value;
 				$interface[$value['XHFSBH']."-".$fplxdm]['DDZXX'][]=$temp;
+				$output->writeln( "【 $date 】开票单号".$invNo);
 			}
 			$this->CheckInvoice($interface);
+	        $output->writeln( "【 $date 】开票申请成功");
+	        Db::commit();
+	        Cache::store("redis")->set("generrateinvoice",0);
 		}catch (\Exception $e){
         	Cache::store("redis")->set("generrateinvoice",0);
-        	return $e->getMessage();
+        	Db::rollback();
+	        $output->writeln( "【 $date 】开票申请失败".$e->getMessage());
 		}
 		Cache::store("redis")->set("generrateinvoice",0);
-        $output->writeln('generrateinvoice');
     }
 
     protected function GetAll(){
-        $list =Db::name("invoice_interface")->json(["DDMXXX"])->withoutField("id,status,is_check,result,remark,addtime,updatetime")->limit(1)->where(["status"=>0])->select();
+        $list =Db::name("invoice_interface")->json(["DDMXXX"])->lock(true)->withoutField("id,status,is_check,result,remark,addtime,updatetime")->limit(1)->where(["status"=>0])->select()->toArray();
         return $list;
     }
 
@@ -88,16 +87,17 @@ class GenerrateInvoice extends Command
 
     protected function CheckInvoice($data){
     	if(empty($data)){
-    		return '';
+    		throw  new  \Exception("开票数据不能为空");
     	}
     	$invoice=Config::get("invoice");
     	$tax =new TaxInvoice($invoice['appKey'],$invoice['appSecret'],$invoice['entCode']);
     	foreach ($data AS $value){
-			$result = $tax->GenerateInvoice($OrderBatchArr=$value['DDPCXX'],$OrderInvList=$value['DDZXX']);
+
+			$result = $tax->GenerateInvoice($value['DDPCXX'],$value['DDZXX']);
+
 			if(isset($result['ZTDM'])&&$result['ZTDM']=='010000'){
 				Db::name("invoice_interface")->where(['DDQQPCH'=>$result['DDQQPCH']])->update(['status'=>1,
 				"remark"=>$result['ZTXX'],"updatetime"=>date("Y-m-d H:i:s")]);
-				Cache::push("DDQQPCH",$result['DDQQPCH']);
 			}else{
 				Db::name("invoice_interface")->where(['DDQQPCH'=>$value['DDPCXX']['DDQQPCH']])->update(['status'=>4,"remark"=>$result['ZTXX']??$result['message'],"updatetime"=>date("Y-m-d H:i:s")]);
 			}

+ 101 - 71
app/admin/command/GetOrderInfoAndInvoiceInfo.php

@@ -26,91 +26,98 @@ class GetOrderInfoAndInvoiceInfo extends Command
         // 指令输出
        $GetOrderInfoAndInvoiceInfo= Cache::store("redis")->get("GetOrderInfoAndInvoiceInfo");
        if($GetOrderInfoAndInvoiceInfo==0) Cache::store("redis")->set("GetOrderInfoAndInvoiceInfo",1,180);
-		$data = $this->GetData();
-		foreach ($data as $value){
-			if($value['status']==1){
-				$res=$this->GetOrderInfo($value);
+	    Db::startTrans();
+		try{
+			$data = $this->GetData();
+			if(empty($data)) {
+				Db::rollback();
+				return '';
 			}
-			if($value['status']==2){
-				if($value['KPLX']==1){
-					$red=Db::name("invoice_red")->where(["invRed"=>$value['invNo'],"is_del"=>0])->find();
-					if($red){
-						$invNo=$red['invNo'];
-						Db::name("invoice_return")->where(["returnCode"=>$red['returnCode'],"status"=>1])->update
-						(["status"=>2,"updatetime"=>date("Y-m-d H:i:s")]);
-						Db::name("invoice_red")->where(["invRed"=>$value['invNo'],"is_del"=>0])->update(["status"=>4,"updatetime"=>date("Y-m-d H:i:s")]);
-						Db::name("invoice_pool")->where(["invNo"=>$red['invNo'],"is_del"=>0])->update(["status"=>6,"updatetime"=>date("Y-m-d H:i:s")]);
-					}
-				}else{
-					$invNo=$value['invNo'];
-					$status=3;
-					$rmark=$this->updateQRd($invNo);
-					if($rmark==''){
-						Db::name("invoice_pool")->where(["invNo"=>$value['invNo'],"is_del"=>0])->update
-						(["status"=>$status,"seller_check"=>1,"buyer_check"=>1,"updatetime"=>date("Y-m-d H:i:s")]);
+			$date=date("Y-m-d H:i:s");
+			foreach ($data as $value){
+				if($value['status']==1){
+					$this->GetOrderInfo($value);
+				}
+				if($value['status']==2){
+					if($value['KPLX']==1){
+							$red=Db::name("invoice_red")->where(["invRed"=>$value['invNo'],"is_del"=>0])->find();
+							if($red){
+								$invNo=$red['invNo'];
+								Db::name("invoice_return")->where(["returnCode"=>$red['returnCode'],"status"=>1])->update(["status"=>2,"updatetime"=>date("Y-m-d H:i:s")]);
+								Db::name("invoice_red")->where($red)->update(["status"=>4,"remark"=>"开票成功","updatetime"=>date("Y-m-d H:i:s")]);
+								Db::name("invoice_pool")->where(["invNo"=>$red['invNo'],"is_del"=>0])->update(["status"=>6,"updatetime"=>date("Y-m-d H:i:s")]);
+							}
+
 					}else{
-						Db::name("invoice_pool")->where(["invNo"=>$value['invNo'],"is_del"=>0])->update(["status"=>5,"remark"=>$rmark,"updatetime"=>date("Y-m-d H:i:s")]);
+							$invNo = $value['invNo'];
+							Db::name("invoice_pool")->where(["invNo"=>$value['invNo'],"is_del"=>0])->update(["status"=>4,"seller_check"=>1,"buyer_check"=>1,"updatetime"=>date("Y-m-d H:i:s")]);
 					}
+					$da=Db::name("invoice_interface")->where($value)->update(["is_check"=>1,"updatetime"=>date("Y-m-d H:i:s")]);
+					if($da) $this->insertTicket($value['result'],$invNo);
 				}
-				$da=Db::name("invoice_interface")->where($value)->update(["is_check"=>1,"updatetime"=>date("Y-m-d 
-				H:i:s")]);
-				if($da) $this->insertTicket($value['result'],$invNo);
-			}
-			if($value['status']==3 || $value['status']==4){
-				if($value['KPLX']==1){
-					Db::name("invoice_red")->where(["invRed"=>$value['invNo'],"is_del"=>0])->update(["status"=>6,"updatetime"=>date("Y-m-d H:i:s")]);
-
-				}else{
-					Db::name("invoice_pool")->where(["invNo"=>$value['invNo'],"is_del"=>0])->update(["status"=>5,"updatetime"=>date("Y-m-d H:i:s")]);
+				if($value['status']==3 || $value['status']==4){
+					if($value['KPLX']==1){
+						Db::name("invoice_red")->where(["invRed"=>$value['invNo'],"is_del"=>0])->update(["status"=>6,"remark"=>"红冲开票失败","updatetime"=>date("Y-m-d H:i:s")]);
+						Db::name("invoice_return")->where(["returnCode"=>$red['returnCode'],"status"=>1])->update(["status"=>4,"remark"=>"红冲开票失败","updatetime"=>date("Y-m-d H:i:s")]);
+					}else{
+						Db::name("invoice_pool")->where(["invNo"=>$value['invNo'],"is_del"=>0])->update(["status"=>5,"check_remark"=>$value['remark'],"updatetime"=>date("Y-m-d H:i:s")]);
 
+					}
+					Db::name("invoice_interface")->where($value)->update(["is_check"=>1,"updatetime"=>date("Y-m-d H:i:s")]);
 				}
-				Db::name("invoice_interface")->where($value)->update(["is_check"=>1,"updatetime"=>date("Y-m-d H:i:s")]);
 			}
+			$output->writeln( "【 $date 】验票完成".$value['invNo']);
+			Db::commit();
+			Cache::store("redis")->set("GetOrderInfoAndInvoiceInfo",0);
+		}catch (\Exception $exception){
+			Cache::store("redis")->set("generrateinvoice",0);
+			Db::rollback();
+			$output->writeln( "【 $date 】开票申请失败".$exception->getMessage().$exception->getLine());
 		}
+
 		 Cache::store("redis")->set("GetOrderInfoAndInvoiceInfo",0);
-        $output->writeln('getorderinfoandinvoiceinfo');
+
     }
 
     protected function GetData(){
     	$list=Db::name("invoice_interface")->where([["status",">=",1],["is_check","=",0],["updatetime","<=",date("Y-m-d 
-    	H:i:s")]])->cursor();
-    	foreach ($list as $value){
-    		yield $value;
-    	}
+    	H:i:s")]])->limit(20)->lock(true)->select()->toArray();
+        return $list;
     }
 
     protected function GetOrderInfo($order){
     	$invoice=Config::get("invoice");
-    	$tax =new \TaxInvoice($invoice['appKey'],$invoice['appSecret'],'911101050628285328');
+    	$tax =new \TaxInvoice($invoice['appKey'],$invoice['appSecret'],$invoice['entCode']);
 		$result=$tax->GetOrderInfoAndInvoiceInfo($order['XHFSBH'],$order['DDQQLSH']);
-		if($result['ZTDM'] && $result['ZTDM']=='000000'){
+		if(isset($result['ZTDM'])&& $result['ZTDM']=='000000'){
 			foreach ($result['DDFPZXX'] as $value){
 				$zt=$value['DDFPXX']['DDZT'];
 				$ztxx=$value['DDFPXX']['DDZTXX'];
 				if($zt=='030000'){
 					$data= $value['DDFPXX'];
 					$data['itemlist'] = $value['DDMXXX'];
-					if($data['KPLX']==0)$this->updateGood($value['DDMXXX'],$order['invNo']);
+					if($data['KPLX']==0)$this->updateGood($value['DDMXXX'],$order['invNo'],4);
+					else $this->updateGood($value['DDMXXX'],$order['invNo'],6);
 					$exit= json_encode($data,JSON_UNESCAPED_UNICODE);
 					Db::name("invoice_interface")->where(["DDQQLSH"=>$value['DDFPXX']['DDQQLSH']])->update(["status"=>2,"result"=>$exit,"remark"=>$ztxx,"updatetime"=>date("Y-m-d H:i:s")]);
 				}
 				if($zt=='031999' ||$zt=='032997'||$zt=='032999'||$zt=='032998' ){
-					Db::name("invoice_interface")->where(["DDQQLSH"=>$value['DDFPXX']['DDQQLSH']])->update
-					(["status"=>4,"is_check"=>1,"remark"=>$ztxx,"updatetime"=>date("Y-m-d H:i:s")]);
+					Db::name("invoice_interface")->where(["DDQQLSH"=>$value['DDFPXX']['DDQQLSH']])->update(["status"=>4,"is_check"=>1,"remark"=>$ztxx,"updatetime"=>date("Y-m-d H:i:s")]);
 				}
 				if($zt=='031000' ||$zt=='032000'){
 					Db::name("invoice_interface")->where(["DDQQLSH"=>$value['DDFPXX']['DDQQLSH']])->update(["remark"=>$ztxx,"updatetime"=>date("Y-m-d H:i:s")]);
-//					Db::name("invoice_red")->where(["DDQQLSH"=>$value['DDFPXX']['DDQQLSH']])->update(["remark"=>$ztxx,"updatetime"=>date("Y-m-d H:i:s")]);
-
 				}
 			}
+		}else{
+			throw new \Exception($result['message']);
 		}
     }
 
     protected function insertTicket($data,$invNo=''){
-    	$invinfo =Db::name("invoice_ticket")->where(["invNo"=>$invNo,'is_del'=>0])->findOrEmpty();
-		$json= json_decode($data,true);
+	    $json= json_decode($data,true);
+
 		if(is_array($json)&&!empty($json)){
+			$invinfo =Db::name("invoice_ticket")->where(["invNo"=>$invNo,'type'=>$json['KPLX'],'is_del'=>0])->findOrEmpty();
 			if(empty($invinfo)){
 				$invinfo["invNo"]=$invNo;
 				$invinfo["status"]=1;
@@ -147,52 +154,75 @@ class GetOrderInfoAndInvoiceInfo extends Command
 		}
 
     }
-    private function updateGood($data,$invNo){
+    private function updateGood($data,$invNo,$status=4){
 			if(empty($data))return;
+			if($status==6)$invNo =Db::name("invoice_red")->where(["invRed"=>$invNo,"is_del"=>0])->value("invNo",'');
 			foreach ($data as $value){
 				if($value['ZXBM']!=''){
-				$invinfo =Db::name("invoice_good")->where(["invNo"=>$invNo,"id"=>$value['ZXBM'],'is_del'=>0])->findOrEmpty();
-				if(empty($invinfo)) continue;
-				$invinfo['goodPrice'] = $value['DJ'];
-				$invinfo['totalPrice'] = $value['JE'];
-				$invinfo['taxPrice'] = $value['SE'];
-				Db::name("invoice_good")->save($invinfo);
+					$invinfo =Db::name("invoice_good")->where(["invNo"=>$invNo,"id"=>$value['ZXBM'],'is_del'=>0])->findOrEmpty();
+					if(empty($invinfo)) continue;
+					if($status==4){
+					$invinfo['goodPrice'] = $value['DJ'];
+					$invinfo['totalPrice'] = $value['JE'];
+					$invinfo['taxPrice'] = $value['SE'];
+					}else{
+					$invinfo['goodNum'] =0;
+					}
+					$invinfo['updatetime'] = date("Y-m-d H:i:s");
+					Db::name("invoice_good")->save($invinfo);
 				}
 			}
+			$this->updateQRd($invNo,$status);
 		}
 
 
-		private  function updateQRd($invNo){
+		private  function updateQRd($invNo,$status){
             	$qrdArr=Db::name("assoc")->where(["viceCode"=>$invNo,"is_del"=>0])->column("id,orderCode,cancel_fee");
                  if(!empty($qrdArr)){
-
                       foreach ($qrdArr as $value){
                           $qrdinfo =Db::name("qrd_info")->where(["sequenceNo"=>$value['orderCode']])->find();
                           if($qrdinfo==false){
-                              return "确认单信息未找到";
+                              echo  "$invNo 确认单信息未找到\r\n";break;
                           }
-                          if($qrdinfo['inv_fee']<$value['cancel_fee']){
-
-                              return "确认单信息开票金额不足";
+                          if($status==4){
+	                            if($qrdinfo['inv_fee']<$value['cancel_fee']){
+	                              echo  "$invNo 确认单信息开票金额不足 \r\n";
+	                              break;
+	                          }
+	                          $update =[
+	                              "ainv_fee"=>$qrdinfo['ainv_fee']+$value['cancel_fee'],
+	                              "inv_fee"=>$qrdinfo['inv_fee']-$value['cancel_fee'],
+	                              "invtime"=>date("Y-m-d H:i:s"),
+	                              "inv_status"=>$qrdinfo['winv_fee']==0 &&($qrdinfo['inv_fee']-$value['cancel_fee'])==0 ? 3 : 2,
+	                              "updatetime"=>date("Y-m-d H:i:s"),
+	                          ];
+                          }
+                           if($status==6){
+	                             if($qrdinfo['ainv_fee']<$value['cancel_fee']){
+	                              echo "$invNo 确认单信息开票金额不足 \r\n";break;
+	                          }
+	                          $update =[
+	                              "ainv_fee"=>$qrdinfo['ainv_fee']-$value['cancel_fee'],
+	                              "winv_fee"=>$qrdinfo['winv_fee']+$value['cancel_fee'],
+	                              "invtime"=>'',
+	                              "inv_status"=>$qrdinfo['inv_fee']==0 &&($qrdinfo['ainv_fee']-$value['cancel_fee'])==0 ? 1 : 2,
+	                              "status"=>$qrdinfo['inv_fee']==0 &&($qrdinfo['ainv_fee']-$value['cancel_fee'])==0  && $qrdinfo['pay_status']==0 ? 0 : 1,
+	                              "updatetime"=>date("Y-m-d H:i:s"),
+	                          ];
                           }
-                          $update =[
-                              "ainv_fee"=>$qrdinfo['ainv_fee']+$value['cancel_fee'],
-                              "inv_fee"=>$qrdinfo['inv_fee']-$value['cancel_fee'],
-                              "invtime"=>date("Y-m-d H:i:s"),
-                              "inv_status"=>$qrdinfo['winv_fee']==0 &&($qrdinfo['inv_fee']-$value['cancel_fee'])==0 ? 3 : 2,
-                              "updatetime"=>date("Y-m-d H:i:s"),
-                          ];
+
                           $qrdup = Db::name("qrd_info")->where($qrdinfo)->update($update);
                           if($qrdup==false){
-                              return "确认单信息更新失败";
+//                              return "确认单信息更新失败";
+                              echo "$invNo 确认单信息更新失败 \r\n";break;
                           }
-                          $assoc=["status"=>2,"assoc_time"=>date("Y-m-d H:i:s"),"updatetime"=>date("Y-m-d H:i:s")];
+                          $assoc=["status"=>$status==4?2:3,"assoc_time"=>date("Y-m-d H:i:s"),"updatetime"=>date("Y-m-d H:i:s")];
                           $assocup =Db::name("assoc")->where($value)->update($assoc);
                           if($assocup==false){
-                              return "确认单关联信息更新失败";
+//                              return "确认单关联信息更新失败";
+                               echo "$invNo 确认单关联信息更新失败 \r\n";break;
                           }
                       }
                  }
-				return '';
 		}
 }

+ 108 - 0
app/admin/command/QueryInvalidInvoice.php

@@ -0,0 +1,108 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\admin\command;
+
+use think\console\Command;
+use think\console\Input;
+use think\console\input\Argument;
+use think\console\input\Option;
+use think\console\Output;
+use think\facade\Cache;use think\facade\Config;
+use TaxInvoice;
+use think\facade\Db;
+class QueryInvalidInvoice extends Command
+{
+    protected function configure()
+    {
+        // 指令配置
+        $this->setName('queryinvalidinvoice')
+            ->setDescription('the queryinvalidinvoice command');
+    }
+
+    protected function execute(Input $input, Output $output)
+    {
+		$generrateinvoice= Cache::store("redis")->get("queryinvalidinvoice");
+	    if($generrateinvoice==0) Cache::store("redis")->set("queryinvalidinvoice",1,180);
+    	$date=date("Y-m-d H:i:s");
+    	Db::startTrans();
+    	try{
+    	$data =Db::name("invoice_return")->where(["status"=>1,"discard"=>2])->where("updatetime","<=",date("Y-m-d H:i:s"))->lock(true)->findOrEmpty();
+    	if(empty($data)){
+    		Db::rollback();
+    		return ;
+	    };
+    	$invoiceInfo = Db::name("invoice_ticket")->where(["invNo"=>$data['invNo'],"is_del"=>0,"status"=>1])->findOrEmpty();
+    	if(empty($invoiceInfo))throw new \Exception($data['invNo']."未找到开票数据");
+		$check=$this->ChickInvoice($invoiceInfo['seller_id'],$invoiceInfo['inv_code'],$invoiceInfo['inv_number']);
+		if(isset($check['ZTDM']) && $check['ZTDM']=='001000') {
+			$reups=Db::name("invoice_return")->where($data)->update(["discard"=>2,"remark"=>$data['remark']."({$check['ZTXX']})","updatetime"=>date("Y-m-d H:i:s",time()+120)]);
+			if($reups==false)throw new \Exception("退票数据更新失败");
+			Db::commit();
+			$output->writeln("[$date] {$data['invNo']} {$check['ZTXX']}");
+			return ;
+
+		}
+		if(isset($check['ZTDM']) && $check['ZTDM']=='000000'){
+			$reup=Db::name("invoice_return")->where($data)->update(["status"=>2,"discard"=>1,"updatetime"=>date("Y-m-d H:i:s")]);
+			if($reup==false)throw new \Exception($data['invNo']."退票数据更新失败");
+			$poolup=Db::name("invoice_pool")->where(["invNo"=>$data['invNo'],"is_del"=>0,"status"=>4])->update(["status"=>6,"updatetime"=>date("Y-m-d H:i:s")]);
+			if($poolup==false)throw new \Exception($data['invNo']."开票票数据更新失败");
+			$ticket =  Db::name("invoice_ticket")->where(["invNo"=>$data['invNo'],"is_del"=>0,"status"=>1])->update(["status"=>2,"updatetime"=>date("Y-m-d H:i:s")]);
+			if($ticket==false)throw new \Exception($data['invNo']."发票详情数据更新失败");
+			$infoup =Db::name("invoice_good")->where(["invNo"=>$data['invNo'],"is_del"=>0])->update(["goodNum"=>0,"updatetime"=>date("Y-m-d H:i:s")]);
+            if($infoup==false)throw  new \Exception($data['invNo']."发票商品信息修改失败");
+			  $qrdArr=Db::name("assoc")->where(["viceCode"=>$data['invNo'],"is_del"=>0,"status"=>2])->column("id,orderCode,cancel_fee");
+                     if(!empty($qrdArr)){
+                          foreach ($qrdArr as $value){
+                              $qrdinfo =Db::name("qrd_info")->where(["sequenceNo"=>$value['orderCode']])->find();
+                              if($qrdinfo==false){
+                                throw  new \Exception($value['orderCode']."确认单信息未找到");
+                              }
+                              if($qrdinfo['ainv_fee']<$value['cancel_fee']){
+                                   throw  new \Exception($value['orderCode']."确认单信息开票金额不足");
+                              }
+                              $update =[
+                                  "winv_fee"=>$qrdinfo['winv_fee']+$value['cancel_fee'],
+                                  "ainv_fee"=>$qrdinfo['ainv_fee']-$value['cancel_fee'],
+                                  "inv_status"=>$qrdinfo['inv_fee']==0 &&$qrdinfo['ainv_fee']-$value['cancel_fee']==0 ? 1 : 2,
+                                  "status"=>$qrdinfo['ainv_fee']==0 &&$qrdinfo['inv_fee']-$value['cancel_fee']==0&&$qrdinfo['pay_status']==1 ?0 : 1,
+                                  "updatetime"=>date("Y-m-d H:i:s"),
+                              ];
+                              $qrdup = Db::name("qrd_info")->where($qrdinfo)->update($update);
+                              if($qrdup==false){
+                                  throw  new \Exception($value['orderCode']."确认单信息更新失败");
+                              }
+                              $assoc=["status"=>3,"updatetime"=>date("Y-m-d H:i:s")];
+                              $assocup =Db::name("assoc")->where($value)->update($assoc);
+                              if($assocup==false){
+                                  throw  new \Exception($value['orderCode']."确认单关联信息更新失败");
+                              }
+                          }
+                     }else{
+                     	throw  new \Exception($data['invNo']."未找到关联订单数据信息");
+                     }
+		}else{
+			$reup=Db::name("invoice_return")->where($data)->update(["status"=>4,"remark"=>$data['remark']."({$check['ZTXX']})","updatetime"=>date("Y-m-d H:i:s")]);
+			if($reup==false)throw new \Exception($data['invNo']."退票数据更新失败");
+		}
+		Cache::store("redis")->set("queryinvalidinvoice",0);
+		Db::commit();
+		$output->writeln("[$date] {$data['invNo']}数据处理完成");
+    	}catch (\Exception $e){
+    		Db::rollback();
+    		Cache::store("redis")->set("queryinvalidinvoice",0);
+    		$output->writeln("[$date] ".$e->getMessage());
+    	}
+
+
+    }
+
+
+    private function ChickInvoice($sellid,$invoice_code,$invoice_num){
+    	$invoice=Config::get("invoice");
+    	$tax =new TaxInvoice($invoice['appKey'],$invoice['appSecret'],$invoice['entCode']);
+    	$reuslt = $tax->QueryInvalidInvoice($sellid,$invoice_num,$invoice_code);
+    	return $reuslt;
+    }
+}

+ 136 - 0
app/admin/command/downredinvres.php

@@ -0,0 +1,136 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\admin\command;
+
+use think\console\Command;
+use think\console\Input;
+use think\facade\Config;
+use think\console\input\Argument;
+use think\console\input\Option;
+use think\console\Output;
+use think\facade\Cache;
+use think\facade\Db;
+
+class downredinvres extends Command
+{
+    protected function configure()
+    {
+        // 指令配置
+        $this->setName('downredinvres')
+            ->setDescription('the downredinvres command');
+    }
+
+    protected function execute(Input $input, Output $output)
+    {
+		$GetOrderInfoAndInvoiceInfo= Cache::store("redis")->get("downredinvres");
+       if($GetOrderInfoAndInvoiceInfo==0) Cache::store("redis")->set("downredinvres",1,180);
+        Db::startTrans();
+        $date= date("Y-m-d H:i:s");
+        $row =Db::name("invoice_red")->where(["status"=>1,"is_del"=>0])->where("updatetime","<=",date("Y-m-d H:i:s"))
+        ->lock(true)->findOrEmpty();
+        if(empty($row)) {
+        	Db::rollback();return;
+        }
+        try{
+		$data=["updatetime"=>date("Y-m-d H:i:s",time()+3600)];
+        $opendatetime =date("Ymd",strtotime($row['addtime']));
+        $ebddatetime =date("Ymd",strtotime("+2 days",strtotime($row['addtime'])));
+		$invoice=Config::get("invoice");
+		$Tax =new \TaxInvoice($invoice['appKey'],$invoice['appSecret'],$invoice['entCode']);
+		$pch= randomkeys(26).date("YmdHis");
+		$result=$Tax->DownloadRedInvoiceApplicationResult($row['SQBSCQQPCH'],$row['XHFSBH'],$row['FPLXDM'],$opendatetime,$opendatetime);
+		var_dump($result);
+		if(isset($result['ZTDM']) && $result['ZTDM']=='060000'){
+			if(isset($result['HZSQDXZZXX']) && !empty($result['HZSQDXZZXX'])){
+				foreach ($result['HZSQDXZZXX'] as $item){
+					$resultChild=$item['HZSQDXZTXX'];
+					if($resultChild['ZTDM']=='060000'){
+						$data['status']=2;
+						$data['XXBBH']=$resultChild['XXBBH'];
+						$data['remark']=$resultChild['ZTXX'];
+					}else{
+						$data['status']=1;
+						$data['XXBBH']=$resultChild['XXBBH'];
+						$data['remark']=$resultChild['ZTXX'];
+					}
+					$where=["YFPDM"=>$resultChild['YFPDM'],"YFPHM"=>$resultChild['YFPHM'],"status"=>1];
+					$row= Db::name("invoice_red")->where($where)->update($data);
+					if($row && $data['status']==2 ){
+						$this->AddRed($resultChild['YFPDM'],$resultChild['YFPHM']);
+					}
+				}
+			}
+		}
+		Db::commit();
+		$output->writeln("[$date] ".$row['invRed'].'发票申请表获取成功');
+        }catch (\Exception $e){
+			Db::rollback();
+			$output->writeln("[$date] ".$row['invRed'].$e->getMessage());
+        }
+
+    }
+
+	public function AddRed($fpdm,$fphm){
+    	$cod=["YFPDM"=>$fpdm,"YFPHM"=>$fphm,"status"=>2,"is_del"=>0];
+    	$red=Db::name("invoice_red")->where($cod)->findOrEmpty();
+    	if(empty($red))throw new \Exception("未找到发票红冲申请信息");
+    	$where=["invNo"=>$red["invNo"],"type"=>0,"status"=>1];
+		$ticket =Db::name("invoice_ticket")->where($where)->findOrEmpty();
+		$invinfo = Db::name("invoice_pool")->where(["invNo"=>$red['invNo'],"is_del"=>0,"status"=>4])->findOrEmpty();
+		if(empty($ticket) || empty($invinfo)){
+			Db::name("invoice_red")->where($red)->update(["status"=>6,"updatetime"=>date("Y-m-d H:i:s"),"remark"=>"申请成功,原票信息本地未找到"]);
+			Db::name("invoice_return")->where(["returnCode"=>$red['returnCode']])->update(["status"=>4,"updatetime"=>date("Y-m-d H:i:s"),"remark"=>"申请成功,原票信息本地未找到"]);
+			return ;
+		}
+				$data=[	    "invNo"=>$red['invRed'],
+							"KPLX"=>"1",
+							"XHFSBH"=>$ticket['seller_id'],
+							"XHFMC"=>$ticket['seller_title'],
+							"XHFDZ"=>$ticket['seller_addr'],
+							"XHFDH"=>$ticket['seller_mobile'],
+							"XHFYH"=>$ticket['seller_bank'],
+							"XHFZH"=>$ticket['seller_bankNo'],
+							"GMFBM"=>"",
+							"GMFSBH"=>$ticket['buyer_id'],
+							"GMFMC"=>$ticket['buyer_title'],
+							"GMFDZ"=>$ticket['buyer_addr'],
+							"GMFDH"=>$ticket['buyer_mobile'],
+							"GMFYH"=>$ticket['buyer_bank'],
+							"GMFZH"=>$ticket['buyer_bankNo'],
+							"GMFLX"=>$invinfo['company_type']??'01',
+							"GMFSJH"=>"",
+							"GMFDZYX"=>'',
+							"KPR"=>$ticket['issuer'],
+							"SKR"=>$ticket['reciver'],
+							"FHR"=>$ticket['reviewer'],
+							"QDBZ"=>"0",
+							"YFPDM"=>$red['YFPDM'],
+							"YFPHM"=>$red['YFPHM'],
+//							"YFPLX"=>$red['FPLXDM'],
+//							"YFPKPRQ"=>date("Y-m-d",strtotime($red['YFPKPRQ'])),
+//							"CHYY"=>$red['red_reason'],
+							"YFPLX"=>$red['FPLXDM'] == '004' ||$red['FPLXDM'] =='028'||$red['red_reason']=='' ?'':$red['FPLXDM'],
+							"YFPKPRQ"=>$red['FPLXDM'] == '004' ||$red['FPLXDM'] =='028'||$red['red_reason']=='' ? '':date("Y-m-d",strtotime($red['YFPKPRQ'])),
+							"CHYY"=>$red['FPLXDM'] == '004' ||$red['FPLXDM'] =='028' ? '':$red['red_reason'],
+							"TSCHBZ"=>"0",
+							"JSHJ"=>"-".$ticket['inv_total'],
+							"HJJE"=>$red['HJJE'],
+							"HJSE"=>$red['HJSE'],
+							"BZ"=>   $red['FPLXDM'] == '004' || $red['FPLXDM'] =='028'?"开具红字增值税专用发票信息表编号{$red['XXBBH']}":"对应正数发票代码:{$red['YFPDM']} 号码:{$red['YFPHM']}",
+							"DDMXXX"=>$red['DDMXXX'],
+							"FPLXDM"=>$red['FPLXDM'],
+							"DDQQPCH"=>"",
+							"DDQQLSH"=>randomkeys(26).date("YmdHis"),
+							"status"=>"0",
+							"result"=>"",
+							"addtime"=>date("Y-m-d H:i:s"),
+							"updatetime"=>date("Y-m-d H:i:s")
+						];
+			$invoice=Db::name("invoice_interface")->insert($data);
+			if($invoice==false){
+				throw new \Exception("红冲提交失败");
+			}
+			Db::name("invoice_red")->where($red)->update(["status"=>3,"updatetime"=>date("Y-m-d H:i:s"),"remark"=>"红冲开票申请已提交待开票"]);
+	}
+}

+ 3 - 8
app/admin/controller/Customer.php

@@ -15,11 +15,6 @@ class Customer extends BaseController
     {
         $post = $this->post;
         $condition=[];
-//        $roleid = $this->roleid;
-//        $check = checkRole($roleid,'73');
-//        if($check){
-//        	$condition[]=["apply_id","=",$this->uid];
-//        }
         isset($post['company'])&&$post['company']!=""? $condition[]=['companyName|contactor',"like","%{$post['company']}%"] : "";
         isset($post['contactor'])&&$post['contactor']!=""? $condition[]=['contactor',"like","%{$post['contactor']}%"] :
         isset($post['companyNo'])&&$post['companyNo']!=""? $condition[]=['companyNo',"=",$post['companyNo']] :
@@ -244,9 +239,9 @@ class Customer extends BaseController
              return error_show(1004,"开票信息已存在");
         }
         $people = isset($this->post['invoice_people'])&&$this->post['invoice_people']!=''?trim($this->post['invoice_people']):"";
-        if($people==''){
-           return error_show(1004,"参数 invoice_people 不能为空");
-        }
+//        if($people==''){
+//           return error_show(1004,"参数 invoice_people 不能为空");
+//        }
         $invoice_addr = isset($this->post['invoice_addr'])&&$this->post['invoice_addr']!=''?trim($this->post['invoice_addr']):"";
         if($invoice_addr==''){
            return error_show(1004,"参数 invoice_addr 不能为空");

+ 4 - 2
app/admin/controller/Exec.php

@@ -115,7 +115,7 @@ class Exec extends \app\admin\BaseController{
 
 	public function loglist(){
 		$param=$this->request->param(["name"=>"","apply_name"=>"","status"=>"","action"=>"","type"=>"","companyNo"=>"",'relaComNo'=>'',"page"=>1,"size"=>15],"post","trim");
-		$where=[["is_del","=",0]];
+		$where=[["is_del","=",0],["addtime",">=",date("Y-m-d H:i:s",strtotime("-30 day"))]];
 		$check = checkRole($this->roleid,147);
         if($check){
             $where[]=["apply_id","=",$this->uid];
@@ -157,7 +157,9 @@ class Exec extends \app\admin\BaseController{
 			["action"=>"J","name"=>'用友销票表'],
 			["action"=>"K","name"=>'采购单明细表'],
 			["action"=>"M","name"=>'对账单汇总表'],
-			["action"=>"N","name"=>'退货台账']
+			["action"=>"N","name"=>'退货台账'],
+			["action"=>"Q","name"=>'产品部门销售业绩'],
+			["action"=>"R","name"=>'采购部门销售业绩'],
 			];
 		return app_show(0,"获取成功",$ation);
 	}

+ 2 - 2
app/admin/controller/Export.php

@@ -129,9 +129,9 @@ class Export extends BaseController
 		          CONCAT(d.catName,"*",d.goodName) 发票货物或应税劳务、服务名称,
 		          d.unitName 单位,
 		          d.goodNum 数量,
-		          d.goodPrice 单价,
+		          round(d.totalTax/d.goodNum,2) 单价,
 		          d.tax 税率,
-		          d.totalPrice 总价,
+		          d.totalTax 总价,
 		          a.inv_type 开票种类,
 		          a.open_type 开票方式,
 		          a.exam_remark 申请备注,

File diff suppressed because it is too large
+ 677 - 746
app/admin/controller/OrderInv.php


+ 0 - 9
app/admin/controller/OrderPay.php

@@ -21,10 +21,6 @@ class OrderPay extends BaseController{
         if(empty($orderArr)){
             return error_show(1004,"参数 orderArr 不能为空");
         }
-//        $platform = array_column($orderArr,'platform_type');
-//        if(count(array_unique($platform))!=1){
-//            return error_show(1004,"订单平台类型不一致");
-//        }
        Db::startTrans();
         try{
             $trade =Db::name("trade")->where(["tradNo"=>$tradNo,"is_del"=>0])->lock(true)->findOrEmpty();
@@ -265,11 +261,6 @@ class OrderPay extends BaseController{
     //资金信息列表
     public function list(){
         $condition=[];
-//         $roleid = $this->roleid;
-//        $check = checkRole($roleid,'85');
-//        if($check){
-//        	$condition[]=["apply_id","=",$this->uid];
-//        }
         $page=isset($this->post['page'])&&$this->post['page']!="" ? intval($this->post['page']) :1;
         $size=isset($this->post['size'])&&$this->post['size']!="" ? intval($this->post['size']) :15;
         $name =isset($this->post['name'])&&$this->post['name']!=""? trim($this->post['name']):"";

+ 53 - 27
app/admin/controller/Payment.php

@@ -531,6 +531,11 @@ class Payment extends BaseController
                             Db::rollback();
                            return error_show(1004,"对账驳回失败");
                        }
+                       $payinfoup =Db::name("pay_info")->where(["payNo"=>$payNo,"is_del"=>0])->update(['status'=>0,"updatetime"=>date("Y-m-d H:i:s")]);
+                       if($payinfoup==false){
+                            Db::rollback();
+                           return error_show(1004,"对账驳回失败");
+                       }
                        foreach ($cgdNo as $value){
                            $report=ReportCode::where(["cgdNo"=>$value])->find();
                            if($report)$report->rmField("payNo",$payNo);
@@ -720,7 +725,8 @@ class Payment extends BaseController
             if($status==3) $mentupdate['return_time'] = $return_time;
             $payup=Db::name("pay_payment")->where($payment)->update($mentupdate);
             if($payup){
-                if (in_array($status,[4,5])){
+                if (in_array($status,[4,5,6,7])){
+                	if($payinfo['pay_fee']<$payment['pay_fee']) throw new Exception("对账单付款中金额不足");
                     if($status==4){ //审核通过 扣减对账付款中的金额 添加到已付金额
                         $payupdate =[
                             "apay_fee"=>$payinfo['apay_fee']+$payment['pay_fee'],
@@ -729,7 +735,7 @@ class Payment extends BaseController
                              "updatetime" => date("Y-m-d H:i:s")
                         ];
                 }
-                if($status==5){//审核驳回 扣减对账付款中的金额 返回到待付金额中
+                if(in_array($status,[5,6,7])){//审核驳回 扣减对账付款中的金额 返回到待付金额中
                     $payupdate =[
                         "wpay_fee"=>$payinfo['wpay_fee']+$payment['pay_fee'],
                         "pay_fee"=>$payinfo['pay_fee']-$payment['pay_fee'],
@@ -891,6 +897,12 @@ class Payment extends BaseController
         if($supplierNo!=""){
           $condition []=["supplierNo","=",$supplierNo];
         }
+		$start=isset($post['start'])&& $post['start']!=''?trim($post['start']):"";
+		$end=isset($post['end'])&& $post['end']!=''?trim($post['end']):"";
+		if($start!='') $condition []=["cgdTime",">=",date("Y-m-d 00:00:00",strtotime($start))];
+		if($end!='') $condition []=["cgdTime","<=",date("Y-m-d 23:59:59",strtotime($end))];
+
+
 		  $cgder= isset($post['cgder']) && $post['cgder']!='' ? trim($post['cgder']) :"";
         if($cgder!='') $condition []=["ownerName","like","%$cgder%"];
         $cgderid= isset($post['cgderid']) && $post['cgderid']!='' ? trim($post['cgderid']) :"";
@@ -1046,6 +1058,7 @@ class Payment extends BaseController
         if($payinfo==false){
               return error_show(1004,"对账单数据未找到");
         }
+        if($payinfo['winv_fee']<=0)  return error_show(1004,"对账单数据未开票金额为0");
 		$result=$this->checkSupplier($payinfo['supplierNo']);
         if($result['code']!=0){
         	 return error_show($result['code'],$result['message']);
@@ -1075,6 +1088,11 @@ class Payment extends BaseController
 				if(!isset($item['invoiceType'])||$item['invoiceType']=='')  return error_show(1004,"参数 invoiceType 不能为空");
 				if(!isset($item['open_time'])||$item['open_time']=='')  return error_show(1004,"参数 open_time 不能为空");
 				if(!isset($item['subtotal_amount'])||$item['subtotal_amount']=='')  return error_show(1004,"参数 subtotal_amount 不能为空");
+				$invamount=0;
+				if(in_array($item['invoiceType'],['fully_digitalized_special_electronic','fully_digitalized_normal_electronic'])){
+					$invamount = $item['subtotal_amount']??0;
+					$item['subtotal_amount']=0;
+				}
 				//普票需要校验码
 				if(in_array($item['invoiceType'],['normal','roll',"toll",'electronic'])){
 					if(!isset($item['checkNumber'])||$item['checkNumber']=='')  return error_show(1004,"参数 checkNumber 不能为空");
@@ -1096,6 +1114,7 @@ class Payment extends BaseController
                 "apply_name"=>$this->uname,
                 "inv_fee"=> 0,//核算金额
                 "inv_subtotal_amount"=> $item['subtotal_amount']??0, //票面金额
+                "inv_amount"=> $invamount, //票面金额
                 "invType"=> $item['invType'],
                 "invoiceType"=>$item['invoiceType']??"",
                 "inv_img"=>$item['inv_img']??'',
@@ -1192,7 +1211,11 @@ class Payment extends BaseController
 
                 if (!isset($payinfo[$item['payNo']])) throw new Exception('对账单数据未找到');
                 if ($payinfo[$item['payNo']]['status'] != 2) throw new Exception('对账单数据未完成审核');
-
+				$invamount=0;
+				if(in_array($item['invoiceType'],['fully_digitalized_special_electronic','fully_digitalized_normal_electronic'])){
+					$invamount = $item['inv_subtotal_amount']??0;
+					$item['inv_subtotal_amount']=0;
+				}
                 $hpNo = makeNo('hp');
                 $da_insert[] = [
                     'payNo' => $item['payNo'],
@@ -1201,6 +1224,7 @@ class Payment extends BaseController
                     'apply_name' => $this->uname,
                     'inv_fee' => 0,//核算金额
                     'inv_subtotal_amount' => $item['inv_subtotal_amount'] ?? 0, //票面金额
+                    'inv_amount' => $invamount, //票面金额
                     'invType' => 1,
                     'invoiceType' => $item['invoiceType'],
                     'inv_img' => '',
@@ -1989,28 +2013,26 @@ class Payment extends BaseController
         try {
             $pay_invoice_allow = [];
 
-            $hpNo_item = array_column($post['list'], null, 'hpNo');
-
-            $date = date('Y-m-d H:i:s');
-
             foreach ($post['list'] as $val) {
 
-                if (!$val_hpNo->check($item)) throw new \Exception($val_hpNo->getError());
+                if (!$val_hpNo->check($val)) throw new \Exception($val_hpNo->getError());
                 if (!isset($payArr[$val['hpNo']])) throw new \Exception("{$val['hpNo']}记录不存在");
 
                 $value = $payArr[$val['hpNo']];
-
-                if ($value['companyNo'] == '') throw new Exception("{$value['hpNo']}对账信息有误");
-                if ($value['companyNo'] != $companyNo) throw new Exception("{$value['hpNo']}不属于当前业务公司发票");
+				$payinfo = Db::name("pay")->where(["payNo"=>$payArr[$val['hpNo']]['payNo'],"status"=>2,"is_del"=>0])
+->findOrEmpty();
+				if(empty($payinfo)) throw new Exception("{$value['hpNo']}对账信息有误");
+                if ($payinfo['companyNo'] == '') throw new Exception("{$value['hpNo']}对账信息有误");
+                if ($payinfo['companyNo'] != $companyNo) throw new Exception("{$value['hpNo']}不属于当前业务公司发票");
                 if ($value['status'] != '3') throw new Exception("{$value['hpNo']}状态有误");
-                if ($value['invoice_fee'] > $value['inv_fee']) throw new Exception("{$value['hpNo']}对账单开票中金额不足");
+                if ($value['invoice_fee'] > $payinfo['inv_fee']) throw new Exception("{$value['hpNo']}对账单开票中金额不足");
 
-                if ($hpNo_item[$value['hpNo']]['status'] == 4) {
+                if ($val['status'] == 4) {
                     //审核通过
                     $payupdate = [
-                        "ainv_fee" => $value['ainv_fee'] + $value['invoice_fee'],
-                        "inv_fee" => $value['inv_fee'] - $value['invoice_fee'],
-                        "inv_status" => ($value['inv_fee'] - $value['invoice_fee']) == 0 && $value['winv_fee'] == 0 ? 3 : 2,
+                        "ainv_fee" => $payinfo['ainv_fee'] + $value['invoice_fee'],
+                        "inv_fee" => $payinfo['inv_fee'] - $value['invoice_fee'],
+                        "inv_status" => ($payinfo['inv_fee'] - $value['invoice_fee']) == 0 && $payinfo['winv_fee'] == 0 ? 3 : 2,
                         "updatetime" => date("Y-m-d H:i:s")
                     ];
 
@@ -2019,24 +2041,28 @@ class Payment extends BaseController
                 } else {
                     //审核不通过
                     $payupdate = [
-                        "winv_fee" => $value['winv_fee'] + $value['invoice_fee'],
-                        "inv_fee" => $value['inv_fee'] - $value['invoice_fee'],
-                        "inv_status" => ($value['inv_fee'] - $value['invoice_fee']) == 0 && $value['ainv_fee'] == 0 ? 1 : 2,
-                        "updatetime" => $date
+                        "winv_fee" => $payinfo['winv_fee'] + $value['invoice_fee'],
+                        "inv_fee" => $payinfo['inv_fee'] - $value['invoice_fee'],
+                        "inv_status" => ($payinfo['inv_fee'] - $value['invoice_fee']) == 0 && $payinfo['ainv_fee'] == 0 ? 1 : 2,
+                        "updatetime" => date("Y-m-d H:i:s")
                     ];
 //                        $pay_invoice_not_allow[]=$value['id'];
                     Db::name("pay_invoice")
                         ->where(["id" => $value['id'], "status" => 3, "is_del" => 0])
-                        ->update(["status" => $hpNo_item[$value['hpNo']]['status'], "updatetime" => $date, 'remark' => $hpNo_item[$value['hpNo']]['remark']]);
+                        ->update(["status" => $val['status'], "updatetime" => date("Y-m-d H:i:s"), 'remark' =>$val['remark']]);
+                }
+//                $where = ['payNo' => $value['payNo'], "inv_status" => $ $val['inv_status'], "companyNo" => $companyNo, "status" => 2, "is_del" => 0];
+                $pay = Db::name("pay")->where($payinfo)->update($payupdate);
+
+                if ($pay == false) {
+//                	echo Db::name("pay")->getLastSql();
+//	                var_dump($where,$payupdate);
+                	throw new Exception("{$value['hpNo']}回票申请对账单状态更新失败");
                 }
-                $where = ['payNo' => $value['payNo'], "inv_status" => $value['inv_status'], "companyNo" => $companyNo, "status" => 2, "is_del" => 0];
-                $pay = Db::name("pay")->where($where)->update($payupdate);
-                if ($pay == false) throw new Exception("{$value['hpNo']}回票申请对账单状态更新失败");
-//                    $invIdArr[] = $value['id'];
+
             }
-//            }
 
-            if ($pay_invoice_allow) Db::name("pay_invoice")->where(["id" => $pay_invoice_allow, "status" => 3, "is_del" => 0])->update(["status" => 4, "updatetime" => $date]);
+            if ($pay_invoice_allow) Db::name("pay_invoice")->where(["id" => $pay_invoice_allow, "status" => 3, "is_del" => 0])->update(["status" => 4, "updatetime" =>date("Y-m-d H:i:s")]);
 
 //            if ($update == false) throw new Exception("回票申请状态更新失败");
             Db::commit();

+ 6 - 1
app/admin/middleware/checkRela.php

@@ -31,7 +31,12 @@ class checkRela
                 $companyinfo = UserHandle("/hqInfo", ["code" => $relaComNo]);
                 if ($companyinfo['code'] != 0) return error_show($companyinfo['code'], $companyinfo['message']);
                 if (!empty($companyinfo['data']) && $companyinfo['data']['relation_code'] != "") {
-                    return error_show(1004, "业务公司存在供应商账户,请用供应商账户操作");
+                 $db= UserHandle("/userCompanyBasicList", ["companyNo" =>$companyinfo['data']['relation_code']]);
+	                if ($db['code'] != 0) return ["code"=>$db['code'],"message"=> $db['message']];
+	                if (!empty($db['data']) && $db['data']['count'] > 0) {
+	                    return ["code"=>1004,"message"=> "供应商公司存在操作账户,请用供应商账户操作"];
+	                }
+
                 }
             }
         }

+ 137 - 133
app/command/Report.php

@@ -16,7 +16,9 @@ class Report extends Command
 	private $key='Reportexec';
 	private $param=[];
 	private $qrdType = [1 => '库存品', 2 => '非库存品', 3 => '采购反馈'];
-	private $qrdSource = [1 => '直接下单', 2 => '竞价转单', 3 => '项目转单', 4 => '平台导入', 5 => '有赞平台', 6 => '售后补换货',7=>'报备转单',8=>'支付渠道拆单'];
+	private $qrdSource = [1 => '直接下单', 2 => '竞价转单', 3 => '项目转单', 4 => '平台导入', 5 => '有赞平台', 6 => '售后补换货',7=>'报备转单',8=>'支付渠道拆单',9=>"采销补录",10=>"结算补录"];
+	private $cgdSource = [0=>"备库单",1 => '直接下单', 2 => '竞价转单', 3 => '项目转单', 4 => '平台导入', 5 => '有赞平台', 6 => '售后补换货',7=>'报备转单',
+	8=>'支付渠道拆单',9=>"采销补录",10=>"结算补录"];
 	private $sendType = [1 => '包邮', 2 => '自提'];
 	private $pay_status = [1 => '未回', 2 => '部分回款', 3 => '已回'];
 	private $inv_status = [1 => '未开', 2 => '部分开票', 3 => '已开'];
@@ -26,6 +28,7 @@ class Report extends Command
 	private $cgdType = [1 => '库存', 2 => '非库存', 3 => '咨询'];
 	private $invoice_return_status = [0 => '待财务审核', 1 => '退票中', 2 => '退票成功', 3 => '审核驳回', 4 => '退票失败'];
 	private $sendStatus = [1=>'未发货',2=>'部分发货',3=>'全部发货'];
+	private $TagName = [1=>'采购单付款',2=>'采购单回票',3=>'销售回款',4=>"销售开票"];
 
     protected function configure()
     {
@@ -46,7 +49,7 @@ class Report extends Command
         Db::startTrans();
         try{
         $info = json_decode($info,true);
-	    ini_set ('memory_limit', '1024M') ;
+	    ini_set ('memory_limit', '2048M') ;
         $date=date("Y-m-d H:i:s");
         $param = Db::name("exec_log")->where("id",$info['id'])->findOrEmpty();
         if(isset($param) && !empty($param)){
@@ -99,6 +102,14 @@ class Report extends Command
             case 'N':
                 $method="N";
                 $file='退货台账';
+                break;
+            case 'Q':
+                $method="Q";
+                $file='产品部门销售业绩';
+                break;
+            case 'R':
+                $method="R";
+                $file='采购部门销售业绩';
                 break;
 			default:
 				$file='暂无数据';
@@ -131,7 +142,7 @@ class Report extends Command
                         "remark"=>$e->getMessage(),
                         'updatetime' => date('Y-m-d H:i:s')
                     ]);
-			 $output->writeln("[$date]【{$info['name']}】[{$info['apply_name']}]预约记录处理失败 message:【{$e->getMessage()}】");
+			  $output->writeln("[$date]【{$info['name']}】[{$info['apply_name']}]预约记录处理失败 message:【{$e->getMessage()}|{$e->getFile()}|{$e->getCode()}】");
         }
        Cache::store('redis')->handler()->decrby('ExecCommand',1);
 		Db::commit();
@@ -145,19 +156,6 @@ class Report extends Command
 
 		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['a.addtime', 'between', [$param['start'], $param['end']]];
 		if (($param['companyNo'] != '') && ($param['companyNo'] != '')) $where[] = ["a.inv_out","=",$param['companyNo']];
-
-//		if ($param['status'] != '') $where[] = ['a.status', '=', $param['status']];
-//		if ($param['inv_type'] != '') $where[] = ['a.inv_type', '=', $param['inv_type']];
-//		if ($param['inv_out'] != '') $where[] = ['a.inv_out', '=', $param['inv_out']];
-//		if ($param['invNo'] != '') $where[] = ['a.invNo', 'in', $param['invNo']];
-//		if ($param['relaComNo'] != '') $where[] = ['a.inv_out', '=', $param['relaComNo']];
-//		if ($param['inv_number'] != '') $where[] = ['c.inv_number', 'like', '%' . $param['inv_number'] . '%'];
-//		if ($param['inv_code'] != '') $where[] = ['c.inv_code', 'like', '%' . $param['inv_code'] . '%'];
-//		if ($param['inv_company'] != '') $where[] = ['a.inv_company', 'like', '%' . $param['inv_company'] . '%'];
-//		if ($param['buyer_name'] != '') $where[] = ['b.buyer_title', 'like', '%' . $param['buyer_name'] . '%'];
-//		if ($param['apply_id'] != '') $where[] = ['a.apply_id', '=', $param['apply_id']];
-//		if ($param['apply_name'] != '') $where[] = ['a.apply_name', 'like', '%' . $param['apply_name'] . '%'];
-
 		$open_type = [1 => '金税开票', 2 => '金税线下', 3 => '纯线下'];//开票方式
 		$inv_type = config('invoiceType.invoiceName');//开票种类(发票类型)
 
@@ -183,13 +181,15 @@ class Report extends Command
 		          CONCAT(d.catName,"*",d.goodName) 发票货物或应税劳务、服务名称,
 		          d.unitName 单位,
 		          d.goodNum 数量,
-		          d.goodPrice 单价,
+		          round(d.totalTax/d.goodNum,2) 单价,
 		          d.tax 税率,
-		          d.totalPrice 总价,
+		          d.totalTax 总价,
 		          a.inv_type 开票种类,
 		          a.open_type 开票方式,
 		          a.exam_remark 申请备注,
-		          a.remark 发票备注')
+		          a.remark 发票备注,
+		          if(f.cxCode="",f.sequenceNo,f.cxCode) 销售主单号,
+		          f.goodPrice 商品单价')
 		          ->leftJoin('invoice_pool_info b', 'a.invNo=b.invNo')
 		          ->leftJoin('invoice_ticket c', 'a.invNo=c.invNo AND c.type=0 AND c.status=1')
 		          ->leftJoin('invoice_good d', 'd.invNo=a.invNo')
@@ -212,21 +212,6 @@ class Report extends Command
 //		$param = $this->request->only(['start' => '', 'end' => '', 'invType' => '', 'company' => '', 'relaComNo' => '', 'supplierNo' => '', 'hpNo' => '', 'payNo' => '', 'invoiceType' => '', 'status' => '', 'invoiceNumber' => '', 'checkApi' => '', 'invoiceCode' => '', 'open_start' => '', 'open_end' => '', 'apply_id' => '', 'apply_name' => ''], 'post', 'trim');
 
 		$where = [['a.is_del', '=', 0], ['b.is_del', '=', 0]];
-//		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['a.addtime', 'between', [$param['start'], $param['end']]];
-//		if ($param['invType'] != '') $where[] = ['a.invType', '=', $param['invType']];
-//		if ($param['company'] != '') $where[] = ['b.companyNo', 'like', '%' . $param['company'] . '%'];
-//		if ($param['relaComNo'] != '') $where[] = ['b.companyNo|b.supplierNo', 'like', '%' . $param['relaComNo'] . '%'];
-//		if ($param['supplierNo'] != '') $where[] = ['b.supplierNo', '=', $param['supplierNo']];
-//		if ($param['hpNo'] != '') $where[] = ['a.hpNo', 'like', '%' . $param['hpNo'] . '%'];
-//		if ($param['payNo'] != '') $where[] = ['a.payNo', 'like', '%' . $param['payNo'] . '%'];
-//		if ($param['invoiceType'] != '') $where[] = ['a.invoiceType', '=', $param['invoiceType']];
-//		if ($param['status'] != '') $where[] = ['a.status', '=', $param['status']];
-//		if ($param['invoiceNumber'] != '') $where[] = ['a.invoiceNumber', '=', $param['invoiceNumber']];
-//		if ($param['checkApi'] != '') $where[] = ['a.checkApi', '=', $param['checkApi']];
-//		if ($param['invoiceCode'] != '') $where[] = ['a.invoiceCode', '=', $param['invoiceCode']];
-//		if (($param['open_start'] != '') && ($param['open_end'] != '')) $where[] = ['a.open_time', 'between', [$param['open_start'], $param['open_end']]];
-//		if ($param['apply_id'] != '') $where[] = ['a.apply_id', '=', $param['apply_id']];
-//		if ($param['apply_name'] != '') $where[] = ['a.apply_name', 'like', '%' . $param['apply_name'] . '%'];
 		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['a.addtime', 'between', [$param['start'], $param['end']]];
 		if (($param['companyNo'] != '') && ($param['companyNo'] != '')) $where[] = ["b.companyNo","=",$param['companyNo']];
 		$status = [1 => '待系统验证', 2 => '买方公司审核', 3 => '待买方公司认证', 4 => '认证成功', 5 => '验证失败', 6 => '买方审核驳回', 7 => '认证失败', 8 => '回票流程终止', 9 => '验证超次数', 10 => '回票已退'];//认证状态
@@ -235,7 +220,7 @@ class Report extends Command
 
 		$list = Db::name('pay_invoice')
 		          ->alias('a')
-		          ->leftJoin('pay b', 'a.payNo=b.payNo')
+		          ->leftJoin('pay b', 'a.payNo=b.payNo and b.status=2')
 		          ->leftJoin('invoice_info c', 'c.hpNo=a.hpNo AND c.status=1')
 		          ->field('"" 序号,
 		          a.payNo 对账编号,
@@ -243,16 +228,16 @@ class Report extends Command
 		          DATE_FORMAT(a.addtime,\'%Y\') 年,
 		          DATE_FORMAT(a.addtime,\'%m\') 月,
 		          a.invoiceNumber 发票号,
+		          c.total 总额,
+		          c.subtotal_amount 金额,
+		          c.subtotal_tax 税额,		          
 		          a.open_time 开票日期,
 		          b.supplierName 供应商,
 		          a.invoiceType 发票类型,
 		          "" as 业务类型,
 		          a.status 认证状态,
 		          a.updatetime 认证时间,
-		          a.remark 备注,
-		          c.total 总额,
-		          c.subtotal_amount 金额,
-		          c.subtotal_tax 税额')
+		          a.remark 备注')
 		          ->where($where)
 		          ->order('a.addtime desc')
 		          ->cursor();
@@ -273,16 +258,8 @@ class Report extends Command
 	private function C($param=[])
 	{
 //		$param = $this->request->only(['start' => '', 'end' => '', 'name' => '', 'bank' => '', 'status' => '', 'tradNo' => '', 'company' => '', 'userd_lower' => '', 'used_upper' => ''], 'post', 'trim');
-		$where = [['a.is_del', '=', 0], ['b.is_del', '=', 0]];
-//		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['a.trade_time', 'between', [$param['start'], $param['end']]];
-//		if ($param['name'] != '') $where[] = ['a.trade_out', 'like', '%' . $param['name'] . '%'];
-//		if ($param['bank'] != '') $where[] = ['a.trade_bank', 'like', '%' . $param['bank'] . '%'];
-//		if ($param['status'] != '') $where[] = ['a.status', '=', $param['status']];
-//		if ($param['tradNo'] != '') $where[] = ['a.tradNo', 'like', '%' . $param['tradNo'] . '%'];
-//		if ($param['company'] != '') $where[] = ['a.companyNo', 'like', '%' . $param['company'] . '%'];
-//		if ($param['userd_lower'] != '') $where[] = ['a.used_fee', '>=', $param['userd_lower']];
-//		if ($param['used_upper'] != '') $where[] = ['a.used_fee', '<=', $param['used_upper']];
-		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['a.addtime', 'between', [$param['start'], $param['end']]];
+		$where = [['a.is_del', '=', 0]];
+		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['b.addtime', 'between', [$param['start'],$param['end']]];
 		if (($param['companyNo'] != '') && ($param['companyNo'] != '')) $where[] = ["a.companyNo","=",$param['companyNo']];
 		$status = [1 => '未认领', 2 => '部分认领', 3 => '全部认领'];//状态
 		$b_status = [1 => '待审批', 2 => '审批通过', 3 => '审批驳回', 4 => '退款', 5 => '解除认领'];//认领审批状态
@@ -300,17 +277,18 @@ class Report extends Command
 		          a.status 状态,
 		          a.total_fee 收入金额,
 		          a.balance 未认领金额,
-		          a.used_fee 已认领金额,
+		          b.total_fee 已认领金额,
 		          b.logNo 资金认领编号,
-		          a.customerNo 认领企业,
+		          b.customerNo 认领企业,
 		          c.orderCode 订单编号,
+		          d.cxCode 销售主单号,
 		          d.poCode 平台编号,
 		          d.goodName 产品名称,
 		          d.ownerName 资金创建人,
 		          c.apply_name 认领创建人,
 		          b.status 认领审批状态,
 		          b.remark 驳回原因')
-		          ->leftJoin('trade_pool b', 'b.tradNo=a.tradNo')
+		          ->leftJoin('trade_pool b', 'b.tradNo=a.tradNo and b.is_del=0')
 		          ->leftJoin('assoc c', 'c.viceCode=b.logNo and c.type=2 and c.status<>3')
 		          ->leftJoin('qrd_info d', 'd.sequenceNo=c.orderCode')
 		          ->where($where)
@@ -338,7 +316,7 @@ class Report extends Command
 
 		$data = Db::name('assoc')
 		          ->alias('b')
-		          ->field('DATE_FORMAT(b.addtime,\'%Y\') 年,DATE_FORMAT(b.addtime,\'%m\') 月,DATE_FORMAT(b.addtime,\'%d\') 日,a.companyName 业务公司名称,a.companyNo 业务公司编号,b.viceCode 资金认领编号,c.tradNo 资金编号,c.total_fee 本次核销金额,c.addtime 本次核销时间,c.status 资金认领状态,a.sequenceNo 确认单编号,a.department 业务员部门,a.ownerName 业务员,a.platName 平台类型,a.qrdSource 确认单类型,a.qrdType 商品类型,a.poCode PO编号,a.customerAttr 客户属性,a.branch 分公司,a.customerName 客户名称,a.firstCat 一级分类,a.goodName 产品名称,round(a.tax/100,2) 税点,(a.goodNum-a.thNum) 下单数量,a.goodPrice 销售单价,(a.totalPrice-a.th_fee) 销售总额')
+		          ->field('DATE_FORMAT(b.addtime,\'%Y\') 年,DATE_FORMAT(b.addtime,\'%m\') 月,DATE_FORMAT(b.addtime,\'%d\') 日,a.companyName 业务公司名称,a.companyNo 业务公司编号,b.viceCode 资金认领编号,c.tradNo 资金编号,c.total_fee 本次核销金额,c.addtime 本次核销时间,c.status 资金认领状态,a.sequenceNo 确认单编号,a.department 业务员部门,a.ownerName 业务员,a.platName 平台类型,a.qrdSource 确认单类型,a.qrdType 商品类型,a.poCode 平台订单号,a.customerAttr 客户属性,a.branch 分公司,a.customerName 客户名称,a.firstCat 一级分类,a.goodName 产品名称,round(a.tax/100,2) 税点,(a.goodNum-a.thNum) 下单数量,a.goodPrice 销售单价,(a.totalPrice-a.th_fee) 销售总额')
 		          ->leftJoin('qrd_info a', 'b.orderCode=a.sequenceNo')
 		          ->leftJoin('trade_pool c', 'c.logNo=b.viceCode')
 		          ->where($where)
@@ -356,11 +334,6 @@ class Report extends Command
 			$value['商品类型'] = $this->qrdType[$value['商品类型']] ?? '';
 			yield $value;
 		}
-		//
-		//        if (empty($list)) $list[] = ['导出数据为空' => ''];
-		//
-		//        excelExport('回款核销明细表', array_keys($list[0]), $list);
-
 	}
 
 	//回票明细表
@@ -368,7 +341,7 @@ class Report extends Command
 	{
 //		$param = $this->request->only(['company' => '', 'start' => '', 'end' => ''], 'post', 'trim');
 
-		$where = [['a.is_del', '=', 0], ['b.is_del', '=', 0], ['c.is_del', '=', 0], ['d.is_del', '=', 0]];
+		$where = [['a.is_del', '=', 0],['a.status', 'in',[3,4]],['b.is_del', '=', 0], ['c.is_del', '=', 0], ['d.is_del', '=', 0]];
 
 		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['a.check_time', 'between', [$param['start'], $param['end']]];
 		if ($param['companyNo'] != '') $where[] = ['b.companyNo', '=', $param['companyNo']];
@@ -384,6 +357,7 @@ class Report extends Command
 		          a.check_time 本次回票时间,
 		          a.invoiceNumber 发票号,
 		          a.inv_amount 本次回票金额,
+		          d.totalPrice 采购单回票金额,
 		          "" 不含税采购成本,
 	                "" 税额,
                     d.companyName 公司回票抬头,
@@ -413,48 +387,31 @@ class Report extends Command
                     d.qrdCode 确认单编号,
                     d.bkCode 备库编号,
                     d.thNum 退货数量,
-                    d.th_fee 退货金额')
+                    d.th_fee 退货金额,
+                    a.exam_remark 回票审核备注,
+                    a.remark 回票申请备注')
 		          ->leftJoin('pay b', 'a.payNo=b.payNo')
-		          ->leftJoin('pay_info c', 'c.payNo=a.payNo')
+		          ->leftJoin('pay_info c', 'c.payNo=a.payNo and c.status=1 and c.is_del=0')
 		          ->leftJoin('cgd_info d', 'd.sequenceNo=c.cgdNo')
-		          ->leftJoin('invoice_info e', 'e.payNo=a.payNo')
 		          ->where($where)
 		          ->order(['a.id' => 'desc'])
 		          ->cursor();
 
 		//采购单类型
-		$cgdSource = [1 => '直接下单', 2 => '咨询', 3 => '项目', 4 => '平台', 5 => '有赞'];
+//		$cgdSource = [1 => '直接下单', 2 => '咨询', 3 => '项目', 4 => '平台', 5 => '有赞'];
 		//商品类型
 		$goodType = [1 => '正常商品', 2 => '赠品', 3 => '样品'];
 
 		//        $list = [];
 
 		foreach ($data as $value) {
-			$value['采购单类型'] = $cgdSource[$value['采购单类型']] ?? '';
+			$value['采购单类型'] = $this->cgdSource[$value['采购单类型']] ?? '';
 			$value['商品类型'] = $goodType[$value['商品类型']] ?? '';
 			$value['不含税采购成本'] = round($value['采购总货款']/(1+$value['税率']),2) ;
 			$value['税额'] = round($value['不含税采购成本']*$value['税率'],2) ;
 
 			yield $value;
-//			$item_list = json_decode($value['item_list'], true);
-//
-//			unset($value['item_list']);
-//			foreach ($item_list as $item) {
-//				$value['税额']= $item['tax'] ?? '';
-//				$value['票面税率']= $item['tax_rate'] ?? '';
-//				//                $list = array_merge($value, [
-//				//                    '税额' => $item['tax'] ?? '',
-//				//                    '票面税率' => $item['tax_rate'] ?? '',
-//				//                ]);
-//				yield $value;
-//			}
-
 		}
-
-		//        if (empty($list)) $list[] = ['导出数据为空' => ''];
-		//
-		//        excelExport('回票明细表', array_keys($list[0]), $list);
-
 	}
 
 	//经营分析报表
@@ -485,7 +442,7 @@ class Report extends Command
             b.bkCode 备库单编号,
             b.sequenceNo 采购单单号,
             a.platName 平台类型,
-            a.poCode PO编号,
+            a.poCode 平台订单号,
             a.customerAttr 客户属性,
             a.branch 分公司,
             a.customerName 客户名称,
@@ -528,21 +485,13 @@ class Report extends Command
 		foreach ($data as $value) {
 			$value['订单来源'] = $this->qrdSource[$value['订单来源']] ?? '';
 			$value['库存性质'] = $this->qrdType[$value['库存性质']] ?? '';
-			//            $value['开票状态'] = $this->inv_status[$value['开票状态']] ?? '';
-			//            $value['回款状态'] = $this->pay_status[$value['回款状态']] ?? '';
 			$value['发货方式'] = $this->sendType[$value['发货方式']] ?? '';
-
 			$value['毛利润'] = round(bcsub($value['销售总额'], $value['采购总货款'], 3), 2);
-			$value['毛利率'] = $value['销售总额'] == 0 ? 0 : round(bcmul(bcsub(1, bcdiv($value['采购总货款'], $value['销售总额'], 5), 5), 100), 2) . '%';
-			$value['不含税采购成本'] = round(bcdiv($value['采购总货款'], bcadd(1,$value['采购税点']), 3), 2);
+			$value['毛利率'] = $value['销售总额'] == 0 ? 0 : round(bcmul(bcsub(1, bcdiv($value['采购总货款'], $value['销售总额'], 5),5), 100,2), 2) . '%';
+			$value['不含税采购成本'] = round(bcdiv($value['采购总货款'], bcadd(1,$value['采购税点'],3), 3), 2);
 
 			yield $value;
 		}
-
-		//        if (empty($list)) $list[] = ['导出数据为空' => ''];
-		//
-		//        excelExport('经营分析报表', array_keys($list[0]), $list);
-
 	}
 
 	//收入成本明细表
@@ -552,7 +501,7 @@ class Report extends Command
 
 		$where = [['a.is_del', '=', 0], ['a.status', '>=', 4]];
 
-		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['a.addtime', 'between', [$param['start'], $param['end']]];
+		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['c.open_date', 'between', [$param['start'],$param['end']]];
 		if ($param['companyNo'] != '') $where[] = ['a.inv_out', '=', $param['companyNo']];
 
 		$data = Db::name('invoice_pool')
@@ -566,7 +515,7 @@ class Report extends Command
             e.department 业务部门,
             e.ownerName 业务人员,
             m.goodNum 本次开票数量,
-            m.totalPrice 本次开票金额,
+            m.totalTax  本次开票金额,
             e.goodPrice 销售单价,
             c.open_date 本次开票时间,
             c.inv_number 发票号,
@@ -603,7 +552,7 @@ class Report extends Command
             f.th_fee 退货金额            
             ')
 		          ->leftJoin('invoice_pool_info b', 'b.invNo=a.invNo')
-		          ->leftJoin('invoice_ticket c', 'c.invNo=a.invNo and c.type=0 and c.status=1')
+		          ->leftJoin('invoice_ticket c', 'c.invNo=a.invNo and c.type=0 and c.status in (0,1,2,3)')
 		          ->leftJoin("invoice_good m","m.invNo=a.invNo and m.invtype=0 and m.is_del=0")
 //		          ->leftJoin('assoc d', 'd.viceCode=a.invNo and d.type=1')
 		          ->leftJoin('qrd_info e', 'e.sequenceNo=m.orderCode')
@@ -623,11 +572,6 @@ class Report extends Command
 			$value['销售来源'] = $this->qrdSource[$value['销售来源']] ?? '';
 			yield $value;
 		}
-
-		//        if (empty($list)) $list[] = ['导出数据为空' => ''];
-		//
-		//        excelExport('收入成本明细表', array_keys($list[0]), $list);
-
 	}
 
 	//应收台账表
@@ -652,7 +596,7 @@ class Report extends Command
             a.ownerName 销售员,
             a.qrdSource 订单来源,
             a.platName 平台类型,
-            a.poCode PO编号,
+            a.poCode 平台订单号,
             a.customerName 客户名称,
             a.customerAttr 客户属性,
             a.branch 客户分公司,
@@ -690,24 +634,34 @@ class Report extends Command
 		$time = time();
 
 		foreach ($data as $value) {
-			$value['订单来源'] = $this->qrdSource[$value['订单来源']] ?? '';
-			$value['回款状态'] = $this->pay_status[$value['回款状态']] ?? '';
-			$value['开票状态'] = $this->inv_status[$value['开票状态']] ?? '';
-			$value['发货状态'] = $this->sendStatus[$value['发货状态']] ?? '';
+//			$value['订单来源'] = $this->qrdSource[$value['订单来源']] ?? '';
+//			$value['回款状态'] = $this->pay_status[$value['回款状态']] ?? '';
+//			$value['开票状态'] = $this->inv_status[$value['开票状态']] ?? '';
+//			$value['发货状态'] = $this->sendStatus[$value['发货状态']] ?? '';
 			$value['业务提票时间'] =Db::name("assoc")->where(["type"=>1,"status"=>[1,2],"is_del"=>0,'orderCode'=>$value['业务订单编号']])
 			                    ->order("id desc")->value('addtime','');
 			//计算账期
-			$value['账期'] = round(bcdiv(bcsub($time,strtotime($value['最近回款时间']??$value['下单时间']), 3), 86400, 3),
-				2);
-			$value['比率'] = round(bcdiv($value['账期'], 30, 1));
+			$value['账期'] = bcdiv(bcsub($time,strtotime($value['最近回款时间']==''?$value['下单时间']:$value['最近回款时间']), 3), 86400, 0);
+			$value['比率'] = round(bcdiv($value['账期'], 30, 4),3);
 			$value['订单是否超期'] = $value['比率'] > 6 ? '是' : '否';
 
-			$value['开票是否超期'] = round(bcdiv(bcsub($time, strtotime($value['最近开票时间']??$value['下单时间']), 1), 86400, 1)) > 15 ? '是' : '否';
+			$value['开票是否超期'] = round(bcdiv(bcsub($time, strtotime($value['最近开票时间']==''?$value['下单时间']:$value['最近开票时间']), 1), 86400, 1)
+			) >
+			15 ? '是' : '否';
 
             $value['最近一次发货时间'] = Db::table('fh_source')
                 ->whereIn('qrdNo', [$value['业务订单编号'], $value['销售订单主编号']])
                 ->order(['id' => 'desc'])
                 ->value('send_date', '');
+            $value['销售回款'] = Db::name("tag_log")->alias("a")->leftJoin("order_tag b","a.tag_id=b.id")
+                ->where(["a.code"=>$value['业务订单编号'],"a.status"=>1,"b.type"=>3])->value("b.tag_name",'');
+             $value['销售开票'] = Db::name("tag_log")->alias("a")->leftJoin("order_tag b","a.tag_id=b.id")
+                ->where(["a.code"=>$value['业务订单编号'],"a.status"=>1,"b.type"=>4])->value("b.tag_name",'');
+			if($value['订单来源']==10)$value['最近一次发货时间']=$value['下单时间'];
+			$value['订单来源'] = $this->qrdSource[$value['订单来源']] ?? '';
+			$value['回款状态'] = $this->pay_status[$value['回款状态']] ?? '';
+			$value['开票状态'] = $this->inv_status[$value['开票状态']] ?? '';
+			$value['发货状态'] = $this->sendStatus[$value['发货状态']] ?? '';
 			yield $value;
 		}
 
@@ -718,7 +672,7 @@ class Report extends Command
 	{
 //		$param = $this->request->only(['company' => '', 'start' => '', 'end' => ''], 'post', 'trim');
 
-		$where = [['a.is_del', '=', 0], ['c.is_del', '=', 0], ['d.is_del', '=', 0], ['e.is_del', '=', 0]];
+		$where = [['a.is_del', '=', 0],["a.status","in",[3,4]], ['e.is_del','=', 0]];
 
 		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['a.check_time', 'between', [$param['start'], $param['end']]];
 		if ($param['companyNo'] != '') $where[] = ['e.companyNo', '=', $param['companyNo']];
@@ -726,12 +680,9 @@ class Report extends Command
 		$data = Db::name('pay_invoice')
 		          ->alias('a')
 		          ->field('
-            d.companyName 回票业务公司名称,
+            e.companyName 回票业务公司名称,
             a.hpNo 回票编码,
-            c.cgdNo 采购单编号,
-            d.fundCode 财务核算编码,
-            d.goodName 产品名称,
-            d.supplierName 供应商名称,
+            e.supplierName 供应商名称,
             a.invoiceNumber 发票号,
             b.item_list,
             "" 发票货物或应税劳务、服务名称,
@@ -742,9 +693,7 @@ class Report extends Command
             b.total 本次回票总金额,
             a.check_time 本次回票时间
             ')
-		          ->leftJoin('invoice_info b', 'b.payNo=a.payNo')
-		          ->leftJoin('pay_info c', 'c.payNo=a.payNo')
-		          ->leftJoin('cgd_info d', 'd.sequenceNo=c.cgdNo')
+		          ->leftJoin('invoice_info b', 'b.hpNo=a.hpNo and b.status=1')
 		          ->leftJoin('pay e', 'e.payNo=a.payNo')
 		          ->where($where)
 		          ->order(['a.id' => 'desc'])
@@ -785,7 +734,6 @@ class Report extends Command
 
 		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['createdTime', 'between', [$param['start'], $param['end']]];
 		if ($param['companyNo'] != '') $where[] = ['companyNo', '=', $param['companyNo']];
-//		if ($param['supplierNo'] != '') $where[] = ['supplierNo', '=', $param['supplierNo']];
 		$data = Db::name("cgd_info")->where($where)
 		          ->field("
         sequenceNo '采购单编号',
@@ -796,7 +744,7 @@ class Report extends Command
         createdTime '采购时间',
         cgdType '采购单类型',
         if(qrdCode='',bkCode,qrdCode) '确认单编号/备库单编号',
-        if(cxCode='',sequenceNo,cxCode) '销售单主单号',
+        if(cxCode='',if(qrdCode='',bkCode,qrdCode),cxCode) '销售单主单号',
         goodNo '商品编号',
         goodName '商品名称',
         firstCat '一级分类',
@@ -836,10 +784,6 @@ class Report extends Command
 			$value['发货状态'] = $this->sendStatus[$value['发货状态']];
 			yield $value;
 		}
-
-		//        if (empty($list)) $list[] = ['导出数据为空' => ''];
-		//
-		//        excelExport('采购单明细表', array_keys($list[0]), $list);
 	}
 
 	/**
@@ -904,18 +848,16 @@ class Report extends Command
 	DATE_FORMAT( a.createtime, '%Y' ) 年,
 	DATE_FORMAT( a.createtime, '%m' ) 月,
 	DATE_FORMAT( a.createtime, '%d' ) 日,
-	a.createtime 退货创建时间,
-	a.thNo 退货单号,
 	b.companyName 退货公司名称,
 	b.companyNo 退货公司编号,
-	b.ownerName 销售员,
 	b.department 销售部门,
+	b.ownerName 销售员,
 	b.qrdSource 销售来源,
 	b.pay_source 支付渠道,
 	'' 活动类型,
 	b.sequenceNo 订单编号,
 	if(b.cxCode='',b.sequenceNo,b.cxCode) 销售订单编号,
-	c.bkCode 备库编号,
+	a.thNo 退货单号,
 	b.cgdNo 采购单号,
 	b.platName 平台类型,
 	b.poCode 平台订单号,
@@ -931,7 +873,7 @@ class Report extends Command
 	a.th_num 退货数量,
 	b.goodPrice 销售单价,
 	a.th_qrd_fee 退货金额,
-	b.tax 税点,
+	ifnull(b.tax,0)/100 税点,
 	c.ownerName 采购员,
 	c.barePrice 采购裸价,
 	c.markPrice 加标费,
@@ -942,14 +884,15 @@ class Report extends Command
 	c.deliveryPrice 物流费,
 	c.goodPrice 采购单价,
 	round(a.th_num * ifnull(c.goodPrice,b.total_origin_price/b.goodNum),2) 退货采购货款,
-	c.tax 采购税点,
-	c.supplierName 供应商名称,
+	ifnull(c.tax,0)/100 采购税点,
 	if(b.isStock=1,'是','否') 是否库存,
+	c.supplierName 供应商名称,
 	c.sendType 发货方式,
 	if(a.is_th=1,'是','否') 供应商是否同意退货,
 	'' as 付款方式,
 	b.fundCode 财务核算码,
-	a.th_remark 退货备注 
+	a.th_remark 退货备注,
+	c.bkCode 备库单号
 		")->cursor();
 		foreach ($list as $value) {
 			$value['销售来源']= $this->qrdSource[$value['销售来源']]??"";
@@ -957,4 +900,65 @@ class Report extends Command
 			yield $value;
 		}
 	}
+	//产品部门销售业绩
+	private function Q($param=[]){
+		$where = [["is_del","=",0],["status","in",[0,1,2]]];
+		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['addtime', 'between', [date("Y-m-d 00:00:00",strtotime($param['start'])),date("Y-m-d 23:59:59",
+		strtotime($param['end']))]];
+//		if ($param['companyNo'] != '') $where[] = ['supplierNo', '=', $param['companyNo']];
+		$Db= Db::connect("mysql_wsm");
+		$list =$Db->name("sale")->field("orderCode 销售单号,apply_name 业务人员,apply_id 业务部门,cat_id 分类,total_price 产品货款总额,addtime 日期")
+		->where($where)
+		->cursor();
+		foreach ($list as $value){
+			$value['业务部门'] = $Db->name("depart_user")->alias("a")->leftjoin("company_item b","a.itemid=b.id")
+			->where(["a.is_del"=>0,"a.status"=>1,"a.uid"=>$value['业务部门']])->value("b.name",'');
+			$value['分类'] = $Db->name("cat")->where(["id"=>$value['分类']])->value("search","");
+			yield $value;
+		}
+	}
+
+		//采购部门销售业绩
+	private function R($param=[]){
+		$where = [["a.is_del","=",0],["a.status","=",2],["b.is_stock","=",0]];
+		if (($param['start'] != '') && ($param['end'] != '')) $where[] = ['a.sendtime', 'between', [date("Y-m-d 00:00:00",
+		strtotime($param['start'])),date("Y-m-d 23:59:59",strtotime($param['end']))]];
+//		if ($param['companyNo'] != '') $where[] = ['supplierNo', '=', $param['companyNo']];
+		$Db= Db::connect("mysql_wsm");
+		$list =$Db->name("order_out")->alias("a")
+		->leftjoin("sale b","a.orderCode=b.orderCode")
+		->leftjoin("order_send c","a.outCode=c.outCode")
+		->leftjoin("purchease_order d","c.cgdNo=d.cgdNo")
+		->field("
+			a.outCode 发货单号,
+			c.cgdNo 采购单号,
+			a.orderCode 销售单号,
+			b.platform_id 平台类型,
+			d.cgder_id 业务部门,
+			d.cgder 采购人员,
+			b.order_source 咨询类型,
+			a.sendtime 发货时间,
+			b.cat_id `一级分类`,
+			b.good_name 商品名称,
+			a.post_name 物流公司,
+			a.post_code 物流单号,
+			a.send_num 本次发货数量,
+			a.send_num*b.sale_price 本次发货金额,
+			b.sale_price 销售单价,
+			b.good_num-b.th_num 销售数量,
+			b.total_price-b.th_fee 销售金额,
+			d.supplier_name `供应商名称`
+		")
+		->where($where)
+		->cursor();
+		foreach ($list as $value){
+			$value['业务部门'] = $Db->name("depart_user")->alias("a")->leftjoin("company_item b","a.itemid=b.id")
+			->where(["a.is_del"=>0,"a.status"=>1,"a.uid"=>$value['业务部门']])->value("b.name",'');
+			$value['一级分类'] = $Db->name("cat")->where(["id"=>$value['一级分类']])->value("search","");
+			$value['平台类型'] = $Db->name("platform")->where(["id"=>$value['平台类型']])->value("platform_name","");
+			$value['咨询类型']=$this->qrdSource[$value['咨询类型']]??"";
+			$value['物流单号'].='';
+			yield $value;
+		}
+	}
 }

+ 6 - 5
app/command/good.php

@@ -27,13 +27,12 @@ class good extends Command
 	    $goodset =Cache::store("redis")->get("goodSet");
 	    if($goodset ==1) return;
 	    Cache::store("redis")->set("goodSet",1,1800);
-//	    $this->date="2022-06-01 00:00:00";
 	    try{
 		    $this->goodBasic();
 		    $this->goodZx();
-		    Cache::store("redis")->set("goodSet",0);
+//		    Cache::store("redis")->set("goodSet",0);
 	    }catch (\Exception $e){
-		    Cache::store("redis")->set("goodSet",0);
+//		    Cache::store("redis")->set("goodSet",0);
 		    $output->writeln("【".date("Y-m-d H:i:s")."】".$e->getMessage());
 	    }
 
@@ -82,8 +81,10 @@ class good extends Command
             })
             ->withAttr("good_unit",function ($m){
             	return Db::connect('mysql_wsm')->name('unit')->where("id",$m)->value("unit","");
-            })->field("spuCode,good_name,cat_id,good_unit,craft_desc,after_sales,supplierNo,companyNo,good_img,good_info_img,good_thumb_img,creater,createrid,is_stock,0 isZx")
-            ->where("addtime",">=", $this->date)
+            })->field("spuCode,good_name,cat_id,good_unit,craft_desc,after_sales,supplierNo,companyNo,good_img,
+            good_info_img,good_thumb_img,creater,createrid,is_stock,0 isZx")
+            ->where("updatetime",">=", $this->date)
+            ->where("status","=", 1)
             ->select()->toArray();
     	    return $this->addGood($list);
     }

+ 10 - 7
extend/TaxInvoice.php

@@ -106,7 +106,7 @@ class TaxInvoice {
     protected $entCode;//企业税号
     protected $zipCode;//压缩标识
     protected $encryptCode;//加密标识 0 base64 1 3DES
-    protected $domain='https://sandbox.ele-cloud.com';//测试域名
+    protected $domain='https://openapi.ele-cloud.com';//测试域名
 //    protected $domain='https://sandbox.ele-cloud.com';
     public function __construct(string $appKey,string $appSecret,string $entCode='',$zipCode=0,$encryptCode=0){
         $this->appKey=$appKey;
@@ -184,6 +184,7 @@ class TaxInvoice {
             "dataExchangeId"=>$this->ts_time().rand(pow(10,14),pow(10,15)-1),
             "content"=>base64_encode(json_encode($data,JSON_UNESCAPED_UNICODE))
         ];
+        \think\facade\Log::info("参数:".json_encode($data,JSON_UNESCAPED_UNICODE));
         return $param;
     }
 
@@ -191,16 +192,18 @@ class TaxInvoice {
 * @param $data
  * @return array|bool|float|int|mixed|stdClass|string|null
 */public function ReturnData($data){
+	$return =["code"=>0,"message"=>"fail"];
       if(key_exists("returnCode",$data['returnStateInfo'])){
          	if ($data['returnStateInfo']['returnCode']=='0000'){
          	$result= base64_decode($data['content']);
-            return json_decode($result,true);
+            $return = json_decode($result,true);
          	}else{
-				$returnMessage= base64_decode($data['returnStateInfo']['returnMessage']);
-            return ["code"=>$data['returnStateInfo']['returnCode'],"message"=>$returnMessage];
+			$returnMessage= base64_decode($data['returnStateInfo']['returnMessage']);
+            $return =["code"=>$data['returnStateInfo']['returnCode'],"message"=>$returnMessage];
          	}
         }
-         return ["code"=>0,"message"=>"fail"];
+        \think\facade\Log::info("返回值:".json_encode($return,JSON_UNESCAPED_UNICODE));
+         return $return;
     }
 
     /**
@@ -499,7 +502,7 @@ class TaxInvoice {
 * @param string $invoiceCode
  * @return array|bool|float|int|mixed|\stdClass|string|null
 */public function QueryInvalidInvoice(string $seller_id='',string $invoiceNumber='',string $invoiceCode=''){
-    	$url=$this->domain."/api/order-api/order-api/v5/DeprecateInvoices?access_token=".$this->GetToken();
+    	$url=$this->domain."/api/order-api/order-api/v5/QueryInvalidInvoice?access_token=".$this->GetToken();
 		$param=[
 			"XHFSBH"=>$seller_id,
 			"FPDM"=>$invoiceCode,
@@ -669,7 +672,7 @@ class TaxInvoice {
  * @return array|bool|float|int|mixed|\stdClass|string|null
 */public function DownloadRedInvoiceApplicationResult(string $resultBatchNum='',string $idCard='',string
     $invoiceType='',string $start='',string $end='',string $buyer_id='',string $seller_id='',string $infoCode='',
-    string $downScope='',string $page='',string $size=''){
+    string $downScope='0',string $page='1',string $size='10'){
 		$url=$this->domain."/api/order-api/order-api/v5/DownloadRedInvoiceApplicationResult?access_token=".$this->GetToken();
 		$param=[
 			"SQBXZQQPCH"=>$resultBatchNum,

Some files were not shown because too many files changed in this diff