瀏覽代碼

Merge branch 'master' into Haozi

# Conflicts:
#	app/Services/CommodityService.php
#	app/Services/OrderService.php
#	app/Services/WarehouseService.php
#	config/cache.php
#	phpunit.xml
haozi 5 年之前
父節點
當前提交
f154794510
共有 100 個文件被更改,包括 2207 次插入313 次删除
  1. 3 2
      app/Console/Commands/CreateOwnerBillReport.php
  2. 2 0
      app/Console/Commands/SyncBatchTask.php
  3. 16 8
      app/Console/Commands/SyncWMSOrderTask.php
  4. 8 17
      app/Http/Controllers/LogController.php
  5. 35 0
      app/Http/Controllers/OrderCommodityAssignController.php
  6. 10 10
      app/Http/Controllers/StationTaskBatchController.php
  7. 10 10
      app/Http/Controllers/StationTaskBatchTypeController.php
  8. 10 10
      app/Http/Controllers/StationTaskCommodityController.php
  9. 85 0
      app/Http/Controllers/StationTaskController.php
  10. 10 10
      app/Http/Controllers/StationTaskMaterialBoxController.php
  11. 85 0
      app/Http/Controllers/StationTaskTypeController.php
  12. 7 1
      app/Http/Controllers/StoreCheckingReceiveController.php
  13. 10 23
      app/Http/Controllers/TestController.php
  14. 27 0
      app/Http/Controllers/api/thirdPart/haiq/LightController.php
  15. 9 4
      app/Http/Controllers/api/thirdPart/haiq/PickStationController.php
  16. 24 7
      app/Http/Controllers/api/thirdPart/haiq/StorageController.php
  17. 153 0
      app/Imports/UpdatePickZone.php
  18. 44 0
      app/Jobs/OrderCreateInstantBill.php
  19. 44 0
      app/Jobs/ProcessCreateInstantBill.php
  20. 45 0
      app/Jobs/StoreCreateInstantBill.php
  21. 7 0
      app/Log.php
  22. 3 0
      app/OracleDOCOrderHeader.php
  23. 4 1
      app/Order.php
  24. 33 0
      app/OrderCommodityAssign.php
  25. 14 2
      app/Providers/AppServiceProvider.php
  26. 30 5
      app/Services/BatchService.php
  27. 125 3
      app/Services/CommodityService.php
  28. 25 0
      app/Services/ForeignHaiRoboticsService.php
  29. 20 0
      app/Services/LogisticService.php
  30. 8 3
      app/Services/OracleDOCOrderHeaderService.php
  31. 31 0
      app/Services/OrderCommodityAssignService.php
  32. 212 0
      app/Services/OrderCommodityService.php
  33. 15 2
      app/Services/OrderIssueService.php
  34. 46 33
      app/Services/OrderPackageCommoditiesService.php
  35. 9 1
      app/Services/OrderPackageService.php
  36. 132 83
      app/Services/OrderService.php
  37. 8 4
      app/Services/OrderTrackingService.php
  38. 20 0
      app/Services/OwnerFeeDetailService.php
  39. 29 10
      app/Services/OwnerPriceOperationService.php
  40. 16 1
      app/Services/OwnerService.php
  41. 20 0
      app/Services/ProcessService.php
  42. 33 0
      app/Services/ShopService.php
  43. 28 0
      app/Services/StationService.php
  44. 61 0
      app/Services/StationTaskBatchService.php
  45. 26 0
      app/Services/StationTaskBatchTypeService.php
  46. 28 0
      app/Services/StoreService.php
  47. 20 8
      app/Services/WarehouseService.php
  48. 43 0
      app/Services/WaybillService.php
  49. 1 1
      app/StationTask.php
  50. 1 1
      app/StationTaskBatch.php
  51. 10 0
      app/StationTaskBatchType.php
  52. 1 1
      app/StationTaskCommodity.php
  53. 1 1
      app/StationTaskMaterialBox.php
  54. 10 0
      app/StationTaskType.php
  55. 11 0
      app/Utils/helpers.php
  56. 3 0
      composer.json
  57. 9 1
      config/api.php
  58. 7 6
      config/cache.php
  59. 1 0
      config/sync.php
  60. 18 0
      database/factories/OracleActAllocationDetailsFactory.php
  61. 14 0
      database/factories/OracleBasCodeFactory.php
  62. 14 0
      database/factories/OracleBasCustomerFactory.php
  63. 15 0
      database/factories/OracleBasSKUFactory.php
  64. 16 0
      database/factories/OracleDOCOrderDetailFactory.php
  65. 35 0
      database/factories/OrcaleDOCOrderHeaderFactory.php
  66. 1 1
      database/factories/ShopFactory.php
  67. 2 2
      database/factories/StationMissionBatchFactory.php
  68. 2 2
      database/factories/StationMissionBatchTypeFactory.php
  69. 2 2
      database/factories/StationMissionCommodityFactory.php
  70. 2 2
      database/factories/StationMissionMaterialBoxFactory.php
  71. 12 0
      database/factories/StationTaskFactory.php
  72. 12 0
      database/factories/StationTaskTypeFactory.php
  73. 13 0
      database/factories/WarehouseFactory.php
  74. 1 1
      database/migrations/2020_01_02_172739_change_waybill_price_model_field.php
  75. 1 1
      database/migrations/2020_03_09_153510_create_stores_table.php
  76. 2 1
      database/migrations/2020_04_09_111540_change_tutorial_table.php
  77. 0 1
      database/migrations/2020_06_02_130804_change_user_duty_check.php
  78. 4 4
      database/migrations/2020_06_11_112028_change_rejected_bills_table.php
  79. 1 1
      database/migrations/2020_06_16_173559_add_authorrities_waybillmanagement_freigt.php
  80. 0 1
      database/migrations/2020_06_30_133655_change_processes_contents_column_type.php
  81. 1 1
      database/migrations/2020_09_10_143926_drop_shop_unique_name_index.php
  82. 1 1
      database/migrations/2020_10_19_113042_create_logistic_timings_table.php
  83. 3 1
      database/migrations/2020_11_19_113955_change_order_issue_type_id_index.php
  84. 2 2
      database/migrations/2020_11_30_140958_create_stations_table.php
  85. 4 4
      database/migrations/2020_11_30_142430_create_station_task_batches_table.php
  86. 33 0
      database/migrations/2020_11_30_151800_create_station_task_batch_types_table.php
  87. 3 3
      database/migrations/2020_11_30_155713_create_station_task_material_boxes_table.php
  88. 4 4
      database/migrations/2020_11_30_174327_create_station_task_commodities_table.php
  89. 32 0
      database/migrations/2020_12_01_134905_add_order_type_to_orders.php
  90. 27 0
      database/migrations/2020_12_01_150439_change_batch_field_status_add_executing.php
  91. 52 0
      database/migrations/2020_12_02_150054_create_order_commodity_assigns_table.php
  92. 38 0
      database/migrations/2020_12_03_114353_add_auth_of_station.php
  93. 4 3
      database/migrations/2020_12_04_160314_create_station_task_types_table.php
  94. 34 0
      database/migrations/2020_12_04_175932_create_station_tasks_table.php
  95. 16 0
      database/seeds/StationTaskSeeder.php
  96. 16 0
      database/seeds/StationTaskTypeSeeder.php
  97. 2 2
      phpunit.xml
  98. 5 0
      resources/views/layouts/menu.blade.php
  99. 19 0
      resources/views/maintenance/log/_taskModal.blade.php
  100. 6 4
      resources/views/maintenance/log/index.blade.php

+ 3 - 2
app/Console/Commands/CreateOwnerBillReport.php

@@ -46,7 +46,8 @@ class CreateOwnerBillReport extends Command
             $year--;
             $lastMonth = '12';
         }else $lastMonth = ($month-1) < 10 ? "0".($month-1) : ($month-1);
-        $bills = DB::select(DB::raw("select owner_id,SUM(work_fee)+SUM(logistic_fee) as total from owner_fee_details where worked_at like ? GROUP BY owner_id"),[$year."-".$lastMonth."%"]);
+        $sql = "SELECT owner_id,SUM(work_fee)+SUM(logistic_fee) AS total FROM owner_fee_details WHERE worked_at LIKE ? AND (type = '发货' AND logistic_fee IS NOT NULL AND work_fee IS NOT NULL) OR (type <> '发货' AND work_fee IS NOT NULL)  GROUP BY owner_id";
+        $billDetails = DB::select(DB::raw($sql),[$year."-".$lastMonth."%"]);
 
         $areas = OwnerAreaReport::query()->with("ownerStoragePriceModel")->where("counting_month","like",$year."-".$lastMonth."%")->get();
         $map = [];
@@ -62,7 +63,7 @@ class CreateOwnerBillReport extends Command
             }
         }
 
-        $chunks = array_chunk($bills,50);
+        $chunks = array_chunk($billDetails,50);
         foreach ($chunks as $bills){
             $date = date('Y-m-d H:i:s');
             $createOwnerBillReport = [];

+ 2 - 0
app/Console/Commands/SyncBatchTask.php

@@ -138,6 +138,8 @@ class SyncBatchTask extends Command
                 }
             }
         }
+//        $this->batchService->assignTasks($batches);
+
 
         ValueStore::query()->where("name","wave_last_sync_date")->update(["value"=>Carbon::now()->subSeconds(1)->toDateTimeString()]);
     }

+ 16 - 8
app/Console/Commands/SyncWMSOrderTask.php

@@ -38,6 +38,8 @@ class SyncWMSOrderTask extends Command
      */
     public function handle()
     {
+        $is_enabled= config('sync.order_sync.cache_prefix.enabled');
+        if($is_enabled=='false')return;
         $this->syncCreatedOrder();
         $this->syncUpdatedOrder();
     }
@@ -52,24 +54,27 @@ class SyncWMSOrderTask extends Command
         $newest_list    = config('sync.order_sync.cache_prefix.newest_list');
         $hasKey         = config('sync.order_sync.cache_prefix.newest_has');
         $prefixKey      = config('sync.order_sync.cache_prefix.newest');
-
+        ini_set('memory_limit', '512M');
         $orderService = app('OrderService');
         $oracleDOCOrderHeaderService = app('OracleDocOrderHeaderService');
 
-        $last_date = $orderService->getOrderSyncAt($newest,'newest');                              // 获取时间点
-        $orderHeaders = $oracleDOCOrderHeaderService->getWMSOrderOnStartDate($last_date);           // WMS订单
-        if(!$orderHeaders)return;
+        $last_date = $orderService->getOrderSyncAt($newest,'newest');                             // 获取时间点
+
+        $orderHeaders = $oracleDOCOrderHeaderService->getWMSOrderOnStartDate($last_date);               // WMS订单
+        if($orderHeaders->count()==0)return;
         $last_order = $orderHeaders->first();                                                           // 时间点靠后的
-        $renewal_orders = $orderHeaders->where('addtime',$last_order->addtime);
+        $newest_orders = $orderHeaders->where('addtime',$last_order->addtime);
 
         $orderHeaders = $orderService->filterOrderByCache($orderHeaders,$newest_list);                  // 对比缓存
 
-        if(count($orderHeaders)>0 && count($orderHeaders) >0){
+        if(count($newest_orders)>0 && count($orderHeaders) >0){
+
             $orderService->syncOrder($orderHeaders);                                                //  同步订单
             $orderService->cancelOrderCache($newest_list,$prefixKey);                                   //  清除缓存
-            $orderService->pushOrderCache($renewal_orders,$prefixKey,$hasKey,$newest_list);             //  添加缓存
+            $orderService->pushOrderCache($newest_orders,$prefixKey,$hasKey,$newest_list);              //  添加缓存
             $orderService->setOrderSyncAt($newest,$last_order->addtime,count($orderHeaders)>0);   //  更新时间
         }
+
     }
 
     public function syncUpdatedOrder()
@@ -82,20 +87,23 @@ class SyncWMSOrderTask extends Command
         $renewal_list   = config('sync.order_sync.cache_prefix.renewal_list');
         $hasKey         = config('sync.order_sync.cache_prefix.renewal_has');
         $prefixKey      = config('sync.order_sync.cache_prefix.renewal');
+        ini_set('memory_limit', '512M');
 
         $orderService = app('OrderService');
         $oracleDOCOrderHeaderService = app('OracleDocOrderHeaderService');
 
         $last_date = $orderService->getOrderSyncAt($renewal,'renewal');                               // 获取时间点
+
         $orderHeaders = $oracleDOCOrderHeaderService->getWMSOrderOnEditDate($last_date);                   // WMS订单
 
-        if(!$orderHeaders)return;
+        if($orderHeaders->count()==0)return;
         $renewal_order = $orderHeaders->first();                                                            // 时间点靠后的
         $renewal_orders =  $orderHeaders->where('edittime',$renewal_order->edittime);
 
         $orderHeaders = $orderService->filterOrderByCache($orderHeaders,$renewal_list);                     // 对比缓存
 
         if(count($renewal_orders)>0 && count($orderHeaders)>0){
+
             $orderService->syncOrder($orderHeaders);                                                    // 同步订单
             $orderService->cancelOrderCache($renewal_list,$prefixKey);                                      // 清除缓存
             $orderService->pushOrderCache($renewal_orders,$prefixKey,$hasKey,$renewal_list);                // 添加缓存

+ 8 - 17
app/Http/Controllers/LogController.php

@@ -7,6 +7,7 @@ use App\Services\LogService;
 use Exception;
 use Illuminate\Contracts\Foundation\Application;
 use Illuminate\Contracts\Pagination\LengthAwarePaginator;
+use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
 use Illuminate\Http\Response;
@@ -34,7 +35,8 @@ class LogController extends Controller
             !$request->has('created_at_end') &&
             !$request->has('operation') &&
             !$request->has('type') &&
-            !$request->has('description')
+            !$request->has('description') &&
+            !$request->has("is_exception")
         ) {
             $logs = Log::query()
                 ->orderBy('id', 'desc')
@@ -65,6 +67,11 @@ class LogController extends Controller
         if ($request->has('created_at_end')) {
             $query->where('created_at', '<=', $request->created_at_end);
         }
+        if ($request->has("is_exception")){
+            $query->where(function(Builder $query){
+                $query->where("type","like","ERROR%")->orWhere("type","like","EXCEPTION%");
+            });
+        }
         $query->orderByDesc('id');
         $logs = $query->paginate($request->paginate??50);
         return view('maintenance.log.index', ['logs' => $logs]);
@@ -81,22 +88,6 @@ class LogController extends Controller
         return view('maintenance.log.show', ['log' => $log]);
     }
 
