cqpCow 2 жил өмнө
parent
commit
376ebdbbdc

+ 7 - 4
app/Http/Controllers/Api/FyyOrderController.php

@@ -13,12 +13,15 @@ class FyyOrderController extends BaseController
     public function setFyy(Request $request)
     {
         $data = $request->all();
-        if(! isset($data['host']) || ! isset($data['port']) || ! isset($data['database'])) return;
 
         $array = [
-            'sqlserver_host' => $data['host'],
-            'sqlserver_port' => $data['port'],
-            'sqlserver_database' => $data['database']
+            'sqlserver_host' => $data['host'] ?? '',
+            'sqlserver_port' => $data['port'] ?? 0,
+            'sqlserver_database' => $data['database'] ?? '',
+            'sqlserver_zt' => $data['zt'] ?? '',
+            'sqlserver_account' => $data['account'] ?? '',
+            'sqlserver_password' => $data['password'] ?? '',
+            'sqlserver_host_api' => $data['host_api'] ?? '',
         ];
         Redis::set('fyy_sql_server',json_encode($array));
         Redis::expire('fyy_sql_server', 86400);

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

@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api;
 
 
 use App\Model\BoxDetail;
+use App\Service\FinishedOrderService;
 use App\Service\MeasureService;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\DB;
@@ -1028,4 +1029,11 @@ public function testa(Request $request){
         curl_close($curl);
         echo $response;
     }
+
+    public function testapp(){
+        $str = '{"result":[{"id":121,"finished_num":0,"dispatch_quantity":100,"out_order_no_time":"1691683200","process_id":9,"dispatch_no":"20230811001","order_product_id":119,"sale_orders_product_id":4499,"order_no":"2023081116917417502029","product_no":"00031412","product_title":"\u65b0\u897f\u5170\u677e","price":"10.0000000000","customer_name":"\u6c5f\u897f\u5fb7\u514b\u65af\u8bfa\uff08\u4e0a\u6d77\u5ba6\u821f\u53a8\u5177\u6709\u9650\u516c\u53f8\uff09"}],"data":{"id":[121],"quantity":["10"],"team_id":[68],"equipment_id":[8],"waste":[[]],"finish_id":[0]}}';
+        $data = json_decode($str,true);
+        list($status,$msg) =  (new FinishedOrderService())->addInJob($data['result'],$data['data']);
+        dump($msg);die;
+    }
 }

+ 156 - 0
app/Jobs/ProcessDataJob.php

