cqp 2 săptămâni în urmă
părinte
comite
a6e90f9da8

+ 14 - 0
app/Http/Controllers/Api/DingTalkController.php

@@ -31,4 +31,18 @@ class DingTalkController extends BaseController
             return $this->json_return(201,$data);
         }
     }
+
+    public function createProcessInstance(Request $request)
+    {
+        $service = new DrbService();
+        list($status,$data) = $service->createProcessInstance($request->all());
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+
+
 }

+ 0 - 19
app/Http/Controllers/Api/EmployeeController.php

@@ -7,25 +7,6 @@ use Illuminate\Http\Request;
 
 class EmployeeController extends BaseController
 {
-    public function getLoginMan(Request $request){
-        $user = $request->userData->toArray();
-
-        return $this->json_return(200,'',$user);
-    }
-
-    public function employeeEditOther(Request $request)
-    {
-        $service = new EmployeeService();
-        $user = $request->userData->toArray();
-        list($status,$data) = $service->employeeEditOther($request->all(),$user);
-
-        if($status){
-            return $this->json_return(200,'',$data);
-        }else{
-            return $this->json_return(201,$data);
-        }
-    }
-
     public function employeeEdit(Request $request)
     {
         $service = new EmployeeService();

+ 0 - 264
app/Http/Controllers/Api/TestController.php

@@ -2,270 +2,6 @@
 
 namespace App\Http\Controllers\Api;
 
-
-use App\Model\BoxDetail;
-use App\Model\Depart;
-use App\Model\InOutRecord;
-use App\Model\Inventory;
-use App\Model\OutBoundOrder;
-use App\Model\Product;
-use App\Model\ProductInventory;
-use App\Model\ProductPriceDetail;
-use App\Model\PurchaseOrderInfoForOutBound;
-use App\Model\ReturnExchangeOrder;
-use App\Service\Box\BoxHookService;
-use App\Service\CheckService;
-use App\Service\EmployeeService;
-use App\Service\MeasureService;
-use App\Service\OaService;
-use App\Service\OperationLogService;
-use App\Service\OrderNoService;
-use App\Service\SalesOrderService;
-use App\Service\TPlusDatabaseServerService;
-use App\Service\WDTService;
-use Illuminate\Http\Request;
-use Illuminate\Support\Facades\DB;
-use Illuminate\Support\Facades\Hash;
-
-
 class TestController extends BaseController
 {
-
-
-    public function tt(){
-
-    }
-
-    public function boxInsert(){
-
-    }
-
-    public function aa(){echo 'ok';die;
-        $service = new TPlusDatabaseServerService(true);
-        if(! empty($service->error)) return [false, $service->error];
-        list($s, $msg) = $service->getSnList(["sn_type"=>1,"code"=>"1000004805"],[]);
-        return $this->json_return(200,'',$msg);dd(1111);
-        $array = (new SalesOrderService())->salesOrderPdf(['id' => 37938],['id'=>1,'head'=>['id' =>2]]);dd($array);
-        dd(2);$this->test3();dd(222);
-        (new WDTService())->getOrderListAuto([]);dd(222);
-        $service = new TPlusDatabaseServerService(true);
-        if(! empty($service->error)) return [false, $service->error];
-        dd(11111);
-        $this->test1();
-//        $array = (new SalesOrderService())->salesOrderPdf(['id' => 26604],['id'=>1,'head'=>['id' =>2]]);
-//        return view('pdf.salesOrder',['order' => $array]);
-        $send_data[] = [
-            'employee_id' => 1,
-            'type' => 2,
-            'state' => 0,
-            'menu_id' => 34,
-            'order_number' => "T9RMO.202408071529012839",
-            'tmp_data' => [
-                "T9RMO.202408071529012839",
-                "施工单",
-                '已完结',
-                "ee",
-                date('Y-m-d H:i:s'),
-            ],
-        ];
-        (new OaService())->sendWxOaCheckMessage($send_data);dd(11)
-               (new OaService())->sendWxMsg(1,2,0,34,["T9RMO.202408071529012839","施工单","待确认","陈庆鹏","2024-08-07 15:29:44"]);dd(1);
-//       (new OaService())->sendWxMsg(1,3,2,48,["T9RMO.202408071529012839","拒绝","2024-08-07 15:29:44","(未填写原因)"],"/pages/ReturnExchangeOrder/detail/detail?order_number=55");
-
-        //测试消息发送
-//        $tmp_data = [
-//            "T9XS.20240824095952611883",
-//            '陈庆鹏(订单合同)',
-//            '刁法森',
-//            date('Y-m-d H:i:s'),
-//        ];
-//        (new OaService())->sendWxMsg(1,1,0,37,$tmp_data,"/pageA/pages/SalesOrder/detail/detail?order_number=T9XS.20240824095952611883");
-        $tmp_data = [
-            "XNCG202411241422297482",
-            "拒绝",
-            "2024-11-24 14:22:29",
-            "测试"
-        ];
-        (new OaService())->sendWxMsg(1,3,2,44,$tmp_data,"/pageA/pages/SalesOrder/detail/detail?order_number=T9XX.2024080912410029251");dd(1);
-
-        //测试消息发送
-        $tmp_data = [
-            "22222",
-            '222',
-            '审核通过',
-            '22222',
-            date('Y-m-d H:i:s'),
-
-        ];
-//        (new OaService())->sendWxMsg(1,2,1,37,$tmp_data,"/pages/SalesOrder/index/index");
-
-        //测试消息发送
-        $tmp_data = [
-            "333333",
-            '审核通过',
-            date('Y-m-d H:i:s'),
-            '22222',
-        ];
-//        (new OaService())->sendWxMsg(1,3,2,37,$tmp_data,"/pages/SalesOrder/index/index");
-die;
-        $params = json_decode('{"api_key":"d3848b47-4179-4b02-8d32-b78cd7672c6c","return_url":"https://payment.rummyliver.in/notify/s2pay/payment","mode":"LIVE","order_id":"1710493215363410880003","amount":"501.00","currency":"INR","description":"for payment","name":"iahfi","email":"jvqbgvv2908699@outlook.com","phone":"9329086994","city":"Mumbai","zip_code":"400002","country":"IND"}',true);
-
-        $hash_columns = ['merchant_reference_number','Amount','account_name','account_number','ifsc_code','bank_name','bank_branch','transfer_type','address_line_1', 'address_line_2', 'amount', 'api_key', 'city', 'country', 'currency', 'description', 'email', 'mode', 'name', 'order_id', 'phone', 'return_url', 'state', 'udf1', 'udf2', 'udf3', 'udf4', 'udf5', 'zip_code',];
-        sort($hash_columns);
-        $hash_data = '3b1db341fa70abc03af5c3676811a82bec99673f';
-        foreach ($hash_columns as $column) {
-            if (isset($params[$column])) {
-                if (strlen($params[$column]) > 0) {
-                    $hash_data .= '|' . trim($params[$column]);
-                }
-            }
-        }
-        $hash = strtoupper(hash("sha512", $hash_data));
-        var_dump($hash);die;
-        return $hash;
-
-        $text = '这是测试';
-        $key = '72f8c912d462b1md034ff46cbedaskc80bf';
-        $sign = Hash::make($text.$key);
-        var_dump(Hash::check('这是测试'.'72f8c912d462b1md034ff46cbedaskc80bf',$sign));
-        var_dump($sign);die;
-    }
-
-
-    public function test1(){dd(222);
-        $service = new CheckService();
-        $service->recordReturnExchangeOrder([],ReturnExchangeOrder::where('order_number',"TH202503071106328078")->first()->toArray());
-dd(1);
-        $data = OutBoundOrder::where('del_time',0)->select('data_id')->get()->toArray();
-        $data = array_column($data,'data_id');
-        $data = ReturnExchangeOrder::where('del_time',0)
-            ->whereIn('data_id',$data)
-            ->where('type',ReturnExchangeOrder::Order_type)
-            ->get()->toArray();
-        dd($data);
-        foreach ($data as $value){
-        }
-        dd(1);
-    }
-    public function clear(){
-        $in_record = InOutRecord::select('top_depart_id')
-            ->groupBy('top_depart_id')
-            ->get()->toArray();
-        $in_record = array_column($in_record,'top_depart_id');
-
-        $depart = Depart::whereIn('id',$in_record)
-            ->pluck('basic_type_id', 'id')
-            ->toArray();
-
-        $product_inventory = ProductInventory::whereIn('top_depart_id',$in_record)
-            ->select('id','product_id','storehouse_id','number','lock_number','top_depart_id')
-            ->get()->toArray();
-        $product_inventory_map = [];
-        foreach ($product_inventory as $value){
-            $key = $value['top_depart_id'] . $value['product_id'];
-            $product_inventory_map[$key] = 111;
-        }
-
-        $record_list = InOutRecord::where('del_time',0)
-            ->whereIn('top_depart_id',$in_record)
-            ->get()->toArray();
-        $list = [];$error1 = [];
-        foreach ($record_list as $value){
-            $key = $value['top_depart_id'] . $value['product_id'];
-            if(! isset($product_inventory_map[$key])){
-                $error1[] = $value;
-            }else{
-                if(isset($list[$key])){
-                    $number = bcadd($value['number'],$list[$key],2);
-                    $list[$key] = $number;
-                }else{
-                    $list[$key] = $value['number'];
-                }
-            }
-        }
-        if(! empty($error1)){
-            foreach ($error1 as $value){
-                InOutRecord::where('id', $value['id'])->update(['del_time' => 1233]);
-            }dd(1);
-        }
-
-        $error = [];
-        foreach ($product_inventory as $value){
-            $key = $value['top_depart_id'] . $value['product_id'];
-            if(isset($list[$key])){
-                $tmp = $list[$key];
-                if($tmp != $value['number']){
-                    $numbers = bcsub($value['number'],$tmp,2);
-                    $error[] = [
-                        'product_id' => $value['product_id'],
-                        'top_depart_id' => $value['top_depart_id'],
-                        'depart_id' => $value['top_depart_id'],
-                        'storehouse_id' => $value['storehouse_id'],
-                        'number' => $numbers,
-                    ];
-                }
-            }else{
-                $error[] = [
-                    'product_id' => $value['product_id'],
-                    'top_depart_id' => $value['top_depart_id'],
-                    'depart_id' => $value['top_depart_id'],
-                    'storehouse_id' => $value['storehouse_id'],
-                    'number' => $value['number'],
-                ];
-            }
-        }
-
-        if(empty($error)) dd('no data');
-dd($error);
-        $price_detail_map = [];
-        $price_detail = ProductPriceDetail::whereIn('product_id',array_unique(array_column($error,'product_id')))
-            ->select('product_id','price','basic_type_id')
-            ->get()->toArray();
-        foreach ($price_detail as $value){
-            $price_detail_map[$value['product_id'] . $value['basic_type_id']] = $value['price'];
-        }
-
-        $price_2 = Product::whereIn('id',array_unique(array_column($error,'product_id')))
-            ->pluck('retail_price','id')
-            ->toArray();
-
-        foreach ($error as $e => $value){
-            $basic_type_id = $depart[$value['top_depart_id']] ?? 0;
-            $key = $value['product_id'] . $basic_type_id;
-            $price = $price_detail_map[$key] ?? 0;
-            if(! $price) $price = $price_2[$value['product_id']] ?? 0;
-            if(! $price) dd(1);
-            if(! $value['number'] > 0) dd(2222);
-
-            $error[$e]['price'] = $price;
-            $error[$e]['crt_time'] = 1740758399;
-            $error[$e]['order_type'] = PurchaseOrderInfoForOutBound::prefix2;
-            $error[$e]['order_number'] = (new OrderNoService())->createOrderNumber(PurchaseOrderInfoForOutBound::prefix2);
-        }
-
-        InOutRecord::insert($error);
-        dd(count($error),$error);
-    }
-    public function test2(){
-        $server = "8u80504l59.vicp.fun,57323"; // 如 localhost, IP 或域名
-        $database = "UFDATA_101_2023";
-        $username = "sa";
-        $password = "Aa1";
-
-        try {
-            $conn = new \PDO("sqlsrv:Server=$server;Database=$database;Driver={ODBC Driver 17 for SQL Server}", $username, $password);
-            echo "Connected successfully\n";
-        } catch (\PDOException $e) {
-            echo "Connection failed: " . $e->getMessage() . "\n";
-        }
-    }
-    public function test3(){
-        $dsn = "sqlsrv:Server=8u80504l59.vicp.fun,57323;Database=UFDATA_101_2023";
-        $pdo = new \PDO($dsn, "sa", "TiZi#40068642538");
-        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
-
-        // 成功连接
-        $this->db = DB::setPdo($pdo); // 可选:将这个 pdo 绑定给 DB Facade 使用
-        dd(11222333);
-    }
 }

+ 25 - 0
app/Http/Controllers/Api/U8Controller.php

@@ -0,0 +1,25 @@
+<?php
+
+namespace App\Http\Controllers\Api;
+
+use App\Service\U8ServerService;
+use Illuminate\Http\Request;
+
+class U8Controller extends BaseController
+{
+    public function purchaseRequisition(Request $request)
+    {
+        $userData = $request->userData;
+        $service = new U8ServerService($userData);
+        $error = $service->getError();
+        if(! empty($error)) return $this->json_return(201, $error);
+
+        list($status,$data) = $service->purchaseRequisition($request->all(),$userData);
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+}

+ 9 - 20
app/Http/Middleware/CheckLogin.php

@@ -22,26 +22,15 @@ class CheckLogin
      */
     public function handle($request, Closure $next)
     {
-        $token=$request->header('Authorization');
-        if (empty($token)) return response()->json(['code'=>1,'msg'=>'缺少登录凭证','data'=>null]);
-
-        //校验token
-        $result = TokenService::verifyToken($token);
-        if ($result < -1) return response()->json(['code'=>1,'msg'=>TokenService::error[$result],'data'=>null]);
-
-        //校验用户
-        $checkResult = EmployeeService::checkUser($result);
-        list($state, $data) = $checkResult;
-        if(! $state) return response()->json(['code'=>1,'msg'=>$data,'data'=>null]);
+        $loginUser = $request->header('Login');
+        $loginUser = json_decode($loginUser,true);
+        if (empty($loginUser) || empty($loginUser['zt']) || empty($loginUser['username'])) return response()->json(['code'=>1,'msg'=>'缺少登录信息','data'=>null]);
+        if($loginUser['zt'] == 1){
+            $loginUser['zt_database'] = "UFDATA_200_2021";
+        }else{
+            $loginUser['zt_database'] = "UFDATA_002_2021";
+        }
 
-        //人员角色
-        $data['role'] = EmployeeService::getPersonRole($result);
-        //角色里所有菜单权限
-        $data['role_authority'] = EmployeeService::getPersonRoleQx($data['role']);
-        //角色里特殊的按钮
-        $data['special_button'] = EmployeeService::getSpecialButton($data['role'],$result);
-        //拥有的部门
-        $data['depart_range'] = EmployeeService::getLoginDepart($result);
         $query = config('morequery');
         $url = $request->path();
 
@@ -60,7 +49,7 @@ class CheckLogin
         }
 
         //写入user信息
-        $request->userData = $data;
+        $request->userData = $loginUser;
 
         return $next($request);
     }

+ 0 - 1
app/Jobs/ProcessDataJob.php

@@ -3,7 +3,6 @@
 namespace App\Jobs;
 
 use App\Model\RevenueCostMain;
-use App\Service\TPlusServerService;
 use Illuminate\Bus\Queueable;
 use Illuminate\Contracts\Queue\ShouldQueue;
 use Illuminate\Foundation\Bus\Dispatchable;

+ 100 - 7
app/Service/DrbService.php

@@ -38,8 +38,9 @@ class DrbService extends Service
      * @param string $code 前端 dd.getAuthCode 获取的 code
      * @return array [bool, data]  bool 表示成功与否,data 成功返回用户信息,失败返回错误信息
      */
-    public function getUserByCode(string $code)
+    public function getUserByCode($data)
     {
+        $code = $data['code'] ?? "";
         if (empty($code)) return [false, '钉钉授权code不能为空'];
 
         // 1. 获取 access_token
@@ -70,15 +71,108 @@ class DrbService extends Service
             return [false, '获取用户信息失败: ' . $res['errmsg']];
         }
 
-        // v2 接口返回的是 result.user_id
-        $userid = $res['result']['user_id'] ?? null;
-        if (!$userid) {
-            return [false, '获取userid失败'];
+        return [true, $res];
+    }
+
+    private function getManDetail($user){
+        // 1. 获取 access_token
+        [$success, $tokenData] = $this->getAccessToken();
+        if (! $success) return [false, $tokenData]; // tokenData 是错误信息
+        $accessToken = $tokenData['access_token'];
+
+        // 3. 根据 userid 获取详细用户信息(包括部门)
+        $urlDetail = "https://oapi.dingtalk.com/topapi/v2/user/get?access_token={$accessToken}";
+        $respDetail = $this->curlOpen1($urlDetail, [
+            'request' => 'post',
+            'header'  => ["Content-Type: application/json"],
+            'json'    => ["userid" => $user['userId']]
+        ]);
+        $detail = json_decode($respDetail, true);
+
+        if (!isset($detail['errcode'])) return [false, '获取用户详情接口异常: ' . $respDetail];
+        if ($detail['errcode'] !== 0) return [false, '获取用户详情失败: ' . $detail['errmsg']];
+        if (empty($detail['result'])) return [false, '获取用户详情失败,结果为空'];
+
+        // 返回完整用户信息
+        return [true, $detail['result']];
+    }
+
+    public function createProcessInstance($data, $user)
+    {
+        if(empty($data['type'])) return [false, '单据类型不能为空'];
+        $type = $data['type'];
+        $userId = $user['userId'];
+        [$success, $userDetail] = $this->getManDetail($user);
+        if(!$success) return [false, $userDetail];
+
+        // 1. 获取 access_token
+        [$success, $tokenData] = $this->getAccessToken();
+        if (!$success) return [false, $tokenData];
+        $accessToken = $tokenData['access_token'];
+
+        //获取模板id
+        $code = $this->getModelCode($type);
+        //获取模板数据
+        $formData = $this->getFormData($data);
+
+        //创建审批
+        [$success, $msg] = $this->createFlow($accessToken, $code, $userId, $userDetail, $formData);
+        if(! $success) return [false, $msg];
+
+        return [true, ''];
+    }
+
+    private function createFlow($accessToken, $code, $userId, $userDetail, $formData){
+        // 2. 请求 URL
+        $url = "https://oapi.dingtalk.com/topapi/processinstance/create?access_token={$accessToken}";
+
+        // 3. 请求体
+        $payload = [
+            "process_code" => $code,            // 审批模板编码
+            "originator_user_id" => $userId,    // 发起人 userId
+            "dept_id" => $userDetail['dept_id_list'],               // 发起人部门 ID
+            "form_component_values" => $formData, // 表单数据
+        ];
+
+        // 4. 发送请求
+        $resp = $this->curlOpen1($url, [
+            'request' => 'post',
+            'header'  => [
+                "Content-Type: application/json",
+            ],
+            'json'    => $payload
+        ]);
+
+        $res = json_decode($resp, true);
+
+        if (!isset($res['errcode'])) {
+            return [false, "接口返回异常: " . $resp];
         }
 
-        return [true, $res];
+        if ($res['errcode'] !== 0) {
+            return [false, "创建审批实例失败: " . $res['errmsg']];
+        }
+
+        return [true, $res['process_instance_id']];
+    }
+
+    private function getModelCode($type){
+        if($type == 1){
+            $code = "";
+        }elseif ($type == 2){
+            $code = "";
+        }else{
+            $code = "";
+        }
+
+        return $code;
     }
 
+    private function getFormData($data){
+        $model = [];
+
+        return $model;
+    }
 
     protected function curlOpen1($url, $config = [])
     {
@@ -120,5 +214,4 @@ class DrbService extends Service
         curl_close($ch);
         return $result;
     }
-
 }

+ 0 - 984
app/Service/TPlusServerService.php

@@ -1,984 +0,0 @@
-<?php
-
-namespace App\Service;
-
-use App\Jobs\ProcessDataJob;
-use App\Model\Depart;
-use App\Model\Employee;
-use App\Model\EmployeeDepartPermission;
-use App\Model\EmployeeIndex;
-use App\Model\Product;
-use App\Model\RevenueCost;
-use App\Model\RevenueCostTotal;
-use App\Model\SalaryEmployee;
-use Illuminate\Database\Schema\Blueprint;
-use Illuminate\Support\Facades\DB;
-use Illuminate\Support\Facades\Schema;
-
-class TPlusServerService extends Service
-{
-    /**
-     * @var TPlusDatabaseServerService
-     */
-    protected $databaseService;
-
-    /**
-     * @var string|null
-     */
-    protected $error;
-
-    /**
-     * TPlusServerService constructor.
-     */
-    public function __construct()
-    {
-        $service = new TPlusDatabaseServerService();
-        $this->databaseService = $service->db;
-        $this->error = $service->error;
-    }
-
-    /**
-     * 获取错误信息
-     *
-     * @return string|null
-     */
-    public function getError()
-    {
-        return $this->error;
-    }
-
-    private $table = "tmp_revenue_cost_data";
-    private $table_2 = "tmp_salary_employee";
-
-    /**
-     * 同步人员部门
-     *
-     * @param array $data
-     * @param array $user
-     * @return array
-     */
-    public function synPersonDepart($data, $user)
-    {
-        try {
-            $this->databaseService->table('AA_Department')
-                ->select('id','idparent as parent_id','name as title','code','disabled as is_use')
-                ->chunkById(100, function ($data) {
-                    DB::transaction(function () use ($data) {
-                        $dataArray = Collect($data)->map(function ($object) {
-                            return (array)$object;
-                        })->toArray();
-
-                        $d_id = Depart::whereIn('id', array_column($dataArray,'id'))
-                            ->pluck('id')
-                            ->toArray();
-
-                        $insert = $update = [];
-                        foreach ($dataArray as $value){
-                            $is_use = $value['is_use'] ? 0 : 1;
-                            if(in_array($value['id'], $d_id)){
-                                $update[] = [
-                                    'id' => $value['id'],
-                                    'parent_id' => $value['parent_id'],
-                                    'title' => $value['title'],
-                                    'code' => $value['code'],
-                                    'is_use' => $is_use
-                                ];
-                            }else{
-                                $insert[] = [
-                                    'id' => $value['id'],
-                                    'parent_id' => $value['parent_id'],
-                                    'title' => $value['title'],
-                                    'code' => $value['code'],
-                                    'is_use' => $is_use
-                                ];
-                            }
-                        }
-                        if(! empty($insert)) Depart::insert($insert);
-                        if(! empty($update)) {
-                            foreach ($update as $value){
-                                Depart::where('id', $value['id'])
-                                    ->update($value);
-                            }
-                        }
-                    });
-                });
-            $this->databaseService->table('AA_Person')
-                ->select('id','code as number','name as emp_name','mobilePhoneNo as mobile','iddepartment as depart_id','disabled as state')
-                ->chunkById(100, function ($data) {
-                    DB::transaction(function () use ($data) {
-                        $dataArray = Collect($data)->map(function ($object) {
-                            return (array)$object;
-                        })->toArray();
-
-                        $employee_id = Employee::whereIn('id', array_column($dataArray,'id'))
-                            ->pluck('id')
-                            ->toArray();
-
-                        $insert = $update = $depart_update = [];
-                        foreach ($dataArray as $value){
-                            $state = $value['state'] ? Employee::NOT_USE : Employee::USE;
-                            if(in_array($value['id'], $employee_id)){
-                                $update[] = [
-                                    'id' => $value['id'],
-                                    'number' => $value['number'],
-                                    'emp_name' => $value['emp_name'],
-                                    'mobile' => $value['mobile'],
-                                    'state' => $state
-                                ];
-                            }else{
-                                $insert[] = [
-                                    'id' => $value['id'],
-                                    'number' => $value['number'],
-                                    'emp_name' => $value['emp_name'],
-                                    'mobile' => $value['mobile'],
-                                    'state' => $state
-                                ];
-                            }
-                            $depart_update[] = [
-                                'employee_id' => $value['id'],
-                                'depart_id' => $value['depart_id']
-                            ];
-                        }
-                        if(! empty($insert)) Employee::insert($insert);
-                        if(! empty($update)) {
-                            foreach ($update as $value){
-                                Employee::where('id', $value['id'])
-                                    ->update($value);
-                            }
-                        }
-                        if(! empty($depart_update)){
-                            EmployeeDepartPermission::whereIn('employee_id',array_column($depart_update,'employee_id'))->delete();
-                            EmployeeDepartPermission::insert($depart_update);
-                        }
-                    });
-                });
-        } catch (\Throwable $e) {
-            return [false, $e->getMessage()];
-        }
-
-        return [true, ''];
-    }
-
-    /**
-     * 收入成本统计同步
-     *
-     * @param array $data
-     * @param array $user
-     * @return array
-     */
-    public function synRevenueCost($data, $user){
-        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '同步时间不能为空'];
-        list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['crt_time'],false);
-        if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "同步时间:时间区间无效"];
-        list($bool, $bool_msg) = $this->isOverThreeMonths($start_time, $end_time);
-        if(! $bool) return [false, $bool_msg];
-        $data['start_timeStamp'] = $start_time;
-        $data['end_timeStamp'] = $end_time;
-        $start = date('Y-m-d H:i:s.000', $start_time);
-        $end = date('Y-m-d H:i:s.000', $end_time);
-        $data['start_time'] = $start;
-        $data['end_time'] = $end;
-        $data['operation_time'] = time();
-        if(empty($data['type'])) return [false, '同步类型不能为空'];
-        if(in_array($data['type'],[1,2,3,4])){
-            list($status,$msg) = $this->limitingSendRequest($this->table);
-            if(! $status) return [false, '收入成本相关信息同步正在后台运行,请稍后'];
-
-//            //同步
-//            list($status, $msg) = $this->synRevenueCostFromTPlus($data, $user);
-//            if(! $status) {
-//                $this->clearTmpTable();
-//                $this->dellimitingSendRequest($this->table);
-//                return [false, $msg];
-//            }
-
-            //队列
-            ProcessDataJob::dispatch($data, $user)->onQueue(RevenueCost::job);
-        }else{
-            return [false, '同步类型错误'];
-        }
-
-        return [true, '收入成本相关信息同步已进入后台任务'];
-    }
-
-    public function synRevenueCostFromTPlus($data, $user){
-        //创建临时表 如果不存在
-        $this->createTmpTable();
-        //清理临时表 如果内容不为空
-        $this->clearTmpTable();
-        $type = $data['type'];
-
-        //写入临时数据
-        if($type == 1){
-            list($status, $msg) = $this->xhdTPlus($data, $user);
-            if(! $status) return [false, $msg];
-            list($status, $msg) = $this->xsfpTPlus($data, $user);
-            if(! $status) return [false, $msg];
-            list($status, $msg) = $this->hkdTPlus($data, $user);
-            if(! $status) return [false, $msg];
-        }elseif ($type == 2){
-            list($status, $msg) = $this->xhdTPlus($data, $user);
-            if(! $status) return [false, $msg];
-        }elseif ($type == 3){
-            list($status, $msg) = $this->xsfpTPlus($data, $user);
-            if(! $status) return [false, $msg];
-        }elseif ($type == 4){
-            list($status, $msg) = $this->hkdTPlus($data, $user);
-            if(! $status) return [false, $msg];
-        }
-
-        //更新数据
-        list($status,$msg) = $this->updateRevenueCost($data);
-        if(! $status) return [false, $msg];
-
-//        //更新主表数据
-//        list($status,$msg) = $this->updateRevenueCostTotal($data);
-//        if(! $status) return [false, $msg];
-
-        //都成功后 清理临时表
-        $this->clearTmpTable();
-        //释放redis
-        $this->delTableKey();
-
-        return [true, '同步成功'];
-    }
-
-    private function xhdTPlus($data, $user){
-        try {
-            $table = $this->table;
-            $limit = 500;
-            $lastId = 0;
-
-            do {
-                $rows = $this->databaseService->table('SA_SaleDelivery_b as sd_b')
-                    ->join('SA_SaleDelivery as sd', 'sd_b.idSaleDeliveryDTO', '=', 'sd.ID')
-                    ->leftJoin('AA_Partner as pn', 'sd.idsettlecustomer', '=', 'pn.ID')
-                    ->leftJoin('AA_Person as ps', 'sd.idclerk', '=', 'ps.ID')
-                    ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
-                    ->leftJoin('AA_Inventory as it', 'sd_b.idinventory', '=', 'it.ID')
-                    ->leftJoin('AA_Unit as ui', 'sd_b.idbaseunit', '=', 'ui.ID')
-                    ->where('sd.voucherdate', '>=', $data['start_time'])
-                    ->where('sd.voucherdate', '<=', $data['end_time'])
-                    ->where('sd_b.ID', '>', $lastId) // 用真实字段
-                    ->orderBy('sd_b.ID')
-                    ->limit($limit)
-                    ->selectRaw("
-                        COALESCE(sd.ID, 0) as order_id,
-                        COALESCE(sd.code, '') as order_number,
-                        sd.voucherdate as order_time,
-                        COALESCE(ps.name, '') as employee_id_1_title,
-                        COALESCE(sd.idclerk, 0) as employee_id_1,
-                        COALESCE(ps2.name, '') as employee_id_2_title,
-                        COALESCE(pn.idsaleman, 0) as employee_id_2,
-                        COALESCE(pn.code, '') as customer_code,
-                        COALESCE(pn.name, '') as customer_title,
-                        COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
-                        COALESCE(sd.pubuserdefnvc11, '') as channel_finance,
-                        COALESCE(sd.pubuserdefnvc12, '') as channel_details,
-                        COALESCE(it.code, '') as product_code,
-                        COALESCE(it.name, '') as product_title,
-                        COALESCE(it.specification, '') as product_size,
-                        COALESCE(ui.name, '') as unit,
-                        COALESCE(sd_b.quantity, 0) as quantity,
-                        COALESCE(sd_b.taxPrice, 0) as price_3,
-                        COALESCE(sd_b.taxAmount, 0) as price_3_total,
-                        COALESCE(sd_b.ID, 0) as id_detail,
-                        COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
-                    ")
-                    ->get();
-
-                if ($rows->isEmpty()) break;
-
-                $dataArray = Collect($rows)->map(function ($object) {
-                    return (array)$object;
-                })->toArray();
-
-                //存货档案
-                $product = Product::where('del_time', 0)
-                    ->whereIn('code', array_unique(array_column($dataArray, 'product_code')))
-                    ->select('code', 'write_off_price', 'freight_price', 'business_cost')
-                    ->get()->toArray();
-                $product_map = array_column($product, null, 'code');
-
-                //组织数据
-                foreach ($dataArray as $key => $value) {
-                    $customer_profit_rate = rtrim($value['customer_profit_rate'],'%');
-                    if(is_numeric($customer_profit_rate)){
-                        $customer_profit_rate = bcdiv($customer_profit_rate,100,3);
-                    }else{
-                        $customer_profit_rate = 0;
-                    }
-                    $dataArray[$key]['customer_profit_rate'] = $customer_profit_rate;
-                    $p_tmp = $product_map[$value['product_code']] ?? [];
-                    $dataArray[$key]['order_type'] = RevenueCost::ORDER_ONE;
-                    $dataArray[$key]['order_time'] = strtotime($value['order_time']);
-                    $write_off_price = $p_tmp['write_off_price'] ?? 0;
-                    $dataArray[$key]['price_1'] = $write_off_price;
-                    $dataArray[$key]['price_1_total'] = bcmul($write_off_price, $value['quantity'], 2);
-                    $freight_price = $p_tmp['freight_price'] ?? 0;
-                    $dataArray[$key]['price_2'] = $freight_price;
-                    $dataArray[$key]['price_2_total'] = bcmul($freight_price, $value['quantity'], 2);
-                    $business_cost = $p_tmp['business_cost'] ?? 0;
-                    $dataArray[$key]['price_4'] = $business_cost;
-                    $price_4_total = bcmul($business_cost, $value['quantity'], 2);
-                    $dataArray[$key]['price_4_total'] = bcmul($business_cost, $value['quantity'], 2);
-                    $profit = bcsub($value['price_3_total'], $price_4_total, 2);
-                    $dataArray[$key]['profit'] = $profit;
-                    $dataArray[$key]['profit_rate'] = $value['price_3_total'] > 0 ? bcdiv($profit, $value['price_3_total'], 2) : 0;
-                }
-
-                DB::table($table)->insert($dataArray);
-
-                // 更新 lastId 继续下一批
-                $lastId = end($dataArray)['id_detail'] ?? $lastId;
-
-            } while (count($rows) === $limit);
-        }catch  (\Throwable $exception){
-            return [false, "销货单同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
-        }
-
-        return [true, ''];
-    }
-
-    private function xsfpTPlus($data, $user){
-        try {
-            $table = $this->table;
-            $limit = 500;
-            $lastId = 0;
-
-            do {
-                $rows = $this->databaseService->table('SA_SaleInvoice_b as si_b')
-                    ->join('SA_SaleInvoice as si', 'si_b.idSaleInvoiceDTO', '=', 'si.ID')
-                    ->leftJoin('SA_SaleDelivery_b as sd_b', 'si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
-                    ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID')
-                    ->leftJoin('AA_Person as ps', 'si.idclerk', '=', 'ps.ID')
-                    ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
-                    ->leftJoin('AA_Inventory as it', 'si_b.idinventory', '=', 'it.ID')
-                    ->leftJoin('AA_Unit as ui', 'si_b.idbaseunit', '=', 'ui.ID')
-                    ->where('si.voucherdate','>=',$data['start_time'])
-                    ->where('si.voucherdate','<=',$data['end_time'])
-                    ->where('si_b.ID', '>', $lastId) // 用真实字段
-                    ->orderBy('si_b.ID')
-                    ->limit($limit)
-                    ->selectRaw("
-                        COALESCE(si.ID, 0) as order_id,
-                        COALESCE(si.code, '') as order_number,
-                        si.voucherdate as order_time,
-                        COALESCE(pn.code, '') as customer_code,
-                        COALESCE(pn.name, '') as customer_title,
-                        COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
-                        COALESCE(si.idclerk, 0) as employee_id_1,
-                        COALESCE(ps.name, '') as employee_id_1_title,
-                        COALESCE(pn.idsaleman, 0) as employee_id_2,
-                        COALESCE(ps2.name, '') as employee_id_2_title,
-                        COALESCE(it.code, '') as product_code,
-                        COALESCE(it.name, '') as product_title,
-                        COALESCE(it.specification, '') as product_size,
-                        COALESCE(ui.name, '') as unit,
-                        COALESCE(si_b.quantity, 0) as quantity,
-                        COALESCE(si_b.taxPrice, 0) as price_1,
-                        COALESCE(si_b.taxAmount, 0) as price_1_total,
-                        COALESCE(si_b.ID, 0) as id_detail,
-                        COALESCE(si_b.sourceVoucherDetailId, 0) as id_detail_upstream,
-                        COALESCE(si_b.sourceVoucherCode, '') as order_number_upstream,
-                        COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
-                    ")
-                    ->get();
-
-                if ($rows->isEmpty()) break;
-
-                $dataArray = Collect($rows)->map(function ($object) {
-                    return (array)$object;
-                })->toArray();
-
-                //存货档案
-                $product = Product::where('del_time',0)
-                    ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
-                    ->select('code','business_cost')
-                    ->get()->toArray();
-                $product_map = array_column($product,null,'code');
-
-                //组织数据
-                foreach ($dataArray as $key => $value){
-                    $customer_profit_rate = rtrim($value['customer_profit_rate'],'%');
-                    if(is_numeric($customer_profit_rate)){
-                        $customer_profit_rate = bcdiv($customer_profit_rate,100,3);
-                    }else{
-                        $customer_profit_rate = 0;
-                    }
-                    $dataArray[$key]['customer_profit_rate'] = $customer_profit_rate;
-                    $p_tmp = $product_map[$value['product_code']] ?? [];
-                    $dataArray[$key]['order_type'] = RevenueCost::ORDER_TWO;
-                    $dataArray[$key]['order_time'] = strtotime($value['order_time']);
-                    $business_cost = $p_tmp['business_cost'] ?? 0;
-                    $dataArray[$key]['price_4'] = $business_cost;
-                    $price_4_total = bcmul($business_cost, $value['quantity'],2);
-                    $dataArray[$key]['price_4_total'] = bcmul($business_cost, $value['quantity'],2);
-                    $profit = bcsub($value['price_1_total'], $price_4_total,2);
-                    $dataArray[$key]['profit'] = $profit;
-                    $dataArray[$key]['profit_rate'] = $value['price_1_total'] > 0 ? bcdiv($profit, $value['price_1_total'],2) : 0;
-                }
-
-                DB::table($table)->insert($dataArray);
-
-                // 更新 lastId 继续下一批
-                $lastId = end($dataArray)['id_detail'] ?? $lastId;
-
-            } while (count($rows) === $limit);
-        }catch  (\Throwable $exception){
-            return [false, "销售发票同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
-        }
-
-        return [true, ''];
-    }
-
-    private function hkdTPlus($data, $user){
-        try{
-            $table = $this->table;
-            $limit = 500;
-            $lastId = 0;
-
-            do {
-                $rows = $this->databaseService->table('ARAP_ReceivePayment_b as rp_b')
-                    ->join('ARAP_ReceivePayment as rp', 'rp_b.idArapReceivePaymentDTO', '=', 'rp.ID')
-                    ->leftJoin('SA_SaleInvoice_b as si_b', 'rp_b.voucherDetailID', '=', 'si_b.ID')
-                    ->leftJoin('SA_SaleInvoice as si', 'si_b.idSaleInvoiceDTO', '=', 'si.ID')
-                    ->leftJoin('SA_SaleDelivery_b as sd_b', 'si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
-                    ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID')
-                    ->leftJoin('AA_Person as ps', 'rp.idperson', '=', 'ps.ID')
-                    ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
-                    ->leftJoin('AA_Inventory as it', 'si_b.idinventory', '=', 'it.ID')
-                    ->leftJoin('AA_Unit as ui', 'si_b.idbaseunit', '=', 'ui.ID')
-                    ->where('rp.voucherdate','>=',$data['start_time'])
-                    ->where('rp.voucherdate','<=',$data['end_time'])
-                    ->where('rp_b.idvouchertype','=', 20) // 销售发票
-                    ->where('rp.isReceiveFlag','=', 1)
-                    ->where('rp_b.ID', '>', $lastId)
-                    ->orderBy('rp_b.ID')
-                    ->limit($limit)
-                    ->selectRaw("
-                        COALESCE(rp.ID, 0) as order_id,
-                        COALESCE(rp.code, '') as order_number,
-                        rp.voucherdate as order_time,
-                        COALESCE(pn.code, '') as customer_code,
-                        COALESCE(pn.name, '') as customer_title,
-                        COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
-                        COALESCE(it.code, '') as product_code,
-                        COALESCE(it.name, '') as product_title,
-                        COALESCE(rp.idperson, 0) as employee_id_1,
-                        COALESCE(ps.name, '') as employee_id_1_title,
-                        COALESCE(pn.idsaleman, 0) as employee_id_2,
-                        COALESCE(ps2.name, '') as employee_id_2_title,
-                        COALESCE(it.specification, '') as product_size,
-                        COALESCE(ui.name, '') as unit,
-                        COALESCE(si_b.quantity, 0) as quantity,
-                        COALESCE(si_b.taxPrice, 0) as price_1,
-                        COALESCE(si_b.taxAmount, 0) as price_1_total,
-                        COALESCE(rp_b.amount, 0) as payment_amount,
-                        COALESCE(rp_b.ID, 0) as id_detail,
-                        COALESCE(rp_b.voucherDetailID, 0) as id_detail_upstream,
-                        COALESCE(rp_b.voucherCode, '') as order_number_upstream,
-                        COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
-                    ")
-                    ->get();
-
-                if ($rows->isEmpty()) break;
-
-                $dataArray = Collect($rows)->map(function ($object) {
-                    return (array)$object;
-                })->toArray();
-
-                //存货档案
-                $product = Product::where('del_time',0)
-                    ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
-                    ->select('code','business_cost')
-                    ->get()->toArray();
-                $product_map = array_column($product,null,'code');
-
-                //组织数据
-                foreach ($dataArray as $key => $value){
-                    $customer_profit_rate = rtrim($value['customer_profit_rate'],'%');
-                    if(is_numeric($customer_profit_rate)){
-                        $customer_profit_rate = bcdiv($customer_profit_rate,100,3);
-                    }else{
-                        $customer_profit_rate = 0;
-                    }
-                    $dataArray[$key]['customer_profit_rate'] = $customer_profit_rate;
-                    $p_tmp = $product_map[$value['product_code']] ?? [];
-                    $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
-                    $dataArray[$key]['order_time'] = strtotime($value['order_time']);
-                    $business_cost = $p_tmp['business_cost'] ?? 0;
-                    $dataArray[$key]['price_4'] = $business_cost;
-                    $price_4_total = bcmul($business_cost, $value['quantity'],2);
-                    $dataArray[$key]['price_4_total'] = $price_4_total;
-                    $profit = bcsub($value['price_1_total'], $price_4_total,2);
-                    $dataArray[$key]['profit'] = $profit;
-                    $dataArray[$key]['profit_rate'] = $value['price_1_total'] > 0 ? bcdiv($profit, $value['price_1_total'],2) : 0;
-                }
-
-                DB::table($table)->insert($dataArray);
-
-                // 更新 lastId 继续下一批
-                $lastId = end($dataArray)['id_detail'] ?? $lastId;
-
-            } while (count($rows) === $limit);
-
-        }catch (\Throwable $exception){
-            return [false, "回款单同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
-        }
-
-        return [true, ''];
-    }
-
-    private function updateRevenueCost($data){
-        try {
-            $start_timeStamp = $data['start_timeStamp'];
-            $end_timeStamp = $data['end_timeStamp'];
-            $tmpTable = $this->table;
-            $time = time();
-            $ergs = $data;
-
-            DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $tmpTable,$time, $ergs) {
-                // 1. 先软删除旧数据(你已有)
-                RevenueCost::where('del_time', 0)
-                    ->where('order_time', '>=', $start_timeStamp)
-                    ->where('order_time', '<=', $end_timeStamp)
-                    ->update(['del_time' => $time]);
-
-                // 2. 分批从临时表插入新数据
-                $batchSize = 500;
-                $lastId = 0;
-                do {
-                    $chunk = DB::table($tmpTable)
-                        ->where('id', '>', $lastId)
-                        ->orderBy('id')
-                        ->limit($batchSize)
-                        ->get();
-
-                    if ($chunk->isEmpty()) {
-                        break;
-                    }
-
-                    $data = $chunk->map(function ($item) use($time){
-                        return [
-                            'order_id' => $item->order_id,
-                            'order_number' => $item->order_number,
-                            'order_time' => $item->order_time,
-                            'employee_id_1_title' => $item->employee_id_1_title,
-                            'employee_id_1' => $item->employee_id_1 ?? 0,
-                            'employee_id_2' => $item->employee_id_2 ?? 0,
-                            'employee_id_2_title' => $item->employee_id_2_title ?? "",
-                            'customer_code' => $item->customer_code,
-                            'customer_title' => $item->customer_title,
-                            'channel_finance' => $item->channel_finance,
-                            'channel_details' => $item->channel_details,
-                            'product_code' => $item->product_code,
-                            'product_title' => $item->product_title,
-                            'product_size' => $item->product_size,
-                            'unit' => $item->unit,
-                            'quantity' => $item->quantity,
-                            'price_1' => $item->price_1,
-                            'price_1_total' => $item->price_1_total,
-                            'price_2' => $item->price_2,
-                            'price_2_total' => $item->price_2_total,
-                            'price_3' => $item->price_3,
-                            'price_3_total' => $item->price_3_total,
-                            'price_4' => $item->price_4,
-                            'price_4_total' => $item->price_4_total,
-                            'profit' => $item->profit,
-                            'profit_rate' => $item->profit_rate,
-                            'id_detail' => $item->id_detail,
-                            'order_type' => $item->order_type,
-                            'payment_amount' => $item->payment_amount ?? 0,
-                            'id_detail_upstream' => $item->id_detail_upstream?? 0,
-                            'order_number_upstream' => $item->order_number_upstream ?? "",
-                            'is_activity' => $item->is_activity ?? 0,
-                            'customer_profit_rate' => $item->customer_profit_rate ?? '',
-                            'crt_time' => $time,
-                        ];
-                    })->toArray();
-
-                    // 每批单独插入(可选:加小事务)
-                    RevenueCost::insert($data);
-
-                    // 更新 lastId
-                    $lastId = $chunk->last()->id;
-
-                } while ($chunk->count() == $batchSize);
-
-                // 3. 更新主表
-                list($status, $msg) = $this->updateRevenueCostTotal($ergs);
-                if (! $status) {
-                    throw new \Exception($msg);
-                }
-            });
-        }catch  (\Throwable $exception){
-            return [false, "单据明细同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
-        }
-
-        return [true, ''];
-    }
-
-    private function updateRevenueCostTotal($data){
-        try {
-            $start_timeStamp = $data['start_timeStamp'];
-            $end_timeStamp = $data['end_timeStamp'];
-            $time = time();
-
-            //组织写入数据
-            $return = [];
-            $update_stamp = [];
-            DB::table('revenue_cost')
-                ->where('del_time',0)
-                ->where('order_time', '>=', $start_timeStamp)
-                ->where('order_time', '<=', $end_timeStamp)
-                ->select(RevenueCost::$field)
-                ->chunkById(100, function ($data) use(&$return,&$update_stamp){
-                    $dataArray = Collect($data)->map(function ($object){
-                        return (array)$object;
-                    })->toArray();
-                    foreach ($dataArray as $value){
-                        //变成每个月第一天的时间戳
-                        $time = date("Y-m-01", $value['order_time']);
-                        $stamp = strtotime($time);
-                        if(! in_array($stamp, $update_stamp)) $update_stamp[] = $stamp;
-                        if($value['order_type'] == RevenueCost::ORDER_ONE){
-                            $income = $value['price_3_total'];
-                        }elseif ($value['order_type'] == RevenueCost::ORDER_TWO){
-                            $income = $value['price_1_total'];
-                        }else{
-                            $income = $value['payment_amount'];
-                        }
-                        $adjust = $income < 0 ? $income : 0;
-                        $business = $value['price_4_total'];
-                        if(isset($return[$stamp][$value['order_type']][$value['employee_id_1']])){
-                            $income_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['income'], $income,2);
-                            $adjust_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['adjust'], $adjust,2);
-                            $business_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['business'], $business,2);
-                            $return[$stamp][$value['order_type']][$value['employee_id_1']]['income'] = $income_total;
-                            $return[$stamp][$value['order_type']][$value['employee_id_1']]['adjust'] = $adjust_total;
-                            $return[$stamp][$value['order_type']][$value['employee_id_1']]['business'] = $business_total;
-                        }else{
-                            $return[$stamp][$value['order_type']][$value['employee_id_1']] = [
-                                'income' => $income,
-                                'adjust' => $adjust,
-                                'business' => $business,
-                                'order_time' => $stamp,
-                                'employee_id_1_title' => $value['employee_id_1_title'],
-                            ];
-                        }
-                    }
-                });
-            $insert = [];
-            foreach ($return as $value){
-                foreach ($value as $order_type => $val){
-                   foreach ($val as $employee_id => $v){
-                        $profit = bcsub($v['income'], $v['business'],2);
-                        $profit_rate = $v['income'] > 0 ? bcdiv($profit, $v['income'],2) : 0;
-                        $v['profit'] = $profit;
-                        $v['profit_rate'] = $profit_rate;
-                        $v['order_type'] = $order_type;
-                        $v['employee_id_1'] = $employee_id;
-                        $v['crt_time'] = $time;
-                        $insert[] = $v;
-                    }
-                }
-            }
-
-            RevenueCostTotal::where('del_time', 0)
-                ->whereIn('order_time', $update_stamp)
-                ->update(['del_time' => $time]);
-
-            RevenueCostTotal::insert($insert);
-        }catch  (\Throwable $exception){
-            return [false, "主表同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
-        }
-
-        return [true, ''];
-    }
-
-    private function createTmpTable(){
-        $table = $this->table;
-        if (! Schema::hasTable($table)) {
-            // 可以通过 migration 创建,或程序启动时检查
-            Schema::create($table, function (Blueprint $table) {
-                $table->bigIncrements('id'); // BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
-                $table->integer('order_type')->default(0);
-                $table->bigInteger('order_id')->default(0);
-                $table->string('order_number', 50)->default('');
-                $table->integer('order_time')->nullable();
-                $table->string('employee_id_1_title', 100)->default('');
-                $table->bigInteger('employee_id_1')->default(0);
-                $table->bigInteger('employee_id_2')->default(0);
-                $table->string('employee_id_2_title', 100)->default('');
-                $table->string('customer_code', 50)->default('');
-                $table->string('customer_title', 100)->default('');
-                $table->string('channel_finance', 50)->nullable();
-                $table->string('channel_details', 50)->nullable();
-                $table->string('product_code', 50)->default('');
-                $table->string('product_title', 100)->default('');
-                $table->string('product_size', 100)->nullable();
-                $table->string('unit', 20)->nullable();
-                $table->decimal('quantity', 12, 2)->default(0);
-                $table->decimal('price_1', 12, 2)->default(0); // 销项成本
-                $table->decimal('price_1_total', 12, 2)->default(0);
-                $table->decimal('price_2', 12, 2)->default(0); // 运费
-                $table->decimal('price_2_total', 12, 2)->default(0);
-                $table->decimal('price_3', 12, 2)->default(0); // 含税单价
-                $table->decimal('price_3_total', 12, 2)->default(0); // 含税金额
-                $table->decimal('price_4', 12, 2)->default(0); // 业务成本
-                $table->decimal('price_4_total', 12, 2)->default(0);
-                $table->decimal('profit', 12, 2)->default(0);
-                $table->decimal('payment_amount', 12, 2)->default(0);
-                $table->decimal('profit_rate', 10, 3)->default(0);
-                $table->bigInteger('id_detail')->default(0);
-                $table->bigInteger('id_detail_upstream')->default(0);
-                $table->string('order_number_upstream', 100)->nullable();
-                $table->decimal('is_activity', 2, 0)->default(0);
-                $table->string('customer_profit_rate', 20)->default('');
-            });
-        }
-    }
-
-    public function clearTmpTable(){
-        if (Schema::hasTable($this->table)) DB::table($this->table)->truncate();
-    }
-
-    public function delTableKey($type = 1){
-        $key = $this->table;
-        if($type == 2) $key = $this->table_2;
-        $this->dellimitingSendRequest($key);
-    }
-
-    public function synSalaryEmployee($data, $user){
-        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '同步时间不能为空'];
-        list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['crt_time'],false);
-        if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "同步时间:时间区间无效"];
-        list($bool, $bool_msg) = $this->isOverThreeMonths($start_time, $end_time);
-        if(! $bool) return [false, $bool_msg];
-        $data['start_timeStamp'] = $start_time;
-        $data['end_timeStamp'] = $end_time;
-        $data['start_time'] = strtotime(date("Y-m-01",$data['start_timeStamp']));
-        $data['end_time'] = strtotime(date("Y-m-01"),$data['end_timeStamp']);
-        $data['operation_time'] = time();
-
-        list($status,$msg) = $this->limitingSendRequest($this->table_2);
-        if(! $status) return [false, '业务员工资同步正在后台运行,请稍后'];
-
-        //同步
-//        list($status, $msg) = $this->synSalaryEmployeeFromMine($data, $user);
-//        if(! $status) {
-//            $this->dellimitingSendRequest($this->table_2);
-//            return [false, $msg];
-//        }
-
-        //队列
-        ProcessDataJob::dispatch($data, $user, 2)->onQueue(RevenueCost::job2);
-
-        return [true, '业务员工资相关信息同步已进入后台任务'];
-    }
-
-    public function synSalaryEmployeeFromMine($data, $user){
-        //创建临时表 如果不存在
-        $this->createTmpTable2();
-        //清理临时表 如果内容不为空
-        $this->clearTmpTable2();
-
-        //写入临时表
-        DB::table('revenue_cost')
-            ->where('del_time', 0)
-            ->where('order_type', RevenueCost::ORDER_THREE)
-            ->where('order_time','>=',$data['start_timeStamp'])
-            ->where('order_time','<=',$data['end_timeStamp'])
-            ->select([
-                'employee_id_1',
-                'employee_id_1_title',
-                'order_time as time',
-                DB::raw("DATE_FORMAT(FROM_UNIXTIME(order_time), '%Y-%m-01') as order_time"),
-                DB::raw("SUM(payment_amount) as payment_amount"),
-                DB::raw("SUM(CASE WHEN is_activity = 0 THEN payment_amount ELSE 0 END) as payment_amount_not_include_activity"),
-                DB::raw("SUM(CASE WHEN is_activity = 1 THEN payment_amount ELSE 0 END) as payment_amount_activity"),
-                DB::raw("SUM(CASE WHEN profit_rate < customer_profit_rate and is_activity = 0 THEN payment_amount ELSE 0 END) as payment_amount_lower_than_rate"),
-                DB::raw("SUM(CASE WHEN profit_rate >= customer_profit_rate and is_activity = 0 THEN payment_amount ELSE 0 END) as payment_amount_greater_than_rate"),
-                DB::raw("SUM(CASE WHEN profit_rate >= customer_profit_rate and is_activity = 0 THEN price_4_total ELSE 0 END) as business"),
-                DB::raw("ROW_NUMBER() OVER (ORDER BY MIN(id)) as fake_id")
-            ])
-            ->groupBy('employee_id_1', DB::raw("DATE_FORMAT(FROM_UNIXTIME(order_time), '%Y-%m-01')"))
-            ->orderBy('order_time', 'desc')
-            ->chunkById(500, function ($data){
-                $dataArray = Collect($data)->map(function ($object){
-                    return (array)$object;
-                })->toArray();
-
-                $indexes = $this->getEmployeeIndex($dataArray);
-                foreach ($dataArray as $key => $value){
-                    $value['index_' . EmployeeIndex::TYPE_ONE] = 0;
-                    $value['index_' . EmployeeIndex::TYPE_SIX] = 0;
-                    $value['index_' . EmployeeIndex::TYPE_EIGHT] = 0;
-                    $this->findIndex($indexes, $value);
-
-                    $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
-                    $dataArray[$key]['order_time'] = strtotime($value['order_time']);
-                    $dataArray[$key]['sale_bonus'] = $value['index_' . EmployeeIndex::TYPE_EIGHT];
-                    $dataArray[$key]['index_' . EmployeeIndex::TYPE_ONE] = $value['index_' . EmployeeIndex::TYPE_ONE];
-                    $rate = bcdiv($value['index_' . EmployeeIndex::TYPE_ONE],100,2);
-                    $pay_in_advance = bcmul($rate, $value['payment_amount_greater_than_rate'],2);
-                    $dataArray[$key]['pay_in_advance'] = $pay_in_advance;
-                    $dataArray[$key]['basic_salary'] = $value['index_' . EmployeeIndex::TYPE_SIX];
-                    $dataArray[$key]['should_pay'] = bcadd(bcadd($value['index_' . EmployeeIndex::TYPE_EIGHT], $pay_in_advance,2),$value['index_' . EmployeeIndex::TYPE_SIX],2);
-
-                    unset($dataArray[$key]['fake_id']);
-                    unset($dataArray[$key]['time']);
-                }
-
-                DB::table($this->table_2)->insert($dataArray);
-            }, 'fake_id');
-
-        //更新数据
-        list($status,$msg) = $this->updateSalaryEmployee($data);
-        if(! $status) return [false, $msg];
-
-        //清理临时表 如果内容不为空
-        $this->clearTmpTable2();
-        //释放redis
-        $this->delTableKey(2);
-
-        return [true, '同步成功'];
-    }
-
-    private function getEmployeeIndex($existingData)
-    {
-        if (empty($existingData)) {
-            return collect();
-        }
-
-        // 取出所有涉及的 employee_id 和时间区间
-        $employeeIds = array_column($existingData, 'employee_id_1');
-        $time = array_column($existingData, 'time');
-        $minStart = ! empty($time) ? min($time) : 0;
-        $maxEnd   = ! empty($time) ? max($time) : 0;
-
-        // 一次性查出这些员工在最大区间范围内的所有指标
-        $results = EmployeeIndex::where('del_time', 0)
-            ->whereIn('type', [EmployeeIndex::TYPE_ONE, EmployeeIndex::TYPE_EIGHT])
-            ->whereIn('employee_id', $employeeIds)
-            ->where('start_time', '<=', $maxEnd)
-            ->where('end_time', '>=', $minStart)
-            ->select('start_time','end_time','employee_id','index','type')
-            ->get();
-
-        return $results;
-    }
-
-    private function findIndex($indexes, &$value){
-        // 找到所有符合条件的 index(可能多个 type)
-        $matchedIndexes = $indexes->filter(function ($item) use ($value) {
-            return $item['employee_id'] == $value['employee_id_1']
-                && $item['start_time'] <= $value['time']
-                && $item['end_time'] >= $value['time'];
-        });
-        // 按 type 去重,只保留第一次出现的
-        $uniqueByType = [];
-        foreach ($matchedIndexes as $item) {
-            $index = "index_" . $item['type'];
-            if (! isset($uniqueByType[$index])) {
-                $uniqueByType[$index] = $item['index'];
-            }
-        }
-        $value = array_merge($value, $uniqueByType);
-    }
-
-    private function createTmpTable2(){
-        $table = $this->table_2;
-        if (! Schema::hasTable($table)) {
-            // 可以通过 migration 创建,或程序启动时检查
-            Schema::create($table, function (Blueprint $table) {
-                $table->bigIncrements('id'); // BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
-                $table->integer('order_type')->default(0);
-                $table->integer('order_time')->default(0);
-                $table->string('employee_id_1_title', 100)->default('');
-                $table->bigInteger('employee_id_1')->default(0);
-                $table->decimal('payment_amount', 12, 2)->default(0);
-                $table->decimal('payment_amount_not_include_activity', 12, 2)->default(0);
-                $table->decimal('payment_amount_activity', 12, 2)->default(0);
-                $table->decimal('payment_amount_lower_than_rate', 12, 2)->default(0);
-                $table->decimal('payment_amount_greater_than_rate', 12, 2)->default(0);
-                $table->decimal('business', 12, 2)->default(0);
-                $table->decimal('sale_bonus', 12, 2)->default(0);
-                $table->decimal('index_1', 10, 2)->default(0);
-                $table->decimal('pay_in_advance', 12, 2)->default(0);
-                $table->decimal('basic_salary', 12, 2)->default(0);
-                $table->decimal('should_pay', 12, 2)->default(0);
-            });
-        }
-    }
-
-    public function clearTmpTable2(){
-        if (Schema::hasTable($this->table_2)) DB::table($this->table_2)->truncate();
-    }
-
-    private function updateSalaryEmployee($data){
-        try {
-            $start_timeStamp = $data['start_time'];
-            $end_timeStamp = $data['end_time'];
-            $tmpTable = $this->table_2;
-            $time = time();
-            $ergs = $data;
-
-            DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $tmpTable,$time, $ergs) {
-                // 1. 先软删除旧数据(你已有)
-                SalaryEmployee::where('del_time', 0)
-                    ->where('order_time', '>=', $start_timeStamp)
-                    ->where('order_time', '<=', $end_timeStamp)
-                    ->update(['del_time' => $time]);
-
-                // 2. 分批从临时表插入新数据
-                $batchSize = 500;
-                $lastId = 0;
-                do {
-                    $chunk = DB::table($tmpTable)
-                        ->where('id', '>', $lastId)
-                        ->orderBy('id')
-                        ->limit($batchSize)
-                        ->get();
-
-                    if ($chunk->isEmpty()) {
-                        break;
-                    }
-
-                    $data = $chunk->map(function ($item) use($time){
-                        return [
-                            'order_type' => $item->order_type,
-                            'order_time' => $item->order_time,
-                            'employee_id_1_title' => $item->employee_id_1_title,
-                            'employee_id_1' => $item->employee_id_1 ?? 0,
-                            'payment_amount' => $item->payment_amount,
-                            'payment_amount_not_include_activity' => $item->payment_amount_not_include_activity,
-                            'payment_amount_activity' => $item->payment_amount_activity,
-                            'payment_amount_lower_than_rate' => $item->payment_amount_lower_than_rate,
-                            'payment_amount_greater_than_rate' => $item->payment_amount_greater_than_rate,
-                            'business' => $item->business,
-                            'sale_bonus' => $item->sale_bonus,
-                            'index_1' => $item->index_1,
-                            'pay_in_advance' => $item->pay_in_advance,
-                            'basic_salary' => $item->basic_salary,
-                            'should_pay' => $item->should_pay,
-                            'crt_time' => $time,
-                        ];
-                    })->toArray();
-
-                    // 每批单独插入(可选:加小事务)
-                    SalaryEmployee::insert($data);
-
-                    // 更新 lastId
-                    $lastId = $chunk->last()->id;
-
-                } while ($chunk->count() == $batchSize);
-            });
-        }catch  (\Throwable $exception){
-            return [false, "单据明细同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
-        }
-
-        return [true, ''];
-    }
-}