-
-    /**
-     * Remove the specified resource from storage.
-     *
-     * @param Log $log
-     * @return array|Response
-     * @throws Exception
-     */
-    public function destroy(Log $log)
-    {
-//        if(!Gate::allows('物流公司-删除')){ return redirect(url('/'));  }
-//        app('LogService')->log(__METHOD__,__FUNCTION__,$log->toJson(),Auth::user()['id']);
-//        $re=$log->delete();
-//        return ['success'=>$re];
-    }
-
     public function syncRedisLogs()
     {
         LogService::syncRedisLogs();

+ 35 - 0
app/Http/Controllers/OrderCommodityAssignController.php

@@ -0,0 +1,35 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\Imports\UpdatePickZone;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Gate;
+use Maatwebsite\Excel\Facades\Excel;
+
+class OrderCommodityAssignController extends Controller
+{
+    public function index()
+    {
+        if(!Gate::allows('商品配置-查询')){ return redirect(url('denied'));  }
+        $assigns = app("OrderCommodityAssignService")->paginate();
+        return view("order.index.index",compact("assigns"));
+    }
+
+    public function import(Request $request)
+    {
+        if(!Gate::allows('商品配置-编辑')){ return ["success"=>false,"data"=>"无权操作!"];  }
+        $fileSuffix=$request->file('file')->getClientOriginalExtension();
+        if ($fileSuffix != 'xlsx' && $fileSuffix != 'xls' && $fileSuffix != 'csv')
+            return ['success'=>false,'data'=>'不支持该文件类型'];
+        ini_set('max_execution_time',2500);
+        ini_set('memory_limit','1526M');
+        $fileSuffix = ucwords($fileSuffix);
+
+        Excel::import(new UpdatePickZone(),$request->file('file')->path(),null,$fileSuffix);
+        if (Cache::has('commodityAssign'))return Cache::pull('commodityAssign');
+
+        return ["success"=>false,"data"=>"导入发生错误,数据无响应"];
+    }
+}

+ 10 - 10
app/Http/Controllers/StationMissionBatchController.php → app/Http/Controllers/StationTaskBatchController.php

@@ -2,10 +2,10 @@
 
 namespace App\Http\Controllers;
 
-use App\StationMissionBatch;
+use App\StationTaskBatch;
 use Illuminate\Http\Request;
 
-class StationMissionBatchController extends Controller
+class StationTaskBatchController extends Controller
 {
     /**
      * Display a listing of the resource.
@@ -41,10 +41,10 @@ class StationMissionBatchController extends Controller
     /**
      * Display the specified resource.
      *
-     * @param  \App\StationMissionBatch  $stationMissionBatch
+     * @param  \App\StationTaskBatch  $stationMissionBatch
      * @return \Illuminate\Http\Response
      */
-    public function show(StationMissionBatch $stationMissionBatch)
+    public function show(StationTaskBatch $stationMissionBatch)
     {
         //
     }
@@ -52,10 +52,10 @@ class StationMissionBatchController extends Controller
     /**
      * Show the form for editing the specified resource.
      *
-     * @param  \App\StationMissionBatch  $stationMissionBatch
+     * @param  \App\StationTaskBatch  $stationMissionBatch
      * @return \Illuminate\Http\Response
      */
-    public function edit(StationMissionBatch $stationMissionBatch)
+    public function edit(StationTaskBatch $stationMissionBatch)
     {
         //
     }
@@ -64,10 +64,10 @@ class StationMissionBatchController extends Controller
      * Update the specified resource in storage.
      *
      * @param  \Illuminate\Http\Request  $request
-     * @param  \App\StationMissionBatch  $stationMissionBatch
+     * @param  \App\StationTaskBatch  $stationMissionBatch
      * @return \Illuminate\Http\Response
      */
-    public function update(Request $request, StationMissionBatch $stationMissionBatch)
+    public function update(Request $request, StationTaskBatch $stationMissionBatch)
     {
         //
     }
@@ -75,10 +75,10 @@ class StationMissionBatchController extends Controller
     /**
      * Remove the specified resource from storage.
      *
-     * @param  \App\StationMissionBatch  $stationMissionBatch
+     * @param  \App\StationTaskBatch  $stationMissionBatch
      * @return \Illuminate\Http\Response
      */
-    public function destroy(StationMissionBatch $stationMissionBatch)
+    public function destroy(StationTaskBatch $stationMissionBatch)
     {
         //
     }

+ 10 - 10
app/Http/Controllers/StationMissionBatchTypeController.php → app/Http/Controllers/StationTaskBatchTypeController.php

@@ -2,10 +2,10 @@
 
 namespace App\Http\Controllers;
 
-use App\StationMissionBatchType;
+use App\StationTaskBatchType;
 use Illuminate\Http\Request;
 
-class StationMissionBatchTypeController extends Controller
+class StationTaskBatchTypeController extends Controller
 {
     /**
      * Display a listing of the resource.
@@ -41,10 +41,10 @@ class StationMissionBatchTypeController extends Controller
     /**
      * Display the specified resource.
      *
-     * @param  \App\StationMissionBatchType  $stationMissionBatchType
+     * @param  \App\StationTaskBatchType  $stationMissionBatchType
      * @return \Illuminate\Http\Response
      */
-    public function show(StationMissionBatchType $stationMissionBatchType)
+    public function show(StationTaskBatchType $stationMissionBatchType)
     {
         //
     }
@@ -52,10 +52,10 @@ class StationMissionBatchTypeController extends Controller
     /**
      * Show the form for editing the specified resource.
      *
-     * @param  \App\StationMissionBatchType  $stationMissionBatchType
+     * @param  \App\StationTaskBatchType  $stationMissionBatchType
      * @return \Illuminate\Http\Response
      */
-    public function edit(StationMissionBatchType $stationMissionBatchType)
+    public function edit(StationTaskBatchType $stationMissionBatchType)
     {
         //
     }
@@ -64,10 +64,10 @@ class StationMissionBatchTypeController extends Controller
      * Update the specified resource in storage.
      *
      * @param  \Illuminate\Http\Request  $request
-     * @param  \App\StationMissionBatchType  $stationMissionBatchType
+     * @param  \App\StationTaskBatchType  $stationMissionBatchType
      * @return \Illuminate\Http\Response
      */
-    public function update(Request $request, StationMissionBatchType $stationMissionBatchType)
+    public function update(Request $request, StationTaskBatchType $stationMissionBatchType)
     {
         //
     }
@@ -75,10 +75,10 @@ class StationMissionBatchTypeController extends Controller
     /**
      * Remove the specified resource from storage.
      *
-     * @param  \App\StationMissionBatchType  $stationMissionBatchType
+     * @param  \App\StationTaskBatchType  $stationMissionBatchType
      * @return \Illuminate\Http\Response
      */
-    public function destroy(StationMissionBatchType $stationMissionBatchType)
+    public function destroy(StationTaskBatchType $stationMissionBatchType)
     {
         //
     }

+ 10 - 10
app/Http/Controllers/StationMissionCommodityController.php → app/Http/Controllers/StationTaskCommodityController.php

@@ -2,10 +2,10 @@
 
 namespace App\Http\Controllers;
 
-use App\StationMissionCommodity;
+use App\StationTaskCommodity;
 use Illuminate\Http\Request;
 
-class StationMissionCommodityController extends Controller
+class StationTaskCommodityController extends Controller
 {
     /**
      * Display a listing of the resource.
@@ -41,10 +41,10 @@ class StationMissionCommodityController extends Controller
     /**
      * Display the specified resource.
      *
-     * @param  \App\StationMissionCommodity  $stationMissionCommodity
+     * @param  \App\StationTaskCommodity  $stationMissionCommodity
      * @return \Illuminate\Http\Response
      */
-    public function show(StationMissionCommodity $stationMissionCommodity)
+    public function show(StationTaskCommodity $stationMissionCommodity)
     {
         //
     }
@@ -52,10 +52,10 @@ class StationMissionCommodityController extends Controller
     /**
      * Show the form for editing the specified resource.
      *
-     * @param  \App\StationMissionCommodity  $stationMissionCommodity
+     * @param  \App\StationTaskCommodity  $stationMissionCommodity
      * @return \Illuminate\Http\Response
      */
-    public function edit(StationMissionCommodity $stationMissionCommodity)
+    public function edit(StationTaskCommodity $stationMissionCommodity)
     {
         //
     }
@@ -64,10 +64,10 @@ class StationMissionCommodityController extends Controller
      * Update the specified resource in storage.
      *
      * @param  \Illuminate\Http\Request  $request
-     * @param  \App\StationMissionCommodity  $stationMissionCommodity
+     * @param  \App\StationTaskCommodity  $stationMissionCommodity
      * @return \Illuminate\Http\Response
      */
-    public function update(Request $request, StationMissionCommodity $stationMissionCommodity)
+    public function update(Request $request, StationTaskCommodity $stationMissionCommodity)
     {
         //
     }
@@ -75,10 +75,10 @@ class StationMissionCommodityController extends Controller
     /**
      * Remove the specified resource from storage.
      *
-     * @param  \App\StationMissionCommodity  $stationMissionCommodity
+     * @param  \App\StationTaskCommodity  $stationMissionCommodity
      * @return \Illuminate\Http\Response
      */
-    public function destroy(StationMissionCommodity $stationMissionCommodity)
+    public function destroy(StationTaskCommodity $stationMissionCommodity)
     {
         //
     }

+ 85 - 0
app/Http/Controllers/StationTaskController.php

@@ -0,0 +1,85 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\StationTask;
+use Illuminate\Http\Request;
+
+class StationTaskController extends Controller
+{
+    /**
+     * Display a listing of the resource.
+     *
+     * @return \Illuminate\Http\Response
+     */
+    public function index()
+    {
+        //
+    }
+
+    /**
+     * Show the form for creating a new resource.
+     *
+     * @return \Illuminate\Http\Response
+     */
+    public function create()
+    {
+        //
+    }
+
+    /**
+     * Store a newly created resource in storage.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return \Illuminate\Http\Response
+     */
+    public function store(Request $request)
+    {
+        //
+    }
+
+    /**
+     * Display the specified resource.
+     *
+     * @param  \App\StationTask  $stationTask
+     * @return \Illuminate\Http\Response
+     */
+    public function show(StationTask $stationTask)
+    {
+        //
+    }
+
+    /**
+     * Show the form for editing the specified resource.
+     *
+     * @param  \App\StationTask  $stationTask
+     * @return \Illuminate\Http\Response
+     */
+    public function edit(StationTask $stationTask)
+    {
+        //
+    }
+
+    /**
+     * Update the specified resource in storage.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  \App\StationTask  $stationTask
+     * @return \Illuminate\Http\Response
+     */
+    public function update(Request $request, StationTask $stationTask)
+    {
+        //
+    }
+
+    /**
+     * Remove the specified resource from storage.
+     *
+     * @param  \App\StationTask  $stationTask
+     * @return \Illuminate\Http\Response
+     */
+    public function destroy(StationTask $stationTask)
+    {
+        //
+    }
+}

+ 10 - 10
app/Http/Controllers/StationMissionMaterialBoxController.php → app/Http/Controllers/StationTaskMaterialBoxController.php

@@ -2,10 +2,10 @@
 
 namespace App\Http\Controllers;
 
-use App\StationMissionMaterialBox;
+use App\StationTaskMaterialBox;
 use Illuminate\Http\Request;
 
-class StationMissionMaterialBoxController extends Controller
+class StationTaskMaterialBoxController extends Controller
 {
     /**
      * Display a listing of the resource.
@@ -41,10 +41,10 @@ class StationMissionMaterialBoxController extends Controller
     /**
      * Display the specified resource.
      *
-     * @param  \App\StationMissionMaterialBox  $stationMissionMaterialBox
+     * @param  \App\StationTaskMaterialBox  $stationMissionMaterialBox
      * @return \Illuminate\Http\Response
      */
-    public function show(StationMissionMaterialBox $stationMissionMaterialBox)
+    public function show(StationTaskMaterialBox $stationMissionMaterialBox)
     {
         //
     }
@@ -52,10 +52,10 @@ class StationMissionMaterialBoxController extends Controller
     /**
      * Show the form for editing the specified resource.
      *
-     * @param  \App\StationMissionMaterialBox  $stationMissionMaterialBox
+     * @param  \App\StationTaskMaterialBox  $stationMissionMaterialBox
      * @return \Illuminate\Http\Response
      */
-    public function edit(StationMissionMaterialBox $stationMissionMaterialBox)
+    public function edit(StationTaskMaterialBox $stationMissionMaterialBox)
     {
         //
     }
@@ -64,10 +64,10 @@ class StationMissionMaterialBoxController extends Controller
      * Update the specified resource in storage.
      *
      * @param  \Illuminate\Http\Request  $request
-     * @param  \App\StationMissionMaterialBox  $stationMissionMaterialBox
+     * @param  \App\StationTaskMaterialBox  $stationMissionMaterialBox
      * @return \Illuminate\Http\Response
      */
-    public function update(Request $request, StationMissionMaterialBox $stationMissionMaterialBox)
+    public function update(Request $request, StationTaskMaterialBox $stationMissionMaterialBox)
     {
         //
     }
@@ -75,10 +75,10 @@ class StationMissionMaterialBoxController extends Controller
     /**
      * Remove the specified resource from storage.
      *
-     * @param  \App\StationMissionMaterialBox  $stationMissionMaterialBox
+     * @param  \App\StationTaskMaterialBox  $stationMissionMaterialBox
      * @return \Illuminate\Http\Response
      */
-    public function destroy(StationMissionMaterialBox $stationMissionMaterialBox)
+    public function destroy(StationTaskMaterialBox $stationMissionMaterialBox)
     {
         //
     }

+ 85 - 0
app/Http/Controllers/StationTaskTypeController.php

@@ -0,0 +1,85 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\StationTaskType;
+use Illuminate\Http\Request;
+
+class StationTaskTypeController extends Controller
+{
+    /**
+     * Display a listing of the resource.
+     *
+     * @return \Illuminate\Http\Response
+     */
+    public function index()
+    {
+        //
+    }
+
+    /**
+     * Show the form for creating a new resource.
+     *
+     * @return \Illuminate\Http\Response
+     */
+    public function create()
+    {
+        //
+    }
+
+    /**
+     * Store a newly created resource in storage.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return \Illuminate\Http\Response
+     */
+    public function store(Request $request)
+    {
+        //
+    }
+
+    /**
+     * Display the specified resource.
+     *
+     * @param  \App\StationTaskType  $stationTaskType
+     * @return \Illuminate\Http\Response
+     */
+    public function show(StationTaskType $stationTaskType)
+    {
+        //
+    }
+
+    /**
+     * Show the form for editing the specified resource.
+     *
+     * @param  \App\StationTaskType  $stationTaskType
+     * @return \Illuminate\Http\Response
+     */
+    public function edit(StationTaskType $stationTaskType)
+    {
+        //
+    }
+
+    /**
+     * Update the specified resource in storage.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  \App\StationTaskType  $stationTaskType
+     * @return \Illuminate\Http\Response
+     */
+    public function update(Request $request, StationTaskType $stationTaskType)
+    {
+        //
+    }
+
+    /**
+     * Remove the specified resource from storage.
+     *
+     * @param  \App\StationTaskType  $stationTaskType
+     * @return \Illuminate\Http\Response
+     */
+    public function destroy(StationTaskType $stationTaskType)
+    {
+        //
+    }
+}

+ 7 - 1
app/Http/Controllers/StoreCheckingReceiveController.php

@@ -390,7 +390,7 @@ class StoreCheckingReceiveController extends Controller
         if(!Gate::allows('入库管理-盘收一体-盘收-编辑')){ return ['success'=>false, 'data'=>'无权操作!'];  }
         $id = $request->id ?? null;
         $counted_amount = $request->counted_amount ?? null;
-        if (!$id || !$counted_amount)return ['success'=>false, 'data'=>'参数传递错误!'];
+        if (!$id)return ['success'=>false, 'data'=>'参数传递错误!'];
         $item = app('StoreCheckingReceiveItemService')->find($id);
         if (!$item)return ['success'=>false, 'data'=>'被盘项不存在'];
         $params = ["counted_amount"=>$counted_amount];
@@ -435,4 +435,10 @@ class StoreCheckingReceiveController extends Controller
             app('LogService')->log(__METHOD__,"修改差异状态",json_encode($scr,JSON_UNESCAPED_UNICODE));
         }
     }
+
+    public function destroyItem(Request $request)
+    {
+        if (app("StoreCheckingReceiveItemService")->destroy($request->input("id")))return ["success"=>true];
+        return ["success"=>false,"data"=>"删除失败"];
+    }
 }

+ 10 - 23
app/Http/Controllers/TestController.php

@@ -47,12 +47,11 @@ use App\Services\OrderService;
 use App\Services\OrderTrackingOwnerService;
 use App\Services\OrderTrackingService;
 use App\Services\OwnerService;
-use App\Services\ProvinceService;
+use App\Services\ShopService;
 use App\Services\StoreService;
 use App\Services\WarehouseService;
 use App\StoreCheckingReceiveItem;
 use App\User;
-use App\ValueStore;
 use App\Warehouse;
 use App\Waybill;
 use App\WaybillPriceModel;
@@ -143,16 +142,14 @@ class TestController extends Controller
         }
     }
 
-    private function dd()
+    public function test4(){
+        $arr=[['id'=>3],['id'=>33],];
+        dd(data_get($arr,'*.id'));
+    }
+    public function t($a)
     {
-        StoreCheckingReceiveItem::query()->insert([[
-            "imported_amount" => 1,
-            "produced_at" => null,
-            "invalid_at" => null,
-            "batch_code" => null,
-            "unique_code" => null,
-            "commodity_id" => 36,
-            "store_checking_receive_id" => 2]]);
+        $r = new \ReflectionClass('App\Http\Controllers\UnitsController');
+        dd($r->getMethods(),$r->getConstants());
     }
 
     public function updateLaborRemark(){
@@ -177,17 +174,6 @@ class TestController extends Controller
         }
     }
     public function test2(){
-        $b = Logistic::query()->first();
-        $a = OrderPackage::query()->with("order")->first();
-        $a->bulk = 521;
-        $a->save();
-        if (!$a->order) $a->order = new Order();
-        dd($a);
-        if (!$a->order->logistic)$a->order->logistic = $b;
-        dd($a->order->logistic);
-        dd($a);
-        $a->save();
-        dd($a);
     }
 
     function packageFromLog(Request $request)
@@ -1210,9 +1196,10 @@ where (commodities.owner_id,commodity_barcodes.code) in (select commodities.owne
     }
 
     public function OrderSync(){
+        dump(Carbon::now());
         $tack = new SyncWMSOrderTask();
         $tack->handle();
-        dump(11);
+        dump(Carbon::now());
     }
 
     public function testSyncCommodity(){

+ 27 - 0
app/Http/Controllers/api/thirdPart/haiq/LightController.php

@@ -0,0 +1,27 @@
+<?php
+
+
+namespace App\Http\Controllers\api\thirdPart\haiq;
+
+
+
+
+use App\Services\ForeignHaiRoboticsService;
+use Illuminate\Http\Request;
+
+class LightController
+{
+    protected $request;
+
+    /** @var ForeignHaiRoboticsService $service */
+    private $service;
+    public function __construct(){
+        $this->service=app('ForeignHaiRoboticsService');
+    }
+
+    public function lightOn(Request $request){
+    }
+    public function lightOff(Request $request){
+    }
+
+}

+ 9 - 4
app/Http/Controllers/api/thirdPart/haiq/PickStationController.php

@@ -6,19 +6,24 @@ namespace App\Http\Controllers\api\thirdPart\haiq;
 
 
 
+use App\Services\ForeignHaiRoboticsService;
 use Illuminate\Http\Request;
 
 class PickStationController
 {
-    protected $request;
 
-    public function __construct()
-    {
+    /** @var ForeignHaiRoboticsService $service */
+    private $service;
+    public function __construct(){
+        $this->service=app('ForeignHaiRoboticsService');
     }
 
     public function processed(Request $request){
         $success = $request->input('success');
-        $code= $success?200:0;
+        $code = $success?200:0;
+        $this->service->markBinProcessed();
+        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->all()));
         return ['code'=>$code,'errMsg'=>'','data'=>$request->all()];
     }
+
 }

+ 24 - 7
app/Http/Controllers/api/thirdPart/haiq/StorageController.php

@@ -4,16 +4,20 @@
 namespace App\Http\Controllers\api\thirdPart\haiq;
 
 
+use App\Services\ForeignHaiRoboticsService;
 use App\Services\LogService;
+use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Http;
-use Illuminate\Support\Facades\Request;
 
 class StorageController
 {
     protected $request;
 
+    /** @var ForeignHaiRoboticsService $service */
+    private $service;
     public function __construct()
     {
+        $this->service=app('ForeignHaiRoboticsService');
         $stockInfo = [
             "skuCode" => "TEST-BSSKU",//商品编码 sku
             "qty" => 9,//数量
@@ -34,12 +38,12 @@ class StorageController
             "bins" => [$bin],//可执行货箱任务
         ]];*/
         $this->request = [[
-            "taskMode"      => 8,
+            "taskMode"      => 2,
             "bins"=>[[
                 "taskCode"  =>"TEST-BS2011160004",
-                "binCode"   => "TESTBINCODE-0",
-                "fromLocCode" => "BIN-IN1",
-                //"toLocCode" => "BIN-OUT1",
+                "binCode"   => "IDE0000034",
+//                "fromLocCode" => "BIN-IN1",
+                "toLocCode" => "BIN-OUT1",
             ]],
             "groupCode"     => 4,
             "priority"      => 20,
@@ -48,10 +52,10 @@ class StorageController
     }
 
     public function relocate(Request $request){
-        $response = Http::post(config('api.haiq.storage.relocate'),$this->request);return $response;
+        $response = Http::post(config('api.haiq.storage.moveBin'),$this->request);
         if (!$response->ok()){
             app('LogService')->log(__METHOD__,"haiq-请求失败,路径异常","REQUEST:".json_encode($this->request)." | RESPONSE:".$response);
-            return ['success'=>false,"data"=>"接口异常"];
+            return ['success'=>false,"data"=>$response->body()];
         }
         if (($response["code"] ?? false) && $response["code"] != 200){
             app('LogService')->log(__METHOD__,"haiq-料箱出库失败","REQUEST:".json_encode($this->request)." | RESPONSE:".$response);
@@ -64,4 +68,17 @@ class StorageController
         app('LogService')->log(__METHOD__,"haiq-料箱出库成功","REQUEST:".json_encode($this->request)." | RESPONSE:".$response);
         return ["success"=>true];
     }
+    public function moveBin(Request $request){
+
+    }
+    public function taskUpdate(Request $request){
+        $this->service->taskUpdate();
+        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->all()));
+        return ['code'=>200,'errMsg'=>'','data'=>$request->all()];
+    }
+    public function exception(Request $request){
+        $this->service->taskUpdate();
+        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->all()));
+        return ['code'=>200,'errMsg'=>'','data'=>$request->all()];
+    }
 }

+ 153 - 0
app/Imports/UpdatePickZone.php