@@ -0,0 +1,156 @@
+<?php
+
+namespace App\Jobs;
+
+use App\Model\DispatchSub;
+use App\Model\ErrorTable;
+use App\Service\FinishedOrderService;
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Redis;
+use MongoDB\Driver\Exception\Exception;
+use Symfony\Component\Console\Output\ConsoleOutput;
+use Symfony\Component\Console\Output\OutputInterface;
+
+class ProcessDataJob implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+
+    const job_one = 'finished_operation';
+    const job_two = '';
+
+    protected $data;
+    protected $user;
+    protected $type;
+
+    //1 代表产成品入库  2 销售出库单
+    protected $function = [
+        1 => 'U8Rdrecord10Save',
+        2 => 'U8Rdrecord32Save'
+    ];
+
+    protected $function_reback = [
+        1 => 'reBackOne',
+    ];
+
+    protected $jobs = [
+        1 => self::job_one,
+        2 => self::job_two
+    ];
+
+    /**
+     * Create a new job instance.
+     *  $data = [
+            'result' => $msg, //查询结果
+            'data' => $data, //用户提交的参数
+        ];
+     * $user 提交用户的信息
+     * $type //1 代表产成品入库(完工操作)  2 销售出库单(包装单扫描出库)
+     *
+     * @return void
+     */
+    public function __construct($data, $user = [], $type)
+    {
+        $this->data = $data;
+        $this->user = $user ?? [];
+        $this->type = $type;
+    }
+
+    /**                file_put_contents('charge.txt',"标记位置退出".PHP_EOL,8);
+     * Execute the job.
+     *
+     * @return void
+     */
+    public function handle()
+    {
+        try {
+            $function = $this->function[$this->type] ?? '';//调用方法 入库
+            $function_back = $this->function_reback[$this->type] ?? '';//数据回退方法
+            if(empty($function))  return;
+
+            list($status,$msg) = $this->$function();
+            if(! $status) $this->errorSettle($msg);
+        } catch (\Exception $e) {
+            $this->$function_back();
+            $this->recordErrorTable($e->getFile() . $e->getMessage() . $e->getLine());
+        }
+
+        //输出信息
+        $this->echoMessage(new ConsoleOutput());
+    }
+
+    protected function echoMessage(OutputInterface $output)
+    {
+        //输出消息
+        $output->writeln(json_encode($this->data));
+    }
+
+    //产成品入库
+    private function U8Rdrecord10Save(){
+        $service = new FinishedOrderService();
+        //标记
+        list($status,$msg) = $service->addInJob($this->data['result'],$this->data['data']);
+        return [$status,$msg];
+    }
+
+    private function reBackOne(){
+        //数据回退
+        $data = $this->data['data'];
+
+        //进入队列的数据
+        DispatchSub::whereIn('id',$data['id'])->update([
+            'job_status' => 0,
+        ]);
+    }
+
+    //销售单出库
+    private function U8Rdrecord32Save(){
+
+    }
+
+    private function errorSettle($msg){
+        $redis = Redis::connection();
+
+        $order_failures_key = md5(json_encode($this->data));
+
+        // 从Redis中获取失败计数
+        $failureCount = $redis->hIncrBy('order_failures', $order_failures_key, 1);
+
+        //队列名
+        $job = $this->jobs[$this->type];
+
+        if ($failureCount < 2) {
+            // 将任务重新放回队列
+            self::dispatch($this->data,$this->user,$this->type)->onQueue($job)->delay(now()->addSeconds(2));
+        } else {
+            // 删除失败计数
+            $redis->hDel('order_failures', $order_failures_key);
+
+            //数据回退
+            $function_back = $this->function_reback[$this->type] ?? '';
+            $this->$function_back();
+
+            //记录错误
+            $this->recordErrorTable($msg);
+        }
+    }
+
+    private function recordErrorTable($msg){
+        $model = new ErrorTable();
+        $model->msg = $msg;
+        $model->data = json_encode($this->data);
+        $model->user_data = json_encode($this->user);
+        $model->save();
+    }
+
+    public function failed($exception)
+    {
+        // 记录失败错误信息到日志或其他媒介
+        $errorMessage = $exception->getFile() . $exception->getMessage() . $exception->getLine();
+        $this->recordErrorTable($errorMessage);
+    }
+}

+ 15 - 0
app/Model/ErrorTable.php

@@ -0,0 +1,15 @@
+<?php
+
+namespace App\Model;
+
+use Illuminate\Database\Eloquent\Model;
+
+
+class ErrorTable extends Model
+{
+    protected $table = "error_table"; //指定表
+    const CREATED_AT = 'crt_time';
+    const UPDATED_AT = 'upd_time';
+    protected $dateFormat = 'U';
+
+}

+ 78 - 63
app/Service/FinishedOrderService.php

@@ -2,7 +2,7 @@
 
 namespace App\Service;
 
-use App\Model\Dispatch;
+use App\Jobs\ProcessDataJob;
 use App\Model\DispatchSub;
 use App\Model\Employee;
 use App\Model\EmployeeTeamPermission;
@@ -10,13 +10,13 @@ use App\Model\Equipment;
 use App\Model\FinishedOrder;
 use App\Model\FinishedOrderScrapp;
 use App\Model\FinishedOrderSub;
