wugg 8 months ago
parent
commit
1abcf5ed6b

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

@@ -9,7 +9,6 @@ use think\App;use think\facade\Validate;
 class Menu extends Base{
     protected $noLogin=[
         "GetMenuAction" ,
-         "*"//功能权限集合 工单调用
         ];
 	public function __construct(App $app) {
 		parent::__construct($app);

+ 30 - 0
app/admin/listener/updateSupplierGood.php

@@ -0,0 +1,30 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\admin\listener;
+
+use app\admin\model\GoodBasic;
+use app\admin\model\WarehouseInfo;
+use think\facade\Validate;
+class updateSupplierGood
+{
+    /**
+     * 事件监听处理
+     *
+     * @return mixed
+     */
+    public function handle($event)
+    {
+        $supplierCode=$event["code"];
+        $valide=Validate::rule([
+            "code"=>"require|max:255",
+            "personid"=>"require|number",
+            "person"=>"require|max:255",
+        ]);
+        if(!$valide->check($event)){
+           return $valide->getError();
+        }
+        $update= GoodBasic::where([['supplierNo','=',$supplierCode],['is_del','=',0]])->save(["chargerid" => $event['personid'], "charger" => $event['person']]);
+        $ware =WarehouseInfo::where([['supplierNo','=',$supplierCode],['is_del','=',0],['wsm_type','=',2]])->save([['contactor' => $event['personid'], 'contactor_name' => $event['person']]]);
+    }
+}

+ 1 - 0
app/admin/route/api.php

@@ -1,4 +1,5 @@
 <?php
+
 use think\facade\Route;
 //菜单
 Route::rule('menu', 'admin/Menu/list');

+ 62 - 18
app/common/Ocr.php

@@ -4,13 +4,10 @@
 namespace app\common;
 
 use HuaweiCloud\SDK\Core\Auth\BasicCredentials;
-use HuaweiCloud\SDK\Core\Exceptions\ConnectionException;
-use HuaweiCloud\SDK\Core\Exceptions\RequestTimeoutException;
-use HuaweiCloud\SDK\Core\Exceptions\ServiceResponseException;
+use HuaweiCloud\SDK\Core\Exceptions\{ConnectionException,RequestTimeoutException,ServiceResponseException};
 use HuaweiCloud\SDK\Core\Http\HttpConfig;
-use HuaweiCloud\SDK\Ocr\V1\Model\BusinessLicenseRequestBody;
-use HuaweiCloud\SDK\Ocr\V1\Model\BusinessLicenseResult;use HuaweiCloud\SDK\Ocr\V1\Model\RecognizeBusinessLicenseRequest;
-use HuaweiCloud\SDK\Ocr\V1\OcrClient;use phpDocumentor\Reflection\Types\Self_;
+use HuaweiCloud\SDK\Ocr\V1\Model\{BusinessLicenseRequestBody,InvoiceVerificationRequestBody,RecognizeBusinessLicenseRequest,RecognizeInvoiceVerificationRequest};
+use HuaweiCloud\SDK\Ocr\V1\OcrClient;
 class Ocr {
     private static $endpoint = 'https://ocr.cn-north-4.myhuaweicloud.com';
     private static $projectId = "f3818e89528d4b0db0c6353195653f04";
@@ -28,6 +25,39 @@ class Ocr {
         }
         return self::$instance;
     }
+
+    /**
+    * @param string $url
+    * @param string $image
+    * @return array
+    */
+    public static function businessLicense($url='',$image='') {
+        $client = self::OcrInfo();
+       // 业务公司营业执照识别 为例
+       if ($image!==""&&$url!=="") $url="";//图片数据流优先级最高。链接上传需要下载图片到识别服务器钟速度更慢
+
+        $request = new RecognizeBusinessLicenseRequest();
+        $body = new BusinessLicenseRequestBody();
+        if($image!="")$body->setImage($image);
+        if($url!="")$body->setUrl($url);
+        $request->setBody($body);
+        $msg = '';
+        try {
+          $response = $client->RecognizeBusinessLicense($request);
+        } catch (ConnectionException $e) {
+          $msg = $e->getMessage();
+        } catch (RequestTimeoutException $e) {
+          $msg = $e->getMessage();
+        } catch (ServiceResponseException $e) {
+          $msg = $e->getErrorMsg();
+        }
+        if ($msg) {
+          return ["isResult"=>false,"msg"=>$msg];
+        } else {
+          return ['isResult'=>true,'msg'=>"获取成功","data"=>json_decode($response->getResult()->__toString(),true)];
+        }
+    }
+
     protected static function OcrInfo() {
         $config = HttpConfig::getDefaultConfig();
         $config->setIgnoreSslVerification(true);
@@ -38,22 +68,35 @@ class Ocr {
           ->build();
         return $client;
     }
-    /**
-    * @param string $url
-     * @return array
-     */
-    public static function businessLicense($url='') {
+
+     /**
+    * Array of property to type mappings. Used for (de)serialization
+    * code  发票代码。发票种类为全电发票时,该参数须为空字符串。
+    * number  发票号码
+    * issueDate  发票日期格式YYYY-MM-DD
+    * checkCode  校验码后六位。 - 以下种类发票,参数不可为空    增值税普通发票、增值税电子普通发票、增值税普通发票(卷式)、增值税电子普通发票(通行费)、区块链电子发票。  - 区块链电子发票需要填写5位校验码。
+    * subtotalAmount  合计金额。和票据上的金额的有效数字保持一致,例如票据上的金额为88.00,则需要输入字符串为“88.00”,才能验真成功。如果输入“88”或“88.0”可能会产生\"result_code\": \"1010\", \" Parameter error.\"报错。  发票种类为全电发票时,该参数须为价税合计金额,其他票种使用不含税合计金额。  - 以下种类发票,参数不可为空    增值税专用发票、增值税电子专用发票、机动车销售统一发票、二手车销售统一发票、区块链电子发票、全电发票。  - 填写发票合计金额(不含税)    增值税专用发票、增值税电子专用发票、机动车销售统一发票、区块链电子发票。  - 二手车发票需要填写发票车价合计金额
+    *
+    * @var string[]
+    */
+    public static function InvoiceVerification($code='',$number='',$issueDate='',$checkCode='',$subtotalAmount='') {
         $client = self::OcrInfo();
-       // 业务公司营业执照识别 为例
-        $request = new RecognizeBusinessLicenseRequest();
-        $body = new BusinessLicenseRequestBody();
-        $body->setUrl($url);
+        $request=new RecognizeInvoiceVerificationRequest();
+        $body = new InvoiceVerificationRequestBody();
+        $issueDate = date('Y-m-d',strtotime($issueDate));
+        if($checkCode!=""&&strlen($checkCode)!=6)$checkCode=substr($checkCode,0,6);
+        if($subtotalAmount!="")$subtotalAmount= number_format($subtotalAmount, 2, '.', '');
+        if($code!="")$body->setCode($code);
+        if($number!="")$body->setNumber($number);
+        if($issueDate!="")$body->setIssueDate($issueDate);
+        if($checkCode!="")$body->setCheckCode($checkCode);
+        if($subtotalAmount!="")$body->setSubtotalAmount($subtotalAmount);
         $request->setBody($body);
         $msg = '';
         try {
-          $response = $client->RecognizeBusinessLicense($request);
-        } catch (ConnectionException $e) {
-          $msg = $e->getMessage();
+          $response = $client->RecognizeInvoiceVerification($request);
+        }catch (ConnectionException $e) {
+           $msg = $e->getMessage();
         } catch (RequestTimeoutException $e) {
           $msg = $e->getMessage();
         } catch (ServiceResponseException $e) {
@@ -64,5 +107,6 @@ class Ocr {
         } else {
           return ['isResult'=>true,'msg'=>"获取成功","data"=>json_decode($response->getResult()->__toString(),true)];
         }
+
     }
 }

+ 1 - 0
app/event.php

@@ -13,6 +13,7 @@ return [
         "role_sync"=>[app\bug\listener\RoleEvent::class],
         "user_sync"=>[app\bug\listener\UserEvent::class],
         "PlatCat"=>[app\admin\listener\PlatCat::class],
+        "updateSupplierGood"=>[app\admin\listener\updateSupplierGood::class],
     ],
 
     'subscribe' => [

+ 12 - 2
app/user/controller/Base.php

@@ -4,8 +4,10 @@
 namespace app\user\controller;
 
 
-use think\App;
-class Base extends \app\BaseController{
+use app\BaseController;
+use app\common\Ocr;
+use think\App;use think\Exception;
+class Base extends BaseController{
 	protected  $uid=0;
 	protected  $uname='system';
 	protected  $noLogin=[];
@@ -31,4 +33,12 @@ class Base extends \app\BaseController{
    	  $this->uname = $User->nickname;
    	  $this->level = $User->level;
    }
+
+
+   public function GetBusinessInfoByParam($url='',$image=''){
+          if ($url=="" && $image=="") throw new \Exception("营业执照识别必须上传图片或存在链接");
+          $ocr= Ocr::getInstance();
+          $result= $ocr::businessLicense($url,$image);
+          return $result;
+   }
 }

+ 33 - 44
app/user/controller/Business.php

@@ -4,7 +4,7 @@
 namespace app\user\controller;
 
 
-use think\App;
+use app\user\model\Headquarters;use think\App;
 use think\facade\Validate;
 class Business extends Base{
     public function __construct(App $app) {
@@ -82,7 +82,9 @@ class Business extends Base{
         if(!$valid->check($param)){
             return error($valid->getError());
         }
-        $data = [
+        $this->model->startTrans();
+        try{
+           $data = [
             'company' => $param['company'],
             'companyNo' =>makeNo('GS'),
             'inv_code' =>$param['inv_code'],
@@ -103,28 +105,17 @@ class Business extends Base{
         ];
 
         $model = $this->model->create($data);
-        if($model->isEmpty())return error('添加失败');
-            $headquarters = new \app\user\model\Headquarters();
-            $headquarters->create([
-                'code'=>$model->companyNo,
-                'name'=>$param['company'],
-                'type'=>1,
-                'company_type'=>$param['type'],
-                'invoice_title'=>$param['invoice_title'],
-                'invoice_people'=>$param['inv_legaler'],
-                'invoice_addr'=>$param['inv_addr'],
-                'invoice_mobile'=>$param['mobile'],
-                'invoice_code'=>$param['inv_code'],
-                'invoice_bank'=>$param['inv_bank'],
-                'invoice_bankNo'=>$param['inv_bankNo'],
-                'invoice_img'=>$param['license_img'],
-                'remark'=>"",
-                'status'=>1,
-                'is_del'=>0,
-                'creater'=>$this->uname,
-                'createrid'=>$this->uid,
-            ]);
-//        Cache::store('redis')->handler()->lpush('companycopy',json_encode($data,JSON_UNESCAPED_UNICODE));
+        if($model->isEmpty())throw new \Exception('业务公司创建失败');
+         $model->updater=$this->uname;
+         $model->updaterid=$this->uid;
+         $hqcreate= Headquarters::createInfo($model,1);
+        if (!$hqcreate)throw new \Exception('业务公司信息创建失败');
+        $this->model->commit();
+        }catch (\Exception $exception){
+            $this->model->rollback();
+            return error($exception->getMessage());
+        }
+
         return success('添加成功');
     }
     /**
@@ -150,26 +141,24 @@ class Business extends Base{
         if(!$valid->check($param)) return error($valid->getError());
         $model = $this->model->findOrEmpty($param['id']);
         if($model->isEmpty())return error('数据不存在');
-        $model->inv_addr = $param['inv_addr'];
-        $model->inv_code = $param['inv_code'];
-        $model->inv_bank = $param['inv_bank'];
-        $model->inv_bankNo = $param['inv_bankNo'];
-        $model->invoice_title = $param['invoice_title'];
-        if($model->save()){
-            $headquarters = new \app\user\model\Headquarters();
-            $headquarters->update([
-                'invoice_title'=>$param['invoice_title'],
-                'invoice_people'=>$param['inv_legaler'],
-                'invoice_addr'=>$param['inv_addr'],
-                'invoice_mobile'=>$param['mobile'],
-                'invoice_code'=>$param['inv_code'],
-                'invoice_bank'=>$param['inv_bank'],
-                'invoice_bankNo'=>$param['inv_bankNo'],
-                'updater'=>$this->uname,
-                'updaterid'=>$this->uid,
-            ],['code'=>$model->companyNo]);
-           }
-//        Cache::store('redis')->handler()->lpush('companycopy',json_encode($model->toArray(),JSON_UNESCAPED_UNICODE));
+        $this->model->startTrans();
+        try {
+            $model->inv_addr = $param['inv_addr'];
+            $model->inv_code = $param['inv_code'];
+            $model->inv_bank = $param['inv_bank'];
+            $model->inv_bankNo = $param['inv_bankNo'];
+            $model->invoice_title = $param['invoice_title'];
+            if(!$model->save())throw new \Exception('保存失败');
+            $model->updater=$this->uname;
+            $model->updaterid=$this->uid;
+            $hqcreate= Headquarters::createInfo($model,1);
+            if (!$hqcreate)throw new \Exception('业务公司信息创建失败');
+
+            $this->model->commit();
+         }catch (\Exception $exception){
+            $this->model->rollback();
+            return error($exception->getMessage());
+         }
         return success('保存成功');
     }
 

+ 254 - 0
app/user/controller/Customer.php

@@ -0,0 +1,254 @@
+<?php
+
+
+namespace app\user\controller;
+
+
+use app\user\model\CustomerInfo;
+use app\user\model\CustomerMember;
+use app\user\model\Headquarters;
+use think\App;
+use think\facade\Validate;
+class Customer extends Base{
+    public function __construct(App $app) {
+        parent::__construct($app);
+        $this->model = new CustomerInfo();
+    }
+    /**
+     * @return \think\response\Json|void
+     */
+    public function create(){
+        $param = $this->request->only([
+        	'companyName'=>"",
+        	'parent' => 0,
+        	'is_del' => 0,
+        	'customer_member',
+        	'branch',
+        	'middle',
+        	'area',
+        	], 'post', 'trim');
+
+        $val = Validate::rule([
+            'companyName|客户名称' => 'require|max:255|unique:app\user\model\CustomerInfo,companyName^parent^is_del',
+            'customer_member|联系方式' => 'require|array|max:100',
+            'branch|省级' => 'require',
+            'middle|市级' => 'require',
+            'area|区域' => 'require',
+        ]);
+        if ($val->check($param) == false) return error($val->getError());
+        $code= makeNo("KH");
+        $data = [
+                'companyNo' => $code,
+                'companyName' => $param['companyName'],
+                'parent' => $param['parent'],
+                'itemid' => $param['parent'],
+                'area' =>$param['area'],
+                'status' => 0,
+                'branch' =>$param['branch'],
+                'middle' =>$param['middle'],
+                'is_del' => 0,
+                'createrid' => $this->uid,
+                'creater' => $this->uname,
+            ];
+        $member=[];
+        if(!empty($param['customer_member'])){
+            foreach ($param['customer_member'] as $key => $value) {
+                         $member[] = [
+                                    'commobile' => $value['commobile'] ?? '',
+                                    'contactor' => $value['contactor'] ?? '',
+                                    'position' => $value['position'] ?? '',
+                                    'wxaccount' => $value['wxaccount'] ?? '',
+                                    'qqaccount' => $value['qqaccount'] ?? '',
+                                    'email' => $value['email'] ?? '',
+                                    'comdepart' => $value['comdepart'] ?? '',
+                                    'status' => $value['status'] ?? '',
+                                    'createrid' => $this->uid,
+                                    'creater' => $this->uname,
+                                    'companyNo' => $code,
+                                ];
+                        }
+        }
+
+        $this->model->startTrans();
+        try{
+            $create=$this->model->create($data);
+            if($create->isEmpty()) return error("创建失败");
+            if(!empty($member)){
+                $memberAdd= $this->model->member()->saveAll($member);
+                if($memberAdd==false) return error("创建失败");
+            }
+            $heq=Headquarters::createInfo($create,2);
+            if($heq==false) return error("创建失败");
+            $this->model->commit();
+        }catch (\Exception $e){
+            $this->model->rollback();
+            return error($e->getMessage());
+        }
+        return success("创建成功");
+    }
+    /**
+     * @param id 主键id
+     *            companyName 客户名称
+     *            parent 父级id
+     *            is_del 删除状态
+     *            customer_member 联系方式
+     *            branch 省级
+     *            middle 市级
+     *            area 区域
+    * @return \think\Response|\think\response\Json|void
+    * @throws \think\exception\PDOException
+     */
+    public function save(){
+        $param = $this->request->only([
+            'id'=>"",
+            'companyName'=>"",
+            'parent' => 0,
+            'is_del' => 0,
+            'customer_member',
+            'branch',
+            'middle',
+            'area',
+            ], 'post', 'trim');
+        $val = Validate::rule([
+            'id|主键ID' => 'require',
+            'companyName|客户名称' => 'require|max:255|unique:app\user\model\CustomerInfo,companyName^parent^is_del',
+            'customer_member|联系方式' => 'require|array|max:100',
+            'branch|省级' => 'require',
+            'middle|市级' => 'require',
+            'area|区域' => 'require',
+        ]);
+        if ($val->check($param) == false) return error($val->getError());
+        $info=$this->model->findOrEmpty($param['id']);
+        if($info->isEmpty()) return error("客户不存在");
+        if($info->status==1) return error("客户已启用,不能修改");
+        $member=[];
+        if(!empty($param['customer_member'])){
+            foreach ($param['customer_member'] as $key => $value) {
+                 $member[] = [
+                            "id"=>$value['id'] ?? null,
+                            'commobile' => $value['commobile'] ?? '',
+                            'contactor' => $value['contactor'] ?? '',
+                            'position' => $value['position'] ?? '',
+                            'wxaccount' => $value['wxaccount'] ?? '',
+                            'qqaccount' => $value['qqaccount'] ?? '',
+                            'email' => $value['email'] ?? '',
+                            'comdepart' => $value['comdepart'] ?? '',
+                            'status' => $value['status'] ?? '',
+                            'createrid' => $this->uid,
+                            'creater' => $this->uname,
+                            'companyNo' => $info->companyNo,
+                        ];
+             }
+        }
+        $info->companyName=$param['companyName'];
+        $info->parent=$param['parent'];
+        $info->branch=$param['branch'];
+        $info->middle=$param['middle'];
+        $info->area=$param['area'];
+        $this->model->startTrans();
+        try{
+            $info->save();
+            if(!empty($member)){
+                $memberAdd= $this->model->member()->saveAll($member);
+                if($memberAdd==false) return error("修改失败");
+            }
+            $heq=Headquarters::createInfo($info,2);
+            if($heq==false) return error("修改失败");
+            $this->model->commit();
+        }catch (\Exception $e){
+            $this->model->rollback();
+            return error($e->getMessage());
+        }
+        return success("修改成功");
+    }
+    /**
+     * @param id 主键id
+     * @return \think\Response|\think\response\Json|void
+     * @throws \think\exception\PDOException
+     */
+    public function delete(){
+        $id=$this->request->param('id');
+        if(empty($id)) return error("参数错误");
+        $info=$this->model->findOrEmpty($id);
+        if($info->isEmpty()) return error("客户不存在");
+        if($info->status==1) return error("客户已启用,不能删除");
+        $this->model->startTrans();
+        try{
+            $info->is_del=1;
+            $del=$info->save();
+            if($del==false) return error("删除失败");
+            $delHq=Headquarters::where('code',$info->companyNo)->update(["is_del"=>0,"updater"=>$this->uname,"updaterid"=>$this->uid]);
+            if($delHq==false) return error("删除失败");
+            $this->model->commit();
+        }catch (\Exception $e){
+            $this->model->rollback();
+            return error($e->getMessage());
+        }
+        return success("删除成功");
+    }
+    /**
+    * @return \think\Response|\think\response\Json|void
+    */
+    public function info(){
+        $id=$this->request->param('id');
+        if(empty($id)) return error("参数错误");
+        $info=$this->model->with(['member','parentInfo'])->findOrEmpty($id);
+        if($info->isEmpty()) return error("客户不存在");
+        return success("获取成功",$info);
+    }
+    /**
+     * @param page 页码
+     * @param size 页
+     *             companyName 客户名称
+     *             status 状态
+     *             createrId 创建人id
+     *             start 开始时间
+     *             end 结束时间
+     *             companyNo 公司编号
+     *             itemid 项目id
+     * @return \think\Response|\think\response\Json|void
+     */
+    public function list(){
+       $param=$this->request->param(["page"=>1,"size"=>10,"companyName"=>"","status"=>"","createrId"=>"","start"=>"",
+       "companyNo"=>"","itemid"=>0,"end"=>""],"post","trim");
+       $where= [["is_del","=",0]];
+       if($param['companyName']!="") $where[]=["companyName","like","%".$param['companyName']."%"];
+        if($param['status']!="") $where[]=["status","=",$param['status']];
+        if($param['createrId']!="") $where[]=["createrid","=",$param['createrId']];
+        if($param['start']!="")$where[]=["addtime",">=",startTime($param['start'])];
+        if($param['end']!="")$where[]=["addtime","<=",endTime($param['end'])];
+        if($param['companyNo']!="") $where[]=["companyNo","=",$param['companyNo']];
+        if($param['itemid']!=0)$where[]=["itemid","=",$param['itemid']];
+        $list=$this->model->with(["member","parentInfo"])
+        ->where($where)
+        ->order("id","desc")
+        ->paginate(["list_rows"=>$param['size'],"page"=>$param['page']]);
+        return success("获取成功",["list"=>$list->items(),"count"=>$list->total()]);
+    }
+    /**
+     * @param page 页码
+     *             companyNo 客户编号
+     *             status 状态
+     *             createrId 创建人id
+     *             start 开始时间
+     *             end 结束时间
+     * @return \think\Response|\think\response\Json
+     * @throws \think\exception\DbException
+     */
+    public function customerMember(){
+        $param=$this->request->param(["page"=>1,"size"=>10,"companyNo"=>"","status"=>"","createrId"=>"","start"=>"",
+        "end"=>""],"post","trim");
+        $where= [["is_del","=",0]];
+        if($param['companyNo']!="") $where[]=["companyNo","=",$param['companyNo']];
+        if($param['status']!="") $where[]=["status","=",$param['status']];
+        if($param['createrId']!="") $where[]=["createrid","=",$param['createrId']];
+        if($param['start']!="")$where[]=["addtime",">=",startTime($param['start'])];
+        if($param['end']!="")$where[]=["addtime","<=",endTime($param['end'])];
+        $customerMember= new CustomerMember();
+        $list=$customerMember->with(["customer"])
+        ->where($where)
+        ->order("id","desc")
+        ->paginate(["list_rows"=>$param['size'],"page"=>$param['page']]);
+        return success("获取成功",["list"=>$list->items(),"count"=>$list->total()]);
+    }
+}

+ 354 - 10
app/user/controller/Supplier.php

@@ -3,15 +3,38 @@
 
 namespace app\user\controller;
 
-
-use app\common\Ocr;use think\App;use think\facade\Validate;
+use app\user\model\Headquarters;use app\user\model\SupplierContact;use think\App;use think\facade\Validate;use think\Response;use think\response\Json;
 class Supplier extends Base{
     public $noLogin=["*"];
     public function __construct(App $app) {
         parent::__construct($app);
         $this->model = new \app\user\model\Supplier();
     }
-
+    /** * @param    参数列表如下:
+     *              - name: 供应商名称
+     *              - source: 来源
+     *              - coop_state: 合作状态
+     *              - category: 类别
+     *              - delivery_way: 配送方式
+     *              - level: 级别
+     *              - supplier_type: 供应商类型
+     *              - pay_type: 支付方式
+     *              - registercode: 注册码
+     *              - registertime: 注册时间
+     *              - scope: 业务范围
+     *              - type: 类型
+     *              - nature: 性质
+     *              - legaler: 法人
+     *              - addr: 地址
+     *              - prove_img: 证明图片
+     *              - supplier_img: 供应商图片
+     *              - contactor: 联系人
+     *              - mobile: 手机号
+     *              - telephone: 电话
+     *              - position: 职位
+     *              - email: 电子邮件
+     *              - personid: 负责人id
+     */
     public function create(){
         $param = $this->request->param(["name"=>"","source"=>"","coop_state"=>"","category"=>"","delivery_way"=>"",
         "level"=>"","supplier_type"=>"","pay_type"=>"","registercode"=>"","registertime"=>"","scope"=>"","type"=>"",
@@ -43,17 +66,338 @@ class Supplier extends Base{
             'personid|负责人' => 'require|number|gt:0',
         ]);
         if(!$valid->check($param))return error($valid->getError());
+        if ($param['supplier_img']!=''){
+            $param['license_img'] = $param['supplier_img'];
+                    $result = $this->GetBusinessInfoByParam($param['supplier_img']);
+                    /**
+                        * Array of attributes to getter functions (for serialization of requests)
+                        * registrationNumber  - 老版本营业执照对应注册号。 - 新三证合一版本营业执照对应社会保障号。
+                        * name  企业名称。
+                        * type  公司/企业类型/主体类型/类型。
+                        * address  住所/营业场所/企业住所/主要经营场所/经营场所。
+                        * legalRepresentative  法定代表人/负责人/执行事务合伙人/投资人/经营者。
+                        * registeredCapital  注册资本/出资额。
+                        * organizationForm  组成形式。
+                        * foundDate  成立日期/注册日期。
+                        * businessTerm  营业期限。
+                        * businessScope  经营范围。
+                        * issueDate  发照日期。
+                        * confidence  相关字段的置信度信息,置信度越大,表示本次识别的对应字段的可靠性越高,在统计意义上,置信度越大,准确率越高。 置信度由算法给出,不直接等价于对应字段的准确率。
+                        * @var string[]
+                        */
+                    if($result['code']==200){
+                        $param['ocr_status'] = 1;
+                         if ($param['name'] != $result['name']) {
+                            $param['remark'] = '企业名称与营业执照不匹配';
+                        }
+                        if ($param['registercode'] !=$result['registrationNumber']&& $param['registercode']!= '') {
+                            $param['remark'] .= '企业纳税识别号与营业执照不匹配';
+                        }
+                        $param['addr']=$result['address']??"";
+                        $param['legaler']=$result['legalRepresentative']??"";
+                        $param['registercode']=$result['registrationNumber']??"";
+                        $param['registertime']=$result['foundDate']??"";
+                        $param['scope']=$result['businessScope']??"";
+                        $param['nature']=$result['type']??"";
+                        $param['capital'] = $result['registeredCapital']??"";
 
-
+                    }else{
+                        $param['remark'] = '营业执照识别失败';
+                        $param['ocr_status'] = 2;
+                    }
+        }
+        $this->model->startTrans();
+        try{
+            $data=[
+                'code'=>makeNo('QS'),
+                'person'=>\app\user\model\User::where('account_id','=',$param['personid'])->value('nickname',''),
+                'creater'=>$this->uname,
+                'createrid'=>$this->uid
+            ];
+            $create = \app\user\model\Supplier::create(array_merge($data,$param));
+            if(!$create->isEmpty())throw new Exception('供应商创建失败');
+                $contact=[
+                    "code"=>$data['code'],
+                    "contactor"=>$param['contactor'],
+                    "mobile"=>$param['mobile'],
+                    "position"=>$param['position'],
+                    "telephone"=>$param["telephone"],
+                    "email"=>$param['email'],
+                    ];
+                $contactC= SupplierContact::create($contact);
+                if (!$contactC->isEmpty())throw new Exception("供应商联系人信息创建失败");
+                $create->updater=$this->uname;
+                $create->updaterid=$this->uid;
+                $hqcreate= Headquarters::createInfo($create,3);
+                if (!$hqcreate)throw new Exception("供应商信息创建失败");
+        }catch (Exception $exception){
+            $this->model->rollback();
+            return error($exception->getMessage());
+        }
+        $this->model->commit();
+        return  success("创建成功");
     }
+    /**
+     * 编辑供应商
+     * 参数:
+     * id 供应商id
+     *              - name: 供应商名称
+     *              - source: 来源
+     *              - coop_state: 合作状态
+     *              - category: 类别
+     *              - delivery_way: 配送方式
+     *              - level: 级别
+     *              - supplier_type: 供应商类型
+     *              - pay_type: 支付方式
+     *              - registercode: 注册码
+     *              - registertime: 注册时间
+     *              - scope: 业务范围
+     *              - type: 类型
+     *              - nature: 性质
+     *              - legaler: 法人
+     *              - addr: 地址
+     *              - prove_img: 证明图片
+     *              - supplier_img: 供应商图片
+     *              - contactor: 联系人
+     *              - mobile: 手机号
+     *              - telephone: 电话
+     *              - position: 职位
+     *              - email: 电子邮件
+     *              - personid: 负责人id
+    * @return Response|Json|void
+     */
+    public function save(){
+        $param = $this->request->param([
+            'id' => '',
+            'coop_state' => '0',
+            'source' => '0',
+            'type' => '0',
+            'category' => '1',
+            'delivery_way' => '0',
+            'supplier_type' => '0',
+            'level' => '0',
+            'pay_type' => '0',
+            'supplier_img' => '',
+            'prove_img' => '',
+            'contactor' => '',
+            'mobile' => '', // 确保这是经过验证的格式
+            'telephone' => '',
+            'position' => '',
+            'registercode' => '',
+            'name' => '',
+            'email' => '', // 更正了邮箱格式
+            'nature' => '',
+            'addr' => '',
+            'legaler' => '',
+            'registertime' => '',
+            'scope' => '',
+            'personid' => ''],"post",'json');
+        $valid=Validate::rule([
+            "id|主键ID"=>"require|number|gt:0",
+            'name|供应商名称' => 'requireIf:supplier_img,""|max:255',
+            'source|供应商来源' => 'require|number|in:0,1,2',
+            'coop_state|合作状态' => 'require|number|in:0,1',
+            'category|所属类别' => 'require|number|in:0,1',
+            'delivery_way|提供物流方式' => 'require|number|in:0,1',
+            'level|供应商级别' => 'require|number|in:0,1,2',
+            'supplier_type|供应商性质' => 'require|number|in:0,1,2,3,4',
+            'pay_type|付款方式' => 'require|number|in:0,1,2',
+            'registercode|纳税识别编号' => 'requireIf:supplier_img,""|max:255',
+            'registertime|成立日期' => 'requireIf:supplier_img,""|max:255',
+            'scope|经营范围' => 'requireIf:supplier_img,""|max:3000',
+            'type|申请类型' => 'require|number|in:0,1',
+            'nature|公司类型' => 'require|number|in:1,2,3,4,5,6,7,8,9',
+            'legaler|法人' => 'requireIf:supplier_img,""|max:255',
+            'addr|公司详细地址' => 'requireIf:supplier_img,""|max:255',
+            'prove_img|资质证明' => 'url',
+            'supplier_img|营业执照' => 'requireIf:name,""|url',
+            'contactor|联系人' => 'require|max:255',
+            'mobile|手机号' => 'require|mobile',
+            'telephone|座机号' => 'max:255',
+            'position|职位' => 'require',
+            'email|邮箱' => 'require|email',
+            'personid|负责人' => 'require|number|gt:0',
+            ]);
+        if(!$valid->check($param))return error($valid->getError());
+        $info = \app\user\model\Supplier::with(["contactInfo"])->where('id','=',$param['id'])->find();
+        if(!$info)return error('供应商不存在');
+        $goodUpdateBool=false;
+        if($info->personid!=$param['personid'])$goodUpdateBool=true;
+        $info->name=$param['name'];
+        $info->personid=$param['personid'];
+        $info->person=\app\user\model\User::where('account_id','=',$param['personid'])->value('nickname','');
+        $info->source=$param['source'];
+        $info->coop_state=$param['coop_state'];
+        $info->category=$param['category'];
+        $info->delivery_way=$param['delivery_way'];
+        $info->level=$param['level'];
+        $info->supplier_type=$param['supplier_type'];
+        $info->pay_type=$param['pay_type'];
+        $info->type=$param['type'];
+        $info->prove_img=$param['prove_img'];
+        $info->updater=$this->uname;
+        $info->updaterid=$this->uid;
 
+        if($param['supplier_img']!='' &&  $info->license_img!=$param['supplier_img']){
+                    $info->license_img=$param['supplier_img'];
+                    $result = $this->GetBusinessInfoByParam($param['supplier_img']);
+                    if($result['code']=='200'){
+                        $info->ocr_status = 1;
+                         if ($param['name'] != $result['name']) {
+                            $info->remark = "企业名称与营业执照不匹配";
+                        }
+                        if ($param['registercode'] !=$result['registrationNumber']&& $param['registercode']!= '') {
+                           $info->remark .= '企业纳税识别号与营业执照不匹配';
+                        }
+                        $param['addr']=$result['address']??'';
+                        $param['legaler']=$result['legalRepresentative']??'';
+                        $param['registercode']=$result['registrationNumber']??'';
+                        $param['registertime']=$result['foundDate']??'';
+                        $param['scope']=$result['businessScope']??'';
+                        $param['nature']=$result['type']??'';
+                        $param['capital'] = $result['registeredCapital']??'';
 
-    public function businessLicese(){
-        $url = $this->request->param('url');
-        if(empty($url))return error('参数错误');
-        $ocr= Ocr::getInstance();
-        $result= $ocr::businessLicense($url);
-        var_dump($result);
+                    }else{
+                        $info->remark = '营业执照识别失败';
+                        $info->ocr_status  = 2;
+                    }
+        }
+        $info->registercode=$param['registercode'];
+        $info->nature=$param['nature'];
+        $info->legaler=$param['legaler'];
+        $info->registertime=$param['registertime'];
+        $info->capital=$param['capital'];
+        $info->addr=$param['addr'];
+        $info->scope=$param['scope'];
+        $this->model->startTrans();
+        try{
+           if($info->save()){
+            $contact=[
+                'contactor'=>$param['contactor'],
+                'mobile'=>$param['mobile'],
+                'position'=>$param['position'],
+                'telephone'=>$param['telephone'],
+                'email'=>$param['email'],
+                ];
+            $contactC=$info->contactInfo->save($contact);
+            if (!$contactC)throw new Exception('供应商联系人信息保存失败');
+            $hqcreate= Headquarters::createInfo($info,3);
+            if(!$hqcreate)throw new Exception('供应商信息保存失败');
+        }else throw new Exception('供应商信息保存失败');
+            $this->model->commit();
+        }catch (Exception $e){
+            $this->model->rollback();
+            return error($e->getMessage());
+        }
+        if($goodUpdateBool)event("updateSupplierGood",["code"=>$info->code,"personid"=>$info->personid,"person"=>$info->person]);
+        return success("保存成功!");
+    }
+    /**
+     * 获取供应商列表
+     */
+    public function list()
+    {
+        $param=$this->request->param(["page"=>1,"size"=>15,"createrid"=>"","name"=>"","start"=>"","end"=>"",'status'=>'','ocr_status'=>''],"post","trim");
+        $where=[["is_del","=",0]];
+        if($param['createrid']!='') $where[]=['createrid','=',$param['createrid']];
+        if($param['name']!='') $where[]=['name','like',"%".$param['name']."%"];
+        if($param['status']!='') $where[]=['status','=',$param['status']];
+        if($param['ocr_status']!='') $where[]=['ocr_status','=',$param['ocr_status']];
+        if($param['start']!='') $where[]=['addtime','>=',$param['start']];
+        if($param['end']!='') $where[]=['addtime','<=',$param['end']];
+        $list = $this->model->with(["contactInfo"])->where($where)->order('id desc')
+        ->paginate(['page'=>$param['page'],'list_rows'=>$param['size']]);
+        return success("获取成功",["list"=>$list->items(),"count"=>$list->total()]);
+    }
+    /**
+     * 获取供应商详情
+     */
+    public function info()
+    {
+        $code=$this->request->param("code");
+        if(!$code=="")return error("参数错误");
+        $info = $this->model->with(["contactInfo"])->where('code','=',$code)->findOrEmpty();
+        if($info->isEmpty())return error("供应商不存在");
+        return success("获取成功",$info);
     }
+    /**删除供应商
+    * @return Response|Json|void
+    */
+    public function delete()
+    {
+        $param=$this->request->param(["id"=>""],"post","trim");
+        if($param['id']=="")return error("参数错误");
+        $info = $this->model->where('id','=',$param['id'])->findOrEmpty();
+        if($info->isEmpty())return error("供应商不存在");
+        $info->is_del=1;
+        if($info->save()){
+                    $headquarters = new Headquarters();
+                    $headquarters->update([
+                        'is_del'=>1,
+                        'updater'=>$this->uname,
+                        'updaterid'=>$this->uid,
+                    ],['code'=>$info->code]);
+          }
+        return success("删除成功");
+    }
+    /**
+     * @return Json|Response|Response|Json|void
+     */
+    public function status()
+    {
+        $param=$this->request->param(["id"=>"","status"=>""],"post","trim");
+        $valid=Validate::check($param,[
+            'id|供应商id'=>'require',
+            'status|状态'=>'require|number|in:0,1',
+        ]);
+        if($valid!==true)return error(Validate::getError());
+        $info = $this->model->where('id','=',$param['id'])->findOrEmpty();
+        if($info->isEmpty())return error("供应商不存在");
+        $info->status=$param['status'];
+        if($info->save()){
+            $headquarters = new Headquarters();
+            $headquarters->update([
+                'status'=>$param['status'],
+                'updater'=>$this->uname,
+                'updaterid'=>$this->uid,
+            ],['code'=>$info->code]);
+        }else return error("修改失败");
+        return success("修改成功");
+    }
+    /**
+    * @param $post
+    * @return Response|Json|void
+    * @throws PDOException
+     */
+    public function upgrade()
+    {
+        $post = $this->request->only(['code', 'inv_bank', 'inv_bankNo', 'inv_addr', 'invoice_mobile', 'uid', 'uname', 'invoice_title'], 'post', 'trim');
+
+        $val = Validate::rule([
+            'code|供应商编码' => 'require',
+            'inv_bank|银行名称' => 'require|max:255',
+            'inv_bankNo|银行卡号' => 'require|number',
+            'inv_addr|联系地址' => 'require|max:255',
+            'invoice_mobile' => 'require',
+            'invoice_title|公司抬头' => 'require',
+        ]);
 
+        if ($val->check($post) == false) return error($val->getError());
+        $supplier = $this->model->with(["contactInfo"])->where([['code',"=", $post['code']],["is_del","=",0]])->findOrEmpty();
+        if ($supplier->isEmpty()) return error("供应商不存在");
+        if ($supplier->status == 0) return error("供应商未启用");
+        if ($supplier->is_upgrade == 1) return error("供应商已升级为业务公司");
+        $this->model->startTrans();
+        try {
+            $post['uid']=$this->uid;
+            $post['uname']=$this->uname;
+            $up= $this->model->upgrade($post);
+            if(!$up)throw new Exception("升级失败");
+            $this->model->commit();
+        }catch (Exception $exception){
+            $this->model->rollback();
+            return error($exception->getMessage());
+        }
+        return success("升级成功");
+    }
 }

+ 8 - 0
app/user/model/CustomerInfo.php

@@ -42,4 +42,12 @@ class CustomerInfo extends Base
     ];
     protected $updateTime='updatetime';
     protected $createTime='addtime';
+
+    public function Member(){
+        return $this->hasMany(CustomerMember::class,'companyNo','companyNo')->where(["is_del"=>0]);
+    }
+    
+    public function ParentInfo(){
+        return $this->belongsTo(CustomerOrg1::class,'parent')->bind(["parentName"=>"name","parentPname"=>"pname","pid","depart_link"]);
+    }
 }

+ 8 - 0
app/user/model/CustomerMember.php

@@ -26,4 +26,12 @@ class CustomerMember extends Base
         'updatetime'       =>'datetime',//
 
     ];
+
+    protected $updateTime='updatetime';
+    protected $createTime='addtime';
+
+    public function customerInfo()
+    {
+        return $this->belongsTo(CustomerInfo::class,'companyNo','companyNo')->bind(["companyName","itemid","parent","area"]);
+    }
 }

+ 123 - 1
app/user/model/Headquarters.php

@@ -1,7 +1,7 @@
 <?php
 namespace app\user\model;
 
-class Headquarters extends Base
+use think\Exception;class Headquarters extends Base
 {
 //设置字段信息
     protected $schema = [
@@ -32,6 +32,128 @@ class Headquarters extends Base
     protected $createTime = 'addtime';
     protected $updateTime = 'updatetime';
 
+    /**数据总表创建
+    * @param $object
+    * @param $type 1企业(业务公司),2客户,3供应商(只有供应商升级为业务公司的时候)
+    * @return bool
+    * @throws Exception
+     */
+    public static function createInfo($object,$type){
+        $result =self::checkObject($object,$type);
+        if(empty($result))throw new Exception("公司数据创建失败");
+        $isobj= self::where(['code'=>$object->companyNo,"is_del"=>0])->findOrEmpty();
+        if(!$isobj->isEmpty() && $type==3 && $object->is_upgrade==1)self::sycCompany($isobj->relation_code,$object);
+
+        $result['id']=$isobj->isEmpty()?null:$isobj->id;
+        $info = self::save($result);
+        return $info;
+    }
+    /** 数据转换
+     * @param $object
+     * @param $type 1企业(业务公司),2客户,3供应商(只有供应商升级为业务公司的时候)
+     * @return array
+     * @throws Exception
+     */
+    private static function checkObject($object,$type){
+        $result = [];
+        switch ($type){
+            case 1://业务公司
+                $result = [
+                    'code'       =>$object->companyNo,//编号
+                    'name'       =>$object->company,//名称
+                    'type'       =>1,//1企业(业务公司),2客户,3供应商(只有供应商升级为业务公司的时候)
+                    'company_type'       =>0,//公司类型,只有企业有效,对应于company_type表
+                    'invoice_title'       =>$object->invoice_title,//发票抬头
+                    'invoice_people'       =>$object->inv_legaler,//发票纳税人
+                    'invoice_addr'       =>$object->inv_addr,//发票地址
+                    'invoice_mobile'       =>$object->invoice_mobile,//发票联系方式
+                    'invoice_code'       =>$object->inv_code,//纳税识别号
+                    'invoice_bank'       =>$object->inv_bank,//纳税银行
+                    'invoice_bankNo'       =>$object->inv_bankNo,//纳税银行账户
+                    'invoice_img'       =>$object->license_img,//营业执照
+                    'remark'       =>'',//备注
+                    "relation_code"=>$object->relation_code??"",
+                    "creater"=>$object->creater,
+                    "createrid"=>$object->createrid,
+                    'updater' => $object->updater,
+                    'updaterid' => $object->updaterid,
+                 ];
+                break;
+            case 2://客户
+               $result = [
+                    'code'       =>$object->companyNo,//编号
+                    'name'       =>$object->companyName,//名称
+                    'type'       =>2,//1企业(业务公司),2客户,3供应商(只有供应商升级为业务公司的时候)
+                    'company_type'       =>0,//公司类型,只有企业有效,对应于company_type表
+                    'invoice_title'       =>$object->invoice_title,//发票抬头
+                    'invoice_people'       =>$object->invoice_people,//发票纳税人
+                    'invoice_addr'       =>$object->invoice_people,//发票地址
+                    'invoice_mobile'       =>$object->invoice_mobile,//发票联系方式
+                    'invoice_code'       =>$object->invoice_code,//纳税识别号
+                    'invoice_bank'       =>$object->invoice_bank,//纳税银行
+                    'invoice_bankNo'       =>$object->invoice_bankNo,//纳税银行账户
+                    'invoice_img'       =>'',//营业执照
+                    'remark'       =>'',//备注
+                    'creater'=>$object->creater,
+                    'createrid'=>$object->createrid,
+                    'updater' => $object->updater,
+                    'updaterid' => $object->updaterid,
+                   ];
+                break;
+            case 3://供应商
+               $result = [
+                    'code'       =>$object->code,//编号
+                    'name'       =>$object->name,//名称
+                    'type'       =>3,//1企业(业务公司),2客户,3供应商(只有供应商升级为业务公司的时候)
+                    'company_type'       =>0,//公司类型,只有企业有效,对应于company_type表
+                    'invoice_title'       =>$object->name,//发票抬头
+                    'invoice_people'       =>$object->legaler,//发票纳税人
+                    'invoice_addr'       =>$object->addr,//发票地址
+                    'invoice_mobile'       =>'',//发票联系方式
+                    'invoice_code'       =>$object->registercode,//纳税识别号
+                    'invoice_bank'       =>'',//纳税银行
+                    'invoice_bankNo'       =>'',//纳税银行账户
+                    'invoice_img'       =>$object->license_img,//营业执照
+                    'remark'       =>'',//备注
+                    'relation_code'=>$object->relation_code??'',
+                    'creater'=>$object->creater,
+                    'createrid'=>$object->createrid,
+                    'updater' => $object->updater,
+                    'updaterid' => $object->updaterid,
+                  ];
+                break;
+            default:
+               $result=[];
+               break;
+        }
+        return $result;
+    }
+
+    /** 供应商更新 同步业务公司数据
+    * @param $relation_code
+    * @param $object
+    * @throws Exception
+    */
+    private static function sycCompany($relation_code,$object){
+        $result = Business::where(['companyNo'=>$relation_code,"is_del"=>0])->findOrEmpty();
+        if(!$result->isEmpty()){
+            $result->company=$object->name;
+            $result->inv_code=$object->registercode;
+            $result->license_img=$object->license_img;
+            $result->inv_legaler=$object->legaler;
+            $result->inv_time=$object->registertime;
+            $result->addr=$object->addr;
+            $result->inv_scope=$object->scope;
+            $result->contactor=$object->contactor;
+            $result->mobile=$object->mobile;
+            $result->updater=$object->updater;
+            $result->updaterid=$object->updaterid;
+            $busup=$result->save();
+            if($busup) throw new \Exception("业务公司同步失败");
+            self::createInfo($result,1);
+        }
+    }
+
     public function companyInfo(){
         return $this->belongsTo(Business::class,'code','companyNo');
     }

+ 60 - 1
app/user/model/Supplier.php

@@ -44,6 +44,65 @@ class Supplier extends Base
         'addtime'       =>'datetime',//创建时间
         'updatetime'       =>'datetime',//修改时间
         'is_upgrade'       =>'tinyint',//是否升级为业务公司
-
     ];
+
+    protected $createTime='addtime';
+    protected $updateTime='updatetime';
+
+    public function ContactInfo()
+    {
+       return $this->belongsTo(SupplierContact::class,"code","code")->bind(['contactor','mobile','email','telephone','position']);
+    }
+    /**
+    * @param $param 升级参数
+    * @return bool|int
+    * @throws \think\Exception
+    * @throws \think\db\exception\DataNotFoundException
+    * @throws \think\db\exception\ModelNotFoundException
+    * @throws \think\exception\DbException
+     */
+    public function upgrade($param)
+    {
+        $bussinesCode=makeNo('GS');
+        $res=Supplier::with(["contactInfo"])->where('code',$param['code'])->find();
+        if($res->isEmpty())throw new \Exception('供应商不存在');
+        $data=[
+            'company' => $res['name'],
+            'companyNo' => $bussinesCode,
+            'inv_code' => $res['registercode'],
+            'company_type' => $res['nature'],
+            'type' => $temp['id'] ?? 0,
+            'creater' => $param['uname'],
+            'createrid' => $param['uid'],
+            'inv_legaler' => $res['legaler'],
+            'inv_time' => $res['registertime'],
+            'inv_addr' => $param['inv_addr'],
+            'inv_bank' => $param['inv_bank'],
+            'inv_bankNo' => $param['inv_bankNo'],
+            'contactor' => $res['contactor'],
+            'mobile' => $res['mobile'],
+            'addr' => $res['addr'],
+            'inv_scope' => $res['scope'],
+            'license_img' => $res['license_img'],
+            'invoice_title' => $param['invoice_title'],
+            'invoice_mobile' => $param['invoice_mobile'],
+            ];
+        $bussines=Business::create($data);
+        if($bussines->isEmpty())  throw new \Exception('业务公司升级失败');
+        $bussines->relation_code=$param['code'];
+        $bussines->updater=$param['uname'];
+        $bussines->updaterid=$param['uid'];
+        $comp=Headquarters::createInfo($bussines,1);
+        if($comp)throw new \Exception('业务公司信息更新失败');
+        $res->is_upgrade=1;
+        $res->relation_code=$bussinesCode;
+        $res->updater=$param['uname'];
+        $res->updaterid=$param['uid'];
+        $resup=Headquarters::createInfo($bussines,3);
+        if($resup)throw new \Exception('供应商信息失败');
+        $acc= AccountCompany::create(["account_id"=>$param['uid'],"companyCode"=>$bussinesCode,"companyName"=>$data['company'],'company_type' => 2]);
+        if($acc)throw new \Exception('业务公司账户关联失败');
+        return $res->save();
+    }
+
 }