@@ -0,0 +1,153 @@
+<?php
+
+namespace App\Imports;
+
+use App\OracleDOCOrderDetail;
+use App\Services\LogService;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\Auth;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\DB;
+use Maatwebsite\Excel\Concerns\ToCollection;
+use Maatwebsite\Excel\Concerns\WithHeadingRow;
+use Maatwebsite\Excel\Imports\HeadingRowFormatter;
+
+HeadingRowFormatter::default('none');
+class UpdatePickZone implements ToCollection,WithHeadingRow
+{
+    /**
+    * @param Collection $collection
+    * @return bool
+    * @throws
+    */
+    public function collection(Collection $collection)
+    {
+        $row = $collection->first();
+        $headers = ["订单编号","商品条码","数量","生产日期","失效日期"];
+        foreach ($headers as $header){
+            if (!isset($row[$header])){
+                Cache::put("commodityAssign",["success"=>false, "data"=>"表头不存在“".$header."”"],86400);
+                return false;
+            }
+        }
+
+        $errors = [];
+        $ids = [];
+        foreach ($collection as $index=>$item){
+            if ($item["生产日期"]) $item["生产日期"] = formatExcelDate($item["生产日期"]);
+            if ($item["失效日期"]) $item["失效日期"] = formatExcelDate($item["失效日期"]);
+
+            if (!$item["订单编号"]){
+                $errors[] = "第“" . ($index + 2) . "”行订单编号为空";
+                continue;
+            }
+            if (!$item["商品条码"]){
+                $errors[] = "第“" . ($index + 2) . "”行商品条码为空";
+                continue;
+            }
+            if (!$item["生产日期"] && !$item["失效日期"]){
+                $errors[] = "第“" . ($index + 2) . "”行不存在日期";
+                continue;
+            }
+            $detail = OracleDOCOrderDetail::query()->select("customerid","sku")
+                ->where("orderno",$item["订单编号"])
+                ->whereHas("sku",function ($query)use($item){
+                    /** @var Builder $query */
+                    $query->where("alternate_sku1",$item["商品条码"]);
+                })->first();
+            if (!$detail){
+                $errors[] = "第“" . ($index + 2) . "”行未知订单商品";
+                continue;
+            }
+            $sql = "select INV_LOT_LOC_ID.LOCATIONID,INV_LOT_LOC_ID.LOTNUM,BAS_LOCATION.PICKZONE,INV_LOT_LOC_ID.QTY from INV_LOT_ATT LEFT JOIN
+                        INV_LOT_LOC_ID ON INV_LOT_ATT.LOTNUM = INV_LOT_LOC_ID.LOTNUM LEFT JOIN BAS_LOCATION ON INV_LOT_LOC_ID.LOCATIONID = BAS_LOCATION.LOCATIONID
+                    where INV_LOT_ATT.LOTNUM in (select LOTNUM from INV_LOT_LOC_ID where CUSTOMERID = ? AND SKU = ? GROUP BY LOTNUM)";
+            $bindings = [$detail->customerid,$detail->sku];
+            if ($item["生产日期"]){
+                $sql .= " AND LOTATT01 = ?";
+                $bindings[] = $item["生产日期"];
+            }else $sql .= " AND LOTATT01 IS NULL";
+            if ($item["失效日期"]){
+                $sql .= " AND LOTATT02 = ?";
+                $bindings[] = $item["失效日期"];
+            }else $sql .= " AND LOTATT02 IS NULL";
+
+            $lot = DB::connection("oracle")->select(DB::raw($sql),$bindings);
+            if (!$lot){
+                $errors[] = "第“" . ($index + 2) . "”行未找到库位";
+                continue;
+            }
+            $result = null;
+            if (count($lot)>1){
+                $min = null;
+                $max = null;
+                $map = [];
+                foreach ($lot as $i => $l){
+                    $qty = (int)$l->quty;
+                    $map[$qty] = $i;
+                    if ($qty >= (int)$item["数量"] && $qty<=$max)$max = $qty;
+                    if ($qty < (int)$item["数量"] && $qty>=$min)$min = $qty;
+                }
+                if ($max !== null)$result = $lot[$map[$max]];
+                else $result = $lot[$map[$min]];
+            }
+            if (count($lot) == 1)$result = $lot[0];
+            if ($result){dd($result);
+                try{
+                    $detail->update([
+                        "lotnum" => $result->lotnum,
+                        "pickzone" => $result->pickzone,
+                        "kitreferenceno" => '0',
+                        "d_edi_09" => '0',
+                        "d_edi_10" => '0',
+                    ]);
+                    DB::connection("oracle")->commit();
+                    LogService::log(__METHOD__,"SUCCESS-指定效期分配修改库位",json_encode($detail)." | ".json_encode($result));
+                    $order = app("OrderService")->first(["code"=>$item["订单编号"]]);
+                    if (!$order){
+                        $errors[] = "第“" . ($index + 2) . "”行已成功修改FLUX库位但在本地未找到订单";
+                        continue;
+                    }
+                    $barcode = app("CommodityBarcodeService")->first(["code"=>$item["商品条码"]]);
+                    if (!$barcode){
+                        $errors[] = "第“" . ($index + 2) . "”行已成功修改FLUX库位但在本地未找到条码";
+                        continue;
+                    }
+                    $model = app("OrderCommodityAssignService")->create([
+                        "order_id"      =>  1,//$order->id,
+                        "commodity_id"  =>  1,//$barcode->commodity_id,
+                        "amount"        =>  $item["数量"],
+                        "produced_at"   =>  $item["生产日期"],
+                        "valid_at"      =>  $item["失效日期"],
+                        "batch_number"  =>  $result->lotnum,
+                        "location"      =>  $result->locationid,
+                        "region"        =>  $result->pickzone,
+                        "user_id"       =>  Auth::id(),
+                    ]);
+                    LogService::log(__METHOD__,"SUCCESS-生成配置记录",json_encode($model));
+                    $ids[] = $model->id;
+                }catch (\Exception $e){
+                    LogService::log(__METHOD__,"ERROR-指定效期分配修改库位",json_encode($detail)." | ".json_encode($result));
+                }
+            }else $errors[] = "第“" . ($index + 2) . "”行未找到可分配库位";
+        }
+        $assigns = app("OrderCommodityAssignService")->get(["id"=>$ids]);
+        $models = [];
+        foreach ($assigns as $assign){
+            $models[] = [
+                "orderNumber"   => $assign->order ? $assign->order->code : '',
+                "barcode"       => $assign->commodity ? $assign->commodity->barcode : '',
+                "amount"        => $assign->amount,
+                "producedAt"    => $assign->produced_at,
+                "validAt"       => $assign->valid_at,
+                "batchNumber"   => $assign->batch_number,
+                "location"      => $assign->location,
+                "region"        => $assign->region,
+                "createdAt"     => $assign->created_at,
+                "userName"      => $assign->user ? $assign->user->name : 'system',
+            ];
+        }
+        Cache::put("commodityAssign",["success"=>true,"data"=>$models,"errors"=>$errors]);
+    }
+}

+ 44 - 0
app/Jobs/OrderCreateInstantBill.php

@@ -0,0 +1,44 @@
+<?php
+
+namespace App\Jobs;
+
+use App\Order;
+use App\Services\LogService;
+use App\Services\OrderService;
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
+
+class OrderCreateInstantBill implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+
+
+    protected $order;
+    /**
+     * Create a new job instance.
+     *
+     * @param Order $order
+     * @return void
+     */
+    public function __construct(Order $order)
+    {
+        $this->order = $order;
+    }
+
+    /**
+     *
+     * @param OrderService $service
+     * @return void
+     */
+    public function handle(OrderService $service)
+    {
+        try{
+            $service->createInstantBill($this->order);
+        }catch (\Exception $e){
+            LogService::log(__METHOD__,"ERROR-订单生成即时账单",$this->order->toJson()." | ".$e->getMessage());
+        }
+    }
+}

+ 44 - 0
app/Jobs/ProcessCreateInstantBill.php

@@ -0,0 +1,44 @@
+<?php
+
+namespace App\Jobs;
+
+use App\Process;
+use App\Services\LogService;
+use App\Services\ProcessService;
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
+
+class ProcessCreateInstantBill implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+
+    protected $process;
+    /**
+     * Create a new job instance.
+     *
+     * @param Process $process
+     * @return void
+     */
+    public function __construct(Process $process)
+    {
+        $this->process = $process;
+    }
+
+    /**
+     * Execute the job.
+     *
+     * @param ProcessService $service
+     * @return void
+     */
+    public function handle(ProcessService $service)
+    {
+        try{
+            $service->createInstantBill($this->process);
+        }catch (\Exception $e){
+            LogService::log(__METHOD__,"ERROR-入库生成即时账单",$this->process->toJson()." | ".$e->getMessage());
+        }
+    }
+}

+ 45 - 0
app/Jobs/StoreCreateInstantBill.php

@@ -0,0 +1,45 @@
+<?php
+
+namespace App\Jobs;
+
+use App\Services\LogService;
+use App\Services\StoreService;
+use App\Store;
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
+
+class StoreCreateInstantBill implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+
+
+    protected $store;
+    /**
+     * Create a new job instance.
+     *
+     * @param Store $store
+     * @return void
+     */
+    public function __construct(Store $store)
+    {
+        $this->store = $store;
+    }
+
+    /**
+     * Execute the job.
+     *
+     * @param StoreService $service
+     * @return void
+     */
+    public function handle(StoreService $service)
+    {
+        try{
+            $service->createInstantBill($this->store);
+        }catch (\Exception $e){
+            LogService::log(__METHOD__,"ERROR-入库生成即时账单",$this->store->toJson()." | ".$e->getMessage());
+        }
+    }
+}

+ 7 - 0
app/Log.php

@@ -4,6 +4,7 @@ namespace App;
 
 use Illuminate\Database\Eloquent\Model;
 use App\Traits\ModelTimeFormat;
+use Illuminate\Support\Str;
 
 class Log extends Model
 {
@@ -19,4 +20,10 @@ class Log extends Model
         }
         return '';
     }
+    public function getExceptionMarkAttribute(){
+        if (Str::upper(substr($this->type,0,1)) != 'E')return 'N';
+        if (Str::upper(substr($this->type,0,5)) == 'ERROR' || Str::upper(substr($this->type,0,9)) == 'EXCEPTION')
+            return 'Y';
+        return 'N';
+    }
 }

+ 3 - 0
app/OracleDOCOrderHeader.php

@@ -50,4 +50,7 @@ class OracleDOCOrderHeader extends Model
     public function hasUn(){
         return $this->hasMany('App\OracleDOCOrderDetail','orderno','orderno');
     }
+    public function orderType(){
+        return $this->hasOne('App\OracleBasCode','code','ordertype')->where('codeid','SO_TYP');
+    }
 }

+ 4 - 1
app/Order.php

@@ -14,7 +14,8 @@ class Order extends Model
         'id', 'batch_id',  'owner_id', 'status',
         'created_at', 'code', 'shop_id',  'client_code',
         'logistic_id', 'consignee_name', 'consignee_phone', 'province',
-        'city', 'district', 'address', 'wms_status','warehouse_id','wms_edittime'];
+        'city', 'district', 'address','warehouse_id',
+        'wms_edittime', 'wms_status','order_type'];
 
     /*
      * wms订单号             code=>DOC_ORDER_HEADER[orderno]
@@ -148,6 +149,7 @@ class Order extends Model
             $this['client_code'] = $order['client_code'] &&
             $this['wms_status'] == $order['wms_status'] &&
             $this['wms_edittime'] == $order['wms_edittime'] &&
+            $this['order_type'] == $order['order_type'] &&
             (string)$this['created_at'] == (string)$order['created_at'];
     }
 
@@ -167,6 +169,7 @@ class Order extends Model
         $this['client_code'] = $order['client_code'] ;
         $this['wms_status'] = $order['wms_status'] ;
         $this['wms_edittime'] = $order['wms_edittime'];
+        $this['order_type'] = $order['order_type'];
         $this['created_at'] =$order['created_at'];
     }
 }

+ 33 - 0
app/OrderCommodityAssign.php

@@ -0,0 +1,33 @@
+<?php
+
+namespace App;
+
+use Illuminate\Database\Eloquent\Model;
+
+class OrderCommodityAssign extends Model
+{
+    protected $fillable = [
+        "order_id",         //外键订单
+        "commodity_id",     //外键商品
+        "amount",           //数量  default 0
+        "produced_at",      //生产日期
+        "valid_at",         //失效日期
+        "batch_number",     //批次号
+        "location",         //库位
+        "region",           //库区
+        "user_id",          //操作人
+    ];
+
+    public function order()
+    {   //订单
+        return $this->hasOne(Order::class,"id","order_id");
+    }
+    public function commodity()
+    {   //商品
+        return $this->hasOne(Commodity::class,"id","commodity_id");
+    }
+    public function user()
+    {   //用户
+        return $this->hasOne(User::class,"id","user_id");
+    }
+}

+ 14 - 2
app/Providers/AppServiceProvider.php

@@ -2,9 +2,9 @@
 
 namespace App\Providers;
 
-use App\Customer;
 use App\Http\Controllers\Controller;
 use App\Services\AuthorityService;
+use App\Services\BatchService;
 use App\Services\CacheService;
 use App\Services\CommodityService;
 use App\Services\common\BatchUpdateService;
@@ -13,6 +13,7 @@ use App\Services\common\DataHandlerService;
 use App\Services\CustomerService;
 use App\Services\DepositoryService;
 use App\Services\FeatureService;
+use App\Services\ForeignHaiRoboticsService;
 use App\Services\InventoryAccountMissionService;
 use App\Services\InventoryCompareService;
 use App\Services\LaborReportsCountingRecordService;
@@ -21,8 +22,9 @@ use App\Services\OracleBasCustomerService;
 use App\Services\OracleBasSkuService;
 use App\Services\OracleDocAsnDetailService;
 use App\Services\OracleDOCOrderHeaderService;
+use App\Services\OrderCommodityService;
+use App\Services\OrderCommodityAssignService;
 use App\Services\OrderCountingRecordService;
-use App\Services\OracleDocAsnHerderService;
 use App\Services\OrderIssuePerformanceService;
 use App\Services\AllInventoryService;
 use App\Services\InventoryDailyLogService;
@@ -57,6 +59,9 @@ use App\Services\RejectedBillItemService;
 use App\Services\RejectedBillService;
 use App\Services\ShopService;
 use App\Services\RejectedService;
+use App\Services\StationTaskBatchService;
+use App\Services\StationTaskBatchTypeService;
+use App\Services\StationService;
 use App\Services\StoreCheckingReceiveItemService;
 use App\Services\StoreCheckingReceiveService;
 use App\Services\StoreItemService;
@@ -121,6 +126,7 @@ class AppServiceProvider extends ServiceProvider
     }
 
     private function loadingService(){
+        app()->singleton('BatchService',BatchService::class);
         app()->singleton('CacheService',CacheService::class);
         app()->singleton('UserService',UserService::class);
         app()->singleton('AuthorityService',AuthorityService::class);
@@ -137,6 +143,7 @@ class AppServiceProvider extends ServiceProvider
         app()->singleton('PackageStatisticsService',PackageStatisticsService::class);
         app()->singleton('OracleActAllocationDetailService',OracleActAllocationDetailService::class);
         app()->singleton('ShopService',ShopService::class);
+        app()->singleton('ForeignHaiRoboticsService',ForeignHaiRoboticsService::class);
         app()->singleton('OrderPackageService',OrderPackageService::class);
         app()->singleton('OrderIssueService',OrderIssueService::class);
         app()->singleton('OrderService',OrderService::class);
@@ -153,6 +160,9 @@ class AppServiceProvider extends ServiceProvider
         app()->singleton('InventoryAccountMissionService',InventoryAccountMissionService::class);
         app()->singleton('ProcessesContentService',ProcessesContentService::class);
         app()->singleton('StoreService',StoreService::class);
+        app()->singleton('StationTaskBatchService',StationTaskBatchService::class);
+        app()->singleton('StationTaskBatchTypeService',StationTaskBatchTypeService::class);
+        app()->singleton('StationService',StationService::class);
         app()->singleton('WarehouseService',WarehouseService::class);
         app()->singleton('StoreItemService',StoreItemService::class);
         app()->singleton('PackageService',PackageService::class);
@@ -164,6 +174,7 @@ class AppServiceProvider extends ServiceProvider
         app()->singleton('OwnerPriceExpressService',OwnerPriceExpressService::class);
         app()->singleton('OwnerPriceLogisticService',OwnerPriceLogisticService::class);
         app()->singleton('OwnerPriceDirectLogisticService',OwnerPriceDirectLogisticService::class);
+        app()->singleton('OrderCommodityAssignService',OrderCommodityAssignService::class);
 
         $this->loadingOrderModuleService();
         $this->loadingBasedModuleService();
@@ -185,6 +196,7 @@ class AppServiceProvider extends ServiceProvider
         app()->singleton('OracleDocOrderHeaderService',OracleDOCOrderHeaderService::class);
         app()->singleton('OracleActAllocationDetailService',OracleActAllocationDetailService::class);
         app()->singleton('OrderIssueProcessLogService',OrderIssueProcessLogService::class);
+        app()->singleton('OrderCommodityService',OrderCommodityService::class);
     }
 
     private function loadingBasedModuleService(){

+ 30 - 5
app/Services/BatchService.php

@@ -1,11 +1,18 @@
-<?php 
+<?php
 
-namespace App\Services; 
+namespace App\Services;
 
 use App\Batch;
+use Exception;
 
 Class BatchService
-{ 
+{
+    /** @var StationTaskBatchService $stationTaskBatchService */
+    private $stationTaskBatchService;
+    public function __construct(){
+        $this->stationTaskBatchService=null;
+    }
+
     public function get(array $params)
     {
         $query = Batch::query();
@@ -18,7 +25,25 @@ Class BatchService
 
     public function insert(array $insert)
     {
-        return Batch::query()->insert($insert);
+        $result = Batch::query()->insert($insert);
+        if($result)$this->assignTasks($insert);
+        return $result;
+    }
+
+    public function updateWhereIn($key,$values,$updateKeyValues){
+        Batch::query()->whereIn($key,$values)->update($updateKeyValues);
+    }
+
+    /**
+     * 为波次附加任务,已附加的重复任务不影响
+     * @param Batch[] $batches
+     * @throws Exception
+     */
+    public function assignTasks(array $batches)
+    {
+        $this->stationTaskBatchService=app('StationTaskBatchService');
+        $stationTaskBatches=$this->stationTaskBatchService->createByBatches($batches);
+
     }
 
-}
+}

+ 125 - 3
app/Services/CommodityService.php

@@ -10,6 +10,7 @@ use App\Owner;
 use App\Services\common\BatchUpdateService;
 use App\Services\common\DataHandlerService;
 use App\ValueStore;
+use App\Shop;
 use Carbon\Carbon;
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Collection;
@@ -17,9 +18,14 @@ use Illuminate\Support\Facades\Cache;
 
 Class CommodityService
 {
-    public function firstOrCreate($param, $column = null): Commodity
-    {
-        if ($column) return Commodity::query()->firstOrCreate($param, $column);
+    /** @var CacheService $cacheService */
+    private $cacheService;
+    function __construct(){
+        $this->cacheService=app('CacheService');
+    }
+
+    public function firstOrCreate($param,$column = null):Commodity{
+        if ($column) return Commodity::query()->firstOrCreate($param,$column);
         return Commodity::query()->firstOrCreate($param);
     }
 
@@ -353,6 +359,122 @@ Class CommodityService
         return false;
     }
 
+    public function getCommoditiesByMap($map)
+    {
+        /**
+         * @var OwnerService $ownerService
+         * @var OracleBasSkuService $oracleBasSkuService
+         */
+        $ownerService = app('OwnerService');
+        $oracleBasSkuService = app('OracleBasSkuService');
+
+        $commodities_map = (function()use($map){
+            $commodities_map = [];
+            if(count($map)==0)return $commodities_map;
+            Commodity::query()->with("owner")->whereIn('sku',array_unique(data_get($map,'*.sku')))->whereHas('owner',function($query)use($map){
+                $query->whereIn('code',array_unique(data_get($map,'*.owner_code')));
+            })->get()->each(function($commodity)use(&$commodities_map){
+                $commodities_map[json_encode(['owner_code' => $commodity['owner']['code'], 'sku' => $commodity['sku']])] = $commodity;
+            });
+            return $commodities_map;
+        })();
+
+        $owner_codes = (function()use($map){
+            $owner_codes = [];
+            if(count($map) == 0)return $owner_codes;
+            foreach ($map as $item) {
+                $owner_codes[$item['owner_code']] = $item['owner_code'];
+            }
+            return $owner_codes;
+        })();
+
+        $owner_map = (function()use($ownerService,$owner_codes){
+            $owners = $ownerService->getOwnerByCodes($owner_codes);
+            $map = [];
+            $owners->each(function ($owner)use(&$map){
+                $map[$owner['code']] = $owner['id'];
+            });
+            return $map;
+        })();
+
+        $collect = collect();
+        if(count($map) == 0) return $collect;
+        $unexists = [];$sku = [];$owner_code = [];
+
+        foreach ($map as $item) {
+            $owner = Cache::get("owner_code_{$item['owner_code']}_sku_{$item['sku']}");
+            if($owner){
+                $collect->push($owner);
+                continue;
+            }
+            $key = json_encode( ['owner_code' => $item['owner_code'], 'sku' => $item['sku']]);
+            if(!empty($commodities_map[json_encode($key)])){
+                 $commodities_map[$key];
+                continue;
+            }
+            $unexists[json_encode($key)] = true;
+            $sku[] = $item['sku'];
+            $owner_code[] = $item['owner_code'];
+        }
+
+        if(count($unexists) == 0)return $collect;
+        $BasSKUs = $oracleBasSkuService->get( ['SKU'=>$sku,'CustomerID'=>$owner_code]);
+        $BasSKUs = $BasSKUs->filter(function($bas_sku)use($unexists,$commodities_map){
+            $arr = [
+                'owner_code' => $bas_sku['customerid'],
+                'sku' => $bas_sku['sku']
+            ];
+            $key = json_encode($arr);
+            if(!empty($commodities_map($key)))return false;
+            return $unexists[json_encode($arr)] ?? false;
+        });
+        $inner_params = (function()use($BasSKUs,$owner_map){
+            $map = [];
+            $date = Carbon::now();
+            $BasSKUs->each(function($basSku)use(&$map,$owner_map,$date){
+                $map[] = [
+                    'owner_id' => $owner_map[$basSku['customerid']] ?? '',
+                    'sku' => $basSku->sku,
+                    'name' =>$basSku->descr_c,
+                    'length' =>$basSku->skulength,
+                    'width' => $basSku->skuwidth,
+                    'height' => $basSku->skuhigh,
+                    'volumn' => $basSku->cube,
+                    'created_at' => $date,
+                    'updated_at' => $date,
+                ];
+            });
+            return $map;
+        })();
+        if(count($inner_params)==0)return $collect;
+        foreach (array_chunk($inner_params,4000) as $item) {
+            try {
+                $bool = Commodity::query()->insert($item);
+                if($bool){
+                    app('LogService')->log(__METHOD__,__FUNCTION__,"批量添加 Commodity Success ".count($inner_params).' || '.json_encode($inner_params));
+                    $commodities = Commodity::query()->with('owner')->whereIn('owner_id',data_get($item,'*.owner_id'))->whereIn('sku',data_get($item,'*.sku'))->get();
+                    $this->pushToCache($commodities);
+                    $collect = $collect->concat($commodities);
+                }
+                else app('LogService')->log(__METHOD__,__FUNCTION__,"批量添加 Commodity FAILED ".' || '.json_encode($inner_params));
+            } catch (\Exception $e) {
+                app('LogService')->log(__METHOD__,__FUNCTION__,"批量添加 Commodity ERROR ".' || '.json_encode($inner_params).' || '.json_encode($e->getMessage()).' || '.json_encode($e->getTraceAsString()));
+            }
+        }
+        return $collect;
+    }
+
+    private function pushToCache($commodities)
+    {
+        if (count($commodities) < 1) return null;
+        foreach ($commodities as $commodity) {
+            $commodity_key = "owner_code_{$commodity['owner']['code']}_sku_{$commodity['sku']}";
+            Cache::remember($commodity_key, config('cache.expirations.forever'), function () use ($commodity) {
+                return $commodity;
+            });
+        }
+    }
+
 
     public function pushCommodityToCache()
     {

+ 25 - 0
app/Services/ForeignHaiRoboticsService.php

@@ -0,0 +1,25 @@
+<?php
+
+
+namespace App\Services;
+
+
+use Illuminate\Http\Request;
+
+class ForeignHaiRoboticsService
+{
+
+    public function moveBin(){
+
+    }
+
+    public function markBinProcessed(){
+
+    }
+    public function taskUpdate(){
+
+    }
+    public function throwException(){
+
+    }
+}

+ 20 - 0
app/Services/LogisticService.php

@@ -4,9 +4,11 @@ namespace App\Services;
 
 use App\Logistic;
 use App\OracleBasCustomer;
+use App\Shop;
 use Carbon\Carbon;
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Support\Facades\Auth;
+use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Str;
 
 Class LogisticService
@@ -88,5 +90,23 @@ Class LogisticService
         return Logistic::query()->find($id);
     }
 
+    public function getLogisticByCodes($codes)
+    {
+        $collect = collect();
+        if(count($codes) == 0) return $collect;
+        foreach ($codes as $code) {
+            $collect->push(Cache::remember("getLogisticByCodes_{$code}", config('database.cache.expirations.rand'), function()use($code){
+                $logistic = Logistic::query()->where('code',$code)->first();
+                if($logistic)return $logistic;
+                $baseCustomers = OracleBasCustomer::query()
+                    ->selectRaw('Customer_Type,CustomerID,Descr_C')
+                    ->where('Customer_Type','CA')
+                    ->where('CustomerID',$code)->first();
+                if(!$baseCustomers)return null;
+                return Logistic::query()->create(['name' => $baseCustomers['descr_c'], 'code' => $baseCustomers['customerid']]);
+            }));
+        }
+        return $collect;
+    }
 
 }