+ 5 - 3
app/Service/TPlusDatabaseServerService.php → app/Service/U8DatabaseServerService.php

@@ -6,13 +6,15 @@ use Illuminate\Support\Facades\Config;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
 
-class TPlusDatabaseServerService extends Service
+class U8DatabaseServerService extends Service
 {
     public $db = null;
     public $error = null; // 错误信息
+    private $database = "";
 
-    public function __construct()
+    public function __construct($loginUser = [])
     {
+        $this->database = $loginUser['zt_database'] ?? "";
         $this->createConnection();
     }
 
@@ -24,7 +26,7 @@ class TPlusDatabaseServerService extends Service
             'driver' => 'sqlsrv',
             'host' => env('SQLSRV_HOST'),
             'port' => env('SQLSRV_PORT'),
-            'database' => env('SQLSRV_DATABASE'),
+            'database' => $this->database,
             'username' => env('SQLSRV_USERNAME'),
             'password' => env('SQLSRV_PASSWORD'),
             'options' => [

+ 58 - 0
app/Service/U8ServerService.php

@@ -0,0 +1,58 @@
+<?php
+
+namespace App\Service;
+
+use App\Jobs\ProcessDataJob;
+use App\Model\Depart;
+use App\Model\Employee;
+use App\Model\EmployeeDepartPermission;
+use App\Model\EmployeeIndex;
+use App\Model\Product;
+use App\Model\RevenueCost;
+use App\Model\RevenueCostTotal;
+use App\Model\SalaryEmployee;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Schema;
+
+class U8ServerService extends Service
+{
+    protected $databaseService;
+
+    /**
+     * @var string|null
+     */
+    protected $error;
+
+    /**
+     * U8ServerService constructor.
+     */
+    public function __construct($loginUser = [])
+    {
+        $service = new U8DatabaseServerService($loginUser);
+        $this->databaseService = $service->db;
+        $this->error = $service->error;
+    }
+
+    /**
+     * 获取错误信息
+     *
+     * @return string|null
+     */
+    public function getError()
+    {
+        return $this->error;
+    }
+
+
+    public function purchaseRequisition($data, $user){
+        $model = $this->databaseService->table('DispatchList as a')
+            ->leftJoin('DispatchLists as b', 'b.DLID', 'a.DLID')
+            ->leftJoin('Inventory as c', 'c.cInvCode', 'b.cInvCode')
+            ->select('a.cDLCode as cdlcode', 'a.DLID as id', 'a.cCusName as customer_name', 'b.cSOCode as csocode', 'a.cDepCode as cdepcode', 'a.cCusCode as cuscode', 'a.dDate as date','b.irowno', 'b.iDLsID as idlsid', 'b.cWhCode as cwhcode', 'b.cInvCode as cinvcode', 'b.cInvName as product_title', 'b.cFree1 as cfree1', 'b.cFree2 as cfree2', 'b.cPosition as cposition', 'b.cBatch as cbatch', 'b.iQuantity as iquantity', 'b.iNum as inum', 'b.iInvExchRate as iinvexchrate', 'b.fOutQuantity as out_quantity', 'b.iUnitPrice as iunitcost', 'b.iMoney as imoney', 'b.cDefine28 as technology_material', 'b.cDefine30 as process_mark', 'c.cInvStd as product_size', DB::raw('(b.iQuantity - b.fOutQuantity) as quantity'), 'a.cMemo as table_header_mark', 'b.cMemo as table_body_mark');
+
+       $list = $this->limit($model,'',$data);
+
+       return [true , $list];
+    }
+}

+ 4 - 0
routes/api.php

@@ -83,4 +83,8 @@ Route::group(['middleware'=> ['checkLogin']],function ($route){
     $route->any('importAll','Api\ImportController@importAll');
     //导出统一方法
     $route->any('exportFile', 'Api\ExportFileController@exportFile');
+
+    $route->any('purchaseRequisition', 'Api\U8Controller@purchaseRequisition');
+    $route->any('purchaseOrder', 'Api\U8Controller@purchaseOrder');
+    $route->any('paymentOrder', 'Api\U8Controller@paymentOrder');
 });