-use App\Model\OrdersProduct;
 use App\Model\OrdersProductProcess;
 use App\Model\Process;
 use App\Model\SaleOrdersProduct;
 use App\Model\Scrapp;
 use App\Model\Team;
 use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Redis;
 
 class FinishedOrderService extends Service
 {
@@ -50,34 +50,81 @@ class FinishedOrderService extends Service
         list($status,$msg) = $this->orderRule($data);
         if(!$status) return [$status,$msg];
 
+        $user = [
+            'id' => $user['id'],
+            'operate_time' => time()
+        ];
+        $redis = [
+            'result' => $msg,
+            'data' => $data,
+        ];
+        $job = dispatch(new ProcessDataJob($redis,$user,1))->onQueue(ProcessDataJob::job_one);
+        if(! $job){
+            return [false,'任务没有进入队列!'];
+        }
+
+        //错误计数
+        Redis::hSet('order_failures', md5(json_encode($redis)), 0);
+
+        //标记进入队列的数据
+        DispatchSub::whereIn('id',$data['id'])->update([
+            'job_status' => 1,
+        ]);
+        return [true,'任务已进入队列!'];
+    }
+
+    public function addInJob($result,$data){
         try{
-            DB::beginTransaction();
+            date_default_timezone_set("PRC");
+
+            //用友数据插入------------
+            $insert_sql_server = [];
+            foreach ($result as $key => $value){
+                $quantity_tmp = $data['quantity'][$key];
+                $result[$key]['quantity'] = $quantity_tmp;
+
+                //工序表
+                $process_model = new OrdersProductProcess(['channel' => date("Ymd",$value['out_order_no_time'])]);
+                $process_id = $process_model->select('process_id')
+                    ->where('sort',$process_model->where('del_time',0)
+                        ->where('order_product_id',$value['order_product_id'])
+                        ->max('sort'))
+                    ->first();
+                if(empty($process_id)) return [false,"未找到最后一道工序"];
+
+                $process_id = $process_id->process_id;
+                if($process_id == $value['process_id']){
+                    $insert_sql_server[] = $result[$key];
+                }
+            }
 
+            if(! empty($insert_sql_server)){
+                $sqlServerModel = new FyySqlServerService();
+                if($sqlServerModel->error) return [false,$sqlServerModel->error];
+                foreach ($insert_sql_server as $value){
+                    list($status,$msg) = $sqlServerModel->U8Rdrecord10Save($value);
+                    if(! $status) return [false,$msg];
+                }
+            }
+            //用友数据插入结束----------
+
+            //本地数据更新
             $waste = [];
             foreach ($data['waste'] as $key => $value){
                 $waste[$key] = array_sum(array_column($value,'num'));
             }
-
-            //生产数据的源数据
-            $result = $msg;
             $time = time();
 
-            date_default_timezone_set("PRC");
-
-            $insert_sql_server = [];
             foreach ($result as $key => $value){
-                $quantity_tmp = $data['quantity'][$key];
                 $finished_id_tmp = $data['finish_id'][$key];
                 $team_tmp = $data['team_id'][$key];
                 $equipment_id_tmp = $data['equipment_id'][$key];
-                $result[$key]['quantity'] = $quantity_tmp;
+                $finished_num = $value['quantity'] + $value['finished_num'];
 
-                $finished_num = $quantity_tmp + $value['finished_num'];
-                DispatchSub::where('id',$value['id'])
-                    ->update([
-                        'finished_num' => $finished_num,
-                        'waste_num' => $waste[$key]
-                    ]);
+                DispatchSub::where('id',$value['id'])->update([
+                    'finished_num' => $finished_num,
+                    'waste_num' => $waste[$key]
+                ]);
 
                 $insert_waste = [];
                 if(! empty($data['waste'][$key])){
@@ -103,26 +150,10 @@ class FinishedOrderService extends Service
 
                 //工序表
                 $process_model = new OrdersProductProcess(['channel' => date("Ymd",$value['out_order_no_time'])]);
-
-                $process_id = $process_model->select('process_id')
-                    ->where('sort',$process_model->where('del_time',0)
-                        ->where('order_product_id',$value['order_product_id'])
-                        ->max('sort'))
-                    ->first();
-
-                if(empty($process_id)){
-                    DB::rollBack();
-                    return [false,"未找到最后一道工序"];
-                }
-                $process_id = $process_id->process_id;
-                if($process_id == $value['process_id']){
-                    $insert_sql_server[] = $result[$key];
-                }
-
                 $process_model->where('order_product_id',$value['order_product_id'])
                     ->where('process_id',$value['process_id'])
                     ->where('dispatch_no',$value['dispatch_no'])
-                    ->take($quantity_tmp)
+                    ->take($value['quantity'])
                     ->update([
                         'finished_time' => $time,
                         'status' => 2,
@@ -136,24 +167,11 @@ class FinishedOrderService extends Service
 
             //反写数量
             $this->writeFinishedQuantity(array_column($result,'sale_orders_product_id'));
-
-            if(! empty($insert_sql_server)){
-                foreach ($insert_sql_server as $value){
-                    list($status,$msg) = $this->insertSqlServer($value);
-                    if(! $status) {
-                        DB::rollBack();
-                        return [false,$msg];
-                    }
-                }
-            }
-
-            DB::commit();
         }catch (\Exception $e){
-            DB::rollBack();
-            return [false,$e->getLine().':'.$e->getMessage()];
+            return [false,$e->getFile() . $e->getLine(). $e->getMessage()];
         }
 
-        return [true,'保存成功!'];
+        return [true,''];
     }
 
     public function del($data){
@@ -210,6 +228,9 @@ class FinishedOrderService extends Service
         if($this->isEmpty($data,'quantity')) return [false,'请填写完工数量!'];
         if($this->isEmpty($data,'finish_id') && $this->isEmpty($data,'team_id')) return [false,'人员和班组不能都为空!'];
 
+        $bool = DispatchSub::whereIn('id',$data['id'])->where('job_status',1)->exists();
+        if($bool) return [false,'正在队列中,请不要重复操作!'];
+
         $result = DispatchSub::whereIn('id',$data['id'])
             ->select('id','finished_num','dispatch_quantity','out_order_no_time','process_id','dispatch_no','order_product_id','sale_orders_product_id','order_no','product_no','product_title','price','customer_name')
             ->orderBy('id','desc')
@@ -410,10 +431,14 @@ class FinishedOrderService extends Service
             //反写数量
             $this->writeFinishedQuantity(array_column($result,'sale_orders_product_id'));
 
-            list($status,$msg) = $this->insertSqlServer($insert_sql_server);
-            if(! $status) {
-                DB::rollBack();
-                return [false,$msg];
+            if(! empty($insert_sql_server)){
+                foreach ($insert_sql_server as $value){
+                    list($status,$msg) = $this->insertSqlServer($value);
+                    if(! $status) {
+                        DB::rollBack();
+                        return [false,$msg];
+                    }
+                }
             }
 
             DB::commit();
@@ -450,14 +475,4 @@ class FinishedOrderService extends Service
 
         return [true, $result,$post];
     }
-
-    //产成品入库
-    public function insertSqlServer($array){
-        if(empty($array)) return [true,''];
-
-        $sqlServerModel = new FyySqlServerService();
-        list($status,$msg) = $sqlServerModel->U8Rdrecord10Save($array);
-
-        return [$status,$msg];
-    }
 }

+ 44 - 41
app/Service/FyySqlServerService.php

@@ -14,31 +14,36 @@ class FyySqlServerService extends Service
 {
     public $db = null;
     public $error = null;
-    public $host = "";
-    public $port = 0;
-    public $database = "";
+    public $host = "s6j9560970.goho.co";//数据库外网域名
+    public $host_api = '13083970779.gnway.cc:8000';//用友接口外网域名
+    public $port = 29703;
+    public $database = "UFDATA_999_2023";
     public $url = "";
+    public $sAccID = "(default)@999";
+    public $sUserID = "demo";
+    public $sPassword = "";
 
     public function __construct()
     {
         $fyy_array = Redis::get('fyy_sql_server');
-        if(empty($fyy_array)) {
-            $this->error = 'SQLSERVER设置不存在!';
-            return;
+        if(! empty($fyy_array)) {
+            $fyy_array = json_decode($fyy_array,true);
+            if(! empty($fyy_array['sqlserver_host'])) $this->host = $fyy_array['sqlserver_host'];
+            if(! empty($fyy_array['sqlserver_host_api'])) $this->host_api = $fyy_array['sqlserver_host_api'];
+            if(! empty($fyy_array['sqlserver_port'])) $this->port = $fyy_array['sqlserver_port'];
+            if(! empty($fyy_array['sqlserver_database'])) $this->database = $fyy_array['sqlserver_database'];
+            if(! empty($fyy_array['sqlserver_zt'])) $this->sAccID = '(default)@' . $fyy_array['sqlserver_zt'];
+            if(! empty($fyy_array['sqlserver_account'])) $this->sUserID = $fyy_array['sqlserver_account'];
+            if(! empty($fyy_array['sqlserver_password'])) $this->sPassword = $fyy_array['sqlserver_password'];
         }
-        $fyy_array = json_decode($fyy_array,true);
-
-        $this->host = $fyy_array['sqlserver_host'] ?? '';
-        $this->port = $fyy_array['sqlserver_port'] ?? 0;
-        $this->database = $fyy_array['sqlserver_database'] ?? '';
-        $this->url = empty($this->host)?: "http://" . $this->host . ":12365/U8Sys/U8API";
+        $this->url = $this->host_api . "/U8Sys/U8API";
 
         if(! $this->db){
             $config = [
                 'driver' => 'sqlsrv',
-                'host' =>  $fyy_array['sqlserver_host'] ?? '',
-                'port' => $fyy_array['sqlserver_port'] ?? '',
-                'database' => $fyy_array['sqlserver_database'] ?? '',
+                'host' =>  $this->host,
+                'port' => $this->port,
+                'database' => $this->database,
                 'username' => env('SQLSRV_USERNAME'),
                 'password' => env('SQLSRV_PASSWORD'),
             ];
@@ -296,9 +301,6 @@ class FyySqlServerService extends Service
         if(! empty($this->error)) return [false,$this->error];
         date_default_timezone_set("PRC");
 
-        list($bool,$msg) = $this->createOrderNumberAboutSCRK();
-        if(! $bool) return [false,$msg];
-
         if($bredvouch){
             $cmemo = '来源:福羊羊完工操作撤回';
         }else{
@@ -307,36 +309,36 @@ class FyySqlServerService extends Service
 
         //数据
         $bodys[] = [
-            "cinvcode" => $data["product_no"],
-            "cposition" => "",
-            "cbatch" => "",
-            "iquantity" => $data["quantity"],
-            "inum" => $data["quantity"],
-            "iunitcost" => $data["price"] * 0.95,
-            "iprice" => $data["price"] * 0.95 * $data['quantity'],
-            "iinvexchrate" => "1.00",
-            "impoids" => "",
-            "cmocode" => "",
-            "imoseq" => "",
-            "cbmemo" => "",
-            "cfree1" => "",
-            "cfree2" => "",
+            "cinvcode"=> $data["product_no"],
+            "cposition"=> "",
+            "cbatch"=> "",
+            "iquantity"=> $data["quantity"],
+            "inum"=> $data["quantity"],
+            "iunitcost"=> $data["price"] * 0.95,
+            "iprice"=> $data["price"] * 0.95 * $data['quantity'],
+            "iinvexchrate"=> "1.00",
+            "impoids"=> "",
+            "cmocode"=> "",
+            "imoseq"=> "",
+            "cbmemo"=> "",
+            "cfree1"=> "",
+            "cfree2"=> "",
         ];
         $post = [
             "password"=>"cloud@123456",
             "entity"=>"U8Rdrecord10Save",
             "login"=>[
-                "sAccID"=> "(default)@001",
+                "sAccID"=> $this->sAccID,
                 "sDate"=> date("Y-m-d"),
                 "sServer"=> '127.0.0.1',
-                "sUserID"=> "董晓磊",
+                "sUserID"=> $this->sUserID,
                 "sSerial"=> "",
-                "sPassword"=> ""
+                "sPassword"=> $this->sPassword
             ],
             "data"=>[
                 "ccode"=>'',
                 "ddate"=>date("Y-m-d"),
-                "cmaker"=>"董晓磊",
+                "cmaker"=>$this->sUserID,
                 "dnmaketime"=> date("Y-m-d"),
                 "IsExamine"=>true,
                 "bredvouch"=> $bredvouch,
@@ -348,8 +350,9 @@ class FyySqlServerService extends Service
                 "bodys"=>$bodys
             ]
         ];
-
         $return = $this->post_helper($this->url,json_encode($post), ['Content-Type:application/json']);
+
+        if(empty($return))  return [false, '异常错误,请确认请求接口地址!'];
         return [$return['flag'], $return['msg']];
     }
 
@@ -411,17 +414,17 @@ class FyySqlServerService extends Service
                 "password"=>"cloud@123456",
                 "entity"=>"U8Rdrecord32Save",
                 "login"=>[
-                    "sAccID"=> "(default)@001",
+                    "sAccID"=> $this->sAccID,
                     "sDate"=> date("Y-m-d"),
                     "sServer"=> '127.0.0.1',
-                    "sUserID"=> "董晓磊",
+                    "sUserID"=> $this->sUserID,
                     "sSerial"=> "",
-                    "sPassword"=> ""
+                    "sPassword"=> $this->sPassword
                 ],
                 "data"=>[
                     "ccode"=>'',
                     "ddate"=>date("Y-m-d"),
-                    "cmaker"=>"董晓磊",
+                    "cmaker"=>$this->sUserID,
                     "dnmaketime"=> date("Y-m-d"),
                     "IsExamine"=>true,
                     "bredvouch"=> $bredvouch,