+ 8 - 3
app/Services/OracleDOCOrderHeaderService.php

@@ -20,7 +20,7 @@ Class OracleDOCOrderHeaderService
         'DOC_Order_Header.CarrierName', 'DOC_Order_Header.LastShipmentTime','DOC_Order_Header.EDISendFlag',
         'DOC_Order_Header.SOReference5', 'DOC_Order_Header.C_Tel2','DOC_Order_Header.Transportation',
         'DOC_Order_Header.WareHouseId','DOC_Order_Header.SOStatus','DOC_Order_Header.C_Tel1','DOC_Order_Header.C_District',
-        'DOC_Order_Header.IssuePartyName'
+        'DOC_Order_Header.IssuePartyName','DOC_Order_Header.OrderType'
     ];
 
     function first(array $params){
@@ -71,13 +71,16 @@ Class OracleDOCOrderHeaderService
             ->with(['oracleBASCustomer'=>function($query){
                 $query->selectRaw('BAS_CUSTOMER.CustomerID,BAS_CUSTOMER.Customer_Type,BAS_CUSTOMER.Descr_C,BAS_CUSTOMER.Active_Flag');
             },'oracleDOCOrderDetails'=>function($query){
-                $query->selectRaw('doc_order_details.orderNo,doc_order_details.customerid,doc_order_details.sku,doc_order_details.QtyOrdered');
+                $query->selectRaw('doc_order_details.orderNo,doc_order_details.customerid,doc_order_details.sku,doc_order_details.QtyOrdered,doc_order_details.Location');
             }, 'actAllocationDetails'=>function($query){
                 $query->selectRaw('ACT_Allocation_Details.AllocationDetailsID,ACT_Allocation_Details.OrderNo,ACT_Allocation_Details.Qty_Each,ACT_Allocation_Details.PickToTraceID,ACT_Allocation_Details.CustomerID,ACT_Allocation_Details.Sku');
             },'oracleBASCode'=>function($query){
                 $query->selectRaw('BAS_Codes.CodeID,BAS_Codes.CodeName_C,BAS_Codes.Code');
+            },'orderType'=>function($query){
+                $query->selectRaw('BAS_Codes.CodeID,BAS_Codes.CodeName_C,BAS_Codes.Code');
             }])
             ->where('DOC_Order_Header.addTime','>=',$startDate)
+            ->whereColumn('DOC_Order_Header.editTime','=','DOC_Order_Header.addTime')
             ->orderByDesc('DOC_Order_Header.addTime')
             ->get();
     }
@@ -87,11 +90,13 @@ Class OracleDOCOrderHeaderService
             ->with(['oracleBASCustomer'=>function($query){
                 $query->selectRaw('BAS_CUSTOMER.CustomerID,BAS_CUSTOMER.Customer_Type,BAS_CUSTOMER.Descr_C,BAS_CUSTOMER.Active_Flag');
             },'oracleDOCOrderDetails'=>function($query){
-                $query->selectRaw('doc_order_details.orderNo,doc_order_details.customerid,doc_order_details.sku,doc_order_details.QtyOrdered');
+                $query->selectRaw('doc_order_details.orderNo,doc_order_details.customerid,doc_order_details.sku,doc_order_details.QtyOrdered,doc_order_details.Location');
             }, 'actAllocationDetails'=>function($query){
                 $query->selectRaw('ACT_Allocation_Details.AllocationDetailsID,ACT_Allocation_Details.OrderNo,ACT_Allocation_Details.Qty_Each,ACT_Allocation_Details.PickToTraceID,ACT_Allocation_Details.CustomerID,ACT_Allocation_Details.Sku');
             },'oracleBASCode'=>function($query){
                 $query->selectRaw('BAS_Codes.CodeID,BAS_Codes.CodeName_C,BAS_Codes.Code');
+            },'orderType'=>function($query){
+                $query->selectRaw('BAS_Codes.CodeID,BAS_Codes.CodeName_C,BAS_Codes.Code');
             }])
             ->where('DOC_Order_Header.editTime','>=',$startDate)
             ->whereColumn('DOC_Order_Header.editTime','!=','DOC_Order_Header.addTime')

+ 31 - 0
app/Services/OrderCommodityAssignService.php

@@ -0,0 +1,31 @@
+<?php 
+
+namespace App\Services; 
+
+use App\OrderCommodityAssign;
+
+Class OrderCommodityAssignService
+{ 
+
+    public function paginate(array $params = null)
+    {
+        $query = OrderCommodityAssign::query()->with(["order","commodity.barcodes","user"])->orderByDesc("id");
+        return $query->paginate($params["paginate"] ?? 50);
+    }
+
+    public function create(array $params)
+    {
+        return OrderCommodityAssign::query()->create($params);
+    }
+
+    public function get(array $params)
+    {
+        $query = OrderCommodityAssign::query()->with(["order","commodity.barcodes","user"]);
+        foreach ($params as $column=>$param){
+            if (is_array($param))$query->whereIn($column,$param);
+            else $query->where($column,$param);
+        }
+        return $query->get();
+    }
+
+}

+ 212 - 0
app/Services/OrderCommodityService.php

@@ -0,0 +1,212 @@
+<?php
+
+namespace App\Services;
+
+use App\Order;
+use App\OrderCommodity;
+use Carbon\Carbon;
+
+Class OrderCommodityService
+{
+    public function syncOrderCommodities(&$orderHeaders)
+    {
+        /**
+         * @var CommodityService $commodityService
+         * @var OwnerService $ownerService
+         */
+        $commodityService = app('CommodityService');
+        $ownerService = app('OwnerService');
+        if(count($orderHeaders) == 0)return ;
+        $order_nos = array_unique(data_get($orderHeaders,'*.orderno'));
+        $commodities_map = [];$owners_id_maps = [];
+        $owner_code_maps = (function()use(&$ownerService,&$orderHeaders,&$owners_id_maps){
+            $customer_ids= array_unique(data_get($orderHeaders,'*.customerid'));
+            $owners = $ownerService->getOwnerByCodes($customer_ids);
+            $owner_code_maps = [];
+            if(count($owners) == 0)return $owner_code_maps;
+            foreach ($owners as $owner) {
+                $owner_code_maps[$owner['code']]= $owner['id'];
+                $owners_id_maps[$owner['id']] =  $owner['code'];
+            }
+            return $owner_code_maps;
+        })();
+        // 重组OrderDetails
+        $orderDetails_map = (function()use(&$orderHeaders,&$owner_code_maps,&$commodities_map){
+            $map = [];
+            if(count($orderHeaders)==0)return $map;
+            foreach ($orderHeaders as $orderHeader) {
+                $Order_Details = $orderHeader->oracleDOCOrderDetails;
+                $Order_Details->each(function($item)use(&$map,&$owner_code_maps,&$commodities_map){
+                    if(!empty($item['customerid']) && !empty($item['sku'])){
+                        $key = "owner_code_{$item['customerid']}_sku_{$item['sku']}";
+                        $commodities_map[$key] =  ['owner_code'=>$item['customerid'],'sku'=>$item['sku']];
+                    }
+                    $key = "orderno_{$item['orderno']}_sku{$item['sku']}_each_{$item['qtyordered']}_location_{$item['location']}";
+                    if(empty($map[$key]))$map[$key]=[];
+                    $map[$key][] = [
+                        'code' => $item['orderno'],
+                        'sku' => $item['sku'],
+                        'owner_id'=>$owner_code_maps[$item['customerid']],
+                        'amount' => $item['qtyordered'],
+                        'location' => $item['location']
+                    ];
+                });
+            }
+            return $map;
+        })();
+        $commodities = $commodityService->getCommoditiesByMap($commodities_map);
+        $commodities_maps = (function()use($commodities,$owners_id_maps){
+            $map = [];
+            if(count($commodities) == 0)return $map;
+            foreach ($commodities as $commodity) {
+                $owner_code = $owners_id_maps[$commodity['owner_id']];
+                $key ="owner_code_{$owner_code}_sku_{$commodity['sku']}";
+                $map[$key] = $commodity;
+            }
+            return $map;
+        })();
+        $order_id_map = [];
+        $orders_map = (function()use($order_nos,&$order_id_map){
+            $map = [];
+            if(count($order_nos)==0)return $map;
+            $orders = Order::query()->whereIn('code',$order_nos)->get();
+            $orders->each(function($item)use(&$map,&$order_id_map){
+                $map[$item['code']] = ['id'=>  $item['id'], 'owner_id' =>  $item['owner_id']];
+                $order_id_map[$item['id']] = ['code'=>  $item['code'], 'owner_id' =>  $item['owner_id']];
+            });
+            return $map;
+        })();
+        $orderCommodities = OrderCommodity::query()->with('commodity','order')->whereHas('order',function($query)use($order_nos){
+            $query->whereIn('code',$order_nos);
+        })->get();
+
+        $orderCommodities_map = $this->regroupOrderCommodities($orderCommodities);              // 重组orderCommodities
+        $inner_params = $this->filterInnerParams($orderDetails_map,$orderCommodities_map);
+        $del_ids = $this->filterDeleteParams($orderDetails_map,$orderCommodities_map);
+        if(count($inner_params)>0){
+            $inner_arr = array_chunk($inner_params,4000);
+            foreach ($inner_arr as $item) {
+                $created_params = $this->createByInnerParams($item,$orders_map,$commodities_maps,$owners_id_maps);
+                $this->insert($created_params);
+            }
+        }
+        if(count($del_ids)>0){
+            $orderCommodities = OrderCommodity::query()->whereIn('id',$del_ids)->get();
+            $this->batchDelete($orderCommodities);
+        }
+    }
+
+    private function regroupOrderCommodities(&$orderCommodities)
+    {
+        $map = [];
+        if(count($orderCommodities)==0)return $map;
+        foreach ($orderCommodities as $orderCommodity) {
+            $key = "orderno_{$orderCommodity['order']['code']}_sku{$orderCommodity['commodity']['sku']}_each_{$orderCommodity['amount']}_location_{$orderCommodity['location']}";
+            if(empty($map[$key]))$map[$key] =[];
+            $map[$key][] = [
+                'id' =>$orderCommodity['id'],
+                'code' => $orderCommodity['order']['orderno'],
+                'sku' => $orderCommodity['commodity']['sku'],
+                'owner_id' => $orderCommodity['order']['owner_id'],
+                'amount' => $orderCommodity['amount'],
+                'location' => $orderCommodity['location']
+            ];
+        }
+        return $map;
+    }
+
+    private function filterInnerParams(&$orderDetails_map,&$orderCommodities_map)
+    {
+        $inner_params = [];
+        if(count($orderDetails_map) == 0)return $inner_params;
+        foreach ($orderDetails_map as $key=>&$map) {
+            if(empty($orderCommodities_map[$key])){
+                foreach ($map as &$item) {
+                    $inner_params[] = $item;
+                }
+            }elseif(count($map)>count($orderCommodities_map[$key])){
+                foreach ($map as &$obj) {
+                    if($orderCommodities_map[$key]>0)array_shift($orderCommodities_map[$key]);
+                    elseif($orderCommodities_map[$key]==0)$inner_params[] = $obj;
+                }
+            } elseif(count($map)==count($orderCommodities_map[$key]))continue;
+            unset($orderDetails_map[$key]);
+            $map = null;
+        }
+        return $inner_params;
+    }
+    private function filterDeleteParams(&$orderDetails_map,&$orderCommodities_map)
+    {
+        $del_ids = [];
+        if(count($orderDetails_map) == 0)return $del_ids;
+        foreach ($orderCommodities_map as $key=>$map) {
+            if(empty($orderDetails_map[$key])){
+                foreach ($map as &$item) {
+                    $del_ids[] = $item['id'];
+                }
+            }elseif(count($map)>count($orderDetails_map[$key])){
+                foreach ($map as $key1=>&$obj) {
+                    if(count($orderDetails_map[$key]) == 0){
+                        $del_ids [] = $obj['id'];
+                        unset($map[$key1]);
+                    } else{
+                        array_shift($orderDetails_map[$key]);
+                    }
+                }
+            }
+        }
+        return $del_ids;
+    }
+
+    private function createByInnerParams(&$inner_params,&$orders_map,&$commodities_maps,&$owner_id_maps)
+    {
+        $created_params = [];
+        if(count($inner_params) == 0)return $created_params;
+        $data = Carbon::now();
+        foreach ($inner_params as &$item) {
+            $order = $orders_map[$item['code']] ?? false;
+            if(!$order)continue;
+            $owner_code = $owner_id_maps[$item['owner_id']];
+            $key = "owner_code_{$owner_code}_sku_{$item['sku']}";
+            $commodity = $commodities_maps[$key];
+            $created_params[] = [
+                'order_id' =>$order['id'],
+                'commodity_id' =>$commodity['id'],
+                'amount' =>$item['amount'],
+                'location' =>$item['location'],
+                'created_at' =>$data,
+                'updated_at' => $data
+            ];
+        }
+        return $created_params;
+    }
+
+    public function batchDelete($orderCommodities)
+    {
+        if(count($orderCommodities) == 0)return true;
+        try {
+            $bool =  OrderCommodity::destroy(data_get($orderCommodities, '*.id'));
+            if($bool)app('LogService')->log(__METHOD__,__FUNCTION__,'批量删除 OrderCommodities'.' || '.count($orderCommodities).' || '.json_encode($orderCommodities));
+            else app('LogService')->log(__METHOD__,__FUNCTION__,'批量删除 OrderCommodities FAULT'.' || '.count($orderCommodities).' || '.json_encode($orderCommodities).' || ');
+            return $bool;
+        } catch (\Exception $e) {
+            app('LogService')->log(__METHOD__,__FUNCTION__,'批量删除 OrderCommodities ERROR'.' || '.count($orderCommodities).' || '.json_encode($orderCommodities).' || '.json_encode($e->getMessage()).' || '.json_encode($e->getTraceAsString()));
+            return false;
+        }
+    }
+
+    public function insert($innerParams){
+        if(!$innerParams)return false;
+        if(count($innerParams)==0)return false;
+        try {
+            $bool = OrderCommodity::query()->insert($innerParams);
+            if ($bool) app('LogService')->log(__METHOD__, __FUNCTION__, '批量添加 OrderCommodities SUCCESS' . ' || ' . count($innerParams) . ' || ' . json_encode($innerParams));
+            else app('LogService')->log(__METHOD__, __FUNCTION__, '批量添加 OrderCommodities FAULT' . ' || ' . count($innerParams) . ' || ' . json_encode($innerParams));
+            return $bool;
+        } catch (\Exception $e) {
+            app('LogService')->log(__METHOD__, __FUNCTION__, '批量添加 OrderCommodities ERROR'. ' || ' . count($innerParams) . ' || ' . json_encode($innerParams).' || '.json_encode($e->getMessage()).' || '.json_encode($e->getTraceAsString()));
+            return false;
+        }
+    }
+}
+

+ 15 - 2
app/Services/OrderIssueService.php

@@ -219,6 +219,18 @@ class OrderIssueService
                 }
             });
         }
+        if(isset($condition['sendOrderClientCode'])){
+            $query->whereHas('secondOrder',function($query)use($condition){
+                $this->searchWay($query,$condition['sendOrderClientCode'],'client_code');
+            });
+            $query->orWhere('second_client_no',$condition['sendOrderClientCode']);
+        }
+        if(isset($condition['sendOrderLogisticNumber'])){
+            $query->whereHas('secondOrder.packages',function($query)use($condition){
+                $this->searchWay($query,$condition['sendOrderLogisticNumber'],'logistic_number');
+            });
+            $query->orWhere('second_logistic_number',$condition['sendOrderLogisticNumber']);
+        }
         return $query;
     }
 
@@ -333,7 +345,8 @@ class OrderIssueService
                 'imported_status' => $imported_status,
                 'custom_code' => $custom_code,
                 'hidden_tag' => $hiddenTag,
-                'updated_at' => $data
+                'updated_at' => $data,
+                'created_at' => $data
             ];
         }
         try {
@@ -517,7 +530,7 @@ class OrderIssueService
 
     public function createOrderIssue($logisticNumber, $type, $result_explain, $importedStatus = '正常', $custom_code = null,$hiddenTag = null)
     {
-        $orderHeaders = OracleDOCOrderHeader::query()->with(['oracleDOCOrderDetails', 'actAllocationDetails', 'oracleBASCode'])
+        $orderHeaders = OracleDOCOrderHeader::query()->with(['oracleDOCOrderDetails', 'actAllocationDetails', 'oracleBASCode','orderType'])
             ->whereHas('actAllocationDetails', function ($query) use ($logisticNumber) {
                 $query->where('picktotraceid', $logisticNumber);
             })->get();

+ 46 - 33
app/Services/OrderPackageCommoditiesService.php

@@ -606,28 +606,48 @@ class OrderPackageCommoditiesService
          * @var DataHandlerService $dataHandService
          * @var CommodityService $commodityService
          * @var OrderPackageService $orderPackageService
+         * @var OwnerService $ownerService
          */
         $dataHandService = app('DataHandlerService');
         $commodityService = app('CommodityService');
         $orderPackageService  = app( 'OrderPackageService');
+        $ownerService  = app( 'OwnerService');
         if(!$orderHeaders)return ;
 
-        $commodityService->getByWmsOrders($orderHeaders);   // 预先处理     3s
+        $map = [];
+        foreach ($orderHeaders as $orderHeader) {
+            $Order_Details = $orderHeader->oracleDOCOrderDetails;
+            $Order_Details->each(function($item)use(&$map){
+                if(!empty($item['customerid']) && !empty($item['sku'])){
+                    $key = "owner_code_{$item['customerid']}_sku_{$item['sku']}";
+                    $map[$key] =  ['owner_code'=>$item['customerid'],'sku'=>$item['sku']];  // 货主编码 sku编码
+                }
+            });
+        }
+        $commodities = $commodityService->getCommoditiesByMap($map);   // 预先处理     3s
         $orderPackages = $orderPackageService->getByWmsOrders($orderHeaders);
         $orderCommodities = $this->getByWmsOrder($orderHeaders);
+        $owner_code_map = [];
+        $owner_id_map = (function()use(&$orderHeaders,&$ownerService,&$owner_code_map){
+            $owner_id_map = [];
+            $owners = $ownerService->getOwnerByCodes(array_unique(data_get($orderHeaders,'*.customerid')));
+            if(count($owners) == 0) return $owner_id_map;
+            foreach ($owners as $owner) {
+                $owner_id_map[$owner['id']] = $owner;
+                $owner_code_map[$owner['code']]  = $owner;
+            }
+            return $owner_id_map;
+        })();
 
         $package_map = $dataHandService->dataHeader(['logistic_number'],$orderPackages);
         $orderCommodities = $this->regroupOrderCommodities($orderCommodities);
-
         $orderAllocationDetails = $this->regroupWmsOrderAllocationDetails($orderHeaders);
         $del_orderCommodities  =[];
-
         $update_params =$this->filterUpdateParams($orderAllocationDetails,$orderCommodities,$del_orderCommodities);                  // 修改
-        $inner_params = $this->filterInnerParams($orderAllocationDetails,$orderCommodities);                              // 创建
+        $inner_params = $this->filterInnerParams($orderAllocationDetails,$orderCommodities);                                            // 创建
         $delete_params = $this->filterDeleteParams($orderAllocationDetails,$orderCommodities);                                           // 删除
-
         if(count($inner_params)>0)
-            $this->createOrderCommodities($inner_params,$package_map);  // 创建 3s
+            $this->createOrderCommodities($inner_params,$package_map,$commodities,$owner_id_map);  // 创建 3s
 
         if(count($update_params)>0)
             $this->updateOrderCommodities($update_params);              // 更新
@@ -750,26 +770,19 @@ class OrderPackageCommoditiesService
         return $del_params;
     }
     // TODO  根据数据创建
-    public function createOrderCommodities($inner_params,$package_map)
+    public function createOrderCommodities(&$inner_params,&$package_map,&$commodities,&$owner_id_map)
     {
         /** @var DataHandlerService $dataHandlerService */
         $dataHandlerService  = app('DataHandlerService');
-        $sku = [];$owners = [];
-        foreach ($inner_params as $inner_param) {
-            $sku_code = $inner_param['sku'];$owner_code = $inner_param['owner_code'];
-            if(!isset($sku[$sku_code]))
-                $sku[$sku_code] = $sku_code;
-            if(!isset($owner_code[$owner_code]))
-                $owners[$owner_code] = $owner_code;
-        }
-        $commodities = Commodity::query()->with('owner')->whereHas('owner',function ($query)use($owners){
-            $query->whereIn('code',$owners);
-        })->whereIn('sku',$sku)->get();
-        $commodity_map = [];
-        foreach ($commodities as $commodity) {
-            $key = ' owner='.$commodity->owner->code.' sku='.$commodity->sku;
-            $commodity_map[$key] = $commodity;
-        }
+        $commodity_map = (function()use(&$commodities,&$owner_id_map){
+            $map = [];
+            foreach ($commodities as $commodity) {
+                $owner = $owner_id_map[$commodity['owner_id']] ;
+                $key = ' owner='.$owner->code.' sku='.$commodity->sku;
+                $map[$key] = $commodity;
+            }
+            return $map;
+        })();
         $create_params =[];
         $date = Carbon::now();
         foreach ($inner_params as $inner_param) {
@@ -786,19 +799,19 @@ class OrderPackageCommoditiesService
             ];
         }
         if(count($create_params)>0){
-            try {
-                $inner_array = array_chunk($create_params,1000);
-                foreach ($inner_array as $item) {
+            $inner_array = array_chunk($create_params,5000);
+            foreach ($inner_array as $item) {
+                try {
                     $bool = $this->insert($item);
-                    LogService::log(__METHOD__,__FUNCTION__,'批量添加 orderCommodity --'. $bool ." || ".count($create_params).' || '.json_encode($create_params));
+                    LogService::log(__METHOD__, __FUNCTION__, '批量添加 orderCommodity ' . ($bool > 0 ? 'SUCCESS' : 'FAULT') . " || " . count($item) . ' || ' . json_encode($create_params));
+                } catch (\Exception $e) {
+                    LogService::log(__METHOD__,__FUNCTION__.'error','批量添加 orderCommodity ERROR'." || ".count($item).' || '.json_encode($item). ' || '.json_encode($e->getMessage()). ' || '.json_encode($e->getTraceAsString()));
                 }
-            } catch (\Exception $e) {
-                LogService::log(__METHOD__,__FUNCTION__.'error','批量添加 orderCommodity error'." || ".count($create_params).' || '.json_encode($create_params));
             }
         }
     }
     // TODO
-    public function updateOrderCommodities($orderCommodities)
+    public function updateOrderCommodities(&$orderCommodities)
     {
         if(!$orderCommodities)return ;
         $updated_at = Carbon::now();
@@ -816,17 +829,17 @@ class OrderPackageCommoditiesService
             $this->batchUpdate($update_params);
     }
     // TODO 删除
-    public function deleteOrderCommodities($orderCommodities){
+    public function deleteOrderCommodities(&$orderCommodities){
         if(!$orderCommodities)return;
         if(count($orderCommodities)==0)return;
         try {
             $ids = data_get($orderCommodities, '*.id');
             if(count($ids) >0){
                 $bool = OrderPackageCommodities::query()->whereIn('id', data_get($orderCommodities, '*.id'))->delete();
-                LogService::log(__METHOD__, __FUNCTION__, '批量删除 OrderCommodity -- ' . $bool . '||' .count($orderCommodities)  . ' || ' . json_encode($orderCommodities));
+                LogService::log(__METHOD__, __FUNCTION__, '批量删除 OrderCommodity '  . ($bool > 0 ? 'SUCCESS' : 'FAULT') .'||' .count($orderCommodities)  . ' || ' . json_encode($orderCommodities));
             }
         } catch (\Exception $e) {
-            LogService::log(__METHOD__, __FUNCTION__.' error', '批量删除 OrderCommodity Error-- ' . $e->getMessage() . '||' . $e->getTraceAsString() );
+            LogService::log(__METHOD__, __FUNCTION__.' error', '批量删除 OrderCommodity Error' . ' || ' . json_encode($e->getMessage()) . ' || ' . json_encode($e->getTraceAsString()));
         }
 
     }

+ 9 - 1
app/Services/OrderPackageService.php

@@ -392,7 +392,9 @@ class OrderPackageService
          * @var OrderPackageCommoditiesService $OrderPackageCommoditiesService
          */
         $OrderPackageCommoditiesService = app('OrderPackageCommoditiesService');
+
         $this->syncPackageByOrderHeaders($orderHeaders);
+
         $OrderPackageCommoditiesService->syncOrderPackageCommodities($orderHeaders);
     }
     // TODO
@@ -407,16 +409,22 @@ class OrderPackageService
         $orderPackageCommodityService= app('OrderPackageCommoditiesService');
         $orderTrackingService = app('OrderTrackingService');
         if(!$orderHeaders)return;
+
         $orders = $orderService->getByWmsOrders($orderHeaders);
+
         $packages = $this->getByOrderNos(data_get($orderHeaders,'*.orderno'));          // 已有
+
         $this->createOrderPackage($orderHeaders,$orders,$packages);                     // 创建package
 
         $del_ids = $this->deleteUnnecessaryPackage($orderHeaders,$packages);     // 删除package
+
         $orderPackageCommodityService->deleteUnnecessaryOrderCommodities($del_ids);     // 删除 orderCommodity
 
         $orderTracking = OrderTracking::query()->whereHas('commodities.package',function($query)use($del_ids){
             $query->whereIn('id',$del_ids);
         })->get();
+        if($orderTracking->count()==0)return;
+
         $orderTrackingService->deleteOrderTracings($orderTracking);                     // 删除追踪件
     }
     // TODO
@@ -439,7 +447,7 @@ class OrderPackageService
         }
         if(count($inner_params)>0){
             try {
-                $inner_array = array_chunk($inner_params,1000);
+                $inner_array = array_chunk($inner_params,5000);
                 foreach ($inner_array as $params) {
                     $bool = $this->insert($params);
                     $bool ? LogService::log(__METHOD__, __FUNCTION__, '批量添加 OrderPackage ' . count($inner_params) . ' || ' . json_encode($inner_params)) : null;

+ 132 - 83
app/Services/OrderService.php

@@ -18,6 +18,7 @@ use App\Shop;
 use App\ValueStore;
 use App\Warehouse;
 use Carbon\Carbon;
+use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\App;
 use Illuminate\Support\Facades\Cache;
@@ -697,13 +698,10 @@ class OrderService
         unset($updateParams, $orderHeaders);
     }
 
-    public function getByWmsOrders($orderHeaders)
-    {
-        if (!$orderHeaders) {
-            return null;
-        }
-        $order_nos = data_get($orderHeaders, '*.orderno');
-        return Order::query()->whereIn('code', $order_nos)->get();
+    public function getByWmsOrders($orderHeaders){
+        if(!$orderHeaders){return null;}
+        $order_nos = data_get($orderHeaders,'*.orderno');
+        return Order::query()->with('packages.commodities')->whereIn('code',$order_nos)->get();
     }
 
     public function 返回有问题件的订单号($orders)
@@ -800,21 +798,25 @@ class OrderService
         return $orders ? $orders->first() : null;
     }
 
-    // TODO
     public function syncOrder(&$orderHeaders)
     {
         /**
          * @var OrderPackageService $packageService
+         * @var OrderCommodityService $orderCommodityService
          */
         $packageService = app("OrderPackageService");
+        $orderCommodityService = app("OrderCommodityService");
+
         $this->syncOrderByWMSOrderHeaders($orderHeaders);
+
+        $orderCommodityService->syncOrderCommodities($orderHeaders);
+
         $packageService->syncOrderPackage($orderHeaders);
     }
 
-    // TODO
     public function syncOrderByWMSOrderHeaders(&$orderHeaders)
     {
-        if ($orderHeaders->isEmpty()) return [];
+        if($orderHeaders->isEmpty())return;
         /**
          * @var OwnerService $ownerService
          * @var LogisticService $logisticService
@@ -825,34 +827,51 @@ class OrderService
         $logisticService = app("LogisticService");
         $shopService = app('ShopService');
         $warehouseService = app('WarehouseService');
+        $owner_codes = [];$logistic_codes = [];$warehouse_codes = [];$shop_names = [];
+        foreach ($orderHeaders as $orderHeader) {
+            if(!empty($orderHeader['customerid']))
+                $owner_codes[$orderHeader['customerid']] = $orderHeader['customerid'];
+            if(!empty($orderHeader['warehouseid']))
+                $warehouse_codes[$orderHeader['warehouseid']] = $orderHeader['warehouseid'];
+            if(!empty($orderHeader['userdefine1']))
+                $logistic_codes[$orderHeader['userdefine1']] = $orderHeader['userdefine1'];
+            if(!empty($orderHeader['issuepartyname']) && !empty($orderHeader['customerid'])){
+                $value = ['owner_code'=>$orderHeader['customerid'],'issuepartyname'=>$orderHeader['issuepartyname']];
+                $key = "owner_code_{$orderHeader['customerid']}_issuepartyname_{$orderHeader['issuepartyname']}";
+                $shop_names[$key] = $value;
+            }
+        }
+        $owners = $ownerService->getOwnerByCodes($owner_codes);
+        $logistics = $logisticService->getLogisticByCodes($logistic_codes);
+        $shops = $shopService->getShopByCodeMap($shop_names);
+        $warehouses = $warehouseService->getWareHouseByCode($warehouse_codes);
 
-        $owners = $ownerService->getByWmsOrders($orderHeaders);
-        $logistics = $logisticService->getByWmsOrders($orderHeaders);
-        $shops = $shopService->getByWmsOrders($orderHeaders);
-        $warehouses = $warehouseService->getByWmsOrders($orderHeaders);
         $orders = $this->getByWmsOrders($orderHeaders);
-        $created_params = $this->getCreateOrderModelsByWMSOrderHeaders($orderHeaders, $orders, $warehouses, $owners, $logistics, $shops); //3s
 
-        $update_order = $this->getUpdateOrderModelByWMSOrderHeaders($orderHeaders, $orders, $warehouses, $owners, $logistics, $shops);
+        $created_params = $this->getCreateOrderModelsByWMSOrderHeaders($orderHeaders,$orders,$warehouses,$owners,$logistics,$shops); //3s
+
+        $update_order = $this->getUpdateOrderModelByWMSOrderHeaders($orderHeaders,$orders,$warehouses,$owners,$logistics,$shops);
+
+
         // 转换插入 3s
-        if (count($created_params) > 0) {
-            collect($created_params)->chunk(4000)->each(function ($inner_params) {
+        if(count($created_params) > 0){
+            collect($created_params)->chunk(3500)->each(function($inner_params){
                 $this->insert($inner_params->toArray());
             });
         }
         $update_params = [
-            ['id', 'code', 'warehouse_id', 'owner_id', 'shop_id', 'logistic_id', 'consignee_name', 'consignee_phone', 'province', 'city', 'district', 'address', 'client_code', 'wms_status', 'created_at', 'updated_at', 'wms_edittime']
+            ['id','code','warehouse_id','owner_id','shop_id','logistic_id','consignee_name','consignee_phone','province','city','district','address','client_code','wms_status','created_at','updated_at','wms_edittime','order_type']
         ];
-        $update_order->map(function ($item) {
-            return $item->toArray();
-        })->each(function ($item) use (&$update_params) {
-            $update_params[] = $item;
+
+        $update_order->each(function($item)use(&$update_params){
+            $update_params[] = $item->toArray();
         });
+        if(count($update_order)==0)return;
+
         $this->batchUpdate($update_params);
     }
 
-    // TODO
-    public function getCreateOrderModelsByWMSOrderHeaders($orderHeaders, $orders, $warehouses, $owners, $logistics, $shops)
+    public function getCreateOrderModelsByWMSOrderHeaders(&$orderHeaders,&$orders,&$warehouses,&$owners,&$logistics,&$shops)
     {
         /** @var DataHandlerService $dataHandlerService */
         $dataHandlerService = app('DataHandlerService');
@@ -863,8 +882,7 @@ class OrderService
         $shop_map = $dataHandlerService->dataHeader(['name', 'owner_id'], $shops);
         $order_map = $dataHandlerService->dataHeader(['code'], $orders);
 
-//        $collect = collect();
-        $inner_params = [];
+        $inner_params  = [];
         $date = (string)Carbon::now();
         foreach ($orderHeaders as $orderHeader) {
             $order_no = $orderHeader->orderno;
@@ -872,13 +890,11 @@ class OrderService
             if (isset($order)) continue;
             $order_model = $this->getCreateOrderModels($orderHeader, $warehouse_map, $owner_map, $logistic_map, $shop_map, $date);
             $inner_params[] = $order_model;
-//            $collect->push($order_model);
         }
         return $inner_params;
     }
 
-    // TODO
-    public function getUpdateOrderModelByWMSOrderHeaders($orderHeaders, $orders, $warehouses, $owners, $logistics, $shops)
+    public function getUpdateOrderModelByWMSOrderHeaders(&$orderHeaders,&$orders,&$warehouses,&$owners,&$logistics,&$shops)
     {
         /**
          * @var DataHandlerService $dataHandlerService
@@ -904,8 +920,7 @@ class OrderService
         return $collect;
     }
 
-    // TODO
-    public function getCreateOrderModels(&$orderHeader, &$warehouse_map, &$owner_map, &$logistic_map, &$shop_map, $date)
+    public function getCreateOrderModels(&$orderHeader,&$warehouse_map,&$owner_map,&$logistic_map,&$shop_map,$date)
     {
         /** @var DataHandlerService $dataHandlerService */
         $dataHandlerService = app('DataHandlerService');
@@ -930,7 +945,8 @@ class OrderService
             'address' => $orderHeader['c_address1'],
             'client_code' => $orderHeader['soreference1'],
             'wms_edittime' => $orderHeader['edittime'],
-            'wms_status' => $orderHeader->oracleBASCode->codename_c ?? '',
+            'wms_status' => $orderHeader->oracleBASCode->codename_c??'',
+            'order_type' => $orderHeader->orderType->codename_c??'',
             'updated_at' => $date,
             'created_at' => $orderHeader['addtime']
         ];
@@ -947,7 +963,7 @@ class OrderService
      * @param $updateParams
      * @return mixed
      */
-    public function UpdateOrderParamBy($shop, $logistic, $owner, $warehouse, $order, $orderHeader, string $updated_at, &$updateParams)
+    public function UpdateOrderParamBy(&$shop, &$logistic, &$owner, &$warehouse, &$order, &$orderHeader, string &$updated_at, &$updateParams)
     {
         $shop_id = $shop->id ?? null;
         $logistic_id = $logistic->id ?? null;
@@ -982,11 +998,11 @@ class OrderService
                 'updated_at' => $updated_at,
                 'created_at' => $orderHeader->addtime,
                 'wms_edittime' => $orderHeader->edittime,
+                'order_type' => $orderHeader->orderType->codename_c??'',
                 'warehouse_id' => $warehouse_id];
         }
     }
 
-    // TODO
     public function createOrFindOrder($orderHeader)
     {
         $order = Order::query()->where('code', $orderHeader->orderno)->first();
@@ -1002,7 +1018,6 @@ class OrderService
         }
     }
 
-    // TODO
     public function createOrFindOrderInfo($orderHeader)
     {
         /**
@@ -1015,7 +1030,7 @@ class OrderService
         $orderHeaders->push($orderHeader);
         try {
             $this->syncOrderByWMSOrderHeaders($orderHeaders);
-            $orderPackageService->syncOrderPackage($orderHeaders);
+            $orderPackageService->syncPackageByOrderHeaders($orderHeaders);
             $orderPackageCommoditiesService->syncOrderPackageCommodities($orderHeaders);
             return Order::query()->with('packages.commodities')->where('code', $orderHeader->orderno)->first();
         } catch (\Exception $e) {
@@ -1024,31 +1039,24 @@ class OrderService
         }
     }
 
-
-    // TODO
-    public function setOrderSyncAt($key, $date, $bool = true)
-    {
-        if ($bool) {
-            ValueStore::query()->where('name', $key)->update(['value' => Carbon::parse($date)->subSeconds(1)]);
+    public function setOrderSyncAt($key,$date,$bool=true){
+        if($bool){
+            ValueStore::query()->where('name',$key)->update(['value'=>Carbon::parse($date)->subSeconds(1)]);
         } else {
             ValueStore::query()->where('name', $key)->update(['value' => $date]);
         }
     }
 
-    // TODO
-    public function getOrderSyncAt($key, $type = 'newest')
-    {
-        $keyValue = ValueStore::query()->where('name', $key)->first();
-        if ($keyValue->value) return $keyValue->value;
-        if ($type == 'newest') $order = Order::query()->orderByDesc('Created_At')->first();
+    public function getOrderSyncAt($key,$type='newest'){
+        $keyValue = ValueStore::query()->where('name',$key)->first();
+        if($keyValue->value)return $keyValue->value;
+        if($type == 'newest') $order = Order::query()->orderByDesc('Created_At')->first();
         else $order = Order::query()->orderByDesc('Wms_EditTime')->first();
         if ($order) return $order->created_at;
         return Carbon::now()->subSeconds(65);
     }
 
-    // TODO
-    public function pushOrderCache($orderHeaders, $prefixKey, $hasKey, $list_key)
-    {
+    public function pushOrderCache($orderHeaders,$prefixKey,$hasKey,$list_key){
         $list = [];
         if (Cache::get($hasKey)) {
             collect($orderHeaders)->each(function ($item) use (&$list, $prefixKey) {
@@ -1062,8 +1070,7 @@ class OrderService
         }
     }
 
-    // TODO
-    public function filterOrderByCache($orderHeaders, $key)
+    public function filterOrderByCache($orderHeaders,$key)
     {
         /**
          * @var OracleDOCOrderHeader $item
@@ -1079,10 +1086,10 @@ class OrderService
         return $orderHeaders;
     }
 
-    // TODO
-    public function cancelOrderCache($key, string $prefix)
+    public function cancelOrderCache($key,string $prefix)
     {
-        if (Cache::get($key)) {
+        try {
+            Redis::LLEN($key);
             $list = Cache::get($key);
             collect($list)->each(function ($item) use ($prefix) {
                 Cache::forget($prefix . $item);
@@ -1091,9 +1098,7 @@ class OrderService
         }
     }
 
-    // TODO
-    public function syncCreatedOrder()
-    {
+    public function syncCreatedOrder(){
         /**
          * @var OracleDOCOrderHeaderService $oracleDOCOrderHeaderService
          * @var OrderService $orderService
@@ -1114,15 +1119,13 @@ class OrderService
 
         if (count($orderHeaders) > 0 && count($orderHeaders) > 0) {
             $orderService->syncOrder($orderHeaders);                                                //  同步订单
-            $orderService->cancelOrderCache($newest_list);                                              //  清除缓存
-            $orderService->pushOrderCache($renewal_orders, $prefixKey, $hasKey, $newest_list);             //  添加缓存
-            $orderService->setOrderSyncAt($newest, $last_order->addTime, count($orderHeaders) > 0);   //  更新时间
+            $orderService->cancelOrderCache($newest_list,$prefixKey);                                   //  清除缓存
+            $orderService->pushOrderCache($renewal_orders,$prefixKey,$hasKey,$newest_list);             //  添加缓存
+            $orderService->setOrderSyncAt($newest,$last_order->addTime,count($orderHeaders)>0);   //  更新时间
         }
     }
 
-    // TODO
-    public function syncUpdatedOrder()
-    {
+    public function syncUpdatedOrder(){
         /**
          * @var OracleDOCOrderHeaderService $oracleDOCOrderHeaderService
          * @var OrderService $orderService
@@ -1143,9 +1146,9 @@ class OrderService
 
         if (count($renewal_orders) > 0 && count($orderHeaders) > 0) {
             $orderService->syncOrder($orderHeaders);                                                    // 同步订单
-            $orderService->cancelOrderCache($renewal_list);                                                 // 清除缓存
-            $orderService->pushOrderCache($renewal_orders, $prefixKey, $hasKey, $renewal_list);                // 添加缓存
-            $orderService->setOrderSyncAt($renewal, $renewal_order->addTime, count($orderHeaders) > 0);   // 更新时间
+            $orderService->cancelOrderCache($renewal_list,$prefixKey);                                      // 清除缓存
+            $orderService->pushOrderCache($renewal_orders,$prefixKey,$hasKey,$renewal_list);                // 添加缓存
+            $orderService->setOrderSyncAt($renewal,$renewal_order->addTime,count($orderHeaders)>0);   // 更新时间
         }
     }
 
@@ -1162,29 +1165,75 @@ class OrderService
     public function createInstantBill(Order $order):bool
     {
         //检查订单对象
-        if (!$order || $order->status != "订单完成")return false;
-        if (!$order->packages)$order->load("packages");
+        if (!$order || $order->wms_status != "订单完成")return false;
+        $order->loadMissing(["logistic","packages.commodities.commodity"]);
 
         /** @var OwnerPriceExpressService $service */
         $service = app("OwnerPriceExpressService");
         $logistic_fee = 0;
-        foreach ($order->packages as $package){
-            $provinceName = $order->province;
-            $province = app(CacheService::class)->getOrExecute("province_".$provinceName,function ()use($provinceName){
-                return app("ProvinceService")->first(["name"=>$provinceName]);
-            },86400);
-            if (!$province){$logistic_fee = null;break;}
+        $commodities = [];
+        $amount = 0;
+        $volume = 0;
+        $weight = 0;
+        $logistic_bill = "";
+
+        if (!$order->logistic || $order->logistic->type != "快递")$logistic_fee = null;
+
+        foreach ($order->packages as &$package){
+            $logistic_bill .= $package->logistic_number.",";
+            $volume += $package->bulk;
+            $weight += $package->weight;
+
+            // 四维转二维
+            foreach($package->commodities as &$commodity){
+                $commodity["commodity_name"] = $commodity->commodity ? $commodity->commodity->name : '';
+                $commodity["sku"] = $commodity->commodity ? $commodity->commodity->sku : '';
+                $amount += $commodity->amount;
+            }
+            $commodities = array_merge($commodities,$package->commodities->toArray());
 
-            $fee = $service->matching($package->weight, $order->owner_id, $order->logistic_id, $province->id);
-            if ($fee<0){$logistic_fee = null;break;}
+            if ($logistic_fee!==null){
+                $provinceName = $order->province;
+                $province = app(CacheService::class)->getOrExecute("province_".$provinceName,function ()use($provinceName){
+                    return app("ProvinceService")->first(["name"=>$provinceName]);
+                },60);
+                if (!$province)$logistic_fee = null;
 
-            $logistic_fee += $fee;
+                $fee = $service->matching($package->weight, $order->owner_id, $order->logistic_id, $province->id);
+                if ($fee<0)$logistic_fee = null;
+
+                $logistic_fee += $fee;
+            }
         }
+        if ($logistic_fee!==null && $logistic_fee<0)$logistic_fee = null;
+
+        $object = ["commodities"=>$commodities,"logistic_name"=>($order->logistic ? $order->logistic->name : ''),"shop_name"=>($order->shop ? $order->shop->name : ''),"order_type"=>$order->order_type];
+        $mapping = ["packages"=>"commodities","商品名称"=>"commodity_name","承运商"=>"logistic_name","店铺类型"=>"shop_name","订单类型"=>"order_type"];
 
-        $work_fee = 0;
         /** @var OwnerPriceOperationService $service */
         $service = app("OwnerPriceOperationService");
-        $service->matchRule($order,[]);
-
+        $work_fee = $service->matchRule($object,$mapping,$order->owner_id,"出库");
+        if ($work_fee < 0)$work_fee = null;
+
+       if (app("OwnerFeeDetailService")->create([
+            "owner_id"          => $order->owner_id,
+            "worked_at"         => $order->wms_edittime,
+            "type"              => "发货",
+            "shop_id"           => $order->shop_id,
+            "operation_bill"    => $order->code,
+            "consignee_name"    => $order->consignee_name,
+            "consignee_phone"   => $order->consignee_phone,
+            "commodity_amount"  => $amount,
+            "logistic_bill"     => rtrim($logistic_bill,","),
+            "volume"            => $volume,
+            "weight"            => $weight,
+            "logistic_id"       => $order->logistic_id,
+            "work_fee"          => $work_fee,
+            "logistic_fee"      => $logistic_fee,
+            "created_at"        => date('Y-m-d H:i:s'),
+            "outer_id"          => $order->id,
+            "outer_table_name"  => "orders",
+        ]))return true;
+       return false;
     }
 }

+ 8 - 4
app/Services/OrderTrackingService.php

@@ -77,6 +77,9 @@ class OrderTrackingService
         if ($params['client'] ?? false)  // 客户
             $query->where('client', 'like', $params['client']);
 
+        if(!empty($params['web_order_number']))
+            $query->where('web_order_number', 'like', $params['web_order_number'].'%');
+
         if ($params['sku'] ?? false) {
             $query->whereHas('commodities.commodity', function ($query) use ($params) {
                 $query->where('sku', $params['sku']);
@@ -210,7 +213,7 @@ class OrderTrackingService
             })->update($update);
             return['success'=> $bool > 0];
         } catch (\Exception $e) {
-            app('LogService')->log(__METHOD__,__FUNCTION__,'修改追踪件'.json_encode($orderId,$param,$value).$e->getMessage().$e->getTraceAsString());
+            app('LogService')->log(__METHOD__,__FUNCTION__,'修改追踪件'.json_encode($orderId,$param,$value).json_encode($e->getMessage()).json_encode($e->getTraceAsString()));
             return['success'=> false,'fail_info'=>$e->getMessage()];
         }
     }
@@ -260,9 +263,10 @@ class OrderTrackingService
             if ($order_header['notes'] ?? false) {
                 $notes = $order_header->notes;
                 if (strpos($notes, '[')) {
-                    $arr= str_split($notes,strpos($notes,'['));
-                    $client = $arr[0] ?? '';
-                    $order_remark = str_replace(['[',']'],'', $arr[1] ?? '');
+                    $strings = [];
+                    preg_match_all('/^(.*?)(\\[)(.*?)(\\])(.*?)$/u',$notes,$strings);
+                    $client = $strings[1][0];
+                    $order_remark = $strings[3][0];
                 }
             }
             $web_order_number = null;

+ 20 - 0
app/Services/OwnerFeeDetailService.php

@@ -55,4 +55,24 @@ Class OwnerFeeDetailService
         return $query->sql();
     }
 
+    public function create(array $params)
+    {
+        return OwnerFeeDetail::query()->create($params);
+    }
+
+    public function first(array $params)
+    {
+        $query = OwnerFeeDetail::query();
+        foreach ($params as $column=>$param){
+            if (is_array($param))$query->whereIn($column,$param);
+            else $query->where($column,$param);
+        }
+        return $query->first();
+    }
+
+    public function updateFind(OwnerFeeDetail $detail, array $values)
+    {
+        return $detail->update($values);
+    }
+
 }

+ 29 - 10
app/Services/OwnerPriceOperationService.php

@@ -104,11 +104,10 @@ Class OwnerPriceOperationService
      * @param array $columnMapping       key-val
      * @param string $owner_id
      * @param string $type
-     * @param string $sku
      * @return double
      * 错误代码: -1:无匹配对象 -2:无计费模型 -3:未知单位 -4:sku为空 -5:货主未找到 -6:无箱规 -7:未匹配到计费模型
      */
-    public function matchRule($matchObject, $columnMapping, $owner_id, $sku = null, $type = '出库')
+    public function matchRule($matchObject, $columnMapping, $owner_id, $type = '出库')
     {
         $unitModels = Unit::query()->whereIn("name",["件","箱","单"])->get();
         $units = [];
@@ -144,7 +143,12 @@ Class OwnerPriceOperationService
                     if ($bool === true){
                         if (!isset($units[$rule->ownerInStorageRule->unit_id])) return -3;
                         if ($units[$rule->ownerInStorageRule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
-                            $sum = $this->changeUnit($sum,$owner_id,$sku);
+                            $sumTemp = 0;
+                            $packageColumn = $columnMapping["packages"] ?? "packages";
+                            foreach ($matchObject[$packageColumn] as $commodity){
+                                $sumTemp += $this->changeUnit($sum,$owner_id,$commodity["sku"]);
+                            }
+                            $sum = $sumTemp;
                             if ($sum<0)return $sum;
                         }
                         if ($units[$rule->ownerInStorageRule->unit_id] == '单')$sum = 1; //为单时数量设为1;
@@ -153,7 +157,12 @@ Class OwnerPriceOperationService
                 }else{
                     if (!isset($units[$rule->ownerInStorageRule->unit_id])) return -3;
                     if ($units[$rule->ownerInStorageRule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
-                        $sum = $this->changeUnit($sum,$owner_id,$sku);
+                        $sumTemp = 0;
+                        $packageColumn = $columnMapping["packages"] ?? "packages";
+                        foreach ($matchObject[$packageColumn] as $commodity){
+                            $sumTemp += $this->changeUnit($sum,$owner_id,$commodity["sku"]);
+                        }
+                        $sum = $sumTemp;
                         if ($sum<0)return $sum;
                     }
                     if ($units[$rule->ownerInStorageRule->unit_id] == '单')$sum = 1; //为单时数量设为1;
@@ -168,11 +177,11 @@ Class OwnerPriceOperationService
             if ($rule->strategy == '特征'){
                 $bool = app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject);//匹配特征
                 if ($bool === true){
-                    $money = $this->matchOutStorage($rule->ownerOutStorageRules,$columnMapping,$matchObject,$units,$owner_id,$sku);
+                    $money = $this->matchOutStorage($rule->ownerOutStorageRules,$columnMapping,$matchObject,$units,$owner_id);
                     if ($money>0)return $money;
                 };
             }else{
-                $money = $this->matchOutStorage($rule->ownerOutStorageRules,$columnMapping,$matchObject,$units,$owner_id,$sku);
+                $money = $this->matchOutStorage($rule->ownerOutStorageRules,$columnMapping,$matchObject,$units,$owner_id);
                 if ($money>0)return $money;
             };
         }
@@ -186,7 +195,7 @@ Class OwnerPriceOperationService
         return ceil($amount/$pack);
     }
 
-    private function matchOutStorage($rules, $columnMapping, $matchObject, $units, $owner_id, $sku)
+    private function matchOutStorage($rules, $columnMapping, $matchObject, $units, $owner_id)
     {
         $amountColumn = $columnMapping["amount"] ?? "amount";
         $packageColumn = $columnMapping["packages"] ?? "packages";
@@ -200,7 +209,7 @@ Class OwnerPriceOperationService
                 case "特征":
                     foreach ($packages as &$package){
                         if ($package["price"] ?? false)continue;
-                        if (!app("FeatureService")->matchFeature($rule->feature,["商品名称"=>"commodity"],["commodity"=>$package[$commodityColumn] ?? ''])) continue;
+                        if (!app("FeatureService")->matchFeature($rule->feature,["商品名称"=>$commodityColumn],["commodity"=>$package[$commodityColumn] ?? ''])) continue;
 
                         if (!$unitName)$unitName = $units[$rule->unit_id];
                         else {
@@ -210,7 +219,12 @@ Class OwnerPriceOperationService
                         $package["price"] = $rule->unit_price;
                         if (!isset($units[$rule->unit_id]) || $units[$rule->unit_id] == '单')return -3;
                         if ($units[$rule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
-                            $amount = $this->changeUnit($package[$amountColumn],$owner_id,$sku);
+                            $sumTemp = 0;
+                            $packageColumn = $columnMapping["packages"] ?? "packages";
+                            foreach ($matchObject[$packageColumn] as $commodity){
+                                $sumTemp += $this->changeUnit($package[$amountColumn],$owner_id,$commodity["sku"]);
+                            }
+                            $amount = $sumTemp;
                             if ($amount<0)return $amount;
                             $package[$amountColumn] = $amount;
                         }
@@ -228,7 +242,12 @@ Class OwnerPriceOperationService
                         $package["price"] = $rule->unit_price;
                         if (!isset($units[$rule->unit_id]) || $units[$rule->unit_id] == '单')return -3;
                         if ($units[$rule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
-                            $amount = $this->changeUnit($package[$amountColumn],$owner_id,$sku);
+                            $sumTemp = 0;
+                            $packageColumn = $columnMapping["packages"] ?? "packages";
+                            foreach ($matchObject[$packageColumn] as $commodity){
+                                $sumTemp += $this->changeUnit($package[$amountColumn],$owner_id,$commodity["sku"]);
+                            }
+                            $amount = $sumTemp;
                             if ($amount<0)return $amount;
                             $package[$amountColumn] = $amount;
                         }

+ 16 - 1
app/Services/OwnerService.php

@@ -57,6 +57,7 @@ Class OwnerService
                     'name' => $basCustomer['descr_c'],
                     'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
                 ]);
+                continue;
             }
             if ($owner['name']!=$basCustomer['descr_c']){
                 $owner->update([
@@ -239,5 +240,19 @@ Class OwnerService
             return Owner::query()->firstOrCreate(["code"=>$code],["code"=>$code,"name"=>$code]);
         });
     }
-
+    public function getOwnerByCodes($codes)
+    {
+        $collect = collect();
+        if(count($codes) == 0)return $collect;
+        foreach ($codes as $code) {
+            $collect->push(Cache::remember("getOwnerByCodes_{$code}", config('database.cache.expirations.rand'), function ()use($code){
+                $owner = Owner::query()->where('code',$code)->first();
+                if($owner) return $owner;
+                $basCustomer = OracleBasCustomer::query()->where('Customer_Type','OW')->where('CustomerID', $code)->first();
+                if(!$basCustomer)return null;
+                return Owner::query()->create(['name'=>$basCustomer['descr_c'],'code'=>$basCustomer['customerid']]);
+            }));
+        }
+        return $collect;
+    }
 }

+ 20 - 0
app/Services/ProcessService.php

@@ -94,4 +94,24 @@ Class ProcessService
                 ->selectRaw('sign_commodity_barcode.mark sign_commodity_barcode_mark')
             ->sql();
     }
+
+    public function createInstantBill(Process $process)
+    {
+        if (!$process || $process->status!="交接完成")return false;
+        if (!$process->processStatistic)$process->load("processStatistic");
+
+        if (app("OwnerFeeDetailService")->create([
+            "owner_id"          => $process->owner_id,
+            "worked_at"         => $process->processStatistic ? $process->processStatistic->ended_at : '',
+            "type"              => "增值服务",
+            "operation_bill"    => $process->code,
+            "commodity_amount"  => $process->completed_amount,
+            "process_method_id" => $process->process_method_id,
+            "work_fee"          => $process->processStatistic ? $process->processStatistic->revenue : null,
+            "created_at"        => date('Y-m-d H:i:s'),
+            "outer_id"          => $process->id,
+            "outer_table_name"  => "processes",
+        ]))return true;
+        return false;
+    }
 }

+ 33 - 0
app/Services/ShopService.php

@@ -2,13 +2,21 @@
 
 namespace App\Services;
 
+use App\OracleBasCustomer;
 use App\Owner;
 use App\Services\common\BatchUpdateService;
 use App\Shop;
 use Carbon\Carbon;
+use Illuminate\Support\Facades\Cache;
 
 class ShopService
 {
+    /** @var CacheService $cacheService */
+    private $cacheService;
+    function __construct(){
+        $this->cacheService=app('CacheService');
+    }
+
     public function getSelection(array $column = ['id', 'name'])
     {
         return Shop::query()->select($column)->get();
@@ -86,5 +94,30 @@ class ShopService
         }
     }
 
+    public function getShopByCodeMap($map)
+    {
+        /** @var OwnerService $ownerService */
+        $ownerService = app('OwnerService');
+        $owner_codes = [];
+        foreach ($map as $item) {
+            $owner_codes[$item['owner_code']]= $item['owner_code'];
+        }
+        $owners = $ownerService->getOwnerByCodes($owner_codes);
+        $owner_map  = [];
+        $owners->each(function($owner)use(&$owner_map){
+            $owner_map[$owner['code']] = $owner;
+        });
+        $collect = collect();
+        if(count($map)==0)return $collect;
+        foreach ($map as $item) {
+            $collect->push(Cache::remember("getShopByCodeMap_{$item['owner_code']}_{$item['issuepartyname']}", null, function()use($item,$owner_map){
+                $owner = $owner_map[$item['owner_code']] ;
+                $shop = Shop::query()->where('owner_id',$owner['id'])->where('name',$item['issuepartyname'])->first();
+                if($shop)return $shop;
+                return Shop::query()->create(['owner_id'=>$owner['id'],'name'=>$item['issuepartyname']]);
+            }));
+        }
+        return $collect;
+    }
 
 }

+ 28 - 0
app/Services/StationService.php

@@ -0,0 +1,28 @@
+<?php
+
+
+namespace App\Services;
+
+
+use App\Station;
+use App\StationType;
+use Exception;
+use Illuminate\Support\Facades\Cache;
+
+class StationService
+{
+    /**
+     * @param string $typeName
+     * @return Station
+     * @throws Exception
+     */
+    public function getDefaultStation(string $typeName):Station{
+        $station= Cache::remember('StationType_default_name_'.$typeName,config('rarelyChange'), function ()use($typeName) {
+            $stationType= StationType::query()->where('name',$typeName)->orderBy('id')->get('id')->first();
+            if(!$stationType) throw new Exception('指定站类型获取不到');
+            return Station::query()->where('station_type_id',$stationType['id'])->first();
+        });
+        if(!$station)throw new Exception('默认站获取不到');
+        return $station;
+    }
+}

+ 61 - 0
app/Services/StationTaskBatchService.php

@@ -0,0 +1,61 @@
+<?php
+
+
+namespace App\Services;
+
+
+use App\Batch;
+use App\StationTaskBatch;
+use App\StationTaskBatchType;
+use Exception;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\Cache;
+
+class StationTaskBatchService
+{
+    /** @var StationService $stationService */
+    private $stationService;
+    /** @var StationTaskBatchTypeService $stationTaskBatchTypeService */
+    private $stationTaskBatchTypeService;
+    /** @var BatchService $batchService */
+    private $batchService;
+    public function __construct(){
+        $this->stationService=null;
+        $this->stationTaskBatchTypeService=null;
+        $this->batchService=null;
+    }
+
+    /**
+     * @param $batches Batch[]
+     * @throws Exception
+     */
+    public function createByBatches(array $batches){
+        $this->stationService=app('StationService');
+        $this->stationTaskBatchTypeService=app('StationTaskBatchTypeService');
+        $this->batchService=app('BatchService');
+
+        $stationMissionBatches_toCreate=new Collection();
+        $station=$this->stationService->getDefaultStation('料箱出货口');
+        $id_stationMissionBatchType=$this->stationTaskBatchTypeService->firstByWhere('name','U型线分捡');
+
+        $batches_handled=[];
+        foreach ($batches as $batch){
+            if ($batch['status']=='未处理'){
+                $stationMissionBatches_toCreate->push([
+                    'batch_id'=>$batch['id'],
+                    'station_id'=>$station['id'],
+                    'station_mission_batch_type_id'=> $id_stationMissionBatchType,
+                    'status'=>'待处理'
+                ]);
+                $batches_handled[]=$batch;
+            }
+        }
+        $this->batchService->updateWhereIn('id',data_get($batches_handled,'*.id'),['status'=>'处理中']);
+        $this->insert($stationMissionBatches_toCreate->toArray());
+        return $stationMissionBatches_toCreate;
+    }
+
+    public function insert(array $stationMissionBatches_inArray){
+        return StationTaskBatch::query()->insert($stationMissionBatches_inArray);
+    }
+}

+ 26 - 0
app/Services/StationTaskBatchTypeService.php

@@ -0,0 +1,26 @@
+<?php
+
+
+namespace App\Services;
+
+
+use App\Station;
+use App\StationTaskBatchType;
+use App\StationType;
+use Illuminate\Support\Facades\Cache;
+
+class StationTaskBatchTypeService
+{
+    /**
+     * @param string $key
+     * @param string $value
+     * @return Station
+     */
+    public function firstByWhere(string $key,string $value):Station{
+        return Cache::remember('station_mission_batch_type_id_by_'.$key.$value, config('rarelyChange'), function ()use($key,$value) {
+            $stationMissionBatchType =StationTaskBatchType::query()->where($key, $value)->first();
+            if(!$stationMissionBatchType)throw new \Exception("找不到 StationMissionBatchType,where $key = $value");
+            return $stationMissionBatchType;
+        });
+    }
+}

+ 28 - 0
app/Services/StoreService.php

@@ -316,4 +316,32 @@ Class StoreService
             Cache::put($keys, $cacheKeys);
             Cache::put($set, true);
     }
+
+    public function createInstantBill(Store $store):bool
+    {
+        if (!$store || $store->status!="已入库")return false;
+        if (!$store->storeItems)$store->load("storeItems");
+
+
+        /** @var OwnerPriceOperationService $service */
+        $service = app("OwnerPriceOperationService");
+
+        $mapping = ["packages"=>"storeItems","商品名称"=>"name","订单类型"=>"stored_method"];
+
+        $work_fee = $service->matchRule($store,$mapping,$store->owner_id,"入库");
+        if ($work_fee < 0)$work_fee = null;
+
+        if (app("OwnerFeeDetailService")->create([
+            "owner_id"          => $store->owner_id,
+            "worked_at"         => $store->created_at,
+            "type"              => "收货",
+            "operation_bill"    => $store->asn_code,
+            "commodity_amount"  => array_sum(array_column($store->storeItems->toArray(),"amount")),
+            "work_fee"          => $work_fee,
+            "created_at"        => date('Y-m-d H:i:s'),
+            "outer_id"          => $store->id,
+            "outer_table_name"  => "stores",
+        ]))return true;
+        return false;
+    }
 }

+ 20 - 8
app/Services/WarehouseService.php

@@ -11,6 +11,12 @@ use Illuminate\Support\Facades\Cache;
 
 Class WarehouseService
 {
+    /** @var CacheService $cacheService */
+    private $cacheService;
+    function __construct(){
+        $this->cacheService=app('CacheService');
+    }
+
     public function firstOrCreate(array $params, array $values = null)
     {
         if ($values) return Warehouse::query()->firstOrCreate($params, $values);
@@ -45,11 +51,17 @@ Class WarehouseService
             return $warehouses->where('code',$oracleBasCustomer->warehouseid)->count()==0;
         });
         foreach ($oracleBasCustomers as $oracleBasCustomer){
-            $wereHouse=Warehouse::query()->create([
-                'code'=>$oracleBasCustomer->customerid,
-                'name'=>$oracleBasCustomer->descr_c
-            ]);
-            $collet->push($wereHouse);
+            $params =[
+                'code' => $oracleBasCustomer->customerid,
+                'name' => $oracleBasCustomer->descr_c
+            ];
+            try {
+                $wereHouse = Warehouse::query()->create($params);
+                $collet->push($wereHouse);
+                app('LogService')->log(__METHOD__,__FUNCTION__,'创建 warehouse success'.json_encode($wereHouse));
+            } catch (\Exception $e) {
+                app('LogService')->log(__METHOD__,__FUNCTION__,'创建 warehouse error'.json_encode($params).json_encode($e->getMessage()));
+            }
         }
         return  $collet;
     }
@@ -59,18 +71,18 @@ Class WarehouseService
 
     public function getWareHouseByCode($codes)
     {
-
         $collect = collect();
         if(count($codes)==0)return $collect;
         foreach ($codes as $code) {
-            $collect->push(Cache::remember("WareHouse_{$code}",null,function ()use($code){
+            $collect->push(Cache::remember("WareHouse_{$code}",config('database.cache.expirations.rand'),function()use($code){
                 $wareHouse =  Warehouse::query()->where('code',$code)->first();
                 if($wareHouse)return $wareHouse;
                 $bas_customer = OracleBasCustomer::query()->selectRaw('Customer_Type,CustomerId,Descr_C')->where('CustomerId',$code)->where('Customer_Type','WH')->first();
-                if (!$bas_customer) return null;
+                if(!$bas_customer) return null;
                 return Warehouse::query()->create(['name'=>$bas_customer['descr_c'],'code'=>$bas_customer['customerid']]);
             }));
         }
         return $collect;
     }
 }
+

+ 43 - 0
app/Services/WaybillService.php

@@ -143,4 +143,47 @@ Class WaybillService
             ->selectRaw('logistics.name carrier_name')
             ->sql();
     }
+
+    public function createInstantBill(Waybill $waybill) :bool
+    {
+        if (!$waybill || $waybill->status != "已完结" || !$waybill->wms_bill_number || !$waybill->logistic_id)return false;
+        $waybill->loadMissing("destinationCity");
+        if (!$waybill->destinationCity)return false;
+
+        $detail = app("OwnerFeeDetailService")->first([
+            "type" => "发货","owner_id" => $waybill->owner_id,"operation_bill"=>$waybill->wms_bill_number
+        ]);
+        if (!$detail || $detail->logistic_fee !== null)return false;
+
+        if ($waybill->type == "专线"){
+            /** @var OwnerPriceLogisticService $service */
+            $service = app("OwnerPriceLogisticService");
+            $fee = $service->matching($waybill->carrier_weight_other,$waybill->owner_id,$waybill->logistic_id,
+                $waybill->carrier_weight_unit_id_other,$waybill->destinationCity->province_id,
+                $waybill->destination_city_id);
+        }else{
+            /** @var OwnerPriceDirectLogisticService $service */
+            $service = app("OwnerPriceDirectLogisticService");
+            $fee = $service->matching($waybill->mileage,$waybill->owner_id,$waybill->carType_id);
+        }
+
+        if ($fee >= 0){
+            app("OwnerFeeDetailService")->updateFind($detail,[
+                "owner_id" => $waybill->owner_id,
+                "worked_at"=> $waybill->updated_at,
+                "type" => "发货",
+                "operation_bill" => $waybill->waybill_number,
+                "consignee_name" => $waybill->recipient,
+                "consignee_phone" => $waybill->recipient_mobile,
+                "commodity_amount" => $waybill->amount,
+                "logistic_bill" => $waybill->carrier_bill,
+                "volume" =>$waybill->carrier_weight ?? $waybill->warehouse_weight,
+                "weight" => $waybill->carrier_weight_other ?? $waybill->warehouse_weight_other,
+                "logistic_id" => $waybill->logistic_id,
+                "logistic_fee" => $fee,
+                "outer_id" => $waybill->id,
+                "outer_table_name" => "waybills",
+            ]);
+        }
+    }
 }

+ 1 - 1
app/StationMissionBatchType.php → app/StationTask.php

@@ -4,7 +4,7 @@ namespace App;
 
 use Illuminate\Database\Eloquent\Model;
 
-class StationMissionBatchType extends Model
+class StationTask extends Model
 {
     //
 }

+ 1 - 1
app/StationMissionBatch.php → app/StationTaskBatch.php

@@ -4,7 +4,7 @@ namespace App;
 
 use Illuminate\Database\Eloquent\Model;
 
-class StationMissionBatch extends Model
+class StationTaskBatch extends Model
 {
     protected $fillable=['batch_id','station_id','station_mission_batch_type_id','status'];
 }

+ 10 - 0
app/StationTaskBatchType.php

@@ -0,0 +1,10 @@
+<?php
+
+namespace App;
+
+use Illuminate\Database\Eloquent\Model;
+
+class StationTaskBatchType extends Model
+{
+    protected $fillable=['name'];
+}

+ 1 - 1
app/StationMissionCommodity.php → app/StationTaskCommodity.php

@@ -4,7 +4,7 @@ namespace App;
 
 use Illuminate\Database\Eloquent\Model;
 
-class StationMissionCommodity extends Model
+class StationTaskCommodity extends Model
 {
     protected $fillable= ['station_id','material_box_id','commodity_id','amount','order_id','status','station_id'];
 }

+ 1 - 1
app/StationMissionMaterialBox.php → app/StationTaskMaterialBox.php

@@ -4,7 +4,7 @@ namespace App;
 
 use Illuminate\Database\Eloquent\Model;
 
-class StationMissionMaterialBox extends Model
+class StationTaskMaterialBox extends Model
 {
     protected $fillable=['station_id','material_box_id','status'];
 }

+ 10 - 0
app/StationTaskType.php

@@ -0,0 +1,10 @@
+<?php
+
+namespace App;
+
+use Illuminate\Database\Eloquent\Model;
+
+class StationTaskType extends Model
+{
+    //
+}

+ 11 - 0
app/Utils/helpers.php

@@ -0,0 +1,11 @@
+<?php
+
+use Carbon\Carbon;
+
+function formatExcelDate(int $timestamp)
+{
+    $diff = intval($timestamp);
+    $today=new Carbon('1900-01-01');
+    $day = $today->addDays($diff-2);
+    return $day->toDateString();
+}

+ 3 - 0
composer.json

@@ -57,6 +57,9 @@
         "classmap": [
             "database/seeds",
             "database/factories"
+        ],
+        "files": [
+            "app/Utils/helpers.php"
         ]
     },
     "autoload-dev": {

+ 9 - 1
config/api.php

@@ -37,9 +37,17 @@ return [
         ],
     ],
 
+    /** 海柔
+     *  https://was.baoshi56.com/api/thirdPart/haiq/pickStation/processed  //标记料箱已处理
+     *  https://was.baoshi56.com/api/thirdPart/haiq/storage/taskUpdate  //任务状态更新
+     *  https://was.baoshi56.com/api/thirdPart/haiq/storage/exception  //异常通知
+     */
     'haiq'=>[
         'storage'=>[
-            'relocate' => "http://59.37.126.227:65448/api/haiqEss/gr/relocate",
+//            'relocate' => "http://59.37.126.227:65448/api/haiqEss/gr/relocate",
+            'moveBin' => "http://192.168.1.201:2011/api/haiqEss/gr/relocate",  //移动料箱
+            'lightOn' => "http://192.168.1.201:2011/api/ptl/curlPTL",  //亮灯
+            'lightOff' => "",  //灭灯
         ],
     ],
 

+ 7 - 6
config/cache.php

@@ -5,12 +5,13 @@ use Illuminate\Support\Str;
 return [
 
     'expirations'=>[
-        'default'=>10,
-        'oftenChange'=>5,
-        'rarelyChange'=>60,
-        'commonFrequent'=>20,
-        'owners'=>20,
-        'forever'=>null,
+        'default'=>10,          //默认
+        'oftenChange'=>5,       //经常改
+        'rarelyChange'=>60,     //几乎不变
+        'commonFrequent'=>20,  //一般频率
+        'forever' =>null,       //永久
+
+        'owners'=>20,           //模型Owner
     ],
     /*
     |--------------------------------------------------------------------------

+ 1 - 0
config/sync.php

@@ -33,6 +33,7 @@ return [
         ]
     ],
     'order_sync' => [
+        'enabled' => true,
         'interval' => 1,   // 时间以分为单位
         'start_at'=> '',    // 开始同步WMS的时间  时间格式: yyyy-MM-dd HH:mm:ss 如 2020-09-05 13:15:16
         'cache_prefix' => [

+ 18 - 0
database/factories/OracleActAllocationDetailsFactory.php

@@ -0,0 +1,18 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OracleActAllocationDetails;
+use Faker\Generator as Faker;
+
+$factory->define(OracleActAllocationDetails::class, function (Faker $faker) {
+    return [
+        'orderno' => $faker->uuid,
+        'customerid' => $faker->name,
+        'sku'=>$faker->name,
+        'qtyordered' => $faker->numberBetween(1,50),
+        'qty_each' => $faker->numberBetween(1,50),
+        'location' => $faker->md5,
+        'picktotraceid'  => $faker->uuid
+    ];
+});

+ 14 - 0
database/factories/OracleBasCodeFactory.php

@@ -0,0 +1,14 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OracleBasCode;
+use Faker\Generator as Faker;
+
+$factory->define(OracleBasCode::class, function (Faker $faker) {
+    return [
+        'codeid' => $faker->uuid,
+        'code' => $faker->uuid,
+        'codename_c' => $faker->name,
+    ];
+});

+ 14 - 0
database/factories/OracleBasCustomerFactory.php

@@ -0,0 +1,14 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OracleBasCustomer;
+use Faker\Generator as Faker;
+
+$factory->define(OracleBasCustomer::class, function (Faker $faker) {
+    return [
+        'customer_type'=> $faker->uuid,
+        'customerid'=> $faker->uuid,
+        'descr_c'=> $faker->name
+    ];
+});

+ 15 - 0
database/factories/OracleBasSKUFactory.php

@@ -0,0 +1,15 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OracleBasSKU;
+use Faker\Generator as Faker;
+
+$factory->define(OracleBasSKU::class, function (Faker $faker) {
+    return [
+        'customerid'=>$faker->name,
+        'sku' =>$faker->name,
+        'descr_c' =>$faker->title(20),
+        'packid'=>$faker->name,
+    ];
+});

+ 16 - 0
database/factories/OracleDOCOrderDetailFactory.php

@@ -0,0 +1,16 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OracleDOCOrderDetail;
+use Faker\Generator as Faker;
+
+$factory->define(OracleDOCOrderDetail::class, function (Faker $faker) {
+    return [
+        'orderno' => $faker->uuid,
+        'customerid' => $faker->name,
+        'sku'=>$faker->name,
+        'qtyordered' => $faker->numberBetween(1,50),
+        'location' => $faker->md5
+    ];
+});

+ 35 - 0
database/factories/OrcaleDOCOrderHeaderFactory.php

@@ -0,0 +1,35 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OracleDOCOrderHeader;
+use Faker\Generator as Faker;
+
+$factory->define(OracleDOCOrderHeader::class, function (Faker $faker) {
+    return [
+        'orderno' => $faker->uuid,
+        'customerid' => '',
+        'ordertime' =>$faker->time(),
+        'soreference1' => $faker->uuid,
+        'consigneeid' => '',
+        'c_contact' =>$faker->title(10),
+        'consigneename' => $faker->title(11),
+        'c_address1' => $faker->address,
+        'c_city' =>$faker->city,
+        'c_province' =>$faker->city,
+        'addtime' => $faker->date(),
+        'edittime' => $faker->date(),
+        'notes' => $faker->text(15),
+        'carriername'  =>'',
+        'lastshipmenttime' => $faker->date(),
+        'edisendflag' => "Y",
+        'soreference5' => $faker->uuid,
+        'c_tel2' => $faker->phoneNumber,
+        'transportation' => $faker->phoneNumber,
+        'warehouseid' => '',
+        'sostatus' => '99',
+        'c_tel1' => $faker->phoneNumber,
+        'c_district' => $faker->city,
+        'issuepartyname'=> $faker->date(),
+    ];
+});

+ 1 - 1
database/factories/ShopFactory.php

@@ -8,6 +8,6 @@ use Faker\Generator as Faker;
 $factory->define(Shop::class, function (Faker $faker) {
     return [
         'name' => $faker->name,
-        'owner_id' => factory(\App\Owner::class),
+        'owner_id' => 1,
     ];
 });

+ 2 - 2
database/factories/StationMissionBatchFactory.php

@@ -2,10 +2,10 @@
 
 /** @var \Illuminate\Database\Eloquent\Factory $factory */
 
-use App\StationMissionBatch;
+use App\StationTaskBatch;
 use Faker\Generator as Faker;
 
-$factory->define(StationMissionBatch::class, function (Faker $faker) {
+$factory->define(StationTaskBatch::class, function (Faker $faker) {
     return [
         //
     ];

+ 2 - 2
database/factories/StationMissionBatchTypeFactory.php

@@ -2,10 +2,10 @@
 
 /** @var \Illuminate\Database\Eloquent\Factory $factory */
 
-use App\StationMissionBatchType;
+use App\StationTaskBatchType;
 use Faker\Generator as Faker;
 
-$factory->define(StationMissionBatchType::class, function (Faker $faker) {
+$factory->define(StationTaskBatchType::class, function (Faker $faker) {
     return [
         //
     ];

+ 2 - 2
database/factories/StationMissionCommodityFactory.php

@@ -2,10 +2,10 @@
 
 /** @var \Illuminate\Database\Eloquent\Factory $factory */
 
-use App\StationMissionCommodity;
+use App\StationTaskCommodity;
 use Faker\Generator as Faker;
 
-$factory->define(StationMissionCommodity::class, function (Faker $faker) {
+$factory->define(StationTaskCommodity::class, function (Faker $faker) {
     return [
         //
     ];

+ 2 - 2
database/factories/StationMissionMaterialBoxFactory.php

@@ -2,10 +2,10 @@
 
 /** @var \Illuminate\Database\Eloquent\Factory $factory */
 
-use App\StationMissionMaterialBox;
+use App\StationTaskMaterialBox;
 use Faker\Generator as Faker;
 
-$factory->define(StationMissionMaterialBox::class, function (Faker $faker) {
+$factory->define(StationTaskMaterialBox::class, function (Faker $faker) {
     return [
         //
     ];

+ 12 - 0
database/factories/StationTaskFactory.php

@@ -0,0 +1,12 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\StationTask;
+use Faker\Generator as Faker;
+
+$factory->define(StationTask::class, function (Faker $faker) {
+    return [
+        //
+    ];
+});

+ 12 - 0
database/factories/StationTaskTypeFactory.php

@@ -0,0 +1,12 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\StationTaskType;
+use Faker\Generator as Faker;
+
+$factory->define(StationTaskType::class, function (Faker $faker) {
+    return [
+        //
+    ];
+});

+ 13 - 0
database/factories/WarehouseFactory.php

@@ -0,0 +1,13 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\Warehouse;
+use Faker\Generator as Faker;
+
+$factory->define(Warehouse::class, function (Faker $faker) {
+    return [
+        'name' => $faker->name,
+        'code' => $faker->uuid
+    ];
+});

+ 1 - 1
database/migrations/2020_01_02_172739_change_waybill_price_model_field.php

@@ -26,7 +26,7 @@ class ChangeWaybillPriceModelField extends Migration
     public function down()
     {
         Schema::table('waybill_price_models', function (Blueprint $table) {
-            $table->bigInteger('city_id')->index()->comment('外键城市')->change();
+//            $table->bigInteger('city_id')->index()->comment('外键城市')->change();
         });
     }
 }

+ 1 - 1
database/migrations/2020_03_09_153510_create_stores_table.php

@@ -19,7 +19,7 @@ class CreateStoresTable extends Migration
             $table->integer('warehouse_id')->nullable()->comment('仓库ID');
             $table->integer('owner_id')->index()->nullable()->comment('货主ID');
             $table->enum('stored_method',['正常','快速入库','采购入库','笕尚退货入库单','笕尚进仓入库单','笕尚移仓入库单','B2B入库','笕尚调整入库单','换货入库','初始化库存','虚拟入库','其他入库','退货入库','调拨入库'])->default('正常');
-            $table->enum('status',['待盘点','盘点中','复盘中','已完成','已审核'])->default(null)->nullable();
+            $table->enum('status',['无需入库','已入库','未入库','待推单','完全收货','部分收货','已码盘','订单创建','ASN关闭','等待释放','收货取消'])->default(null)->nullable();
             $table->string('remark')->nullable();
             $table->timestamp('deleted_at')->nullable()->index();
             $table->timestamp('updated_at')->nullable();

+ 2 - 1
database/migrations/2020_04_09_111540_change_tutorial_table.php

@@ -32,7 +32,8 @@ class ChangeTutorialTable extends Migration
             $table->longText('content')->after('name')->nullable()->comment('富文本内容');
         });
         Schema::table('users', function (Blueprint $table) {
-            $table->string('email')->unique()->change();
+//            $table->unique('email','users_email_unique');
+//            $table->string('email')->unique()->change();
         });
     }
 }

+ 0 - 1
database/migrations/2020_06_02_130804_change_user_duty_check.php

@@ -26,7 +26,6 @@ class ChangeUserDutyCheck extends Migration
     public function down()
     {
         Schema::table('user_duty_checks', function (Blueprint $table) {
-            $table->dropColumn('workgroup_id');
         });
     }
 }

+ 4 - 4
database/migrations/2020_06_11_112028_change_rejected_bills_table.php

@@ -14,8 +14,8 @@ class ChangeRejectedBillsTable extends Migration
     public function up()
     {
         Schema::table('rejected_bills',function (Blueprint $table){
-            $table->index('is_loaded');
-            $table->index('is_checked');
+            $table->index('is_loaded','rejected_bills_is_loaded_index');
+            $table->index('is_checked','rejected_bills_is_checked_index');
         });
     }
 
@@ -28,8 +28,8 @@ class ChangeRejectedBillsTable extends Migration
     {
         //
         Schema::table('rejected_bills',function (Blueprint $table){
-            $table->dropIndex('is_loaded');
-            $table->dropIndex('is_checked');
+            $table->dropIndex('rejected_bills_is_loaded_index');
+            $table->dropIndex('rejected_bills_is_checked_index');
         });
     }
 }

+ 1 - 1
database/migrations/2020_06_16_173559_add_authorrities_waybillmanagement_freigt.php

@@ -31,7 +31,7 @@ class AddAuthorritiesWaybillmanagementFreigt extends Migration
     public function down()
     {
         foreach ($this->authNames as $name){
-            \App\Authority::where(['name'=>$name,'alias_name'=>$name])->destroy();
+            \App\Authority::where(['name'=>$name,'alias_name'=>$name])->delete();
         }
     }
 }

+ 0 - 1
database/migrations/2020_06_30_133655_change_processes_contents_column_type.php

@@ -26,7 +26,6 @@ class ChangeProcessesContentsColumnType extends Migration
     public function down()
     {
         Schema::table('processes_contents',function (Blueprint $table){
-            $table->dropColumn('type');
             $table->string('is_full',2)->default('N')->comment('是否成品');
         });
     }

+ 1 - 1
database/migrations/2020_09_10_143926_drop_shop_unique_name_index.php

@@ -27,7 +27,7 @@ class DropShopUniqueNameIndex extends Migration
     public function down()
     {
         Schema::table('shops', function (Blueprint $table) {
-            $table->string('name')->unique('shops_name_unique');
+            $table->string('name')->unique('shops_name_unique')->change();
         });
     }
 }

+ 1 - 1
database/migrations/2020_10_19_113042_create_logistic_timings_table.php

@@ -42,7 +42,7 @@ class CreateLogisticTimingsTable extends Migration
     {
         $create_array = [];
         $map = $this->getMap();
-        $logistic=Logistic::firstOrCreate(['name'=>'顺丰特惠']);
+        $logistic=Logistic::firstOrCreate(['name'=>'顺丰特惠','code'=>'SFTH']);
 //        $logistic = Logistic::query()->where('name','顺丰特惠')->first();
         $time = \Carbon\Carbon::now()->format('Y-m-d H:i:s');
         foreach ($map as $item) {

+ 3 - 1
database/migrations/2020_11_19_113955_change_order_issue_type_id_index.php

@@ -25,6 +25,8 @@ class ChangeOrderIssueTypeIdIndex extends Migration
      */
     public function down()
     {
-        Schema::dropIfExists('order_issues');
+        Schema::table('order_issues', function (Blueprint $table) {
+            $table->dropColumn('order_issue_type_id');
+        });
     }
 }

+ 2 - 2
database/migrations/2020_11_30_140958_create_stations_table.php

@@ -19,13 +19,13 @@ class CreateStationsTable extends Migration
             $table->id();
             $table->integer('parent_id')->index()->nullable();
             $table->string('name')->index()->nullable();
-            $table->string('code')->index()->nullable()->comment('机器编码');
+            $table->string('code')->unique()->nullable()->comment('机器编码');
             $table->integer('station_type_id')->index();
             $table->integer('sequence')->index()->nullable();
             $table->timestamps();
         });
         $stationType= StationType::query()->firstOrCreate(['name'=>'料箱出货口']);
-        $station= Station::query()->firstOrCreate(['code'=>'BIN-OUT01']);
+        $station= Station::query()->firstOrCreate(['code'=>'BIN-OUT01','station_type_id'=>$stationType['id']]);
         $station['sequence']=1;
         $station['station_type_id']=$stationType['id'];
         $station->save();

+ 4 - 4
database/migrations/2020_11_30_142430_create_station_mission_batches_table.php → database/migrations/2020_11_30_142430_create_station_task_batches_table.php

@@ -4,7 +4,7 @@ use Illuminate\Database\Migrations\Migration;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Support\Facades\Schema;
 
-class CreateStationMissionBatchesTable extends Migration
+class CreateStationTaskBatchesTable extends Migration
 {
     /**
      * Run the migrations.
@@ -13,11 +13,11 @@ class CreateStationMissionBatchesTable extends Migration
      */
     public function up()
     {
-        Schema::create('station_mission_batches', function (Blueprint $table) {
+        Schema::create('station_task_batches', function (Blueprint $table) {
             $table->id();
             $table->integer('batch_id')->index();
             $table->integer('station_id')->index();
-            $table->integer('station_mission_batch_type_id')->index();
+            $table->integer('station_task_batch_type_id')->index();
             $table->enum('status',['待处理','挂起','处理中','完成','异常','取消'])->index();
             $table->timestamps();
         });
@@ -30,6 +30,6 @@ class CreateStationMissionBatchesTable extends Migration
      */
     public function down()
     {
-        Schema::dropIfExists('station_mission_batches');
+        Schema::dropIfExists('station_task_batches');
     }
 }

+ 33 - 0
database/migrations/2020_11_30_151800_create_station_task_batch_types_table.php

@@ -0,0 +1,33 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class CreateStationTaskBatchTypesTable extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::create('station_task_batch_types', function (Blueprint $table) {
+            $table->id();
+            $table->string('name');
+            $table->timestamps();
+        });
+        \App\StationTaskBatchType::query()->firstOrCreate(['name'=>'U型线分捡']);
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::dropIfExists('station_task_batch_types');
+    }
+}

+ 3 - 3
database/migrations/2020_11_30_155713_create_station_mission_material_boxes_table.php → database/migrations/2020_11_30_155713_create_station_task_material_boxes_table.php

@@ -4,7 +4,7 @@ use Illuminate\Database\Migrations\Migration;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Support\Facades\Schema;
 
-class CreateStationMissionMaterialBoxesTable extends Migration
+class CreateStationTaskMaterialBoxesTable extends Migration
 {
     /**
      * Run the migrations.
@@ -13,7 +13,7 @@ class CreateStationMissionMaterialBoxesTable extends Migration
      */
     public function up()
     {
-        Schema::create('station_mission_material_boxes', function (Blueprint $table) {
+        Schema::create('station_task_material_boxes', function (Blueprint $table) {
             $table->id();
             $table->integer('station_id')->index();
             $table->integer('material_box_id');  //联合索引
@@ -30,6 +30,6 @@ class CreateStationMissionMaterialBoxesTable extends Migration
      */
     public function down()
     {
-        Schema::dropIfExists('station_mission_material_boxes');
+        Schema::dropIfExists('station_task_material_boxes');
     }
 }

+ 4 - 4
database/migrations/2020_11_30_174327_create_station_mission_commodities_table.php → database/migrations/2020_11_30_174327_create_station_task_commodities_table.php

@@ -4,7 +4,7 @@ use Illuminate\Database\Migrations\Migration;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Support\Facades\Schema;
 
-class CreateStationMissionCommoditiesTable extends Migration
+class CreateStationTaskCommoditiesTable extends Migration
 {
     /**
      * Run the migrations.
@@ -13,7 +13,7 @@ class CreateStationMissionCommoditiesTable extends Migration
      */
     public function up()
     {
-        Schema::create('station_mission_commodities', function (Blueprint $table) {
+        Schema::create('station_task_commodities', function (Blueprint $table) {
             $table->id();
             $table->integer('station_id');  //联合索引
             $table->integer('material_box_id');  //联合索引
@@ -21,7 +21,7 @@ class CreateStationMissionCommoditiesTable extends Migration
             $table->integer('amount')->default(0);
             $table->integer('order_id')->index();
             $table->enum('status',['待处理','挂起','处理中','完成','异常','取消'])->index();  //联合索引
-            $table->index(['station_id','material_box_id','status'],'station_mission_commodities_s_m_s_index');
+            $table->index(['station_id','material_box_id','status'],'station_task_commodities_s_m_s_index');
             $table->timestamps();
         });
     }
@@ -33,6 +33,6 @@ class CreateStationMissionCommoditiesTable extends Migration
      */
     public function down()
     {
-        Schema::dropIfExists('station_mission_commodities');
+        Schema::dropIfExists('station_task_commodities');
     }
 }

+ 32 - 0
database/migrations/2020_12_01_134905_add_order_type_to_orders.php

@@ -0,0 +1,32 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class AddOrderTypeToOrders extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('orders', function (Blueprint $table) {
+            $table->string('order_type')->index()->nullable()->comment('订单类型')->after('wms_status');
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('orders', function (Blueprint $table) {
+            $table->dropColumn('order_type');
+        });
+    }
+}

+ 27 - 0
database/migrations/2020_12_01_150439_change_batch_field_status_add_executing.php

@@ -0,0 +1,27 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Support\Facades\DB;
+
+class ChangeBatchFieldStatusAddExecuting extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        DB::statement("ALTER TABLE batches MODIFY COLUMN status ENUM('未处理','已处理','取消','处理中','挂起','异常')");
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        DB::statement("ALTER TABLE batches MODIFY COLUMN status ENUM('未处理','已处理','取消')");
+    }
+}

+ 52 - 0
database/migrations/2020_12_02_150054_create_order_commodity_assigns_table.php

@@ -0,0 +1,52 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class CreateOrderCommodityAssignsTable extends Migration
+{
+
+    protected $authorities = [
+        "商品配置",
+        "商品配置-查询",
+        "商品配置-编辑",
+    ];
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        foreach ($this->authorities as $val) \App\Authority::query()->firstOrCreate(["name"=>$val,"alias_name"=>$val]);
+
+        Schema::create('order_commodity_assigns', function (Blueprint $table) {
+            $table->id();
+            $table->bigInteger("order_id")->index()->comment("外键订单");
+            $table->bigInteger("commodity_id")->comment("外键商品");
+            $table->integer("amount")->default(0)->comment("数量");
+            $table->date("produced_at")->nullable()->comment("生产日期");
+            $table->date("valid_at")->nullable()->comment("失效日期");
+            $table->string("batch_number")->index()->nullable()->comment("批次号");
+            $table->string("location")->index()->nullable()->comment("库位");
+            $table->string("region")->index()->nullable()->comment("库区");
+            $table->bigInteger("user_id")->index()->nullable()->comment("操作人");
+            $table->timestamps();
+            $table->index(["commodity_id","produced_at"]);
+            $table->index(["commodity_id","valid_at"]);
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::dropIfExists('order_commodity_assigns');
+
+        foreach ($this->authorities as $val) \App\Authority::query()->where("name",$val)->where("alias_name",$val)->delete();
+    }
+}

+ 38 - 0
database/migrations/2020_12_03_114353_add_auth_of_station.php

@@ -0,0 +1,38 @@
+<?php
+
+use App\Authority;
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class AddAuthOfStation extends Migration
+{
+
+    protected $authNames=[
+        "站管理",
+        "站管理-监视器",
+    ];
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        foreach ($this->authNames as $name){
+            if(!Authority::where('name',$name)->first())(new Authority(['name'=>$name,'alias_name'=>$name]))->save();
+        }
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        foreach ($this->authNames as $name){
+            Authority::where('name',$name)->delete();
+        }
+    }
+}

+ 4 - 3
database/migrations/2020_11_30_151800_create_station_mission_batch_types_table.php → database/migrations/2020_12_04_160314_create_station_task_types_table.php

@@ -4,7 +4,7 @@ use Illuminate\Database\Migrations\Migration;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Support\Facades\Schema;
 
-class CreateStationMissionBatchTypesTable extends Migration
+class CreateStationTaskTypesTable extends Migration
 {
     /**
      * Run the migrations.
@@ -13,8 +13,9 @@ class CreateStationMissionBatchTypesTable extends Migration
      */
     public function up()
     {
-        Schema::create('station_mission_batch_types', function (Blueprint $table) {
+        Schema::create('station_task_types', function (Blueprint $table) {
             $table->id();
+            $table->string('name')->index();
             $table->timestamps();
         });
     }
@@ -26,6 +27,6 @@ class CreateStationMissionBatchTypesTable extends Migration
      */
     public function down()
     {
-        Schema::dropIfExists('station_mission_batch_types');
+        Schema::dropIfExists('station_task_types');
     }
 }

+ 34 - 0
database/migrations/2020_12_04_175932_create_station_tasks_table.php

@@ -0,0 +1,34 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class CreateStationTasksTable extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::create('station_tasks', function (Blueprint $table) {
+            $table->id();
+            $table->integer('station_id');
+            $table->integer('station_type_id');
+            $table->index('station_id','station_type_id');
+            $table->timestamps();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::dropIfExists('station_tasks');
+    }
+}

+ 16 - 0
database/seeds/StationTaskSeeder.php

@@ -0,0 +1,16 @@
+<?php
+
+use Illuminate\Database\Seeder;
+
+class StationTaskSeeder extends Seeder
+{
+    /**
+     * Run the database seeds.
+     *
+     * @return void
+     */
+    public function run()
+    {
+        //
+    }
+}

+ 16 - 0
database/seeds/StationTaskTypeSeeder.php

@@ -0,0 +1,16 @@
+<?php
+
+use Illuminate\Database\Seeder;
+
+class StationTaskTypeSeeder extends Seeder
+{
+    /**
+     * Run the database seeds.
+     *
+     * @return void
+     */
+    public function run()
+    {
+        //
+    }
+}

+ 2 - 2
phpunit.xml

@@ -34,8 +34,8 @@
         <server name="APP_ENV" value="testing"/>
         <server name="BCRYPT_ROUNDS" value="4"/>
         <server name="CACHE_DRIVER" value="redis"/>
-<!--        <server name="DB_CONNECTION" value="sqlite"/>-->
-<!--        <server name="DB_DATABASE" value=":memory:"/>-->
+        <!--<server name="DB_CONNECTION" value="sqlite"/>
+        <server name="DB_DATABASE" value=":memory:"/>-->
         <server name="MAIL_DRIVER" value="array"/>
         <server name="QUEUE_CONNECTION" value="sync"/>
         <server name="SESSION_DRIVER" value="array"/>

+ 5 - 0
resources/views/layouts/menu.blade.php

@@ -47,6 +47,11 @@
                                     :class="{active:isActive('personnel',1)}">
                     <span class="fa fa-header" style="color: #72441b"></span>
                     人事管理</a></li> @endcan
+        @can('站管理')
+            <li class="nav-item"><a href="{{url("station/index")}}" class="nav-link"
+                                    :class="{active:isActive('station',1)}">
+                    <span class="fa fa-share-alt-square" style="color: #72441b"></span>
+                    站管理</a></li> @endcan
         @can('基础设置')
             <li class="nav-item"><a href="{{url("maintenance")}}" class="nav-link"
                                     :class="{active:isActive('maintenance',1)}">

+ 19 - 0
resources/views/maintenance/log/_taskModal.blade.php

@@ -0,0 +1,19 @@
+<div class="modal fade" tabindex="-1" role="dialog" id="task">
+    <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
+        <div class="modal-content">
+            <div class="modal-header">
+                <div class="container-fluid">
+                    <div class="row">
+
+                    </div>
+                </div>
+            </div>
+            <div class="modal-body">
+                <div v-html="detail"></div>
+            </div>
+            <div class="modal-footer">
+
+            </div>
+        </div>
+    </div>
+</div>

+ 6 - 4
resources/views/maintenance/log/index.blade.php

@@ -31,8 +31,8 @@
                         <th>ip</th>
                         <th>时间</th>
                     </tr>
-                    <tr v-for="log in logs" class="hover" @click="logsClick(log)" style="cursor: pointer">
-                        <td class="text-muted">@{{log.id}}</td>
+                    <tr v-for="log in logs" class="hover" @click="logsClick(log)" style="cursor: pointer;">
+                        <td class="text-muted">@{{log.id}}<span class="badge badge-danger small pull-right mr-3" v-if="log.mark == 'Y'">异常</span></td>
                         <td>@{{log.user_name}}</td>
                         <td>@{{log.operation}}</td>
                         <td>@{{log.type}}</td>
@@ -70,7 +70,8 @@
                         operation: '{{$log->operation}}',
                         type: '{{$log->type}}',
                         ip: '{{$log->ip}}',
-                        created_at: '{{$log->created_at}}'
+                        created_at: '{{$log->created_at}}',
+                        mark:'{{$log->exception_mark}}',
                     },
                     @endforeach
                     @endif
@@ -83,7 +84,8 @@
                         {name: 'type', type: 'input', tip: '操作', placeholder: '类型'},
                         {name: 'description', type: 'input', tip: '详情:可在两侧添加百分号(%)进行模糊搜索', placeholder: '详情'},
                         {name:'created_at_start',type:'dateTime',tip:'选择显示指定日期的起始时间'},
-                        {name:'created_at_end',type:'dateTime',tip:'选择显示指定日期的截止'}
+                        {name:'created_at_end',type:'dateTime',tip:'选择显示指定日期的截止'},
+                        {name:'is_exception',type:'checkbox',tip:'仅显示异常', data: [{name: 'true', value: '仅显示异常'}]}
                     ]
                 ];
                 this.from = new query({

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