Browse Source

Merge branch 'master' into hz-jwt

# Conflicts:
#	app/Http/Controllers/TestController.php
#	app/OwnerMaterial.php
#	composer.json
#	laravel-echo-server.lock
haozi 5 years ago
parent
commit
ab34ee4583
100 changed files with 1756 additions and 902 deletions
  1. 4 3
      app/Batch.php
  2. 1 1
      app/Commodity.php
  3. 4 3
      app/Console/Commands/CreateWeightStatistic.php
  4. 1 1
      app/Console/Commands/LogExpireDelete.php
  5. 0 1
      app/Console/Commands/MakeServiceCommand.php
  6. 16 8
      app/Console/Commands/SyncBatchTask.php
  7. 46 24
      app/Console/Commands/SyncWMSOrderTask.php
  8. 2 0
      app/Events/WaybillPriceModelEvent.php
  9. 8 0
      app/Feature.php
  10. 12 1
      app/Filters/LogFilters.php
  11. 1 1
      app/Http/Controllers/CitiesController.php
  12. 7 24
      app/Http/Controllers/ControlPanelController.php
  13. 2 0
      app/Http/Controllers/CustomerBaseController.php
  14. 26 15
      app/Http/Controllers/CustomerController.php
  15. 2 2
      app/Http/Controllers/MaterialController.php
  16. 7 11
      app/Http/Controllers/OrderIssueController.php
  17. 0 2
      app/Http/Controllers/OwnerController.php
  18. 13 1
      app/Http/Controllers/OwnerMaterialController.php
  19. 32 24
      app/Http/Controllers/PriceModelController.php
  20. 3 0
      app/Http/Controllers/SendEmailsController.php
  21. 2 2
      app/Http/Controllers/StoreController.php
  22. 3 3
      app/Http/Controllers/StoreItemController.php
  23. 142 27
      app/Http/Controllers/TestController.php
  24. 69 0
      app/Http/Controllers/UnitController.php
  25. 0 87
      app/Http/Controllers/UnitsController.php
  26. 59 30
      app/Http/Controllers/WaybillController.php
  27. 15 22
      app/Http/Controllers/WaybillPriceModelController.php
  28. 5 4
      app/Http/Controllers/WeighController.php
  29. 78 78
      app/Http/Controllers/api/thirdPart/flux/SortingController.php
  30. 4 4
      app/Http/Controllers/api/thirdPart/goodscan/PackageController.php
  31. 2 2
      app/Http/Controllers/api/thirdPart/haiq/PickStationController.php
  32. 11 1
      app/Http/Controllers/api/thirdPart/haochuang/SortingController.php
  33. 6 4
      app/Http/Controllers/api/thirdPart/weight/PackageController.php
  34. 10 14
      app/Imports/WaybillPriceModelsImport.php
  35. 1 0
      app/Jobs/OrderFreeze.php
  36. 45 0
      app/Jobs/WeightUpdateInstantBill.php
  37. 0 38
      app/Listeners/FulfillFulfillPackageCustomer.php
  38. 66 44
      app/Listeners/WaybillPriceModelListener.php
  39. 20 5
      app/Order.php
  40. 3 3
      app/OrderPackage.php
  41. 6 1
      app/Owner.php
  42. 4 0
      app/OwnerFeeDetail.php
  43. 21 0
      app/OwnerFeeDetailLogistic.php
  44. 6 4
      app/OwnerMaterial.php
  45. 2 0
      app/Providers/AppServiceProvider.php
  46. 0 3
      app/Providers/EventServiceProvider.php
  47. 1 1
      app/RejectedBill.php
  48. 33 31
      app/Services/BatchService.php
  49. 0 3
      app/Services/CommodityBarcodeService.php
  50. 22 22
      app/Services/CommodityService.php
  51. 6 5
      app/Services/FeatureService.php
  52. 50 28
      app/Services/ForeignHaiRoboticsService.php
  53. 4 0
      app/Services/LogService.php
  54. 0 3
      app/Services/LogisticService.php
  55. 21 11
      app/Services/OrderIssueService.php
  56. 42 24
      app/Services/OrderPackageCommoditiesService.php
  57. 13 7
      app/Services/OrderPackageService.php
  58. 94 28
      app/Services/OrderService.php
  59. 1 1
      app/Services/OrderTrackingService.php
  60. 64 44
      app/Services/OwnerPriceOperationService.php
  61. 16 11
      app/Services/OwnerStoragePriceModelService.php
  62. 6 2
      app/Services/PackageService.php
  63. 7 0
      app/Services/RegionService.php
  64. 1 3
      app/Services/RejectedBillItemService.php
  65. 0 5
      app/Services/ShopService.php
  66. 2 0
      app/Services/StationRuleBatchService.php
  67. 1 1
      app/Services/StationService.php
  68. 20 18
      app/Services/StationTaskBatchService.php
  69. 1 7
      app/Services/StationTaskChildService.php
  70. 16 20
      app/Services/StationTaskCommodityService.php
  71. 40 35
      app/Services/StationTaskMaterialBoxService.php
  72. 14 2
      app/Services/StationTaskService.php
  73. 1 3
      app/Services/StoreCheckingReceiveItemService.php
  74. 3 7
      app/Services/StoreItemService.php
  75. 1 1
      app/Services/UnitService.php
  76. 20 0
      app/Services/UserWorkgroupService.php
  77. 56 12
      app/Services/WaybillService.php
  78. 2 2
      app/Services/WeighExceptedService.php
  79. 22 0
      app/StationTaskBatch.php
  80. 5 5
      app/StationTaskMaterialBox.php
  81. 1 1
      app/Store.php
  82. 1 1
      app/StoreItem.php
  83. 40 6
      app/Traits/ServiceAppAop.php
  84. 47 20
      app/Traits/TestMockSubServices.php
  85. 1 1
      app/Unit.php
  86. 71 14
      app/Waybill.php
  87. 6 4
      app/WaybillPriceModel.php
  88. 3 3
      composer.json
  89. 4 1
      config/logging.php
  90. 1 1
      database/factories/FeatureFactory.php
  91. 1 4
      database/factories/StationTaskBatchFactory.php
  92. 1 1
      database/factories/StationTaskCommodityFactory.php
  93. 0 0
      database/migrations/2021_01_08_112003_add_default_mail_event_role.php
  94. 32 0
      database/migrations/2021_01_28_094833_edit_order_packages_status_add_uploaded_to_wms_enum.php
  95. 2 5
      database/migrations/2021_01_29_161734_add_units_data.php
  96. 48 0
      database/migrations/2021_02_04_112223_create_owner_fee_detail_logistics_table.php
  97. 41 0
      database/migrations/2021_02_18_105955_change_owner_operation_table.php
  98. 40 0
      database/migrations/2021_02_19_110139_change_owner_operation_owner_table.php
  99. 32 0
      database/migrations/2021_02_19_155516_change_owners_table_add_column_user_workgroup_id.php
  100. 32 0
      database/migrations/2021_02_20_162232_change_units_table_add_sequence_column.php

+ 4 - 3
app/Batch.php

@@ -5,6 +5,7 @@ namespace App;
 use Illuminate\Database\Eloquent\Model;
 
 use App\Traits\ModelLogChanging;
+use Illuminate\Database\Eloquent\Relations\HasOne;
 
 class Batch extends Model
 {
@@ -41,15 +42,15 @@ class Batch extends Model
     {
         return $this->hasOne(Owner::class,"id","owner_id");
     }
-    public function stationBatchTask()
+    public function stationTaskBatch(): HasOne
     {
         return $this->hasOne(StationTaskBatch::class);
     }
     public function stationTask()
     {
 
-        return $this->stationBatchTask?
-            $this->stationBatchTask->belongsTo(StationTask::class):
+        return $this->stationTaskBatch?
+            $this->stationTaskBatch->belongsTo(StationTask::class):
             null;
     }
 

+ 1 - 1
app/Commodity.php

@@ -13,7 +13,7 @@ class Commodity extends Model
     use ModelLogChanging;
 
     use ModelTimeFormat;
-    protected $fillable=['name','sku','owner_id','created_at','length','width','height','volumn',"type","pack_spec"];
+    protected $fillable=['name','sku','owner_id','created_at','length','width','height','volumn',"type","pack_spec",'updated_at'];
     protected $appends=['barcode'];
 //    protected $appends=['barcode','owner_name','owner_code'];
 

+ 4 - 3
app/Console/Commands/CreateWeightStatistic.php

@@ -25,9 +25,10 @@ class CreateWeightStatistic extends Command
     {
         $yesterday = date("Y-m-d",strtotime("-1 day"));
         $sql = <<<sql
-SELECT DATE_FORMAT(created_at,'%Y-%m-%d') date,
-SUM(CASE WHEN weighed_at IS NOT NULL THEN 1 ELSE 0 END) AS count,
-COUNT(1) total FROM order_packages WHERE created_at BETWEEN '{$yesterday} 00:00:00' AND '{$yesterday} 23:59:59' GROUP BY date
+SELECT DATE_FORMAT(order_packages.created_at,'%Y-%m-%d') date,
+SUM(CASE WHEN order_packages.weighed_at IS NOT NULL THEN 1 ELSE 0 END) AS count,
+COUNT(1) total FROM order_packages LEFT JOIN orders ON order_packages.order_id=orders.id WHERE orders.wms_status != '订单取消' 
+AND order_packages.created_at BETWEEN '{$yesterday} 00:00:00' AND '{$yesterday} 23:59:59' GROUP BY date
 sql;
         $result = DB::selectOne(DB::raw($sql));
         if (!$result)$obj = [

+ 1 - 1
app/Console/Commands/LogExpireDelete.php

@@ -44,7 +44,7 @@ class LogExpireDelete extends Command
     }
 
     public function deleteLog(){
-        $expire_duration=config('logging.expire_duration');//前150天
+        $expire_duration=config('logging.expire_duration');//保留的日志天数
         $date=Carbon::now()->subDays($expire_duration)->format('Y-m-d');
         DB::table('logs')->where('created_at','<',$date)->delete();
     }

+ 0 - 1
app/Console/Commands/MakeServiceCommand.php

@@ -45,7 +45,6 @@ class MakeServiceCommand extends Command
             mkdir('app\\Services',666,false);
         }
         preg_match('/(.*?)Service/',$this->argument('name'),$resultNames);
-        var_dump($this->argument('name'),$resultNames);
         if(count($resultNames)==0) {
             $fileName = $this->argument('name');
             $modelName = $this->argument('name');

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

@@ -2,6 +2,8 @@
 
 namespace App\Console\Commands;
 
+use App\Exceptions\ErrorException;
+use App\Exceptions\Exception;
 use App\Order;
 use App\OrderBin;
 use App\Services\BatchService;
@@ -33,7 +35,7 @@ class SyncBatchTask extends Command
 
     public function handle()
     {
-        sleep(rand(0,10));
+        sleep(100+rand(0,10));
         $this->disposeHeader();
         $this->disposeDetail();
     }
@@ -79,17 +81,18 @@ sql
         if ($batches){
             foreach ($batches as $index=>$batch)$map[$batch->code] = $index;
         }
-        $update = [["id","wms_status","remark","updated_at"]];
+        $update = [["id","wms_status","wms_type","updated_at"]];
         $insert = [];
+
         foreach ($waves as $wave){
             if (isset($map[$wave->waveno])){
                 $bat = $batches[$map[$wave->waveno]];
                 $wms_status = $this->wms_status($wave);
-                if ($bat->wms_status != $wms_status || $bat->remark != $wave->descr){
+                if ($bat->wms_status != $wms_status || $bat->wms_type != $wave->descr){
                     $update[] = [
                         "id" => $bat->id,
                         "wms_status" => $this->wms_status($wave),
-                        "remark"=>$wave->descr,
+                        "wms_type"=>$wave->descr,
                         "updated_at"=>$wave->edittime,
                     ];
                 }
@@ -98,7 +101,7 @@ sql
             $owner = app("OwnerService")->codeGetOwner($wave->customerid);
             $insert[] = [
                 "code" => $wave->waveno,
-                "remark"=>$wave->descr,
+                "wms_type"=>$wave->descr,
                 "status" => '未处理',
                 "wms_status" => $this->wms_status($wave),
                 "created_at"=>$wave->addtime,
@@ -166,6 +169,7 @@ sql;
             $batchMapping[$detail->orderno] = $detail->waveno;
         }
         $orders = Order::query()->select("id","batch_id","code")->whereIn("code",$orderCodes)->get();
+        if (count($orderCodes) != count($orders))LogService::log(__CLASS__,"格口号-订单存在差异",json_encode($orderCodes));
         if ($orders){
             $orderIds = [];
             $orderMap = [];
@@ -232,6 +236,7 @@ sql;
             app("OrderService")->batchUpdate($updateOrder);//反向修改订单
             LogService::log(__METHOD__,"波次同步-修改订单波次号",json_encode($updateOrder));
         }
+
         if ($map){
             $waveCodes = array_keys($map);
             $waves = $this->service->get(["waveno"=>$waveCodes],["waveno"=>"in"]);
@@ -242,7 +247,7 @@ sql;
                     "code" => $wave->waveno,
                     "status" => '未处理',
                     "wms_status" => $this->wms_status($wave),
-                    "remark"=>$wave->descr,
+                    "wms_type"=>$wave->descr,
                     "created_at"=>$wave->addtime,
                     "updated_at"=>$wave->edittime,
                     "owner_id"=>$owner->id,
@@ -255,11 +260,14 @@ sql;
                 foreach ($batches as $batch){
                     app("OrderService")->update(["code"=>$map[$batch->code]],["batch_id"=>$batch->id]);
                 }
+                try{
+//                    $this->batchService->assignTasks($batches);    //在这里为波次注册任务!
+                }catch (Exception $e){
+                    //避免影响外部事务:一般异常已在内部日志过
+                }
             }
         }
         ValueStore::query()->where("name","wave_detail_last_sync_date")->update(["value"=>$details[count($details)-1]->edittime]);
-
-        $this->batchService->assignTasks($batches);    //在这里为波次注册任务!
     }
 
     /**

+ 46 - 24
app/Console/Commands/SyncWMSOrderTask.php

@@ -2,6 +2,7 @@
 
 namespace App\Console\Commands;
 
+use App\OracleDOCOrderHeader;
 use App\Services\OracleDOCOrderHeaderService;
 use App\Services\OrderService;
 use App\ValueStore;
@@ -70,24 +71,36 @@ class SyncWMSOrderTask extends Command
     public function syncCreatedOrder()
     {
         /**
-         * @var OrderService $orderService
+         * @var OracleDocOrderHeaderService  $oracleDOCOrderHeaderService
          */
+        $oracleDOCOrderHeaderService = app('OracleDocOrderHeaderService');
+
         $newest_key         = config('sync.order_sync.cache_prefix.created_at');
         $newest_list_key    = 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');
-         $last_date = $this->service->getOrderSyncAt($newest_key,'newest');                             // 获取创建时间点
-        $orderHeaders =  app('OracleDocOrderHeaderService')->getWMSOrderOnStartDate($last_date);               // WMS订单
+        ini_set('memory_limit', '1024M');
+        $last_date = $this->service->getOrderSyncAt($newest_key,'newest');                             // 获取创建时间点
+
+        $orderHeaders = OracleDOCOrderHeader::query()
+            ->selectRaw(implode(',',OracleDOCOrderHeaderService::$columns))
+            ->whereColumn('DOC_Order_Header.editTime','=','DOC_Order_Header.addTime')
+            ->where('addTime','>=',$last_date)
+            ->orderByDesc('DOC_Order_Header.addTime')->get();
+
         if($orderHeaders->count()==0)return;
-        $last_order = $orderHeaders->first();                                                               // 时间点靠后的
-        $newest_orders = $orderHeaders->where('addtime',$last_order->addtime);
-        $orderHeaders = $this->service->filterOrderByCache($orderHeaders,$newest_list_key);                  // 对比缓存
-        if(count($newest_orders)>0 && count($orderHeaders) >0){
-            $this->service->syncOrder($orderHeaders);                                                    //  同步订单
-            $this->service->cancelOrderCache($newest_list_key,$prefixKey);                                   //  清除缓存
-            $this->service->pushOrderCache($newest_orders,$prefixKey,$hasKey,$newest_list_key);              //  添加缓存
-            $this->service->setOrderSyncAt($newest_key,$last_order->addtime,count($orderHeaders)>0);   //  更新时间
+        $orderHeaderList = $orderHeaders->chunk(2000);
+        foreach ($orderHeaderList as $item) {
+            $item = $oracleDOCOrderHeaderService->loadMissing($item);
+            $last_order = $item->first();                                                               // 时间点靠后的
+            $newest_orders = $item->where('addtime',$last_order->addtime);
+            $orderHeaders = $this->service->filterOrderByCache($item,$newest_list_key);                  // 对比缓存
+            if(count($newest_orders)>0 && count($orderHeaders) >0){
+                $this->service->syncOrder($orderHeaders);                                                    //  同步订单
+                $this->service->cancelOrderCache($newest_list_key,$prefixKey);                                   //  清除缓存
+                $this->service->pushOrderCache($newest_orders,$prefixKey,$hasKey,$newest_list_key);              //  添加缓存
+                $this->service->setOrderSyncAt($newest_key,$last_order->addtime,count($orderHeaders)>0);   //  更新时间
+            }
         }
         unset($orderHeaders,$newest_orders,$last_order);
     }
@@ -96,26 +109,35 @@ class SyncWMSOrderTask extends Command
     {
         /**
          * @var OracleDOCOrderHeaderService $oracleDOCOrderHeaderService
-         * @var OrderService $orderService
          */
+        $oracleDOCOrderHeaderService = app('OracleDocOrderHeaderService');
         $renewal_key        = config('sync.order_sync.cache_prefix.updated_at');
         $renewal_list_key   = 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');
-
+        ini_set('memory_limit', '1024M');
         $last_date = $this->service->getOrderSyncAt($renewal_key,'renewal');                               // 获取更新时间点
-        $orderHeaders = app('OracleDocOrderHeaderService')->getWMSOrderOnEditDate($last_date);      // WMS订单
+
+        $orderHeaders = OracleDOCOrderHeader::query()->where('editTime',">=",$last_date)
+            ->selectRaw(implode(',',OracleDOCOrderHeaderService::$columns))
+            ->whereColumn('DOC_Order_Header.editTime','!=','DOC_Order_Header.addTime')
+            ->orderByDesc('editTime')
+            ->get();
 
         if($orderHeaders->count()==0)return;
-        $renewal_order = $orderHeaders->first();                                                            // 时间点靠后的
-        $renewal_orders =  $orderHeaders->where('edittime',$renewal_order->edittime);
-        $orderHeaders = $this->service->filterOrderByCache($orderHeaders,$renewal_list_key);                     // 对比缓存
-        if(count($renewal_orders)>0 && count($orderHeaders)>0){
-            $this->service->syncOrder($orderHeaders);                                                    // 同步订单
-            $this->service->cancelOrderCache($renewal_list_key,$prefixKey);                                      // 清除缓存
-            $this->service->pushOrderCache($renewal_orders,$prefixKey,$hasKey,$renewal_list_key);                // 添加缓存
-            $this->service->setOrderSyncAt($renewal_key,$renewal_order->edittime,count($orderHeaders)>0);   // 更新时间
+
+        $orderHeaderList = $orderHeaders->chunk(2000);
+        foreach ($orderHeaderList as $item) {
+            $item  = $oracleDOCOrderHeaderService->loadMissing($item);
+            $renewal_order = $item->first();                                                            // 时间点靠后的
+            $renewal_orders =  $item->where('edittime',$renewal_order->edittime);
+            $orderHeaders = $this->service->filterOrderByCache($orderHeaders,$renewal_list_key);                     // 对比缓存
+            if(count($renewal_orders)>0 && count($orderHeaders)>0){
+                $this->service->syncOrder($item);                                                    // 同步订单
+                $this->service->cancelOrderCache($renewal_list_key,$prefixKey);                                      // 清除缓存
+                $this->service->pushOrderCache($renewal_orders,$prefixKey,$hasKey,$renewal_list_key);                // 添加缓存
+                $this->service->setOrderSyncAt($renewal_key,$renewal_order->edittime,count($orderHeaders)>0);   // 更新时间
+            }
         }
         unset($orderHeaders,$renewal_orders,$renewal_order);
     }

+ 2 - 0
app/Events/WaybillPriceModelEvent.php

@@ -15,6 +15,8 @@ class WaybillPriceModelEvent
     /**
      * Create a new event instance.
      *
+     * @param WaybillPriceModel $waybillPriceModel
+     *
      * @return void
      */
     public function __construct(WaybillPriceModel $waybillPriceModel)

+ 8 - 0
app/Feature.php

@@ -15,4 +15,12 @@ class Feature extends Model
         "logic",    //逻辑
         "describe", //特征
     ];
+
+    const type = [
+        0 => "商品名称",
+        1 => "订单类型",
+        2 => "承运商",
+        3 => "店铺类型",
+        4 => "波次类型",
+    ];
 }

+ 12 - 1
app/Filters/LogFilters.php

@@ -13,7 +13,7 @@ class LogFilters
     protected $request;
     protected $queryBuilder;
     protected $filters = ['username', 'type', 'description',
-        'created_at_start', 'created_at_end', 'is_exception'];
+        'created_at_start', 'created_at_end', 'is_exception', 'class', 'method'];
     protected $array_filter;
 
     public function __construct(Request $request)
@@ -94,6 +94,17 @@ class LogFilters
         $this->queryBuilder->where("description", 'like', $description . '%');
     }
 
+    private function class($class)
+    {
+        $class = str_replace('\\', '\\\\', $class);
+        $this->queryBuilder->where("class", 'like', $class . '%');
+    }
+
+    private function method($method)
+    {
+        $this->queryBuilder->where("method", 'like', $method . '%');
+    }
+
     private function type($type)
     {
         $types = array_filter(preg_split('/[,, ]+/is', $type));

+ 1 - 1
app/Http/Controllers/CitiesController.php

@@ -13,7 +13,7 @@ use Illuminate\Support\Facades\Validator;
 
 class CitiesController extends Controller
 {
-    public function index(ForeignHaiRobotic_taskUpdateRequest $request)
+    public function index(Request $request)
     {
         if(!Gate::allows('城市-查询')){ return redirect(url('/'));  }
         $cities=City::orderBy('id', 'DESC')->paginate(50);

+ 7 - 24
app/Http/Controllers/ControlPanelController.php

@@ -32,29 +32,11 @@ class ControlPanelController extends Controller
 
     public function index()
     {
-        /**
-         * @var $orderCountingRecordService  NewOrderCountingRecordService
-         * @var $laborReportsCountingRecordService LaborReportsCountingRecordService
-         */
-        $checkActiveMenuService = app(CheckActiveMenuService::class);
-        $menus = $checkActiveMenuService->activeMenus();
-        $realtimePendingOrdersService = app(RealtimePendingOrdersService::class);
-        $warehousesOrders = $realtimePendingOrdersService->warehousesOrders();
-        $orderCountingRecordService = app(NewOrderCountingRecordService::class);
-        //默认查询一个月的数据
-        $start = (new Carbon())->subMonth()->toDateString();
-        $end = (new Carbon())->toDateString();
         $ownerIds = $this->getCountingOwnerIds(null);
+        $menus = app(CheckActiveMenuService::class)->activeMenus();
         $owners=Owner::query()->whereIn('id',$ownerIds)->get();
-        $unit = '日';
-        $orderCountingRecords = $orderCountingRecordService->orderCountingRecordsFromCache($start, $end, $unit, $ownerIds);
-        $logisticsCountingRecords = $orderCountingRecordService->logisticsCountingRecords($start, $end, $ownerIds);
-        $warehouseCountingRecords = $orderCountingRecordService->warehouseCountingRecords($start, $end, $ownerIds);
-
-        $laborReportsCountingRecordService = app(LaborReportsCountingRecordService::class);
-        $laborReportsCountingRecords = $laborReportsCountingRecordService->get($start, $end, $unit);
-        $laborReportsUserGroupsCount = $laborReportsCountingRecordService->userGroupsCount($start, $end);
-        return view('control.panel', compact('owners','menus', 'warehousesOrders', 'orderCountingRecords', 'logisticsCountingRecords', 'warehouseCountingRecords', 'laborReportsCountingRecords', 'laborReportsUserGroupsCount'));
+        $warehousesOrders = app(RealtimePendingOrdersService::class)->warehousesOrders();
+        return view('control.panel', compact('owners','menus', 'warehousesOrders'));
     }
 
     public function orderCountingRecordsApi(Request $request)
@@ -188,9 +170,10 @@ class ControlPanelController extends Controller
     {
         if ($date == date("Y-m-d")){
             $sql = <<<sql
-SELECT DATE_FORMAT(created_at,'%Y-%m-%d') date,
-SUM(CASE WHEN weighed_at IS NOT NULL THEN 1 ELSE 0 END) AS count,
-COUNT(1) total FROM order_packages WHERE created_at >= '{$date} 00:00:00' GROUP BY date
+SELECT DATE_FORMAT(order_packages.created_at,'%Y-%m-%d') date,
+SUM(CASE WHEN order_packages.weighed_at IS NOT NULL THEN 1 ELSE 0 END) AS count,
+COUNT(1) total FROM order_packages LEFT JOIN orders ON order_packages.order_id=orders.id WHERE orders.wms_status != '订单取消' 
+AND order_packages.created_at >= '{$date} 00:00:00' GROUP BY date
 sql;
 
             $pack = DB::selectOne(DB::raw($sql));

+ 2 - 0
app/Http/Controllers/CustomerBaseController.php

@@ -131,6 +131,7 @@ class CustomerBaseController extends Controller
         return Validator::make($params,[
             'code'=>['required',$id?"unique:customers,code,$id":'unique:customers,code','max:20'],
             'name'=>['required','max:20'],
+            'company_name'=>['required'],
         ],[
             'required'=>':attribute 为必填项',
             'max'=>':attribute 字符过多或输入值过大',
@@ -138,6 +139,7 @@ class CustomerBaseController extends Controller
         ],[
             'code'=>'客户代码',
             'name'=>'客户名称',
+            'company_name'=>'公司名称',
         ]);
     }
 

+ 26 - 15
app/Http/Controllers/CustomerController.php

@@ -93,11 +93,12 @@ class CustomerController extends Controller
         if(!Gate::allows('客户管理-项目-查询')){ return redirect('denied');  }
         /** @var OwnerService $service */
         $service = app('OwnerService');
-        $owners = $service->paginate(request()->input(),['customer',"contracts","userOwnerGroup","ownerStoragePriceModels","ownerAreaReport"=>function($query){
+        $owners = $service->paginate(request()->input(),['customer',"userOwnerGroup","userWorkGroup",
+            "ownerStoragePriceModels",/*"ownerAreaReport"=>function($query){
             $month = date('Y-m');
             /** @var Builder $query */
-            $query->where("counting_month","like",$month."%");
-        }]);
+           /*$query->where("counting_month","like",$month."%");
+        }*/]);
         $models = app('OwnerService')->getIntersectPermitting();
         $customers = app('CustomerService')->getSelection();
         $ownerGroups = app('UserOwnerGroupService')->getSelection();
@@ -157,9 +158,10 @@ class CustomerController extends Controller
         if(!Gate::allows('客户管理-项目-录入')){ return redirect('denied');  }
         $customers = app('CustomerService')->getSelection();
         $ownerGroups = app('UserOwnerGroupService')->getSelection();
+        $userGroups = app('UserWorkgroupService')->getSelection(["id","name","warehouse_id"]);
         $warehouses = app('WarehouseService')->getSelection();
         $owner = null;
-        return response()->view('customer.project.create',compact("customers","ownerGroups","owner","warehouses"));
+        return response()->view('customer.project.create',compact("customers","ownerGroups","owner","warehouses","userGroups"));
     }
 
     public function projectUpdate()
@@ -179,6 +181,7 @@ class CustomerController extends Controller
             "linkman"               => request("linkman"),
             "phone_number"          => request("phone_number"),
             "user_owner_group_id"   => request("owner_group_id"),
+            "user_workgroup_id"     => request("user_workgroup_id"),
             "waring_line_on"        => request("waring_line_on"),
             "description"           => request("description"),
         ]);
@@ -204,6 +207,7 @@ class CustomerController extends Controller
         $owner = app('OwnerService')->find($id);
         $owner->loadCount(["ownerStoragePriceModels","ownerPriceOperations","ownerPriceExpresses","ownerPriceLogistics","ownerPriceDirectLogistics"]);
         $isExist = false;
+        /** @var \stdClass $owner */
         if($owner->owner_storage_price_models_count ||
             $owner->owner_price_operations_count ||
             $owner->owner_price_expresses_count ||
@@ -211,14 +215,16 @@ class CustomerController extends Controller
             $owner->owner_price_direct_logistics_count) $isExist = true;
         $customers = app('CustomerService')->getSelection();
         $ownerGroups = app('UserOwnerGroupService')->getSelection();
+        $userGroups = app('UserWorkgroupService')->getSelection(["id","name","warehouse_id"]);
         $warehouses = app('WarehouseService')->getSelection();
-        return response()->view('customer.project.create',compact("customers","ownerGroups","warehouses",'owner',"isExist"));
+        $type = request("type");
+        return response()->view('customer.project.create',compact("customers","ownerGroups","warehouses",'owner',"isExist", "type","userGroups"));
     }
 
     public function projectArea(Request $request)
     {
         if(!Gate::allows('客户管理-项目-面积')){ return redirect('denied');  }
-        $areas = app('OwnerAreaReportService')->paginate($request->input(),["owner"=>function($query){$query->with(["customer","ownerStoragePriceModels"]);}]);
+        $areas = app('OwnerAreaReportService')->paginate($request->input(),["owner"=>function($query){$query->with(["customer","ownerStoragePriceModels.unit"]);}]);
         $ownerGroups = app('UserOwnerGroupService')->getSelection();
         $customers = app('CustomerService')->getSelection();
         $owners = app('OwnerService')->getIntersectPermitting();
@@ -230,13 +236,17 @@ class CustomerController extends Controller
     {
         if(!Gate::allows('客户管理-项目-面积-编辑')){ return ["success"=>false,'data'=>"无权操作!"];  }
         if (!($request->id ?? false) || !($request->area ?? false)) return ["success"=>false,'data'=>"传递错误!"];
-        $values = $request->area ?? null;
-        if (!$values)return ["success"=>true,"data"=>$values];
-        foreach ($values as $column=>$value){
-            if ($value && (!is_numeric($value) || $value<0))return ["success"=>false,'data'=>$column."非数字或小于0!"];
-        }
-        $accounting_area = ((int)$values["area_on_tray"]*2.5) + ((int)$values["area_on_half_tray"]*1.8) + ((int)$values["area_on_flat"]*1.3);
-        $values["accounting_area"] = $accounting_area;
+
+        if (!request("accounting_area")){
+            $values = $request->area ?? null;
+            if (!$values)return ["success"=>true,"data"=>$values];
+            foreach ($values as $column=>$value){
+                if ($value && (!is_numeric($value) || $value<0))return ["success"=>false,'data'=>$column."非数字或小于0!"];
+            }
+            $accounting_area = ((int)$values["area_on_tray"]*2.5) + ((int)$values["area_on_half_tray"]*1.8) + ((int)$values["area_on_flat"]*1.3);
+            $values["accounting_area"] = $accounting_area;
+        }else $values = ["accounting_area"=>request("accounting_area")];
+
         $row = app('OwnerAreaReportService')->update(["id"=>$request->id],$values);
         if ($row==1){
             LogService::log(__METHOD__,"客户管理-修改面积",json_encode($request->input()));
@@ -290,7 +300,7 @@ class CustomerController extends Controller
         $shops = app('ShopService')->getSelection();
         $customers = app('CustomerService')->getSelection();
         $owners = app('OwnerService')->getIntersectPermitting();
-        $details = app('OwnerFeeDetailService')->paginate($params,["owner"=>function($query){$query->with("customer");},"shop","processMethod","logistic"]);
+        $details = app('OwnerFeeDetailService')->paginate($params,["owner.customer","shop","processMethod","logistic","items"]);
         return response()->view('customer.finance.instantBill',compact("details","params","shops","customers","owners"));
     }
 
@@ -480,7 +490,7 @@ class CustomerController extends Controller
         $owners = $service->get(["id"=>$ids],["ownerStoragePriceModels"],false,true);
         app("OwnerAreaReportService")->notExistToInsert($owners);
 
-        $reports = OwnerAreaReport::query()
+        $reports = OwnerAreaReport::query()->with(["owner","ownerStoragePriceModel.unit"])
             ->where("counting_month",">=",date("Y-m")."-01")
             ->whereIn("owner_id",array_column($owners->toArray(),"id"))->get();
         $result = [];
@@ -497,6 +507,7 @@ class CustomerController extends Controller
                 "accountingArea" => $report->accounting_area,
                 "status" => $report->status,
                 "updatedAt" => $report->updated_at,
+                "unitName"  => $report->ownerStoragePriceModel ? ($report->ownerStoragePriceModel->unit ? $report->ownerStoragePriceModel->unit->name : '') : '',
                 "ownerStoragePriceModel"=> $report->ownerStoragePriceModel ? $report->ownerStoragePriceModel->using_type : '' ,
             ];
         }

+ 2 - 2
app/Http/Controllers/MaterialController.php

@@ -10,7 +10,7 @@ use Illuminate\Http\Request;
 
 class MaterialController extends Controller
 {
-    // 耗材
+    // 耗材类型
     use AsyncResponse;
     public function index(Request $request,MaterialFilters  $filter)
     {
@@ -23,7 +23,7 @@ class MaterialController extends Controller
     {
         $this->gate('耗材类型-编辑');
         $material = Material::query()->where('code',$request['code'])->first();
-        if($material)return ['success' => false,'message'=>'code对应的耗材已存在'];
+        if($material)return ['success' => false,'message'=>'code对应的耗材类型已存在'];
         try {
             $material = Material::query()->create($request->all(['code', 'name']));
             return ['success'=>true,'data'=>$material];

+ 7 - 11
app/Http/Controllers/OrderIssueController.php

@@ -171,17 +171,13 @@ class OrderIssueController extends Controller
         if (!$request->input('orderNos')) {
             return ['success' => false, 'fail_info' => '没有传入的订单编号'];
         }
-        /** @var OrderIssueService $orderIssueService */
-        $orderIssueService = app(OrderIssueService::class);
-        $exits_orderNos = $orderIssueService->校验问题件是否存在_WMS订单号_返回存在的订单号($request->input('orderNos'));
-        $count = OracleDOCOrderHeader::query()->with('oracleBASCode')->whereIn('OrderNo',$request['orderNos'])->whereHas('oracleBASCode',function($query){
-            $query->whereNotIn('codename_c',['完全装箱','订单完成','完全发运','分配完成']);
-        })->count();
-        if($count>0)return ['success'=>false,'fail_info'=>'勾选的订单中有没有完成的订单,请取消勾选'];
-        if(count($exits_orderNos)>0){
-            return ['success'=>false,'fail_info'=>'标记问题件存在已有订单号','exitsOrderNos' =>$exits_orderNos];
-        }
-        return $orderIssueService->orderIssueTag($request->all());
+        /** @var OrderIssueService $service */
+        $service = app(OrderIssueService::class);
+        $exits_orderNos = $service->校验问题件是否存在_WMS订单号_返回存在的订单号($request->input('orderNos'));
+        if(count($exits_orderNos)>0) return ['success'=>false,'fail_info'=>'标记问题件存在已有订单号','exitsOrderNos' =>$exits_orderNos];
+        $soft_delete_order_nos = $service->checkOrderIssueIsExistAndSoftDelete($request['orderNos']);
+        if(count($soft_delete_order_nos)>0) return ['success'=>false,'fail_info'=>'订单对应问题件存在回收站,如需要请从回收站恢复','exitsOrderNos' =>$soft_delete_order_nos];
+        return $service->orderIssueTag($request->all());
     }
 
     public function apiDestroy(Request $request)

+ 0 - 2
app/Http/Controllers/OwnerController.php

@@ -58,8 +58,6 @@ class OwnerController extends Controller
         $this->validatorCreate($request->all())->validate();
         $owner = new Owner($request->all());
         $owner->save();
-//        event(new CustomerStoreEvent($owner));
-        event(new CustomerStored($owner));
         $authority = new Authority([
             'name' => "_{$owner['id']}",
             'alias_name' => "(货主:{$owner['name']})",

+ 13 - 1
app/Http/Controllers/OwnerMaterialController.php

@@ -12,6 +12,8 @@ use App\file;
 use Faker\Provider\Uuid;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Auth;
+use Illuminate\Support\Facades\Gate;
+use Illuminate\Support\Facades\Storage;
 
 class OwnerMaterialController extends Controller
 {
@@ -65,6 +67,7 @@ class OwnerMaterialController extends Controller
         if(!$ownerMaterial)$this->error('项目耗材不存在');
         try {
             $file = $request->file('file');
+            if(!$file)$this->error('请选择上传文件');
             $fileType = $file->getMimeType();// 文件类型
             $fileName = strtolower($file->getClientOriginalExtension());// 文件名
             $path = $file->storeAs("ownerMaterial", Uuid::uuid() . "." . $fileName);
@@ -75,9 +78,18 @@ class OwnerMaterialController extends Controller
                 'type' => $fileType,
                 "file_name" => $file->getClientOriginalName()
             ]);
-            $this->success($ownerMaterial->loadMissing(['owner', 'material', 'initiator', 'file']));
+            $ownerMaterial->loadMissing(['owner', 'material', 'initiator', 'file']);
+            $this->success($ownerMaterial);
         } catch (Exception $e) {
             $this->error($e->getMessage());
         }
     }
+
+    public function downFile(Request $request)
+    {
+        if(!Gate::allows('项目耗材'))return ['success'=>false,"data"=>"无权操作"];
+        $file = $request->input("file");
+        $name = $request->input("name");
+        return Storage::download($file,$name);
+    }
 }

+ 32 - 24
app/Http/Controllers/PriceModelController.php

@@ -265,14 +265,19 @@ class PriceModelController extends Controller
             "priority" => $request->input("priority"),
             "remark" => $request->input("remark"),
             "feature" => $request->input("feature"),
-            "discount_count"    => request("discount_count"),
+            "discount_count"    => request("discount_count") ? implode(",",request("discount_count")) : null,
             "total_price"       => request("total_price"),
-            "total_discount_price"=> request("total_discount_price") ?? null,
+            "total_discount_price"=> request("total_discount_price") ? implode(",",request("total_discount_price")) : null,
         ]);
         if ($request->input("items")){
             //录入子表
             $insert = [];
             foreach ($request->input("items") as $rule){
+                if ($rule["discount_price"] ?? false){
+                    foreach ($rule["discount_price"] as $index=>$item){
+                        if ($index!=0 && !$item)$rule["discount_price"][$index] = $rule["discount_price"][$index-1];
+                    }
+                }
                 $insert[] = [
                     "owner_price_operation_id" => $ownerPriceOperation->id,
                     "amount" => $rule["amount"],
@@ -281,7 +286,7 @@ class PriceModelController extends Controller
                     "strategy" => $rule["strategy"],
                     "feature" => $rule["feature"],
                     "priority" => $rule["priority"],
-                    "discount_price" => $rule["discount_price"] ?? null,
+                    "discount_price" =>  implode(",",$rule["discount_price"]),
                 ];
             }
             $service->insertItem($insert);
@@ -318,26 +323,28 @@ class PriceModelController extends Controller
             "priority" => $request->input("priority"),
             "remark" => $request->input("remark"),
             "feature" => $request->input("feature"),
-            "discount_count"    => request("discount_count"),
+            "discount_count"    => implode(",",request("discount_count")),
             "total_price"       => request("total_price"),
-            "total_discount_price"=> request("total_discount_price") ?? null,
+            "total_discount_price"=> implode(",",request("total_discount_price")) ?? null,
         ]);
         $service->destroyItem($id);
-        //录入子表
-        $insert = [];
-        foreach ($request->input("items") as $rule){
-            $insert[] = [
-                "owner_price_operation_id" => $model->id,
-                "amount" => $rule["amount"],
-                "unit_id" => $rule["unit_id"],
-                "unit_price" => $rule["unit_price"],
-                "strategy" => $rule["strategy"],
-                "feature" => $rule["feature"],
-                "priority" => $rule["priority"],
-                "discount_price" => $rule["discount_price"] ?? null,
-            ];
+        if ($request->input("items")){
+            //录入子表
+            $insert = [];
+            foreach ($request->input("items") as $rule){
+                $insert[] = [
+                    "owner_price_operation_id" => $model->id,
+                    "amount" => $rule["amount"],
+                    "unit_id" => $rule["unit_id"],
+                    "unit_price" => $rule["unit_price"],
+                    "strategy" => $rule["strategy"],
+                    "feature" => $rule["feature"],
+                    "priority" => $rule["priority"],
+                    "discount_price" => implode(",",$rule["discount_price"]) ?? null,
+                ];
+            }
+            $service->insertItem($insert);
         }
-        $service->insertItem($insert);
         //录入中间表
         /** @var OwnerPriceOperation $model */
         if ($request->input("owner_id"))$model->ownerPriceOperationOwners()->sync($request->input("owner_id"));
@@ -363,7 +370,7 @@ class PriceModelController extends Controller
                 }
             }],
             'strategy'=>['required'],
-            'name'=>['required',$id?"unique:owner_price_operations,name,$id":'unique:owner_price_operations,name'],
+            'name'=>['required'/*,$id?"unique:owner_price_operations,name,$id":'unique:owner_price_operations,name'*/],
             'priority'=>['sometimes','required','integer','min:0','max:100'],
             'items.*.strategy'=>['required'],
             'items.*.amount'=>["required","integer"],
@@ -1057,9 +1064,9 @@ class PriceModelController extends Controller
             "strategy"          => request("strategy"),
             "feature"           => request("feature"),
             "remark"            => request("remark"),
-            "discount_count"    => request("discount_count"),
+            "discount_count"    => implode(",",request("discount_count")),
             "total_price"       => request("total_price"),
-            "total_discount_price"=> request("total_discount_price"),
+            "total_discount_price"=> implode(",",request("total_discount_price")),
         ];
         if (request("id")){
             $model = app('OwnerPriceOperationService')->find(request("id"),["items"]);
@@ -1074,7 +1081,7 @@ class PriceModelController extends Controller
                     "unit_id"   => $item["unit_id"],
                     "unit_price"=> $item["unit_price"],
                     "feature"   => $item["feature"] ?? null,
-                    "discount_price"   => $item["discount_price"] ?? null,
+                    "discount_price"   => implode(",",$item["discount_price"] ?? []),
                 ];
                 if (isset($item["id"])){
                     $obj["id"] = $item["id"];
@@ -1095,6 +1102,7 @@ class PriceModelController extends Controller
             DB::transaction(function ()use(&$model,$params,$operation){
                 $model = app('OwnerPriceOperationService')->create($operation);
                 foreach ($params["items"] as &$item){
+                    $item["discount_price"]  = implode(",",$item["discount_price"] ?? []);
                     $item["owner_price_operation_id"] = $model->id;
                     if (!isset($item["feature"]))$item["feature"] = null;
                     unset($item["features"]);
@@ -1102,7 +1110,7 @@ class PriceModelController extends Controller
                     unset($item["type"]);
                 }
                 app("OwnerPriceOperationItemService")->insert($params["items"]);
-                DB::insert(DB::raw("INSERT INTO owner_price_operation_owner VALUES(?,?)"),[$model->id,request("owner_id")]);
+                DB::insert(DB::raw("INSERT INTO owner_price_operation_owner(owner_price_operation_id,owner_id) VALUES(?,?)"),[$model->id,request("owner_id")]);
                 DB::commit();
             });
         }

+ 3 - 0
app/Http/Controllers/SendEmailsController.php

@@ -76,6 +76,9 @@ class SendEmailsController extends Controller
 
     public function updateRemark(Request $request)
     {
+        $this->validate($request, [
+            'remark' => 'required|string',
+        ]);
         $model = MailEvent::query()->find($request->id);
         $model->update([
             'remark' => $request->remark,

+ 2 - 2
app/Http/Controllers/StoreController.php

@@ -7,7 +7,7 @@ use App\Owner;
 use App\Services\common\BatchUpdateService;
 use App\Services\StoreService;
 use App\Store;
-use App\StoreItems;
+use App\StoreItem;
 use App\Warehouse;
 use App\WMSReflectReceive;
 use Carbon\Carbon;
@@ -140,7 +140,7 @@ class StoreController extends Controller
                         }
                         return $depository;
                     })();
-                    $storeItem=new StoreItems([
+                    $storeItem=new StoreItem([
                         'store_id'=>$store->id,
                         'asn_line_code'=>$sku->ASNLINENO,
                         'name'=>$sku->SKUDESCRC,

+ 3 - 3
app/Http/Controllers/StoreItemsController.php → app/Http/Controllers/StoreItemController.php

@@ -2,13 +2,13 @@
 
 namespace App\Http\Controllers;
 
-use App\StoreItems;
+use App\StoreItem;
 use Illuminate\Contracts\Foundation\Application;
 use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\Response;
 use Illuminate\View\View;
 
-class StoreItemsController extends Controller
+class StoreItemController extends Controller
 {
     /**
      * Display a listing of the resource.
@@ -17,7 +17,7 @@ class StoreItemsController extends Controller
      */
     public function index()
     {
-        $storeItems=StoreItems::query()->with('store')
+        $storeItems=StoreItem::query()->with('store')
             ->whereHas('store',function($query){
                 $query->where('is_fast_stored','快速入库');
             })

+ 142 - 27
app/Http/Controllers/TestController.php

@@ -83,15 +83,17 @@ use App\Services\OrderTrackingOwnerService;
 use App\Services\OrderTrackingService;
 use App\Services\OwnerPriceOperationService;
 use App\Services\OwnerService;
+use App\Services\RegionService;
 use App\Services\RejectedBillService;
 use App\Services\ShopService;
 use App\Services\StoreService;
 use App\Services\WarehouseService;
 use App\StationRuleBatch;
+use App\StationTask;
 use App\Store;
 use App\StationTaskBatch;
 use App\StoreCheckingReceiveItem;
-use App\StoreItems;
+use App\StoreItem;
 use App\Unit;
 use App\User;
 use App\ValueStore;
@@ -132,14 +134,82 @@ class TestController extends Controller
     {
         return call_user_func([$this, $method], $request);
     }
-
     public function zzd(){
-        $update = [
-            ["id","wms_status","remark","updated_at"],
-            ["id"=>6,"wms_status"=>"完全收货",
-                "remark"=>"01.[ALLBLU]普通波次","updated_at"=>"2021-01-27 08:58:53"]
-        ];
-        dd(app(BatchUpdateService::class)->batchUpdate("batches",$update));
+        ini_set('max_execution_time',2500);
+        ini_set('memory_limit','1526M');
+        $models = WaybillPriceModel::query()->get();
+        foreach ($models as $model){
+            if ($model->city_name == '汕头/汕尾'){
+                $region1 = Region::query()->where("name","汕头")->first();
+                $region2 = Region::query()->where("name","汕尾")->first();
+                $model->update([
+                    "province_id" =>$region1->parent_id,
+                    "city_id" =>$region1->id,
+                ]);
+                WaybillPriceModel::query()->create([
+                    'logistic_id'=> $model->logistic_id,
+                    'province_id' => $region2->parent_id,
+                    'city_id' => $region2->id,
+                    'unit_id' => $model->unit_id,
+                    'range_min' => $model->range_min,
+                    'range_max'=> $model->range_max,
+                    'unit_price'=> $model->unit_price,
+                    'base_fee'=> $model->base_fee,
+                    'initial_weight'=> $model->initial_weight
+                ]);
+                LogService::log(__CLASS__,"修改运输计费",$model->toJson());
+                continue;
+            }
+            $obj = [];
+            if ($model->province_id){
+                $obj["province_id"] = app(RegionService::class)->getProvince($model->province_name);
+            }
+            if ($model->city_id){
+                $obj["city_id"] = app(RegionService::class)->getCity($model->city_name);;
+            }
+            if (count($obj)>0){
+                $model->update($obj);
+                LogService::log(__CLASS__,"修改运输计费",$model->toJson());
+            }
+        }
+        dd("OK");
+    }
+
+    public function zzd1()
+    {
+        ini_set('max_execution_time',2500);
+        ini_set('memory_limit','1526M');
+        $models = Waybill::query()->whereNotNull("origination_city_id")
+            ->orWhereNotNull("destination_city_id")->get();
+        foreach ($models as $model){
+            $obj = [];
+            if ($model->origination_city_id){
+                $city = City::query()->find($model->origination_city_id)->name ?? null;
+                if ($city)$obj["origination_city_id"] = app(RegionService::class)->getCity($city);
+            }
+            if ($model->destination_city_id){
+                $city = City::query()->find($model->destination_city_id)->name ?? null;
+                if ($city)$obj["destination_city_id"] = app(RegionService::class)->getCity($city);
+            }
+            if (count($obj)>0){
+                $model->update($obj);
+                LogService::log(__CLASS__,"修改运输单",$model->toJson());
+            }
+        }
+        dd("OK");
+    }
+
+    public function test1(){
+        $cityIds = [2];
+        $parovince = "北京";
+        $waybills = Waybill::query()->where(function ($query)use($cityIds,$parovince){
+            /** @var Builder $query */
+            $query->whereIn('destination_city_id',$cityIds)->orWhereHas("order",function ($query)use($province){
+                /** @var Builder $query */
+                $query->where("province","like",$province."%");
+            });
+        })->get();
+        dd($waybills);
     }
 
     public function syncWeight()
@@ -150,9 +220,10 @@ class TestController extends Controller
             Cache::pull("weight.".$yesterday);
             OrderPackageCountingRecord::query()->where("targeted_at",$yesterday)->delete();
             $sql = <<<sql
-SELECT DATE_FORMAT(created_at,'%Y-%m-%d') date,
-SUM(CASE WHEN weighed_at IS NOT NULL THEN 1 ELSE 0 END) AS count,
-COUNT(1) total FROM order_packages WHERE created_at BETWEEN '{$yesterday} 00:00:00' AND '{$yesterday} 23:59:59' GROUP BY date
+SELECT DATE_FORMAT(order_packages.created_at,'%Y-%m-%d') date,
+SUM(CASE WHEN order_packages.weighed_at IS NOT NULL THEN 1 ELSE 0 END) AS count,
+COUNT(1) total FROM order_packages LEFT JOIN orders ON order_packages.order_id=orders.id WHERE orders.wms_status != '订单取消'
+AND order_packages.created_at BETWEEN '{$yesterday} 00:00:00' AND '{$yesterday} 23:59:59' GROUP BY date
 sql;
             $result = DB::selectOne(DB::raw($sql));
             if (!$result)$obj = [
@@ -315,9 +386,9 @@ sql;
 
     function t1(Request $request)
     {
-        throw new ErrorException('eeeff');
-        DB::connection('oracle')->update(DB::raw("update BAS_SKU set HAZARD_FLAG= 'N' where SKU= '13564151055'"));
-//        DB::connection('oracle')->update(DB::raw("UPDATE DOC_ORDER_HEADER SET notes = CASE WHEN notes IS NULL THEN '停运' ELSE  notes||',停运' END where ORDERNO in ('','SO190628000050','SO190628000001')"));
+
+        $re=OracleDOCWaveDetails::query()->where('orderno', 'SO201230003574')->get('seqno')->first()['seqno'];
+        dd($re);
     }
 
     function packageT(Request $request)
@@ -809,8 +880,20 @@ where (commodities.owner_id,commodity_barcodes.code) in (select commodities.owne
 
     public function output2()
     {
-        dump(Cache::get('aa'));
-        Cache::put('aa', '2223', 5);
+        StationTaskBatch::query()->insert([[
+            'batch_id' => 41414351,
+            'station_id' => 4131251,
+            'station_task_batch_type_id' => 1231231251,
+            'status' => '待处理',
+            'created_at' => now(),
+            'updated_at' => now(),
+        ]]);
+//        (new StationTaskBatch([
+//            'batch_id' => 41414324,
+//            'station_id' => 4131224,
+//            'station_task_batch_type_id' => 123123124,
+//            'status' => '待处理'
+//        ]))->save();
     }
 
     public function usage()
@@ -1028,7 +1111,7 @@ where (commodities.owner_id,commodity_barcodes.code) in (select commodities.owne
 
     public function reNewBatches3()
     {
-        $batches = Batch::query()->where('id','>', 73620)->get('code');
+        $batches = Batch::query()->where('id','>', 82182)->get('code');
         $batchCodes = $batches->map(function ($batch) {
             return $batch['code'];
         })->toArray();
@@ -1054,7 +1137,7 @@ where (commodities.owner_id,commodity_barcodes.code) in (select commodities.owne
 //        dd($logs);
         foreach ($batchCodes as $code) {
 //            $request=Cache::get('temp'.$code)['description'];
-            $request = Log::query()->select('description')->where('CREATED_AT', '>', '2021-01-22')
+            $request = Log::query()->select('description')->where('CREATED_AT', '>', '2021-02-25')
                 ->where('method', "issued_newBatch")
                 ->where('description', 'like', "%{$code}%")
                 ->first();
@@ -1113,11 +1196,11 @@ where (commodities.owner_id,commodity_barcodes.code) in (select commodities.owne
     public function testUpdateSkuNameBarcodeToCommodity_id()
     {
         $amount = 1000;
-        $storeItem = StoreItems::query()->orderByDesc('id')->first();
+        $storeItem = StoreItem::query()->orderByDesc('id')->first();
         $sum = $storeItem->id;
         $number = ceil($sum / $amount);
         for ($i = 0; $i < $number; $i++) {
-            $storeItems = StoreItems::query()->with('store')
+            $storeItems = StoreItem::query()->with('store')
                 ->where('id', '>=', $i * $amount)
                 ->where('id', '<', ($i * $amount + $amount))
                 ->get();
@@ -1530,13 +1613,45 @@ where (commodities.owner_id,commodity_barcodes.code) in (select commodities.owne
         }
     }
 
-    public function testProcurement()
+    public function syncOrderByWaveNo(Request $request)
     {
-        $procurementQuotation=ProcurementQuotation::query()
-            ->with('supplier')
-            ->select('supplier_id','offer')
-            ->orderBy('offer','asc')
-            ->where('procurement_id',7)->first();
-        dd($procurementQuotation);
+        $input = $request->input('wave');
+        if(!$input){
+            echo 'no wave code!';}
+        else {
+            echo 'syncing ' . $input;
+            return;
+        }
+        $oracleDOCOrderHeaderService = new OracleDOCOrderHeaderService();
+        $orderService = new OrderService();
+        $waveNos = [$input];
+        $orderHeaders = OracleDOCOrderHeader::query()
+            ->selectRaw(implode(',',OracleDOCOrderHeaderService::$columns))
+            ->whereIn('WaveNo',$waveNos)
+            ->get();
+        $orderHeaderList = $orderHeaders->chunk(2000);
+        foreach ($orderHeaderList as $item) {
+            $item = $oracleDOCOrderHeaderService->loadMissing($item);
+//            $last_order = $item->first();                                                               // 时间点靠后的
+//            $newest_orders = $item->where('addtime',$last_order->addtime);
+            if( count($orderHeaders) >0){
+                $orderService->syncOrder($item);                                             //  同步订单
+            }
+        }
+    }
+    public function syncOrderByWaveNo2(Request $request)
+    {
+        $oracleDOCOrderHeaderService = new OracleDOCOrderHeaderService();
+        $orderService = new OrderService();
+        $waveNos = ['W210220000010','W210220000009'];
+        $orderHeaders = OracleDOCOrderHeader::query()
+            ->selectRaw(implode(',',OracleDOCOrderHeaderService::$columns))
+            ->whereIn('WaveNo',$waveNos)
+            ->get();
+        $orderHeaderList = $orderHeaders->chunk(2000);
+        foreach ($orderHeaderList as $item) {
+            $item = $oracleDOCOrderHeaderService->loadMissing($item);
+            $orderService->syncOrder($item);
+        }
     }
 }

+ 69 - 0
app/Http/Controllers/UnitController.php

@@ -0,0 +1,69 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\Components\AsyncResponse;
+use App\Services\common\BatchUpdateService;
+use App\Unit;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Gate;
+use Illuminate\Support\Facades\Validator;
+
+class UnitController extends Controller
+{
+    use AsyncResponse;
+    public function index()
+    {
+        if(!Gate::allows('计量单位-查询')){ return redirect(url('/'));  }
+        $units=Unit::query()->orderBy("sequence")->paginate(50);
+        return view('maintenance.unit.index',['units'=>$units]);
+    }
+
+    public function destroy($id)
+    {
+        if(!Gate::allows('计量单位-删除')){ return redirect(url('/'));  }
+        Unit::destroy($id);
+        return ['success'=>true];
+    }
+
+    public function save()
+    {
+        $this->gate("计量单位-录入");
+        $errors = $this->validatorUnit(request(),request("id"))->errors();
+        if (count($errors)>0)$this->success(["errors"=>$errors]);
+
+        $obj = ["name"=>request("name"),"sequence"=>request("sequence") ?? 0];
+        if (request("id")){
+            Unit::query()->update($obj);
+            $this->success();
+        }
+        $this->success(Unit::query()->create($obj));
+    }
+
+    public function sort()
+    {
+        $this->gate("计量单位-录入");
+
+        if (request("update") && count(request("update"))>1)app(BatchUpdateService::class)->batchUpdate("units",request("update"));
+        $this->success();
+    }
+
+    protected function validatorUnit(Request $request,$id){
+        if ($id){$name=$id;}
+        $validator=Validator::make($request->input(),[
+            'name'=>['required','max:10',isset($name)?"unique:units,name,$name":'unique:units,name'],
+        ],[
+            'required'=>':attribute 为必填项',
+            'max'=>':attribute 过长',
+            'unique'=>':attribute 已存在',
+        ],[
+            'name'=>'计量单位名称',
+        ]);
+        return $validator;
+    }
+
+    public function getUnits()
+    {
+        return ["success"=>true,"data"=>app("UnitService")->getSelection()];
+    }
+}

+ 0 - 87
app/Http/Controllers/UnitsController.php

@@ -1,87 +0,0 @@
-<?php
-
-namespace App\Http\Controllers;
-
-use App\Unit;
-use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Auth;
-use Illuminate\Support\Facades\Gate;
-use Illuminate\Support\Facades\Validator;
-
-class UnitsController extends Controller
-{
-
-    public function index()
-    {
-        if(!Gate::allows('计量单位-查询')){ return redirect(url('/'));  }
-        $units=Unit::paginate(50);
-        return view('maintenance.unit.index',['units'=>$units]);
-    }
-
-    public function create()
-    {
-        if(!Gate::allows('计量单位-录入')){ return redirect(url('/'));  }
-        return view('maintenance.unit.create');
-    }
-
-
-    public function store(Request $request)
-    {
-        if(!Gate::allows('计量单位-录入')){ return redirect(url('/'));  }
-        $id=false;
-        $this->validatorUnit($request,$id)->validate();
-        $units=$request->input('Unit');
-        if(Unit::create($units)){
-            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
-            return redirect('maintenance/unit')->with('successTip','新计量单位“'.$request->input('Unit.name').'”添加成功');
-        };
-    }
-
-    public function edit($id)
-    {
-        if(!Gate::allows('计量单位-编辑')){ return redirect(url('/'));  }
-        $unit=Unit::find($id);
-        return view('maintenance.unit.edit',['unit'=>$unit]);
-    }
-
-    public function update(Request $request, $id)
-    {
-        if(!Gate::allows('计量单位-编辑')){ return redirect(url('/'));  }
-        $this->validatorUnit($request,$id)->validate();
-        $data=$request->input('Unit');
-        $unit=Unit::find($id);
-        $unit->fill($data);
-        if ($unit->save()){
-            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
-            return redirect('maintenance/unit')->with('successTip','计量单位“'.$request->input('Unit.name').'”修改成功');
-        }
-    }
-
-    public function destroy($id)
-    {
-        if(!Gate::allows('计量单位-删除')){ return redirect(url('/'));  }
-        $unit=Unit::find($id);
-        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($unit),Auth::user()['id']);
-        $result=$unit->delete();
-        return ['success'=>$result];
-    }
-
-    protected function validatorUnit(Request $request,$id){
-        if ($id){$name=$id;}
-        $validator=Validator::make($request->input(),[
-            'Unit.name'=>['required','max:10',isset($name)?"unique:units,name,$name":'unique:units,name'],
-        ],[
-            'required'=>':attribute 为必填项',
-            'max'=>':attribute 过长',
-            'unique'=>':attribute 已存在',
-        ],[
-            'Unit.name'=>'计量单位名称',
-        ]);
-        return $validator;
-    }
-
-    public function getUnits()
-    {
-        return ["success"=>true,"data"=>app("UnitService")->getSelection()];
-    }
-}

+ 59 - 30
app/Http/Controllers/WaybillController.php

@@ -5,7 +5,6 @@ namespace App\Http\Controllers;
 
 use App\Components\AsyncResponse;
 use App\Services\CarTypeService;
-use App\Services\CityService;
 use App\Services\LogisticService;
 use App\Services\OwnerService;
 use App\Services\UnitService;
@@ -17,7 +16,6 @@ use App\WaybillAuditLog;
 use App\WaybillOnTop;
 use App\WaybillPriceModel;
 use App\City;
-use App\Owner;
 use App\Unit;
 use App\Waybill;
 use App\WaybillPayoff;
@@ -28,11 +26,11 @@ use Exception;
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Collection;
 use Illuminate\Http\Request;
-use Illuminate\Http\UploadedFile;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Storage;
 use Illuminate\Support\Facades\Validator;
 use Intervention\Image\Facades\Image;
 use Ramsey\Uuid\Uuid;
@@ -78,26 +76,32 @@ class WaybillController extends Controller
     public function store(Request $request)
     {
         if(!Gate::allows('运输管理-录入')){ return redirect(url('/'));  }
-        $id=false;
-        $this->validatorWaybill($request,$id)->validate();
+        $this->validatorWaybill($request,false)->validate();
         /** @var WaybillService */
         $waybill=app('waybillService')->store($request);
         app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
         return redirect('waybill/index')->with('successTip','新运单“'.$waybill->waybill_number.'”录入成功');
     }
 
-    public function edit($id,LogisticService $logisticService,CarTypeService $carTypeService,
-                         CityService $cityService,UnitService $unitService)
+    public function edit($id,LogisticService $logisticService,CarTypeService $carTypeService,UnitService $unitService)
     {
         if(!Gate::allows('运输管理-编辑')){ return redirect(url('/'));  }
-        /** @var WaybillService */
         $waybill = app('waybillService')->find($id);
+        if ($waybill->order_id){
+            /** @var Waybill $waybill */
+            $waybill->load("order.owner");
+            $waybill->destination_city_id = app("RegionService")->getCity($waybill->order->city ?? '',$waybill->order->province ?? '');
+        }else{
+            /** @var Waybill $waybill */
+            $waybill->load("owner");
+        }
+        /** @var \stdClass $waybill */
         if (!$waybill)return view("exception.default",["code"=>"500","message"=>"数据已被删除或丢失"]);
         if ($waybill->deliver_at){
             $waybill->deliver_at_date=Carbon::parse($waybill->deliver_at)->format('Y-m-d');
             $waybill->deliver_at_time=Carbon::parse($waybill->deliver_at)->format('H:i:s');
         }
-        $cities=$cityService->getSelection();
+        $cities=app("RegionService")->getSelection(2);
         $units=$unitService->getSelection();
         $carTypes=$carTypeService->getSelection();
         return view('waybill/edit',['waybill'=>$waybill,'logistics'=>$logisticService->getSelection(["id","name"],"物流"),'cities'=>$cities,'units'=>$units,'carTypes'=>$carTypes]);
@@ -133,7 +137,7 @@ class WaybillController extends Controller
             if ($waybillPriceModel_id){
                 $carrier_weight=$request->input('carrier_weight');
                 $waybillPriceModel=$waybillPriceModelService->find($waybillPriceModel_id);
-                $logistic=$logisticService->find($waybill->logistic_id);
+                $logistic=$logisticService->find($waybill->order->logistic_id ?? $waybill->logistic_id);
                 if ($carrier_weight<$waybillPriceModel->initial_weight){
                     $fee=(($waybillPriceModel->unit_price)*($waybillPriceModel->initial_weight))+$logistic->delivery_fee;
                 }else{
@@ -367,14 +371,14 @@ class WaybillController extends Controller
     public function waybillEdit($id){
         if(!Gate::allows('运输管理-编辑')){ return redirect(url('/'));  }
         $waybill=app('waybillService')->find($id);
-        $owners=Owner::get();
+        $owners=app("OwnerService")->getIntersectPermitting();
         return view('waybill.waybillEdit',['waybill'=>$waybill,'owners'=>$owners]);
     }
     public function waybillRetreatAudit(Request $request){
         if(!Gate::allows('运输管理-调度')){ return redirect(url('/'));  }
         $id=$request->input('id');
         $waybill=app('waybillService')->find($id);
-        WaybillAuditLog::whereRaw('waybill_id = ? and audit_stage = ?',[$id,"运单阶段"])->delete();
+        WaybillAuditLog::query()->whereRaw('waybill_id = ? and audit_stage = ?',[$id,"运单阶段"])->delete();
         $waybill->status='待重审';
         $result=$waybill->save();
         app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($waybill),Auth::user()['id']);
@@ -429,23 +433,25 @@ class WaybillController extends Controller
 
     //生成报表数据
     private function createReportData($waybill,$waybillPayoff){
+        /** @var Waybill $waybill */
+        $waybill->loadMissing(["order.owner",'order.logistic']);
         return [
             "type"=>$waybill->type,
             "waybill_number"=>$waybill->waybill_number,
-            "owner_name"=>$waybill->owner ? $waybill->owner->name : null,
+            "owner_name"=>$waybill->order->owner->name ?? ($waybill->owner->name ?? null),
             "wms_bill_number"=>$waybill->wms_bill_number,
             "source_bill"=>$waybill->source_bill,
             "origination"=>$waybill->origination,
-            "destination"=>$waybill->destination,
-            "recipient"=>$waybill->recipient,
-            "recipient_mobile"=>$waybill->recipient_mobile,
+            "destination"=>$waybill->order->address ?? $waybill->destination,
+            "recipient"=>$waybill->order->consignee_name ?? $waybill->recipient,
+            "recipient_mobile"=>$waybill->order->consignee_phone ?? $waybill->recipient_mobile,
             "charge"=>$waybill->charge,
             "collect_fee"=>$waybill->collect_fee,
             "ordering_remark"=>$waybill->ordering_remark,
-            "carrier_name"=>$waybill->logistic ? $waybill->logistic->name : null,
+            "carrier_name"=>$waybill->order->logistic->name ?? ($waybill->logistic->name ?? null),
             "carrier_bill"=>$waybill->carrier_bill,
             "origination_city_name"=>$waybill->originationCity ? $waybill->originationCity->name : null,
-            "destination_city_name"=>$waybill->destinationCity ? $waybill->destinationCity->name : null,
+            "destination_city_name"=>$waybill->order->city ?? ($waybill->destinationCity->name ?? null),
             "warehouse_weight"=>$waybill->warehouse_weight.($waybill->warehouseWeightUnit ? $waybill->warehouseWeightUnit->name : ''),
             "carrier_weight"=>$waybill->carrier_weight.($waybill->carrierWeightUnit ? $waybill->carrierWeightUnit->name : ''),
             "warehouse_weight_other"=>$waybill->warehouse_weight_other.($waybill->warehouseWeightUnitOther ? $waybill->warehouseWeightUnitOther->name : ''),
@@ -529,19 +535,24 @@ class WaybillController extends Controller
     public function batchUploadImages()
     {
         $this->gate("运输管理-图片上传");
+        ini_set('max_execution_time',1000);
+        ini_set('memory_limit','100M');
         $images = request("images");
         $errors = [];
         $number = [];
         $mapping = [];
         $type = ["jpg","png","gif","jfif","pjpeg","jpeg","webp"];
         foreach ($images as $index => $image){
-            $suffix = $image->getClientOriginalExtension();
-            $name = $image->getClientOriginalName();
+            $arr = explode(".",$image["name"]);
+            $suffix = $arr[count($arr)-1];
+            unset($arr[count($arr)-1]);
+            $name = implode(".",$arr);
             if (array_search(strtolower($suffix),$type) === false){
                 $errors[] = "“".$name."”格式错误";
                 unset($images[$index]);
                 continue;
             }
+            $images[$index]["suffix"] = $suffix;
             $num = trim(rtrim($name,".".$suffix));
             $number[] = $num;
             $mapping[$num] = $index;
@@ -555,11 +566,16 @@ class WaybillController extends Controller
         foreach ($waybills as $waybill){
             $image = $images[$mapping[$waybill->source_bill]];
             $fileName = date('ymd').'-'.Uuid::uuid1();
-            $suffix = $image->getClientOriginalExtension();
+            $suffix = $image["suffix"];
+
             $thumbnailName=storage_path('app/public/files/'.$fileName.'-thumbnail.'.$suffix);
             $commonName=storage_path('app/public/files/'.$fileName.'-common.'.$suffix);
             $bulkyName=storage_path('app/public/files/'.$fileName.'-bulky.'.$suffix);
-            move_uploaded_file ($image->getRealPath() ,$bulkyName);
+
+            preg_match('/^(data:\s*image\/(\w+);base64,)/',$image["src"],$res);
+            $base64_img=base64_decode(str_replace($res[1],'', $image["src"]));
+            Storage::put('public/files/'.$fileName.'-bulky.'.$suffix,$base64_img);
+
             $img=Image::make($bulkyName);
             if ($img->height() > $img->width())
                 $img->heighten(250)->save($commonName);
@@ -674,16 +690,17 @@ class WaybillController extends Controller
     protected function validatorWaybill(Request $request,$id){
         if ($id){$wms_bill_number=$id;};
         $validator=Validator::make($request->input(),[
-            'owner_id'=>'required',
+            'owner_id'=>'required_without:order_id',
             'wms_bill_number'=>['nullable','max:50',isset($wms_bill_number)?"unique:waybills,wms_bill_number,$wms_bill_number":'unique:waybills,wms_bill_number'],
             'origination'=>'required|max:255',
-            'destination'=>'required|max:255',
-            'recipient'=>'required|max:50',
-            'recipient_mobile'=>['required','regex:/^(\d{7,11})|(1[3|4|5|7|8][0-9]\d{4,8})$/'],
+            'destination'=>'required_without:order_id|max:255',
+            'recipient'=>'required_without:order_id|max:50',
+            'recipient_mobile'=>['required_without:order_id','regex:/^(\d{7,11})|(1[3|4|5|7|8][0-9]\d{4,8})$/'],
             'charge'=>'nullable|min:0|max:999999|numeric',
             'collect_fee'=>'nullable|min:0|numeric',
         ],[
             'required'=>':attribute 为必填项',
+            'required_without'=>':attribute 为必填项',
             'alpha_num'=>':attribute 应为字母或数字',
             'max'=>':attribute 字符过多或输入值过大',
             'regex'=>':attribute 输入有误',
@@ -705,7 +722,7 @@ class WaybillController extends Controller
     }
     protected function validatorWaybillDispatch(Request $request,$id){
         $rule=[
-            'logistic_id'=>'required|integer',
+            'logistic_id'=>'required_without:order_id|integer',
             'carrier_bill'=>"sometimes|nullable|max:50|unique:waybills,carrier_bill,$id",
             'fee'=>'sometimes|nullable|min:0|numeric|max:999999',
             'other_fee'=>'sometimes|nullable|min:0|numeric|max:999999',
@@ -714,7 +731,7 @@ class WaybillController extends Controller
             'amount'=>'nullable|numeric|min:0',
             'amount_unit_id'=>'required',
             'origination_city_id'=>'sometimes|required|integer',
-            'destination_city_id'=>'sometimes|required|integer',
+            'destination_city_id'=>'sometimes|required_without:order_id|integer',
             'warehouse_weight_other'=>'sometimes|nullable|min:0|numeric|max:999999',
             'warehouse_weight_unit_id_other'=>'sometimes|required_with:warehouse_weight_other|nullable|integer',
             'pick_up_fee'=>'sometimes|nullable|min:0|numeric|max:999999',
@@ -727,10 +744,11 @@ class WaybillController extends Controller
         ];
         if ($request->type == '专线'){
             $rule['origination_city_id']='required|integer';
-            $rule['destination_city_id']='required|integer';
+            $rule['destination_city_id']='required_without:order_id|integer';
         }
         $validator=Validator::make($request->input(),$rule,[
             'required'=>':attribute 为必填项',
+            'required_without'=>':attribute 为必填项',
             'alpha_num'=>':attribute 应为字母或数字',
             'max'=>':attribute 字符过多或输入值过大',
             'min'=>':attribute 不得为负',
@@ -795,7 +813,7 @@ class WaybillController extends Controller
         if(!Gate::allows('运输管理-删除')){return redirect('/');}
         $paginate = $request->input('paginate')??50;
         /** @var Collection $waybills */
-        $waybills = Waybill::query()->with(['owner','logistic','amountUnit','warehouseWeightUnit','carrierWeightUnit',
+        $waybills = Waybill::query()->with(['owner','order.owner','order.logistic','logistic','amountUnit','warehouseWeightUnit','carrierWeightUnit',
             'warehouseWeightUnitOther','carrierWeightUnitOther','carType','waybillAuditLogs' => function ($query) {
             /** @var Builder $query */
             $query->with('user');
@@ -894,4 +912,15 @@ class WaybillController extends Controller
         return ['success'=>true,'warehouseWeight'=>$warehouseWeight];
     }
 
+    //寻找订单
+    public function seekOrder()
+    {
+        $this->gate("运输管理");
+        $code = request("code");
+        if (!$code)$this->error("暂无绑定订单");
+        $order = app("OrderService")->first(["code"=>$code]);
+        if (!$order)$this->error("暂无绑定订单");
+        $this->success($order);
+    }
+
 }

+ 15 - 22
app/Http/Controllers/WaybillPriceModelsController.php → app/Http/Controllers/WaybillPriceModelController.php

@@ -2,13 +2,12 @@
 
 namespace App\Http\Controllers;
 
+use App\Region;
 use App\WaybillPriceModel;
-use App\City;
 use App\Events\WaybillPriceModelEvent;
 use App\Imports\WaybillPriceModelsImport;
 use App\Province;
 use App\Unit;
-use function GuzzleHttp\Psr7\str;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\Cache;
@@ -16,7 +15,7 @@ use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Validator;
 use Maatwebsite\Excel\Facades\Excel;
 
-class WaybillPriceModelsController extends Controller
+class WaybillPriceModelController extends Controller
 {
     public function index(Request $request)
     {
@@ -24,7 +23,7 @@ class WaybillPriceModelsController extends Controller
         $logistics=app('LogisticService')->getSelection(["id","name"],"物流");
         $provinces=Province::query()->get();
         $data=$request->input();
-        $waybillPriceModels= WaybillPriceModel::query()->orderBy('id', 'DESC');
+        $waybillPriceModels= WaybillPriceModel::query()->with(["logistic","province","city","unit"])->orderBy('id', 'DESC');
         if ($data){
             if ($request->input('logistic_id')){
                 $waybillPriceModels=$waybillPriceModels->where('logistic_id',$request->input('logistic_id'));
@@ -45,14 +44,9 @@ class WaybillPriceModelsController extends Controller
     {
         if(!Gate::allows('计费模型-录入')){ return redirect(url('/'));  }
         $logistics=app('LogisticService')->getSelection(["id","name"],"物流");
-        $provinces=Province::get();
-        $units=Unit::get();
-        return view('maintenance.priceModel.waybillPriceModel.create',['logistics'=>$logistics,'provinces'=>$provinces,'units'=>$units]);
-    }
-
-    public function getCities($province_id){
-        $cities=City::where('province_id',$province_id)->get();
-        return ['cities'=>$cities];
+        $regions=Region::query()->whereIn("type",[1,2])->get();
+        $units=Unit::query()->get();
+        return view('maintenance.priceModel.waybillPriceModel.create',['logistics'=>$logistics,'regions'=>$regions,'units'=>$units]);
     }
 
 
@@ -61,7 +55,7 @@ class WaybillPriceModelsController extends Controller
         if(!Gate::allows('计费模型-录入')){ return redirect(url('/'));  }
         $this->validateWaybillPriceModel($request)->validate();
         $waybillPriceModel=$request->input('WaybillPriceModel');
-        $waybillPriceModelIs=WaybillPriceModel::where('logistic_id',$waybillPriceModel['logistic_id'])->where('province_id',$waybillPriceModel['province_id'])->where('unit_id',$waybillPriceModel['unit_id']);
+        $waybillPriceModelIs=WaybillPriceModel::query()->where('logistic_id',$waybillPriceModel['logistic_id'])->where('province_id',$waybillPriceModel['province_id'])->where('unit_id',$waybillPriceModel['unit_id']);
         if (isset($waybillPriceModel['city_id'])){
             $waybillPriceModelIs=$waybillPriceModelIs->where('city_id',$waybillPriceModel['city_id']);
         }
@@ -74,19 +68,19 @@ class WaybillPriceModelsController extends Controller
         $waybillPriceModelIs=$waybillPriceModelIs->first();
         if (!$waybillPriceModelIs){
             if (isset($waybillPriceModel['city_id'])){
-                $waybillPriceModelProvince=WaybillPriceModel::whereRaw('logistic_id = ? AND province_id = ? AND city_id IS NULL',[$waybillPriceModel['logistic_id'],$waybillPriceModel['province_id']])->first();
+                $waybillPriceModelProvince=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND city_id IS NULL',[$waybillPriceModel['logistic_id'],$waybillPriceModel['province_id']])->first();
                 if ($waybillPriceModelProvince){
                     return redirect()->back()->with('successTip','已存在省份模型,无需录入城市模型');
                 }
             }else{
-                $waybillPriceModelProvince=WaybillPriceModel::whereRaw('logistic_id = ? AND province_id = ? AND city_id IS NOT NULL',[$waybillPriceModel['logistic_id'],$waybillPriceModel['province_id']])->first();
+                $waybillPriceModelProvince=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND city_id IS NOT NULL',[$waybillPriceModel['logistic_id'],$waybillPriceModel['province_id']])->first();
                 if ($waybillPriceModelProvince){
                     return redirect()->back()->with('successTip','已存在城市模型,无法录入省份模型');
                 }
             }
             if ($waybillPriceModel['base_fee']==null){ unset($waybillPriceModel['base_fee']);}
             if ($waybillPriceModel['initial_weight']==null){unset($waybillPriceModel['initial_weight']);}
-            $waybillPriceModel=WaybillPriceModel::create($waybillPriceModel);
+            $waybillPriceModel=WaybillPriceModel::query()->create($waybillPriceModel);
             event(new WaybillPriceModelEvent($waybillPriceModel));
             app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
             return redirect('maintenance/priceModel/waybillPriceModel')->with('successTip','新计费模型录入成功');
@@ -100,12 +94,11 @@ class WaybillPriceModelsController extends Controller
     public function edit($id)
     {
         if(!Gate::allows('计费模型-编辑')){ return redirect(url('/'));  }
-        $waybillPriceModel=WaybillPriceModel::find($id);
+        $waybillPriceModel=WaybillPriceModel::query()->find($id);
         $logistics=app('LogisticService')->getSelection(["id","name"],"物流");
-        $provinces=Province::get();
-        $cities=City::where('province_id',$waybillPriceModel->province_id)->get();
-        $units=Unit::get();
-        return view('maintenance.priceModel.waybillPriceModel.edit',['waybillPriceModel'=>$waybillPriceModel,'logistics'=>$logistics,'provinces'=>$provinces,'units'=>$units,'cities'=>$cities]);
+        $regions=Region::query()->whereIn("type",[1,2])->get();
+        $units=Unit::query()->get();
+        return view('maintenance.priceModel.waybillPriceModel.edit',['waybillPriceModel'=>$waybillPriceModel,'logistics'=>$logistics,'regions'=>$regions,'units'=>$units]);
     }
 
 
@@ -113,7 +106,7 @@ class WaybillPriceModelsController extends Controller
     {
         if(!Gate::allows('计费模型-编辑')){ return redirect(url('/'));  }
         $this->validateWaybillPriceModel($request)->validate();
-        $waybillPriceModel=WaybillPriceModel::find($id);
+        $waybillPriceModel=WaybillPriceModel::query()->find($id);
         $data=$request->input('WaybillPriceModel');
         if ($data['base_fee']==null){ unset($data['base_fee']);}
         if ($data['initial_weight']==null){unset($data['initial_weight']);}

+ 5 - 4
app/Http/Controllers/WeighController.php

@@ -41,6 +41,7 @@ class WeighController extends Controller
      *
      * @param Request $request
      * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void
+     * @throws
      */
     public function store(Request $request)
     {
@@ -103,9 +104,9 @@ class WeighController extends Controller
             if(!$package->paper_box_id)$package->paper_box_id=$paper_box_id;
             $result=$accomplishToWMS->accomplishToWMS($package);
             if ($result['result']){
-                $package->status="已上传";
+                $package->uploaded_to_wms="是";
             }else{
-                $package->status="上传异常";
+                $package->uploaded_to_wms="异常";
             }
             $package->save();
             app('LogService')->log(__METHOD__,'create_'.__FUNCTION__,json_encode($package),Auth::user()['name']);
@@ -117,7 +118,7 @@ class WeighController extends Controller
             $package = app('OrderPackageService')->firstOrCreate($logistic_number,[
                 'weight'=>$weight,
                 'weighed_at'=>Carbon::now(),
-                'status'=>"已上传",
+                'uploaded_to_wms'=>"是",
             ]);
             $package->fetchAllFromOracle();
             $result=$accomplishToWMS->accomplishToWMS($package);
@@ -125,7 +126,7 @@ class WeighController extends Controller
             $str .= $package['logistic_number']?"快递单号:{$package['logistic_number']}":'';
             $str .= $order_code?", 订单号:{$order_code}":'';
             if(!$result||$result['result']=='false'){
-                $package['status'] = '上传失败';
+                $package['uploaded_to_wms'] = '异常';
                 $str = "录入包裹失败!";
                 $str .= $package['logistic_number']?"快递单号:{$package['logistic_number']}":'';
                 $str .= $order_code?", 订单号:{$order_code}":'';

+ 78 - 78
app/Http/Controllers/api/thirdPart/flux/SortingController.php

@@ -30,85 +30,85 @@ class SortingController extends Controller
      */
     public function newBatch(Request $request)
     {
-//       $requestArr=$request->all();
+       $requestArr=$request->all();
         app('LogService')->log(__METHOD__, 'issued_' . __FUNCTION__, json_encode($request->all()));
-//        !$requestArr?$requestArr=json_decode($request->getContent(),true):false;
-//        $errors=$this->newBatchValidator($requestArr)->errors();
-//        if(count($errors)>0){
-//            app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, 'fields wrong, see Errors report please.'.'|'.json_encode($request->all()).'|'.json_encode($errors));
-//            return response()->json(['Response'=>['return'=>['returnFlag'=>'0','returnCode'=>'0001',
-//                'returnDesc'=>':Failure','resultInfo'=>'','errors'=>$errors]]])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
-//        }
-//        $requestBatches = $requestArr['request']?? '';
-//
-//        foreach ($requestBatches as $requestBatch){
-//            $requestBatch['edittime']&&strpos(trim($requestBatch['edittime']),' ')?$editTimeFormat='Y-m-d H:i:s':$editTimeFormat='YmdHis';
-//            $batch=Batch::query()->firstOrCreate(['code' => $requestBatch['waveno']]);
-//
-//            if(!$batch)$batch=new Batch();
-//            $batch->fill([
-//                    'code' => $requestBatch['waveno'],
-//                    'wms_type' => $requestBatch['batch_type']??'',
-//                    'wms_status' => $requestBatch['docstatus']??'',
-//                    'status' => '未处理',
-//                    'wms_created_at' => $requestBatch['edittime']?Carbon::createFromFormat($editTimeFormat,$requestBatch['edittime']):'',
-//            ]);
-//            $batch->save();
-//            $oracleAlloactions=OracleActAllocationDetails::query()->where('waveno',$requestBatch['waveno'])->get();
-//            foreach($requestBatch['order_list'] as $requestOrder){
-//                $owner=Owner::query()->where('code',$requestOrder['customerid'])->first();
-//                $order=app("OrderService")->first(['code'=>$requestOrder['docno']]);
-//                if(!$order){
-//                    $order=app("OrderService")->createOrder([
-//                        'batch_id' => $batch['id'],
-//                        'code' => $requestOrder['docno'],
-//                        'owner_id' => $owner['id'],
-//                        'wms_status' => $requestOrder['docstatus']??'波次下发',
-//                        'status' => '未处理',
-//                    ]);
-//                    app('LogService')->log(__METHOD__,__FUNCTION__,'创建 Order'.json_encode($order));
-//                }else{
-//                    $order['batch_id']= $batch['id'] ;
-//                    $order['owner_id']=$order['owner_id']??$owner['owner_id'];
-//                    $order['wms_status']=$order['wms_status']??$requestOrder['docstatus']??'波次下发';
-//                    $order['status']=$order['status']??'未处理';
-//                }
-//                $order->save();
-//                OrderBin::query()->firstOrCreate([
-//                    'order_id' => $order['id'],
-//                    'number' => $requestOrder['reservedfield01'],
-//                ]);
-//                foreach($requestOrder['barcode_list'] as $requestBarcode){
-//                    $orderCommodity=OrderCommodity::query()
-//                        ->where('order_id',$order['id'])->where('wms_ptltaskid',$requestBarcode['ptltaskid'])->first();
-//                    if(!$orderCommodity){
-//                        /** @var CommodityService $commodityService */
-//                        $commodityService=app('CommodityService');
-//                        $commodity=$commodityService->syncBarcodes($requestBarcode['alternate_sku1'],$owner['id'],$requestBarcode['sku']);
-//                        $orderCommodity=OrderCommodity::query()->firstOrCreate(['order_id'=>$order['id'],'commodity_id'=>$commodity['id']]);
-//                        if(!$orderCommodity){
-//                            $orderCommodity = new OrderCommodity([
-//                                'order_id' => $order['id'],
-//                                'commodity_id' => $commodity['id'],
-//                                'amount' => $requestBarcode['fmqty_each']??0,
-//                                'wms_ptltaskid' => $requestBarcode['ptltaskid'],
-//                            ]);
-//                        }else{
-//                            $orderCommodity['order_id']=$order['id'];
-//                            $orderCommodity['commodity_id']=$commodity['id'];
-//                            $orderCommodity['amount']=$requestBarcode['fmqty_each']??0;
-//                            $orderCommodity['wms_ptltaskid']=$requestBarcode['ptltaskid']??0;
-//                        }
-//                        $allocation=$oracleAlloactions->where('orderno',$requestOrder['docno'])->where('sku',$commodity['sku'])->where('qty',$requestBarcode['fmqty_each'])->first();
-//                        if($allocation)
-//                            $orderCommodity['location'] = $allocation['location'];
-//                        $orderCommodity->save();
-//                    }
-//                }
-//            }
-//        }
-//        return response()->json(['Response'=>['return'=>['returnFlag'=>'1','returnCode'=>'0000',
-//            'returnDesc'=>'消息处理成功:Success','resultInfo'=>'']]])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
+        !$requestArr?$requestArr=json_decode($request->getContent(),true):false;
+        $errors=$this->newBatchValidator($requestArr)->errors();
+        if(count($errors)>0){
+            app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, 'fields wrong, see Errors report please.'.'|'.json_encode($request->all()).'|'.json_encode($errors));
+            return response()->json(['Response'=>['return'=>['returnFlag'=>'0','returnCode'=>'0001',
+                'returnDesc'=>':Failure','resultInfo'=>'','errors'=>$errors]]])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
+        }
+        $requestBatches = $requestArr['request']?? '';
+
+        foreach ($requestBatches as $requestBatch){
+            $requestBatch['edittime']&&strpos(trim($requestBatch['edittime']),' ')?$editTimeFormat='Y-m-d H:i:s':$editTimeFormat='YmdHis';
+            $batch=Batch::query()->firstOrCreate(['code' => $requestBatch['waveno']]);
+
+            if(!$batch)$batch=new Batch();
+            $batch->fill([
+                    'code' => $requestBatch['waveno'],
+                    'wms_type' => $requestBatch['batch_type']??'',
+                    'wms_status' => $requestBatch['docstatus']??'',
+                    'status' => '未处理',
+                    'wms_created_at' => $requestBatch['edittime']?Carbon::createFromFormat($editTimeFormat,$requestBatch['edittime']):'',
+            ]);
+            $batch->save();
+            $oracleAlloactions=OracleActAllocationDetails::query()->where('waveno',$requestBatch['waveno'])->get();
+            foreach($requestBatch['order_list'] as $requestOrder){
+                $owner=Owner::query()->where('code',$requestOrder['customerid'])->first();
+                $order=app("OrderService")->first(['code'=>$requestOrder['docno']]);
+                if(!$order){
+                    $order=app("OrderService")->createOrder([
+                        'batch_id' => $batch['id'],
+                        'code' => $requestOrder['docno'],
+                        'owner_id' => $owner['id'],
+                        'wms_status' => $requestOrder['docstatus']??'波次下发',
+                        'status' => '未处理',
+                    ]);
+                    app('LogService')->log(__METHOD__,__FUNCTION__,'创建 Order'.json_encode($order));
+                }else{
+                    $order['batch_id']= $batch['id'] ;
+                    $order['owner_id']=$order['owner_id']??$owner['owner_id'];
+                    $order['wms_status']=$order['wms_status']??$requestOrder['docstatus']??'波次下发';
+                    $order['status']=$order['status']??'未处理';
+                }
+                $order->save();
+                OrderBin::query()->firstOrCreate([
+                    'order_id' => $order['id'],
+                    'number' => $requestOrder['reservedfield01'],
+                ]);
+                foreach($requestOrder['barcode_list'] as $requestBarcode){
+                    $orderCommodity=OrderCommodity::query()
+                        ->where('order_id',$order['id'])->where('wms_ptltaskid',$requestBarcode['ptltaskid'])->first();
+                    if(!$orderCommodity){
+                        /** @var CommodityService $commodityService */
+                        $commodityService=app('CommodityService');
+                        $commodity=$commodityService->syncBarcodes($requestBarcode['alternate_sku1'],$owner['id'],$requestBarcode['sku']);
+                        $orderCommodity=OrderCommodity::query()->firstOrCreate(['order_id'=>$order['id'],'commodity_id'=>$commodity['id']]);
+                        if(!$orderCommodity){
+                            $orderCommodity = new OrderCommodity([
+                                'order_id' => $order['id'],
+                                'commodity_id' => $commodity['id'],
+                                'amount' => $requestBarcode['fmqty_each']??0,
+                                'wms_ptltaskid' => $requestBarcode['ptltaskid'],
+                            ]);
+                        }else{
+                            $orderCommodity['order_id']=$order['id'];
+                            $orderCommodity['commodity_id']=$commodity['id'];
+                            $orderCommodity['amount']=$requestBarcode['fmqty_each']??0;
+                            $orderCommodity['wms_ptltaskid']=$requestBarcode['ptltaskid']??0;
+                        }
+                        $allocation=$oracleAlloactions->where('orderno',$requestOrder['docno'])->where('sku',$commodity['sku'])->where('qty',$requestBarcode['fmqty_each'])->first();
+                        if($allocation)
+                            $orderCommodity['location'] = $allocation['location'];
+                        $orderCommodity->save();
+                    }
+                }
+            }
+        }
+        return response()->json(['Response'=>['return'=>['returnFlag'=>'1','returnCode'=>'0000',
+            'returnDesc'=>'消息处理成功:Success','resultInfo'=>'']]])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
     }
 
     protected function newBatchValidator(array $data)

+ 4 - 4
app/Http/Controllers/api/thirdPart/goodscan/PackageController.php

@@ -152,18 +152,18 @@ class PackageController
             OrderPackage::query()->where('batch_number',$orderPackage['batch_number'])->update($params);
             $result=$fluxController->markWMSOnBatch($orderPackage['batch_number'], $orderPackage['weight']);
             if(!$result['result']){
-                $orderPackage->status="上传异常";
+                $orderPackage->uploaded_to_wms="异常";
             }
         }else{
             app('LogService')->log(__METHOD__,__FUNCTION__,"GoodScan 写入包裹至WMS:".json_encode($orderPackage),null);
             try{
                 $result=$fluxController->accomplishToWMS($orderPackage);
                 if ($result['result'])
-                    $orderPackage->status="已上传";
+                    $orderPackage->uploaded_to_wms="是";
                 else
-                    $orderPackage->status="上传异常";
+                    $orderPackage->uploaded_to_wms="异常";
             }catch (\Exception $e){
-                $orderPackage->status="未上传";
+                $orderPackage->uploaded_to_wms="否";
             }
         }
         $response=$this->saveOrderPackage($orderPackage);

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

@@ -6,8 +6,8 @@ namespace App\Http\Controllers\api\thirdPart\haiq;
 
 
 
+use App\Http\Requests\ForeignHaiRobotic_processedRequest;
 use App\Services\ForeignHaiRoboticsService;
-use Illuminate\Http\Request;
 
 class PickStationController
 {
@@ -18,7 +18,7 @@ class PickStationController
         $this->service=app('ForeignHaiRoboticsService');
     }
 
-    public function processed(Request $request): array
+    public function processed(ForeignHaiRobotic_processedRequest $request): array
     {
         $failed=
             ($processedResult=

+ 11 - 1
app/Http/Controllers/api/thirdPart/haochuang/SortingController.php

@@ -5,8 +5,10 @@ namespace App\Http\Controllers\Api\thirdPart\haochuang;
 use App\Batch;
 use App\CommodityBarcode;
 use App\Http\Controllers\Controller;
+use App\OracleDOCWaveDetails;
 use App\Order;
 use App\OrderCommodity;
+use App\Services\LogService;
 use App\SortingStation;
 use App\User;
 use App\UserToken;
@@ -82,7 +84,15 @@ class SortingController extends Controller
                 'owner'=>$order->owner()->first()['code'],
                 'status'=>$order['status']=='未处理'?'available':$order['status'],
                 'created_at'=>$order['created_at']->toDateTimeString(),
-                'bin'=>$order->bin()->first()['number'],
+                'bin'=>(function()use($order){
+                    $bin=$order->bin()->first()['number']??'';
+                    if(!$bin){
+                        $bin=OracleDOCWaveDetails::query()->where('orderno', 'SO201230003574')->get('seqno')->first()['seqno']??'';
+                        LogService::log(__METHOD__,__FUNCTION__,'bin缺失补查:'.$bin.'. order:'.$order->toJson());
+                        return $bin;
+                    }
+                    return $bin;
+                })(),
                 'barcodes'=>[]
             ];
             $order->orderCommodities()->each(function(OrderCommodity $orderCommodity)use(&$orderData,$request){

+ 6 - 4
app/Http/Controllers/api/thirdPart/weight/PackageController.php

@@ -6,6 +6,7 @@ use App\Events\WeighedEvent;
 use App\Http\Controllers\Controller;
 use App\Http\Controllers\LogisticNumberFeatureController;
 use App\Jobs\FetchPackageFromOracle;
+use App\Jobs\WeightUpdateInstantBill;
 use App\MeasuringMachine;
 use App\Order;
 use App\OrderPackage;
@@ -203,19 +204,19 @@ class PackageController extends Controller
                 $package->unifyThisMeasureUnderSameBatch();
                 $result=$fluxController->markWMSOnBatch($package['batch_number'], $request['weight']);
                 if(!$result['result']){
-                    $package->status="上传异常";
+                    $package->uploaded_to_wms="异常";
                 }
             }else{
                 app('LogService')->log(__METHOD__,__FUNCTION__,"写入包裹至WMS:".json_encode($package),null);
                 try{
                     $result=$fluxController->accomplishToWMS($package);
                     if ($result['result']){
-                        $package->status="已上传";
+                        $package->uploaded_to_wms="是";
                     }else{
-                        $package->status="上传异常";
+                        $package->uploaded_to_wms="异常";
                     }
                 }catch (\Exception $e){
-                    $package->status="未上传";
+                    $package->uploaded_to_wms="否";
                 }
             }
             try{
@@ -298,6 +299,7 @@ class PackageController extends Controller
         if(!empty($package->order))
             Waybill::setWeightByOrderCode($package->order->code,$package->weight);
         event(new WeighedEvent($package));
+        dispatch(new WeightUpdateInstantBill($package));
         $response=["msg"=>"保存成功",
             "code"=>200,
             "data"=>true,

+ 10 - 14
app/Imports/WaybillPriceModelsImport.php

@@ -45,14 +45,14 @@ class WaybillPriceModelsImport implements ToCollection,WithHeadingRow
                     if (strstr($row['省份'], '省')){$row['省份']=str_replace('省','',$row['省份']);};
                     $logistic = Logistic::query()->where('name', $row['承运商'])->first();
                     $unit = Unit::query()->where('name', $row['计数单位'])->first();
-                    $province = Province::query()->where('name', $row['省份'])->first();
-                    $city = City::query()->where('name', $row['市'])->first();
+                    $province = app("RegionService")->getProvince($row['省份']);
+                    $city = app("RegionService")->getCity($row['市'],$province);
                     if ($logistic && $unit && $province) {
                         $billing = WaybillPriceModel::query()->where('logistic_id', $logistic->id);
                         $billing = $billing->where('unit_id', $unit->id);
-                        $billing = $billing->where('province_id', $province->id);
+                        $billing = $billing->where('province_id', $province);
                         if ($row['市']) {
-                            if ($city) $billing = $billing->where('city_id', $city->id);
+                            if ($city) $billing = $billing->where('city_id', $city);
                             else $billing->whereNull("city_id");
                         }
                         if ($row['计数区间'] && !strstr($row['计数区间'], '∞')) {
@@ -65,20 +65,20 @@ class WaybillPriceModelsImport implements ToCollection,WithHeadingRow
                         $billing = $billing->first();
                         if (!$billing) {
                             if ($row['市']){
-                                $waybillPriceModelProvince=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND city_id IS NULL',[$logistic->id,$province->id])->first();
+                                $waybillPriceModelProvince=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND city_id IS NULL',[$logistic->id,$province])->first();
                                 if ($waybillPriceModelProvince){
                                     $cityIs=false;
                                     array_push($exception, ['第' . $sum . '行数据已存在省份模型,无需录入城市模型']);
                                 }
                             }else{
-                                $waybillPriceModelProvince=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND city_id IS NOT NULL',[$logistic->id,$province->id])->first();
+                                $waybillPriceModelProvince=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND city_id IS NOT NULL',[$logistic->id,$province])->first();
                                 if ($waybillPriceModelProvince){
                                     $cityIs=false;
                                     array_push($exception, ['第' . $sum . '行数据已存在城市模型,无法录入省份模型']);
                                 }
                             }
                             if ($cityIs){
-                                $waybillPriceModel = ['logistic_id' => $logistic->id, 'unit_id' => $unit->id, 'province_id' => $province->id, 'unit_price' => $row['单价']];
+                                $waybillPriceModel = ['logistic_id' => $logistic->id, 'unit_id' => $unit->id, 'province_id' => $province, 'unit_price' => $row['单价']];
                                 if ($row['计数区间']) {
                                     $str = explode('-', $row['计数区间']);
                                     if (preg_match('/^[1-9]\d*\,\d*|[1-9]\d*$/', $str[0]) >= 0
@@ -91,9 +91,7 @@ class WaybillPriceModelsImport implements ToCollection,WithHeadingRow
                                     }
                                 }
                                 if ($row['市']) {
-                                    if ($city) {
-                                        $waybillPriceModel = array_merge($waybillPriceModel, ['city_id' => $city->id]);
-                                    }
+                                    if ($city) $waybillPriceModel = array_merge($waybillPriceModel, ['city_id' => $city]);
                                 }
                                 if ($row['起步费'] && preg_match('/^[1-9]\d*\,\d*|[1-9]\d*$/', $row['起步费']) > 0) {
                                     $waybillPriceModel = array_merge($waybillPriceModel, ['base_fee' => $row['起步费']]);
@@ -113,7 +111,7 @@ class WaybillPriceModelsImport implements ToCollection,WithHeadingRow
                             }
                         } else {
                             if ($this->isOverride) {
-                                $waybillPriceModel = ['logistic_id' => $logistic->id, 'unit_id' => $unit->id, 'province_id' => $province->id, 'unit_price' => $row['单价']];
+                                $waybillPriceModel = ['logistic_id' => $logistic->id, 'unit_id' => $unit->id, 'province_id' => $province, 'unit_price' => $row['单价']];
                                 if ($row['计数区间']&& !strstr($row['计数区间'], '∞')) {
                                     $str = explode('-', $row['计数区间']);
                                     if (preg_match('/^[1-9]\d*\,\d*|[1-9]\d*$/', $str[0]) > 0
@@ -126,9 +124,7 @@ class WaybillPriceModelsImport implements ToCollection,WithHeadingRow
                                     }
                                 }
                                 if ($row['市']) {
-                                    if ($city) {
-                                        $waybillPriceModel = array_merge($waybillPriceModel, ['city_id' => $city->id]);
-                                    }
+                                    if ($city) $waybillPriceModel = array_merge($waybillPriceModel, ['city_id' => $city]);
                                 }
                                 if ($row['起步费'] && preg_match('/^[1-9]\d*\,\d*|[1-9]\d*$/', $row['起步费']) > 0) {
                                     $waybillPriceModel = array_merge($waybillPriceModel, ['base_fee' => $row['起步费']]);

+ 1 - 0
app/Jobs/OrderFreeze.php

@@ -82,6 +82,7 @@ class OrderFreeze implements ShouldQueue
         if (!$freezeOrders)return;
         $where = "''";
         foreach ($freezeOrders as $f)$where .= ",'{$f}'";
+        app("OrderService")->freezeRemoveWave($where,true);
         $edit = date("Y-m-d H:i:s");
         $sql = <<<sql
 UPDATE DOC_ORDER_HEADER SET edittime = TO_DATE('{$edit}','yyyy-mm-dd hh24:mi:ss'),releasestatus = 'H',waveno='*',notes = CASE WHEN notes IS NULL THEN '停运' ELSE  notes||',停运' END where ORDERNO in ({$where})

+ 45 - 0
app/Jobs/WeightUpdateInstantBill.php

@@ -0,0 +1,45 @@
+<?php
+
+namespace App\Jobs;
+
+use App\OrderPackage;
+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 WeightUpdateInstantBill implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+
+    /** @var \stdClass  */
+    protected $package;
+    /**
+     * Create a new job instance.
+     *
+     * @param OrderPackage $package
+     *
+     * @return void
+     */
+    public function __construct(OrderPackage $package)
+    {
+        $this->package = $package;
+    }
+
+    /**
+     * Execute the job.
+     *
+     * @param OrderService $service
+     *
+     * @return void
+     */
+    public function handle(OrderService $service)
+    {
+        if (!$this->package->weight)return;
+        $this->package->loadMissing("order");
+        if (!$this->package->order)return;
+        $service->reviseLogisticFee($this->package->order);
+    }
+}

+ 0 - 38
app/Listeners/FulfillFulfillPackageCustomer.php

@@ -1,38 +0,0 @@
-<?php
-
-namespace App\Listeners;
-
-use App\Events\CustomerStored;
-use App\OrderPackage;
-
-class FulfillPackageCustomer
-{
-    /**
-     * Create the event listener.
-     *
-     * @return void
-     */
-    public function __construct()
-    {
-        //
-    }
-
-    /**
-     * Handle the event.
-     *
-     * @param  CustomerStored  $event
-     * @return bool
-     */
-    public function handle(CustomerStored $event)
-    {
-        $packages=OrderPackage::with('WMSReflectPackage')->where('status','记录异常')->orWhere('status','已上传异常')->get();
-        foreach ($packages as $package){
-            if (isset($package->WMSReflectPackage->Customer)&&$package->WMSReflectPackage->Customer==$event->owner->code){
-                $package->status="未测量";
-                $package->owner_id=$event->owner->id;
-                $package->save();
-            }
-        }
-        return false;
-    }
-}

+ 66 - 44
app/Listeners/WaybillPriceModelListener.php

@@ -3,80 +3,102 @@
 namespace App\Listeners;
 
 use App\Logistic;
-use App\City;
 use App\Events\WaybillPriceModelEvent;
+use App\Region;
 use App\Waybill;
 use App\WaybillFinancialSnapshot;
 use App\WaybillPayoff;
 use App\WaybillFinancialExcepted;
 use App\WaybillPriceModel;
+use Illuminate\Database\Eloquent\Builder;
 
 class WaybillPriceModelListener
 {
-    /**
-     * Create the event listener.
-     *
-     * @return void
-     */
-    public function __construct()
-    {
-        //
-    }
-
     public function waybillPriceModel_check_waybill(WaybillPriceModel $waybillPriceModel){
-        $cityIds=[$waybillPriceModel->city_id];
-        //取省下所有市
+
+        $waybills=Waybill::query()->with(["logistic","order.logistic"])->where('type','专线')
+            ->where('status','!=','已完结');
+
+        //条件携带承运商
+        /** @var \stdClass $waybillPriceModel */
+        $logisticId = $waybillPriceModel->logistic_id;
+        $waybills->where(function ($query)use($logisticId){
+            /** @var Builder $query */
+            $query->where('logistic_id',$logisticId)->orWhereHas("order",function ($query)use($logisticId){
+                /** @var Builder $query */
+                $query->where("logistic_id",$logisticId);
+            });
+        });
+        //市不存在
         if(!$waybillPriceModel->city_id){
-            $cities=City::select('id')->where('province_id',$waybillPriceModel['province_id'])->get();
+            $cities=Region::query()->select('id')->where('parent_id',$waybillPriceModel['province_id'])->get();
+            $province = Region::query()->find($waybillPriceModel['province_id']);
             $cityIds=$cities->map(function ($city){
                 return $city['id'];
             });
+            //条件携带省
+            $waybills->where(function ($query)use($cityIds,$province){
+                    $province = $province->name ?? "";
+                    /** @var Builder $query */
+                    $query->whereIn('destination_city_id',$cityIds)->orWhereHas("order",function ($query)use($province){
+                        /** @var Builder $query */
+                        $query->where("province","like",$province."%");
+                    });
+                });
             //市不存在,价格区间不存在
             if (!$waybillPriceModel->range_max){
-                $waybills=Waybill::query()->where('logistic_id',$waybillPriceModel->logistic_id)->whereIn('destination_city_id',$cityIds)
-                    ->where('type','专线')->where('status','!=','已完结')->where('carrier_weight_unit_id',$waybillPriceModel->unit_id)
-                    ->orWhere('carrier_weight_unit_id_other',$waybillPriceModel->unit_id)->get();
+                $waybills->where('carrier_weight_unit_id',$waybillPriceModel->unit_id)
+                    ->orWhere('carrier_weight_unit_id_other',$waybillPriceModel->unit_id);
+            }else{
+                //市不存在,价格区间存在
+                $waybills->whereRaw('carrier_weight <= ? AND carrier_weight > ? AND carrier_weight_unit_id = ?',[$waybillPriceModel->range_max,$waybillPriceModel->range_min,$waybillPriceModel->unit_id])
+                    ->orWhereRaw('carrier_weight_other <= ? AND carrier_weight_other > ? AND carrier_weight_unit_id_other = ?',[$waybillPriceModel->range_max,$waybillPriceModel->range_min,$waybillPriceModel->unit_id]);
             }
-            //市不存在,价格区间存在
+        }else{
+            //市存在
+            //携带城市条件
+            $city = Region::query()->find($waybillPriceModel->city_id);
+            $id = $city->id ?? "";
+            $name = $city->name ?? "";
+            $waybills->where(function ($query)use($id,$name){
+                /** @var Builder $query */
+                $query->where("destination_city_id",$id)->orWhereHas("order",function($query)use($name){
+                    /** @var Builder $query */
+                    $query->where("city",'like',$name."%");
+                });
+            });
             if ($waybillPriceModel->range_max){
-                $waybills=Waybill::where('logistic_id',$waybillPriceModel->logistic_id)->whereIn('destination_city_id',$cityIds)
-                    ->whereRaw('carrier_weight <= ? AND carrier_weight > ? AND carrier_weight_unit_id = ?',[$waybillPriceModel->range_max,$waybillPriceModel->range_min,$waybillPriceModel->unit_id])
-                    ->orWhereRaw('carrier_weight_other <= ? AND carrier_weight_other > ? AND carrier_weight_unit_id_other = ?',[$waybillPriceModel->range_max,$waybillPriceModel->range_min,$waybillPriceModel->unit_id])
-                    ->where('type','专线')->where('status','!=','已完结')->get();
+                //价格区间存在
+                $waybills->whereRaw('carrier_weight <= ? AND carrier_weight > ? AND carrier_weight_unit_id = ?',[$waybillPriceModel->range_max,$waybillPriceModel->range_min,$waybillPriceModel->unit_id])
+                    ->orWhereRaw('carrier_weight_other <= ? AND carrier_weight_other > ? AND carrier_weight_unit_id_other = ?',[$waybillPriceModel->range_max,$waybillPriceModel->range_min,$waybillPriceModel->unit_id]);
+            }else{
+                //价格区间不存在
+                $waybills->where('carrier_weight_unit_id',$waybillPriceModel->unit_id)
+                    ->orWhere('carrier_weight_unit_id_other',$waybillPriceModel->unit_id);
             }
         }
-
-        //市存在,价格区间存在
-        if ($waybillPriceModel->city_id&&$waybillPriceModel->range_max){
-            $waybills=Waybill::where('logistic_id',$waybillPriceModel->logistic_id)->where('destination_city_id',$waybillPriceModel->city_id)
-                ->whereRaw('carrier_weight <= ? AND carrier_weight > ? AND carrier_weight_unit_id = ?',[$waybillPriceModel->range_max,$waybillPriceModel->range_min,$waybillPriceModel->unit_id])
-                ->orWhereRaw('carrier_weight_other <= ? AND carrier_weight_other > ? AND carrier_weight_unit_id_other = ?',[$waybillPriceModel->range_max,$waybillPriceModel->range_min,$waybillPriceModel->unit_id])
-                ->where('type','专线')->where('status','!=','完结')->get();
-        }
-
-        //市存在,价格区间不存在
-        if ($waybillPriceModel->city_id&&!$waybillPriceModel->range_max){
-            $waybills=Waybill::where('logistic_id',$waybillPriceModel->logistic_id)->where('destination_city_id',$waybillPriceModel->city_id)
-                ->where('type','专线')->where('status','!=','完结')->where('carrier_weight_unit_id',$waybillPriceModel->unit_id)
-                ->orWhere('carrier_weight_unit_id_other',$waybillPriceModel->unit_id)->get();
-        }
-        return $waybills;
+        return $waybills->get();
     }
 
     /**
      * Handle the event.
      *
      * @param  WaybillPriceModelEvent  $event
+     *
      * @return void
+     *
+     * @throws
      */
     public function handle(WaybillPriceModelEvent $event)
     {
         $waybillPriceModel=$event->waybillPriceModel;
         $waybills=$this->waybillPriceModel_check_waybill($waybillPriceModel);
+        /** @var \stdClass $waybillPriceModel */
         if ($waybills){
             foreach ($waybills as $waybill){
                 //修改运单表运费
-                $carrier=Carrier::find($waybill->logistic_id);
+                /** @var \stdClass $carrier */
+                $carrier=$waybill->order->logistic ?? $waybill->logistic;
                 if ($waybill->carrier_weight<$waybillPriceModel->initial_weight){
                     $fee=(($waybillPriceModel->unit_price)*($waybillPriceModel->initial_weight))+$carrier->delivery_fee;
                 }else{
@@ -89,7 +111,7 @@ class WaybillPriceModelListener
 
                 //修改财务表信息
                 if ($total_receivable){
-                    $waybillPayoff=WaybillPayoff::where('waybill_id','=',$waybill->id)->first();
+                    $waybillPayoff=WaybillPayoff::query()->where('waybill_id','=',$waybill->id)->first();
                     if ($waybillPayoff){
                         $waybillPayoff->total_expense=$total_expense;
                         $waybillPayoff->total_receivable=$total_receivable;
@@ -97,7 +119,7 @@ class WaybillPriceModelListener
                         $waybillPayoff->gross_profit_rate=(($total_receivable-$total_expense)/$total_receivable);
                         $waybillPayoff->save();
                     }else{
-                        WaybillPayoff::create([
+                        WaybillPayoff::query()->create([
                             'waybill_id'=>$waybill->id,
                             'total_expense'=>$total_expense,
                             'total_receivable'=>$total_receivable,
@@ -105,16 +127,16 @@ class WaybillPriceModelListener
                             'gross_profit_rate'=>(($total_receivable-$total_expense)/$total_receivable),
                         ]);
                     };
-                    $waybillFinancialExcepted=WaybillFinancialExcepted::where('waybill_id',$waybill->id)->first();
+                    $waybillFinancialExcepted=WaybillFinancialExcepted::query()->where('waybill_id',$waybill->id)->first();
                     if ($waybillFinancialExcepted){
                         $waybillFinancialExcepted->delete();
                         $waybill->status='完结';
-                        $waybillPayoff=WaybillPayoff::where('waybill_id','=',$waybillFinancialExcepted->waybill_id)->first();
+                        $waybillPayoff=WaybillPayoff::query()->where('waybill_id','=',$waybillFinancialExcepted->waybill_id)->first();
                         $waybillPayoff->load(["waybill"]);
                         $waybillPayoff->waybill->load(["owner","carrier","origination_city","destination_city","warehouse_weight_unit","carrier_weight_unit","carType","waybillAuditLogs"]);
                         $waybillPayoff->waybill->waybillAuditLogs->load(["user"]);
                         $waybillPayoffJson=json_encode($waybillPayoff,JSON_UNESCAPED_UNICODE);
-                        WaybillFinancialSnapshot::create([
+                        WaybillFinancialSnapshot::query()->create([
                             'waybill_id'=>$waybillFinancialExcepted->waybill_id,
                             'json_content'=>$waybillPayoffJson,
                         ]);

+ 20 - 5
app/Order.php

@@ -15,11 +15,26 @@ class Order extends Model
     use ModelTimeFormat;
 
     protected $fillable = [
-        'id', 'batch_id',  'owner_id', 'status',
-        'created_at', 'code', 'shop_id',  'client_code',
-        'logistic_id', 'consignee_name', 'consignee_phone', 'province',
-        'city', 'district', 'address','warehouse_id',
-        'wms_edittime', 'wms_status','order_type','frozen'
+        'id',
+        'batch_id',
+        'owner_id',
+        'status',
+        'created_at',
+        'code',
+        'shop_id',
+        'client_code',
+        'logistic_id',
+        'consignee_name',
+        'consignee_phone',
+        'province',
+        'city',
+        'district',
+        'address',
+        'warehouse_id',
+        'wms_edittime',
+        'wms_status',
+        'order_type',
+        'frozen'
     ];
 
     /*

+ 3 - 3
app/OrderPackage.php

@@ -23,7 +23,7 @@ class OrderPackage extends Model
     use ModelTimeFormat;
 
     protected $fillable = ['order_id','logistic_number','batch_number',
-        'batch_rule','bulk','weight','length','width','height','paper_box_id','measuring_machine_id','weighed_at','status','sent_at','received_at','exception','transfer_status','remark','owner_id'];
+        'batch_rule','bulk','weight','length','width','height','paper_box_id','measuring_machine_id','weighed_at','status','sent_at','received_at','exception','transfer_status','remark','owner_id','uploaded_to_wms'];
 
     public function order(){
         return $this->belongsTo('App\Order','order_id','id');
@@ -132,7 +132,7 @@ class OrderPackage extends Model
                 'logistic_number'=>$resultOracleObj['soreference5']??'',
                 'weight'=>$weight,
                 'weighed_at'=> $now,
-                'status'=>"已上传",
+                'uploaded_to_wms'=>"是",
                 "created_at"=>$now,
             ]);
         }
@@ -149,7 +149,7 @@ class OrderPackage extends Model
             'batch_number'=>$batchCode??'',
             'weight'=>$weight,
             'weighed_at'=> $now,
-            'status'=>"已上传",]);
+            'uploaded_to_wms'=>"是",]);
         $newPackages=$packages;
         if($existingOrderPackages->isNotEmpty())
             $newPackages=array_filter($packages,function ($package)use($existingLogisticNumbers){

+ 6 - 1
app/Owner.php

@@ -30,7 +30,8 @@ class Owner extends Model
         "user_owner_group_id",  //项目组ID
         "waring_line_on",       //月单量预警
         "description",          //描述
-        "warehouse_id"          //仓库ID
+        "warehouse_id",         //仓库ID
+        "user_workgroup_id"     //仓库小组(工作组)
     ];
 
     public static function filterAuthorities(){
@@ -79,6 +80,10 @@ class Owner extends Model
     {   //项目组
         return $this->hasOne(UserOwnerGroup::class,"id","user_owner_group_id");
     }
+    public function userWorkGroup()
+    {   //工作组
+        return $this->belongsTo(UserWorkgroup::class,"user_workgroup_id","id");
+    }
     public function ownerStoragePriceModels()
     {   //仓储计费
         return $this->belongsToMany(OwnerStoragePriceModel::class,"owner_storage_price_model_owner","owner_id","owner_storage_price_model_id");

+ 4 - 0
app/OwnerFeeDetail.php

@@ -53,4 +53,8 @@ class OwnerFeeDetail extends Model
     {   //出库单
         return $this->belongsTo(Order::class,"outer_id","id");
     }
+    public function items()
+    {   //快递费子项
+        return $this->hasMany(OwnerFeeDetailLogistic::class,"owner_fee_detail_id","id");
+    }
 }

+ 21 - 0
app/OwnerFeeDetailLogistic.php

@@ -0,0 +1,21 @@
+<?php
+
+namespace App;
+
+use Illuminate\Database\Eloquent\Model;
+
+use App\Traits\ModelLogChanging;
+
+class OwnerFeeDetailLogistic extends Model
+{
+    use ModelLogChanging;
+
+    protected $fillable=[
+      "owner_fee_detail_id","amount","logistic_bill","volume","weight","logistic_fee"
+    ];
+
+    public function logistic()
+    {   //快递
+        return $this->belongsTo(Logistic::class);
+    }
+}

+ 6 - 4
app/OwnerMaterial.php

@@ -6,6 +6,8 @@ use App\Traits\ModelTimeFormat;
 use Illuminate\Database\Eloquent\Model;
 
 use App\Traits\ModelLogChanging;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
+use Illuminate\Database\Eloquent\Relations\HasOne;
 
 class OwnerMaterial extends Model
 {
@@ -14,22 +16,22 @@ class OwnerMaterial extends Model
     protected $table = 'owner_material';
     protected $fillable = ['owner_id','material_id','material_code','size','special','specification','initiator'];
 
-    public function owner()
+    public function owner():BelongsTo
     {
         return $this->belongsTo(Owner::class);
     }
 
-    public function material()
+    public function material():BelongsTo
     {
         return $this->belongsTo(Material::class);
     }
 
-    public function initiator()
+    public function initiator():BelongsTo
     {
         return $this->belongsTo(User::class,'initiator','id');
     }
 
-    public function file()
+    public function file():HasOne
     {
         return $this->hasOne(UploadFile::class,'table_id','id')->where('table_name','owner_material');
     }

+ 2 - 0
app/Providers/AppServiceProvider.php

@@ -92,6 +92,7 @@ use App\Services\WaybillFinancialService;
 use App\Services\WeighExceptedService;
 use App\Services\OrderFreezeService;
 use App\Services\RegionService;
+use App\Services\UserWorkgroupService;
 use Illuminate\Queue\Events\JobFailed;
 use Illuminate\Support\Facades\Queue;
 use Illuminate\Support\Facades\Schema;
@@ -230,6 +231,7 @@ class AppServiceProvider extends ServiceProvider
         app()->singleton('UnitService',UnitService::class);
         app()->singleton('UserOwnerGroupService',UserOwnerGroupService::class);
         app()->singleton('UserService',UserService::class);
+        app()->singleton('UserWorkgroupService',UserWorkgroupService::class);
         app()->singleton('WarehouseService',WarehouseService::class);
         app()->singleton('WaybillFinancialService',WaybillFinancialService::class);
         app()->singleton('WeighExceptedService',WeighExceptedService::class);

+ 0 - 3
app/Providers/EventServiceProvider.php

@@ -26,9 +26,6 @@ class EventServiceProvider extends ServiceProvider
         'App\Events\InformWMSReceivedEvent' => [
             'App\Listeners\InformWMSReceivedListener',
         ],
-        'App\Events\CustomerStored' =>[
-            'App\Listeners\FulfillPackageCustomer'
-        ],
         'App\Events\ResetProcessStatisticStartDateEvent' =>[
             'App\Listeners\ResetProcessStatisticStartDateListener'
         ],

+ 1 - 1
app/RejectedBill.php

@@ -167,7 +167,7 @@ class RejectedBill extends Model
             $orderIssue->update(['is_new_rejecting'=>'无']);
             $orderIssue->syncRejectingStatus();
         }
-        return parent::delete(); // TODO: Change the autogenerated stub
+        return parent::delete();
     }
 
     public function joinOrderIssue()

+ 33 - 31
app/Services/BatchService.php

@@ -7,6 +7,7 @@ use App\OracleActAllocationDetails;
 use App\Order;
 use App\OrderCommodity;
 use App\Owner;
+use ErrorException;
 use Exception;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Http;
@@ -45,12 +46,8 @@ class BatchService
         return $query->get();
     }
 
-    public function insert(array $insert): bool
-    {
-        $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);
@@ -63,32 +60,37 @@ class BatchService
      */
     public function assignTasks(Collection $batches)
     {
+        try{
+
 //        $this->directTemp($batches);
-//        LogService::log(__CLASS__,__FUNCTION__,'1');
-        $this->instant($this->stationTaskBatchService,'StationTaskBatchService');
-        $this->instant($this->stationRuleBatchService,'StationRuleBatchService');
-        $this->instant($this->stationTaskService,'StationTaskService');
-        $this->instant($this->stationTaskCommodityService,'StationTaskCommodityService');
-        $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
-
-//        LogService::log(__CLASS__,__FUNCTION__,'2'.$batches->toJson());
-
-        $batches_shouldProcess = $this->stationRuleBatchService->getBatches_shouldProcess($batches); //按规则过滤需要的波次
-//        LogService::log(__CLASS__,__FUNCTION__,'3 $batches_shouldProcess:'.$batches_shouldProcess->toJson());
-        if($batches_shouldProcess->isEmpty()) return;
-
-//        LogService::log(__CLASS__,__FUNCTION__,'4');
-        $stationTasks =  $this->stationTaskService->create($batches_shouldProcess->count()); //生成总任务
-//        LogService::log(__CLASS__,__FUNCTION__,'5'.$stationTasks->toJson());
-        $stationTaskBatches=$this->stationTaskBatchService->createByBatches($batches_shouldProcess,$stationTasks); //注册波次任务
-//        LogService::log(__CLASS__,__FUNCTION__,'6'.$stationTaskBatches->toJson());
-        $stationTaskCommodities=$this->stationTaskCommodityService->createByBatches($batches_shouldProcess,$stationTasks); //注册商品任务
-//        LogService::log(__CLASS__,__FUNCTION__,'7'.$stationTaskCommodities->toJson());
-        $stationTaskMaterialBoxes=$this->stationTaskMaterialBoxService->createByBatches($batches_shouldProcess,$stationTasks); //注册料箱任务
-//        LogService::log(__CLASS__,__FUNCTION__,'8'.$stationTaskMaterialBoxes->toJson());
-
-        $ran=$this->stationTaskBatchService->runMany($stationTaskBatches);//执行波次任务
-//        LogService::log(__CLASS__,__FUNCTION__,'10'.json_encode([$ran]));
+//            LogService::log(__CLASS__,__FUNCTION__,'1');
+            $this->instant($this->stationTaskBatchService,'StationTaskBatchService');
+            $this->instant($this->stationRuleBatchService,'StationRuleBatchService');
+            $this->instant($this->stationTaskService,'StationTaskService');
+            $this->instant($this->stationTaskCommodityService,'StationTaskCommodityService');
+            $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
+
+//            LogService::log(__CLASS__,__FUNCTION__,'2'.$batches->toJson());
+
+            $batches_shouldProcess = $this->stationRuleBatchService->getBatches_shouldProcess($batches); //按规则过滤需要的波次
+//            LogService::log(__CLASS__,__FUNCTION__,'3 $batches_shouldProcess:'.$batches_shouldProcess->toJson());
+            if($batches_shouldProcess->isEmpty()) return;
+
+//            LogService::log(__CLASS__,__FUNCTION__,'4');
+            $stationTasks =  $this->stationTaskService->create($batches_shouldProcess->count()); //生成总任务
+//            LogService::log(__CLASS__,__FUNCTION__,'5'.$stationTasks->toJson());
+            $stationTaskBatches=$this->stationTaskBatchService->createByBatches($batches_shouldProcess,$stationTasks); //注册波次任务
+//            LogService::log(__CLASS__,__FUNCTION__,'6'.$stationTaskBatches->toJson());
+            $stationTaskCommodities=$this->stationTaskCommodityService->createByBatches($batches_shouldProcess,$stationTasks); //注册商品任务
+//            LogService::log(__CLASS__,__FUNCTION__,'7'.$stationTaskCommodities->toJson());
+            $stationTaskMaterialBoxes=$this->stationTaskMaterialBoxService->createByBatches($batches_shouldProcess,$stationTasks); //注册料箱任务
+//            LogService::log(__CLASS__,__FUNCTION__,'8'.$stationTaskMaterialBoxes->toJson());
+
+            $ran=$this->stationTaskBatchService->runMany($stationTaskBatches);//执行波次任务
+//            LogService::log(__CLASS__,__FUNCTION__,'10'.json_encode([$ran]));
+        }catch(Exception $e){
+            throw new ErrorException('注册任务失败: '.json_encode($batches). $e->getMessage());
+        }
     }
 
 //    public function directTemp($batches){

+ 0 - 3
app/Services/CommodityBarcodeService.php

@@ -20,9 +20,6 @@ class CommodityBarcodeService
         })->select('code','commodity_id')->whereIn('code',$codes)->get();
     }
 
-    public function insert(array $params){
-        return CommodityBarcode::query()->insert($params);
-    }
 
 
     public function first(array $params){

+ 22 - 22
app/Services/CommodityService.php

@@ -71,11 +71,6 @@ class CommodityService
         return $query->get();
     }
 
-    public function insert(array $params)
-    {
-        return Commodity::query()->insert($params);
-    }
-
 
     public function getOwnerCommodities(array $params)
     {
@@ -403,6 +398,8 @@ class CommodityService
         $create_set = config('sync.commodity_sync.cache_prefix.create_set');
         $create_keys = config('sync.commodity_sync.cache_prefix.create_keys');
         $create_key = config('sync.commodity_sync.cache_prefix.create');
+        ini_set('memory_limit', '512M');
+
         /** @var OracleBasSkuService $oracleBasSkuService */
         $oracleBasSkuService = app(OracleBasSkuService::class);
         $last_time = $this->getCommodityLastSyncAt($created_at, 'create');
@@ -422,6 +419,7 @@ class CommodityService
         $update_set = config('sync.commodity_sync.cache_prefix.update_set');
         $update_keys = config('sync.commodity_sync.cache_prefix.update_keys');
         $update_key = config('sync.commodity_sync.cache_prefix.update');
+        ini_set('memory_limit', '1200M');
         /** @var OracleBasSkuService $oracleBasSkuService */
         $oracleBasSkuService = app(OracleBasSkuService::class);
         $last_time = $this->getCommodityLastSyncAt($updated_at, 'update');
@@ -429,7 +427,11 @@ class CommodityService
         $last_time = $basSkus->first()['edittime'];
         $last_records = $basSkus->where('edittime', $last_time);
         if (!$basSkus) return;
-        $this->syncUpdateCommodity($basSkus);
+        set_time_limit(500);
+        $basSkus=$basSkus->chunk(2000);
+        foreach ($basSkus as $basSku){
+            $this->syncUpdateCommodity($basSku);
+        }
         $this->deleteCacheKey($update_set, $update_keys);
         $this->setLastRecordsByRedis($update_key, $update_set, $update_keys, $last_records);
         $this->setCommodityLastSyncAt($updated_at, $last_time);
@@ -451,16 +453,16 @@ class CommodityService
     {
         if (count($insert_params) < 1) return;
         $ownerIds = array_unique(data_get($insert_params, '*.owner_id'));
-        sort($ownerIds);
+        //sort($ownerIds);
         $skus = array_unique(data_get($insert_params, '*.sku'));
-        sort($skus);
+        //sort($skus);
         try {
-            $bool = $this->insert($insert_params);
+            $bool = $this->insert($insert_params,false,false,false);
             if ($bool) {
                 app('LogService')->log(__METHOD__, __FUNCTION__, "批量添加 Commodity Success " . count($insert_params) . ' || ' . json_encode($insert_params));
                 $commodities = Commodity::query()->whereIn('owner_id', $ownerIds)->whereIn('sku', $skus)->get();
-                $md5 = md5(json_encode([$skus, $ownerIds]));
-                if (Cache::has('commodity_' . $md5)) Cache::forget('commodity_' . $md5);
+                //$md5 = md5(json_encode([$skus, $ownerIds]));
+                //if (Cache::has('commodity_' . $md5)) Cache::forget('commodity_' . $md5);
                 if(count($commodities)>0) $this->pushToCache($commodities);
             } else app('LogService')->log(__METHOD__, __FUNCTION__, "批量添加 Commodity FAILED " . ' || ' . json_encode($insert_params));
         } catch (\Exception $e) {
@@ -595,8 +597,7 @@ class CommodityService
         $updateBasSkus=collect();
         foreach ($addBasSkus as $basSku) {
             $commodity = Cache::get("owner_code_{$basSku['customerid']}_sku_{$basSku['sku']}");
-            if (!$commodity) {
-                $commodity = $dataHandlerService->getKeyValue(['owner_id' => $owner_map[$basSku['customerid']], 'sku' => $basSku['sku']], $commodities_map);
+            if (!$commodity) $commodity = $dataHandlerService->getKeyValue(['owner_id' => $owner_map[$basSku['customerid']], 'sku' => $basSku['sku']], $commodities_map);
                 if (!$commodity) {
                     $updateBasSkus->add($basSku);
                     $insert_params[] = [
@@ -612,17 +613,16 @@ class CommodityService
                         'pack_spec' => $basSku->packid == 'STANDARD' ? 0 : explode("/", $basSku->packid)[1],
                     ];
                     continue;
-                };
-            }else if (
-                /*  $commodity->sku != $basSku->sku ||
+                } else if (
+                  $commodity->sku != $basSku->sku ||
                   $commodity->name != $basSku->descr_c ||
                   $commodity->length != $basSku->skulength ||
                   $commodity->width != $basSku->skuwidth ||
                   $commodity->height != $basSku->skuhigh ||
                   $commodity->volumn != $basSku->cube ||
                   $commodity->created_at != $basSku->addtime ||
-                  $commodity->pack_spec != $basSku->pickid*/
-                $commodity->updated_at != $basSku->edittime
+                  $commodity->pack_spec != $basSku->pickid ||
+                  $commodity->updated_at != $basSku->edittime
             ) {
                 $updateBasSkus->add($basSku);
                 $updateParams[] = [
@@ -714,12 +714,12 @@ class CommodityService
     {
         if (count($updateParams) < 1) return;
         $ownerIds = array_unique(data_get($updateParams, '*.owner_id'));
-        sort($ownerIds);
+//        sort($ownerIds);
         $skus = array_unique(data_get($updateParams, '*.sku'));
-        sort($skus);
+//        sort($skus);
         $this->batchUpdate($updateParams);
-        $md5 = md5(json_encode([$skus, $ownerIds]));
-        if (Cache::has('commodity_' . $md5)) Cache::forget('commodity_' . $md5);
+//        $md5 = md5(json_encode([$skus, $ownerIds]));
+//        if (Cache::has('commodity_' . $md5)) Cache::forget('commodity_' . $md5);
         $commodities = Commodity::query()->whereIn('owner_id', $ownerIds)->whereIn('sku', $skus)->get();
         if(count($commodities)>0) $this->pushToCache($commodities);
     }

+ 6 - 5
app/Services/FeatureService.php

@@ -73,7 +73,7 @@ class FeatureService
             foreach ($m as $string){
                 if (is_numeric($string)){//填入特征信息
                     if (isset($featureMap[$string])){
-                        $arr["type"] = $features[$featureMap[$string]]->type;
+                        $arr["type"] = Feature::type[$features[$featureMap[$string]]->type];
                         $arr["id"] = $features[$featureMap[$string]]->id;
                         $arr["logic"] = $features[$featureMap[$string]]->logic;
                         $arr["describe"] = $features[$featureMap[$string]]->describe;
@@ -128,8 +128,9 @@ class FeatureService
         $map = [];
         foreach ($features as &$feature){
             if (!$feature["type"] || !$feature["logic"] || !$feature["describe"])continue;
+            $typeMap = array_flip(Feature::type);
             $f = Feature::query()->firstOrCreate([
-                "type"=>$feature["type"],  //特征类型
+                "type"=>$typeMap[$feature["type"]],  //特征类型
                 "logic"=>$feature["logic"],  //特征逻辑
                 "describe"=>$feature["describe"],  //特征信息
             ]);
@@ -162,7 +163,7 @@ class FeatureService
         preg_match_all('/\d+|[\&\|\(\)]/',$value,$result);
         foreach ($result[0] as &$str){
             if (is_numeric($str) && isset($features[$str])){
-                $column = $features[$str]["type"];
+                $column = Feature::type[$features[$str]["type"]];
                 $logic = $features[$str]["logic"];
                 $describe = $features[$str]["describe"];
                 if ($columnMapping){
@@ -181,7 +182,7 @@ class FeatureService
                             break;
                     }
                     $str = $column.$logic."'".$describe."'";
-                }else $str = $features[$str]["type"].' '.$features[$str]["logic"].' '.$features[$str]["describe"];
+                }else $str = $column.' '.$logic.' '.$describe;
             }
             if ($str == "&"){
                 if ($columnMapping) $str = " and ";
@@ -227,7 +228,7 @@ class FeatureService
 
         foreach ($result[0] as &$str) {
             if (is_numeric($str) && isset($features[$str])) {
-                $column = $features[$str]["type"];
+                $column = Feature::type[$features[$str]["type"]];
                 $logic = $features[$str]["logic"];
                 $describe = $features[$str]["describe"];
                 if ($column == '商品名称' && $isMultiMatching){

+ 50 - 28
app/Services/ForeignHaiRoboticsService.php

@@ -18,10 +18,12 @@ use App\Traits\ServiceAppAop;
 class ForeignHaiRoboticsService
 {
     use ServiceAppAop;
-    protected $modelClass=ForeignHaiRobotics::class;
+//    protected $modelClass=ForeignHaiRobotics::class;
 
     /** @var  $stationTaskMaterialBoxService StationTaskMaterialBoxService */
     private $stationTaskMaterialBoxService;
+    /** @var  $stationTaskCommoditiesService StationTaskCommodityService */
+    private $stationTaskCommoditiesService;
     /** @var  $materialBoxService MaterialBoxService */
     private $materialBoxService;
     /** @var  $stationService StationService */
@@ -106,6 +108,10 @@ class ForeignHaiRoboticsService
         $is_in_plan
     ): bool
     {
+        $this->instant($this->stationService,'StationService');
+        $this->instant($this->materialBoxService,'MaterialBoxService');
+        $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
+        $this->instant($this->stationTaskCommoditiesService,'StationTaskCommodityService');
         try{
             if($failed
                 =!$success)
@@ -115,16 +121,19 @@ class ForeignHaiRoboticsService
                 throw new ErrorException('海柔认为是计划外的料箱:'.$exception);
 
             $materialBox=
-                $this->materialBoxService->get(['code'=>$binCode]);
-            if($stationTaskMaterialBox
+                $this->materialBoxService->get(['code'=>$binCode])->first();
+            $stationTaskMaterialBox
                 =(function()use($materialBox){
                 return $stationTaskMaterialBox=
                     $this->stationTaskMaterialBoxService
-                        ->get([
-                            'material_box_id'=>$materialBox['id'],
-                            'status'=>'处理中',
-                        ])->first();
-            })()){
+                        ->get(
+                            [
+                                'material_box_id'=>$materialBox['id'],
+                                'status'=>['处理中','异常'],
+                            ]
+                        )->first();
+            })();
+            if(!$stationTaskMaterialBox){
                 throw new ErrorException('该料箱没有安排在处理队列中');
             }
             $this->putBinToStore($stationTaskMaterialBox)
@@ -132,19 +141,31 @@ class ForeignHaiRoboticsService
                 :(function(){throw new ErrorException('呼叫机器人回收U型线料箱失败');})();
             $this->stationTaskMaterialBoxService
                 ->markProcessed($stationTaskMaterialBox);
+            $this->stationTaskCommoditiesService
+                ->markProcessed($stationTaskMaterialBox['stationTaskCommodities']);
+            $this->stationService->broadcastBinMonitor($stationTaskMaterialBox['station_id'],$stationTaskMaterialBox['stationTask']);
             return true;
         }catch (\Exception $e){
-            $this->stationTaskMaterialBoxService
-                ->excepted($stationTaskMaterialBox??$materialBox??null);
+            $stationTaskMaterialBox = $stationTaskMaterialBox??$materialBox??null;
+            if($stationTaskMaterialBox && get_class($stationTaskMaterialBox)==MaterialBox::class){
+                $stationTaskMaterialBox = StationTaskMaterialBox::query()
+                    ->where('material_box_id',$stationTaskMaterialBox['id'])
+                    ->where('status','<>','完成')
+                    ->where('created_at','>',now()->format('Y-m-d'))
+                    ->first();
+            }
+            if($stationTaskMaterialBox)
+                $this->stationTaskMaterialBoxService
+                    ->excepted($stationTaskMaterialBox);
             return $e->getMessage();
         }
     }
 
-    public function putBinToStore(StationTaskMaterialBox $stationTaskMaterialBox): bool
+    public function putBinToStore(?StationTaskMaterialBox $stationTaskMaterialBox): bool
     {
         $this->instant($this->stationService,'StationService');
         $dataToPost=$this->makeJson_move(
-            collect($stationTaskMaterialBox),
+            collect([$stationTaskMaterialBox]),
             '缓存架入立架',
             $this->stationService->getULineExit($stationTaskMaterialBox['station'])['name']??'',
             '',
@@ -155,41 +176,42 @@ class ForeignHaiRoboticsService
 
     public function taskUpdate(
 //        $groupCode,
-        $taskCode,
+        $stationTaskMaterialBox_id, //实际对应传入的字段 taskCode, 这里用料箱任务号做taskCode
         $updateEventType,   //0:task_begin(取货)1:task_end(放货)
         $status,            //0:任务成功1:任务失败
         $binCode
     ):bool{
+        $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
         try{
             if(($failed
                     =$status)==1){
                 throw new ErrorException('海柔任务失败');
             }
-            if($boxNotMatch=
+            if($料箱不匹配=
                 !$stationTaskMaterialBox
-                =(function()use($taskCode,$binCode){
-                $stationTaskMaterialBox=StationTaskMaterialBox::query()->find($id=$taskCode);
-                if($stationTaskMaterialBox['code']==$binCode)return $stationTaskMaterialBox;
-                return null;
-            })()){
+                    =(function()use($stationTaskMaterialBox_id,$binCode){
+                    $stationTaskMaterialBox=StationTaskMaterialBox::query()->find($id=$stationTaskMaterialBox_id);
+                    if($stationTaskMaterialBox['materialBox']['code']==$binCode)return $stationTaskMaterialBox;
+                    return null;
+                })()){
                 throw new ErrorException('发回的料箱和任务号(ID)不匹配');
             }
             ($标记已放置在库外=
                 function()use($updateEventType,$stationTaskMaterialBox){
-                if(($isPut
-                        =$updateEventType)==1){
-                    $this->stationTaskMaterialBoxService->markHasPut($stationTaskMaterialBox);
-                }
-            })();
+                    if(($isPut
+                            =$updateEventType)==0){
+                        $this->stationTaskMaterialBoxService->markHasTaken($stationTaskMaterialBox);
+                    }
+                })();
             ($标记已入立架=
                 function()use($updateEventType,$stationTaskMaterialBox){
                     if(($isGet
-                            =$updateEventType)==0){
-                        $this->stationTaskMaterialBoxService->markTaken($stationTaskMaterialBox);
+                            =$updateEventType)==1){
+                        $this->stationTaskMaterialBoxService->markPutStored($stationTaskMaterialBox);
                     }
-            })();
+                })();
         }catch (\Exception $e){
-            $this->excepted($taskCode, $binCode, $e->getMessage());
+            $this->excepted($stationTaskMaterialBox_id, $binCode, $e->getMessage());
             return false;
         }
         return true;

+ 4 - 0
app/Services/LogService.php

@@ -16,6 +16,10 @@ class LogService
     protected $modelClass=Log::class;
     static public function log($class, $method, $description, $id_user = null,$type='log')
     {
+        $passingMethods=config('logging.passing_methods');
+        foreach ($passingMethods as $passingMethod){
+            if($passingMethod==$method)return;
+        }
         if (!$id_user) {
             $id_user = '';
             $user = auth()->user();

+ 0 - 3
app/Services/LogisticService.php

@@ -85,9 +85,6 @@ class LogisticService
         }
     }
 
-    public function insert(array $params){
-        return Logistic::query()->insert($params);
-    }
 
     public function find($id)
     {

+ 21 - 11
app/Services/OrderIssueService.php

@@ -12,6 +12,7 @@ use App\OrderPackage;
 use App\Order;
 use App\RejectedBill;
 use App\RejectedBillItem;
+use App\ValueStore;
 use Carbon\Carbon;
 use Illuminate\Database\Query\Builder;
 use Illuminate\Http\Request;
@@ -203,7 +204,7 @@ class OrderIssueService
         return $orderIssue;
     }
 
-    public function batchDestroy($ids)
+    public function batchDestroy($ids): array
     {
         try {
             $bool = OrderIssue::query()->whereIn('id', $ids)->delete();
@@ -215,17 +216,17 @@ class OrderIssueService
         }
     }
 
-    public function endOrderIssues(array $ids)
+    public function endOrderIssues(array $ids): int
     {
         return OrderIssue::query()->whereIn('id', $ids)->update(['final_status' => '已解决']);
     }
 
-    public function isExistOrderIssueTypeIsEnd($ids)
+    public function isExistOrderIssueTypeIsEnd($ids): bool
     {
-        return OrderIssue::query()->whereIn('id', $ids)->where('final_status', '已解决')->count() > 0;
+        return OrderIssueProcessLog::query()->whereIn('order_issue_id',$ids)->where('type','结束')->exists();
     }
 
-    public function editOrderIssueSecondClientNo($id, $secondClientNo, &$order = null)
+    public function editOrderIssueSecondClientNo($id, $secondClientNo, &$order = null): bool
     {
         $orderService = app(OrderService::class);
         $orderHeaderService = app('OracleDocOrderHeaderService');
@@ -234,7 +235,7 @@ class OrderIssueService
         return OrderIssue::query()->where('id', $id)->update(['second_client_no' => $secondClientNo]) > 0;
     }
 
-    public function updateSecondLogisticNumber($id, $logisticNumber)
+    public function updateSecondLogisticNumber($id, $logisticNumber): array
     {
         $orderIssue = OrderIssue::query()->where('id',$id)->first();
         // 有填写二次订单号 并没有对应的订单号
@@ -260,7 +261,7 @@ class OrderIssueService
         return ['success' => true, 'order' => $order];
     }
 
-    public function createOrderIssue($logisticNumber, $type, $result_explain, $importedStatus = '正常', $custom_code = null,$hiddenTag = null)
+    public function createOrderIssue($logisticNumber, $type, $result_explain, $importedStatus = '正常', $custom_code = null,$hiddenTag = null): bool
     {
         $orderHeaders = OracleDOCOrderHeader::query()->with(['oracleDOCOrderDetails', 'actAllocationDetails', 'oracleBASCode','orderType'])
             ->whereHas('actAllocationDetails', function ($query) use ($logisticNumber) {
@@ -274,7 +275,7 @@ class OrderIssueService
      * @param array $logisticNumbers
      * @return array
      */
-    public function 校验问题件是否存在_快递单号_返回存在的快递单号($logisticNumbers)
+    public function 校验问题件是否存在_快递单号_返回存在的快递单号($logisticNumbers): array
     {
         $orderIssues = OrderIssue::query()->with('order.packages')->whereHas('order.packages', function ($query) use ($logisticNumbers) {
             $query->whereIn('logistic_number', $logisticNumbers);
@@ -287,7 +288,7 @@ class OrderIssueService
      * @param array $orderNos
      * @return array
      */
-    public function 校验问题件是否存在_WMS订单号_返回存在的订单号($orderNos)
+    public function 校验问题件是否存在_WMS订单号_返回存在的订单号($orderNos): array
     {
         $orderIssues = OrderIssue::query()->with('order')->whereHas('order', function ($query) use ($orderNos) {
             $query->whereIn('code', $orderNos);
@@ -296,12 +297,21 @@ class OrderIssueService
         return array_intersect($exits_logistic_number, $orderNos);
     }
 
+    public function checkOrderIssueIsExistAndSoftDelete($orderNos): array
+    {
+        $orderIssues = OrderIssue::query()->onlyTrashed()->whereIn('order_id',function($query)use($orderNos){
+            $query->from('orders')->selectRaw('id')->whereIn('code',$orderNos);
+        })->get();
+        $exits_logistic_number = array_diff(array_unique(data_get($orderIssues, '*.order.code')), ['', null]);
+        return array_intersect($exits_logistic_number, $orderNos);
+    }
+
     /**
      * 导入处理字段
      * @param array $ids
      * @return array|bool[]
      */
-    public function disposeImport(array $ids)
+    public function disposeImport(array $ids): array
     {
         $orderIssues = OrderIssue::query()->with('order')->whereIn('id', $ids)->get();
         if ($orderIssues->count()<count($ids)) {
@@ -331,7 +341,7 @@ class OrderIssueService
         },'orderIssueRejectedBills.rejectedBill.items','issueType','secondOrder.packages.commodities'])->onlyTrashed()->paginate($params['paginate'] ?? 50);
     }
 
-    public function recoverOrderIssue($ids)
+    public function recoverOrderIssue($ids): array
     {
         try {
             $bool = OrderIssue::query()->withTrashed()->whereIn('id', $ids)->restore();

+ 42 - 24
app/Services/OrderPackageCommoditiesService.php

@@ -21,9 +21,6 @@ class OrderPackageCommoditiesService
 {
     use ServiceAppAop;
     protected $modelClass=OrderPackageCommodities::class;
-    public function insert(array $params){
-        return OrderPackageCommodities::query()->insert($params);
-    }
 
     public function batchUpdate($params){
         return app(BatchUpdateService::class)->batchUpdate('order_package_commodities',$params);
@@ -480,7 +477,7 @@ class OrderPackageCommoditiesService
         unset($del_orderCommodities);
     }
 
-    public function regroupOrderCommodities(&$orderCommodities)
+    public function regroupOrderCommodities(&$orderCommodities):array
     {
         $params = [];
         $orderCommodities->each(function($orderCommodity)use(&$params){
@@ -501,7 +498,7 @@ class OrderPackageCommoditiesService
         return $params;
     }
 
-    public function regroupWmsOrderAllocationDetails(&$orderHeaders)
+    public function regroupWmsOrderAllocationDetails(&$orderHeaders):array
     {
         /**
          * @var OracleDOCOrderHeader $orderHeader
@@ -510,27 +507,48 @@ class OrderPackageCommoditiesService
         foreach ($orderHeaders as $orderHeader) {
             $order_no = $orderHeader->orderno;
             $actAllocationDetails = $orderHeader->actAllocationDetails ?? [];
-            $actAllocationDetails->each(function($item)use(&$params,$order_no){
-                $logistic_number = $item->picktotraceid;
-                $sku = $item->sku;
-                $key = ' orderno='.$order_no.' logsitic_number='.$logistic_number.' sku='.$sku.' ';
-                if(isset($params[$key])){
-                    $params[$key]['amount']+= $item->qty_each;
-                }else{
-                    $params[$key] = [
-                        'orderno'=>$item->orderno,
-                        'logistic_number'=>$item->picktotraceid,
-                        'sku' => $sku,
-                        'amount' => $item->qty_each,
-                        'owner_code' => $item->customerid
-                    ];
-                }
-            });
+            if($orderHeader['sostatus'] == '90'){
+                $logistic_number = $orderHeader['soreference5'];
+                if($logistic_number == '' ) $logistic_number= $orderHeader['orderno'];
+                $oracleDOCOrderDetails = $orderHeader->oracleDOCOrderDetails ?? [];
+                $oracleDOCOrderDetails->each(function($item)use(&$params,$order_no,$logistic_number){
+                    $sku = $item->sku;
+                    $key = ' orderno='.$order_no.' logsitic_number='.$logistic_number.' sku='.$sku.' ';
+                    if(isset($params[$key])){
+                        $params[$key]['amount']+= $item->qty_each;
+                    }else{
+                        $params[$key] = [
+                            'orderno'=>$item->orderno,
+                            'logistic_number'=>$logistic_number,
+                            'sku' => $sku,
+                            'amount' => $item->qtyordered,
+                            'owner_code' => $item->customerid
+                        ];
+                    }
+                });
+            }else{
+                $actAllocationDetails->each(function($item)use(&$params,$order_no){
+                    $logistic_number = $item->picktotraceid;
+                    $sku = $item->sku;
+                    $key = ' orderno='.$order_no.' logsitic_number='.$logistic_number.' sku='.$sku.' ';
+                    if(isset($params[$key])){
+                        $params[$key]['amount']+= $item->qty_each;
+                    }else{
+                        $params[$key] = [
+                            'orderno'=>$item->orderno,
+                            'logistic_number'=>$item->picktotraceid,
+                            'sku' => $sku,
+                            'amount' => $item->qty_each,
+                            'owner_code' => $item->customerid
+                        ];
+                    }
+                });
+            }
         }
         return $params;
     }
 
-    public function filterUpdateParams(&$orderAllocationDetails,&$orderCommodities,&$del_orderCommodities)
+    public function filterUpdateParams(&$orderAllocationDetails,&$orderCommodities,&$del_orderCommodities):array
     {
         $update_params = [];
         foreach ($orderCommodities as $key=>$orderCommodity) {
@@ -551,7 +569,7 @@ class OrderPackageCommoditiesService
         return $update_params;
     }
 
-    public function filterInnerParams(&$orderAllocationDetails,&$orderCommodities)
+    public function filterInnerParams(&$orderAllocationDetails,&$orderCommodities):array
     {
         $inner_params = [];
         foreach ($orderAllocationDetails as $key=>$orderAllocationDetail) {
@@ -563,7 +581,7 @@ class OrderPackageCommoditiesService
         return $inner_params;
     }
 
-    public function filterDeleteParams(&$orderAllocationDetails,&$orderCommodities)
+    public function filterDeleteParams(&$orderAllocationDetails,&$orderCommodities):array
     {
         $del_params = [];
         foreach ($orderCommodities as $key => $orderCommodity) {

+ 13 - 7
app/Services/OrderPackageService.php

@@ -23,10 +23,6 @@ class OrderPackageService
         return app(BatchUpdateService::class)->batchUpdate('order_packages',$params);
     }
 
-    public function insert(array $params)
-    {
-        return OrderPackage::query()->insert($params);
-    }
 
     /**
      * @param string $logistic_number
@@ -59,7 +55,7 @@ class OrderPackageService
     {
         return OrderPackage::query()->select('id', 'logistic_number', 'created_at', 'batch_number', 'batch_rule')
             ->where('status', '下发异常')->orWhere('status', '记录异常')
-            ->orWhere('status', '已上传异常')->orderBy('created_at', 'DESC')
+            ->orWhere('uploaded_to_wms', '异常')->orderBy('created_at', 'DESC')
             ->paginate($paginate);
     }
 
@@ -162,6 +158,10 @@ class OrderPackageService
         $dataHandlerService = app('DataHandlerService');
         $logistic_numbers = array_diff(array_unique(data_get($orderHeader->actAllocationDetails,'*.picktotraceid')),['','*']);
         $inner_params = [];
+        if($orderHeader['sostatus'] == '90'){
+            if($orderHeader['soreference5']=='')$logistic_numbers = [$orderHeader['orderno']];
+            else $logistic_numbers = [$orderHeader['soreference5']];
+        }
         $date = Carbon::now()->format('Y-m-d H:i:s');
         $sentAtMap = [];
         foreach ($orderHeader->actAllocationDetails as $item){
@@ -198,7 +198,13 @@ class OrderPackageService
         $dataHandlerService = app(DataHandlerService::class);
         $orderPackageCommoditiesService = app('OrderPackageCommoditiesService');
         $logistic_numbers = data_get($orderHeaders,'*.actAllocationDetails.*.picktotraceid');     // 获取picktotraceid (运单的快递单号)
-        $logistic_numbers = array_unique($logistic_numbers);
+        foreach ($orderHeaders as $orderHeader) {
+            if($orderHeader['sostatus'] == '90'){
+                if($orderHeader['soreference5']=='')$logistic_numbers[] =$orderHeader['orderno'];
+                else $logistic_numbers[] = $orderHeader['soreference5'];
+            }
+        }
+        $logistic_numbers = array_unique(array_values($logistic_numbers));
         $logistic_numbers = array_diff($logistic_numbers,['',' ','*']);
         $packages_maps = $dataHandlerService->dataHeader(['logistic_number'],$packages);
         $exits_number = data_get($packages,'*.logistic_number');
@@ -208,7 +214,7 @@ class OrderPackageService
             $package = $dataHandlerService->getKeyValue(['logistic_number'=>$number],$packages_maps);
             if($package ?? false)$packages[]=$package->id;
         }
-        if(count($packages)==0)return $packages;
+        if(count($packages)==0)return;
         try {
             $bool = OrderPackage::query()->whereIn('id', $packages)->delete();
             $orderPackageCommodities = OrderPackageCommodities::query()->whereIn('order_package_id',$packages)->get();

+ 94 - 28
app/Services/OrderService.php

@@ -4,6 +4,7 @@ namespace App\Services;
 
 use App\Jobs\OrderCreateInstantBill;
 use App\Jobs\OrderFreeze;
+use App\Log;
 use App\Logistic;
 use App\OracleActAllocationDetails;
 use App\OracleDOCASNHeader;
@@ -12,6 +13,7 @@ use App\Order;
 use App\OrderIssue;
 use App\Owner;
 use App\OwnerFeeDetail;
+use App\OwnerFeeDetailLogistic;
 use App\Province;
 use App\RejectedBill;
 use App\Services\common\BatchUpdateService;
@@ -55,19 +57,6 @@ class OrderService
         return app(BatchUpdateService::class)->batchUpdate('orders',$params);
     }
 
-    public function insert(array $params){
-        if(!$params)return true;
-        if(count($params)==0) return true;
-        try {
-            $bool= Order::query()->insert($params);
-            if($bool)app('LogService')->log(__METHOD__, __FUNCTION__, '批量创建 Order' . json_encode($params));
-            else app('LogService')->log(__METHOD__,'ERROR'. __FUNCTION__, '批量创建 Order ERROR' . json_encode($params));
-            return $bool;
-        } catch (\Exception $e) {
-            app('LogService')->log(__METHOD__, 'ERROR'.__FUNCTION__, '批量创建 Order ERROR' . json_encode($params).json_encode($e->getMessage()).json_encode($e->getTraceAsString()));
-            return false;
-        }
-    }
 
     private function preciseQuery(array $params,$sql){
         $orderdate_start=$params["orderdate_start"] ?? null;
@@ -663,7 +652,7 @@ class OrderService
         if(count($created_params) > 0){
             collect($created_params)->chunk(1000)->each(function($inner_params){
                 $arr = $inner_params->toArray();
-                $this->insert($arr);
+                $this->insert($arr,false,false,false);
                 dispatch(new OrderFreeze($arr));
             });
         }
@@ -744,6 +733,9 @@ class OrderService
         if($orderHeader->issuepartyname != null && $orderHeader->issuepartyname != '' ){
             $shop = $dataHandlerService->getKeyValue(['name'=>$orderHeader->issuepartyname ?? '','owner_id'=>$owner->id??''],$shop_map);
         }
+        if(!$batch['id']&&!($orderHeader['status']==90||$orderHeader['status']==00)&&$orderHeader['wave_no']!='*'){
+            LogService::log(__METHOD__,__FUNCTION__,'波次为空: code='.$orderHeader['orderno']);
+        }
         return [
             'code'=>$orderHeader['orderno'],
             'batch_id' =>$batch['id'] ?? null,
@@ -1020,7 +1012,7 @@ class OrderService
         if (Cache::has($key))Cache::increment($key);
         else Cache::put($key,1,2678400);
 
-        $order->loadMissing(["logistic","shop","packages.commodities.commodity"]);
+        $order->loadMissing(["logistic","shop","packages.commodities.commodity","batch"]);
 
         /** @var OwnerPriceExpressService $service */
         $service = app("OwnerPriceExpressService");
@@ -1033,30 +1025,39 @@ class OrderService
 
         if (!$order->logistic || $order->logistic->type != "快递")$logistic_fee = null;
 
+        $items = [];
         foreach ($order->packages as &$package){
             $logistic_bill .= $package->logistic_number.",";
             $volume += $package->bulk;
             $weight += $package->weight;
 
             // 四维转二维
+            $partAmount = 0;
             foreach($package->commodities as &$commodity){
                 $commodity["commodity_name"] = $commodity->commodity ? $commodity->commodity->name : '';
                 $commodity["sku"] = $commodity->commodity ? $commodity->commodity->sku : '';
-                $amount += $commodity->amount;
+                $partAmount += $commodity->amount;
             }
+            $amount += $partAmount;
             $commodities = array_merge($commodities,$package->commodities->toArray());
 
+            $provinceName = mb_substr($order->province,0,2);
+            $province = app(CacheService::class)->getOrExecute("province_".$provinceName,function ()use($provinceName){
+                return Province::query()->where("name","like",$provinceName."%")->first();
+            },86400);
+            if (!$province)$logistic_fee = null;
+
+            $fee = $service->matching($package->weight, $order->owner_id, $order->logistic_id, $province->id);
+            $items[] = [
+                "amount" => $partAmount,
+                "logistic_bill" => $package->logistic_number,
+                "volume"=>$package->bulk,
+                "weight"=>$package->weight,
+                "logistic_fee" => $fee>0 ? $fee : null,
+            ];
             if ($logistic_fee!==null){
-                $provinceName = mb_substr($order->province,0,2);
-                $province = app(CacheService::class)->getOrExecute("province_".$provinceName,function ()use($provinceName){
-                    return Province::query()->where("name","like",$provinceName."%")->first();
-                },86400);
-                if (!$province)$logistic_fee = null;
-
-                $fee = $service->matching($package->weight, $order->owner_id, $order->logistic_id, $province->id);
                 if ($fee<0)$logistic_fee = null;
-
-                $logistic_fee += $fee;
+                else $logistic_fee += $fee;
             }
         }
         if ($logistic_fee!==null && $logistic_fee<0)$logistic_fee = null;
@@ -1065,14 +1066,17 @@ class OrderService
             "logistic_name"=>($order->logistic ? $order->logistic->name : ''),
             "shop_name"=>($order->shop ? $order->shop->name : ''),
             "order_type"=>$order->order_type,
+            "batch_type" => $order->batch ? $order->batch->wms_type : '',
             "owner_id"=>$order->owner_id];
-        $mapping = ["packages"=>"commodities","商品名称"=>"commodity_name","承运商"=>"logistic_name","店铺类型"=>"shop_name","订单类型"=>"order_type","订单数"=>"amount"];
+        $mapping = ["packages"=>"commodities","商品名称"=>"commodity_name",
+            "承运商"=>"logistic_name","店铺类型"=>"shop_name","订单类型"=>"order_type",
+            "波次类型"=>"batch_type"];
 
         /** @var OwnerPriceOperationService $service */
         $service = app("OwnerPriceOperationService");
         $result = $service->matching($object,$mapping,$order->owner_id,"出库");
 
-       if (app("OwnerFeeDetailService")->create([
+        $detail = app("OwnerFeeDetailService")->create([
             "owner_id"          => $order->owner_id,
             "worked_at"         => $order->wms_edittime ?? $order->updated_at,
             "type"              => "发货",
@@ -1091,7 +1095,12 @@ class OrderService
             "created_at"        => date('Y-m-d H:i:s'),
             "outer_id"          => $order->id,
             "outer_table_name"  => "orders",
-        ]))return true;
+       ]);
+       if ($detail){
+            foreach ($items as &$item)$item["owner_fee_detail_id"] = $detail->id;
+            if (count($items)>1)OwnerFeeDetailLogistic::query()->insert($items);
+            return true;
+       }
        return false;
     }
 
@@ -1168,4 +1177,61 @@ class OrderService
                 ->count();
         });
     }
+    /**
+     * 校正运输费
+     *
+     * @param Order $order
+     *
+     * @return bool
+     */
+    public function reviseLogisticFee(Order $order):bool
+    {
+        /** @var \stdClass $order */
+        if (!$order || $order->wms_status != '订单完成')return false; //订单不存在或状态不为完成
+        $feeBill = OwnerFeeDetail::query()->where("outer_table_name","orders")
+            ->where("outer_id",$order->id)->whereNull("logistic_fee")->first();
+        if (!$feeBill)return false; //是否已有即时账单,没有跳出
+        $order->loadMissing("packages","owner");//加载包裹
+        if (!$order->packages || !$order->owner)return false;
+        $order->owner->loadCount("ownerPriceExpresses");
+        if ($order->owner->owner_price_expresses_count < 1)return false; //不存在计费模型 跳出
+        foreach ($order->packages as $package)if (!$package->weight)return false; //包裹存在且全部存在数量
+
+        $logisticFee = 0;
+        foreach ($order->packages as $package){
+            if ($logisticFee!==null){
+                $provinceName = mb_substr($order->province,0,2);
+                $province = app(CacheService::class)->getOrExecute("province_".$provinceName,function ()use($provinceName){
+                    return Province::query()->where("name","like",$provinceName."%")->first();
+                },86400);
+                if (!$province)$logisticFee = null;
+
+                $fee = app("OwnerPriceExpressService")->matching($package->weight, $order->owner_id, $order->logistic_id, $province->id);
+                if ($fee<0)$logisticFee = null;
+                else $logisticFee += $fee;
+            }
+        }
+        if ($logisticFee===null || $logisticFee<0)
+            LogService::log(__METHOD__,"ERROR-校正即时账单计算物流费错误","订单ID:".$order->id."  费用结果:".$logisticFee);
+        else $feeBill->update(["logistic_fee"=>$logisticFee]);
+        return true;
+    }
+
+    public function freezeRemoveWave($orders, $isSql = false)
+    {
+        if (!$isSql && !is_array($orders))$orders = [$orders];
+        if (!$isSql){
+            $where = "''";
+            foreach ($orders as $f)$where .= ",'{$f}'";
+            $orders = $where;
+        }
+        $sql = <<<sql
+    DELETE FROM DOC_WAVE_DETAILS WHERE (WAVENO,ORDERNO) IN (SELECT DOC_ORDER_HEADER.WAVENO,DOC_ORDER_HEADER.ORDERNO FROM DOC_ORDER_HEADER LEFT JOIN DOC_WAVE_DETAILS ON DOC_ORDER_HEADER.WAVENO = DOC_WAVE_DETAILS.WAVENO
+    AND DOC_ORDER_HEADER.ORDERNO = DOC_WAVE_DETAILS.ORDERNO WHERE DOC_ORDER_HEADER.orderno IN ({$orders}) AND DOC_ORDER_HEADER.WAVENO != '*' AND DOC_ORDER_HEADER.WAVENO IS NOT NULL)
+sql;
+        $result = DB::connection("oracle")->delete(DB::raw("$sql"));
+        LogService::log(__METHOD__,"删除波次详情",$sql);
+        return $result;
+    }
+
 }

+ 1 - 1
app/Services/OrderTrackingService.php

@@ -66,7 +66,7 @@ class OrderTrackingService
     {
         $query = $this->getQuery($params);
 
-        if (isset($params['client_code'])|| isset($params['logistic_id'])){     // client_code logistic
+        if (isset($params['client_code'])){     // client_code logistic
             $query->where('order_client_code','like',$params['client_code']);
 //            $query->whereHas('commodities.package.order', function ($query) use ($params) {
 //                if($params['client_code'] ?? false){

+ 64 - 44
app/Services/OwnerPriceOperationService.php

@@ -105,6 +105,8 @@ class OwnerPriceOperationService
      * 三. 2021-01-28 zzd
      *      增加满减策略:子策略匹配时不再考虑单,仅件箱换算,满减满足后标记模型修改历史对账单
      *      增加按订单计价策略:主匹配模型增加字段量价,该字段存在时视为按单计价,价格为该值
+     * 四. 2021-02-18 zzd
+     *      满减多阶段匹配 满减字段由单值改为字符串多值 匹配时转数组寻找最相近
      */
     public function matching($matchObject, $columnMapping, $owner_id, $type = '出库')
     {
@@ -126,59 +128,76 @@ class OwnerPriceOperationService
         foreach ($rules as $rule){
             if (!$rule->items)continue; //不存在子规则跳出
             $isDiscount = false;    //是否存在满减
-            if ($type=='出库' && $rule->discount_count > 0 && $total >= $rule->discount_count)$isDiscount = true;//满足满减条件
-            //满减存在且未被标记过处理时间或处理时间不为本月,处理历史即时账单
-            if ($isDiscount && (!$rule->discount_date || substr($rule->discount_date,0,7)!=date("Y-m"))){
-                try{
-                    DB::beginTransaction();
-                    $month = date("Y-m");
-                    $day = date("t",strtotime($month));
-                    foreach (OwnerFeeDetail::query()->with(["order.logistic","order.shop","order.packages.commodities.commodity"])
-                                 ->where("owner_id",$owner_id)
-                                 ->whereBetween("worked_at",[$month."-01",$month."-".$day])->get() as $detail){
-                        $order = $detail->order;
+            $discountIndex = 0;
+            $targetValue = 0;
+            if ($type=='出库' && $rule->discount_count){
+                foreach (array_reverse(explode(",",$rule->discount_count),true) as $index=>$discount){
+                    if ($total >= $discount){
+                        $isDiscount = true; //第一个满足满减条件
+                        $discountIndex = $index;
+                        $targetValue = $discount;
+                        break;
+                    }
+                }
+            }
+            //满减存在
+            if ($isDiscount){
+                //未被标记过处理时间或处理时间不为本月,或上次处理值过期,处理历史即时账单
+                $pivot = DB::selectOne(DB::raw("SELECT * FROM owner_price_operation_owner WHERE owner_price_operation_id = ? AND owner_id = ?"),[$rule->id,$owner_id]);
+                if ($pivot && (!$pivot->discount_date || substr($pivot->discount_date,0,7)!=date("Y-m") || $pivot->target_value < $targetValue)){
+                    try{
+                        DB::beginTransaction();
+                        $month = date("Y-m");
+                        $day = date("t",strtotime($month));
+                        foreach (OwnerFeeDetail::query()->with(["order.logistic","order.shop","order.packages.commodities.commodity","order.batch"])
+                                     ->where("owner_id",$owner_id)
+                                     ->whereBetween("worked_at",[$month."-01",$month."-".$day])->get() as $detail){
+                            $order = $detail->order;
 
-                        $logistic_fee = 0;
-                        $commodities = [];
-                        foreach ($order->packages as &$package){
-                            // 四维转二维
-                            foreach($package->commodities as &$commodity){
-                                $commodity["commodity_name"] = $commodity->commodity ? $commodity->commodity->name : '';
-                                $commodity["sku"] = $commodity->commodity ? $commodity->commodity->sku : '';
+                            $logistic_fee = 0;
+                            $commodities = [];
+                            foreach ($order->packages as &$package){
+                                // 四维转二维
+                                foreach($package->commodities as &$commodity){
+                                    $commodity["commodity_name"] = $commodity->commodity ? $commodity->commodity->name : '';
+                                    $commodity["sku"] = $commodity->commodity ? $commodity->commodity->sku : '';
+                                }
+                                $commodities = array_merge($commodities,$package->commodities->toArray());
                             }
-                            $commodities = array_merge($commodities,$package->commodities->toArray());
-                        }
-                        if ($logistic_fee!==null && $logistic_fee<0)$logistic_fee = null;
+                            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,
-                            "owner_id"=>$order->owner_id];
-                        $mapping = ["packages"=>"commodities","商品名称"=>"commodity_name",
-                            "承运商"=>"logistic_name", "店铺类型"=>"shop_name",
-                            "订单类型"=>"order_type","订单数"=>"amount"];
-                        $money = $this->matchItem($rule->items,$mapping,$object,$units,$owner_id,'出库',$isDiscount);
-                        if ($money>0)$detail->update(["work_fee"=>$money]);
-                        else LogService::log(__CLASS__,"处理历史即时账单时发生匹配错误","账单主键:".$detail->id."; 错误代码".$money);
-                    };
-                    $rule->update(["discount_date"=>date("Y-m-d")]);
-                    DB::commit();
-                }catch (\Exception $e){
-                    DB::rollBack();
-                    LogService::log(__CLASS__,"处理历史即时账单时发生系统错误","计费模型主键:".$rule->id."; 错误信息".$e->getMessage());
+                            $object = ["commodities"=>$commodities,
+                                "logistic_name"=>($order->logistic ? $order->logistic->name : ''),
+                                "shop_name"=>($order->shop ? $order->shop->name : ''),
+                                "order_type"=>$order->order_type,
+                                "batch_type" => $order->batch ? $order->batch->wms_type : '',
+                                "owner_id"=>$order->owner_id];
+                            $mapping = ["packages"=>"commodities","商品名称"=>"commodity_name",
+                                "承运商"=>"logistic_name", "店铺类型"=>"shop_name",
+                                "订单类型"=>"order_type","波次类型"=>"batch_type"];
+                            $money = $this->matchItem($rule->items,$mapping,$object,$units,$owner_id,false,$isDiscount,$discountIndex);
+                            if ($money>0)$detail->update(["work_fee"=>$money]);
+                            else LogService::log(__CLASS__,"处理历史即时账单时发生匹配错误","账单主键:".$detail->id."; 错误代码".$money);
+                        };
+                        DB::update(DB::raw("UPDATE owner_price_operation_owner SET discount_date = ?,target_value = ? WHERE  owner_price_operation_id = ? AND owner_id = ?"),
+                            [date("Y-m-d"),$targetValue,$rule->id,$owner_id]);
+                        DB::commit();
+                    }catch (\Exception $e){
+                        DB::rollBack();
+                        LogService::log(__CLASS__,"处理历史即时账单时发生系统错误","计费模型主键:".$rule->id."; 错误信息".$e->getMessage());
+                    }
                 }
             }
             if ($rule->strategy == '特征'){//特征策略匹配
                 $bool = app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject);
                 if ($bool === true){
-                    if ($rule->total_price)return ["id"=>$rule->id,"money"=>$isDiscount ? $rule->total_discount_price : $rule->total_price]; //按单计价存在,直接返回单总价或减免总价
-                    $money = $this->matchItem($rule->items,$columnMapping,$matchObject,$units,$owner_id,$type=='入库' ? true : false,$isDiscount);
+                    if ($rule->total_price)return ["id"=>$rule->id,"money"=>$isDiscount ? explode(",",$rule->total_discount_price)[$discountIndex] : $rule->total_price]; //按单计价存在,直接返回单总价或减免总价
+                    $money = $this->matchItem($rule->items,$columnMapping,$matchObject,$units,$owner_id,$type=='入库' ? true : false,$isDiscount,$discountIndex);
                     if ($money>0)return ["id"=>$rule->id,"money"=>$money];
                 };
             }else{//默认策略匹配
-                if ($rule->total_price)return ["id"=>$rule->id,"money"=>$isDiscount ? $rule->total_discount_price : $rule->total_price]; //按单计价存在,直接返回单总价或减免总价
-                $money = $this->matchItem($rule->items,$columnMapping,$matchObject,$units,$owner_id,$type=='入库' ? true : false,$isDiscount);
+                if ($rule->total_price)return ["id"=>$rule->id,"money"=>$isDiscount ? explode(",",$rule->total_discount_price)[$discountIndex] : $rule->total_price]; //按单计价存在,直接返回单总价或减免总价
+                $money = $this->matchItem($rule->items,$columnMapping,$matchObject,$units,$owner_id,$type=='入库' ? true : false,$isDiscount,$discountIndex);
                 if ($money>0)return ["id"=>$rule->id,"money"=>$money];
             };
         }
@@ -212,10 +231,11 @@ class OwnerPriceOperationService
      * @param integer $owner_id 货主ID
      * @param bool $isIn 是否为入库单
      * @param bool $isDiscount 是否为满减单
+     * @param int $discountIndex 阶梯满减所处下标  满减价格此处应为 1,2,3 解析为数组后根据此下标寻找对应值
      *
      * @return double
      */
-    private function matchItem($rules, $columnMapping, $matchObject, $units, $owner_id, $isIn, $isDiscount)
+    private function matchItem($rules, $columnMapping, $matchObject, $units, $owner_id, $isIn, $isDiscount, $discountIndex)
     {
         $amountColumn = $columnMapping["amount"] ?? "amount";
         $packageColumn = $columnMapping["packages"] ?? "packages";
@@ -225,7 +245,7 @@ class OwnerPriceOperationService
 
         $unitName = "";
         foreach ($rules as $rule){
-            if ($isDiscount)$rule->unit_price = $rule->discount_price; //满足满减条件,单价调整为满减单价
+            if ($isDiscount)$rule->unit_price = explode(",",$rule->discount_price)[$discountIndex]; //满足满减条件,单价调整为满减单价
             switch ($rule->strategy){
                 case "特征":
                     $inMoney = 0;

+ 16 - 11
app/Services/OwnerStoragePriceModelService.php

@@ -63,23 +63,28 @@ class OwnerStoragePriceModelService
                             ->where("owner_id",$owner_id)
                             ->where("counting_month","like",$month."%")->first();
                         $money -= $report ? ($report->total)*($model->discount_value) : 0;
+                    }else{
+                        $days = date('t', strtotime($month."-01"));
+                        $money *= $days;
+                        for($i=1;$i<=$days;$i++){
+                            $d = $i<10 ? "0".$i : $i;
+                            $query = DB::raw("SELECT COUNT(1) c FROM orders WHERE wms_status = ? and updated_at between ? and ?");
+                            $count = DB::selectOne($query,['订单完成',$month."-".$d." 00:00:00",$month."-".$d." 23:59:59"]);
+                            $money -= $count ? ($count->c)*($model->discount_value) : 0;
+                        }
                     }
                 }
                 break;
             case "固定减免":
-                $money -= $model->discount_value;
+                if ($model->timeUnit->name == '月'){
+                    $money -= $model->discount_value;
+                }else{
+                    $days = date('t', strtotime($month."-01"));
+                    $money *= $days;
+                    $money -= $days*$model->discount_value;
+                }
                 break;
         }
-        if ($model->timeUnit->name == '日'){
-            $days = date('t', strtotime($month."-01"));
-            $money *= $days;
-            for($i=1;$i<=$days;$i++){
-                $d = $i<10 ? "0".$i : $i;
-                $query = DB::raw("SELECT COUNT(1) c FROM orders WHERE wms_status = ? and updated_at between ? and ?");
-                $count = DB::selectOne($query,['订单完成',$month."-".$d." 00:00:00",$month."-".$d." 23:59:59"]);
-                $money -= $count ? ($count->c)*($model->discount_value) : 0;
-            }
-        }
         return $money;
     }
 }

+ 6 - 2
app/Services/PackageService.php

@@ -4,8 +4,8 @@ namespace App\Services;
 
 use App\OrderPackage;
 use App\Services\common\QueryService;
-use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Http\Request;
+use Illuminate\Support\Arr;
 use Illuminate\Support\Facades\Auth;
 
 const TABLE = "order_packages.";
@@ -19,7 +19,7 @@ class PackageService
     private function conditionQuery($params){
         $ownerIds=app('UserService')->getPermittingOwnerIds(Auth::user());
         $packages = OrderPackage::query()->with(['order'=>function($query){
-            return  $query->with(['owner','logistic']);
+            return  $query->with(['owner','logistic','batch']);
         },'paperBox','measuringMachine'])
         ->whereIn('order_packages.owner_id',$ownerIds)->orderBy(TABLE.'id','DESC');
         if ($params['owner_id'] ?? false){
@@ -31,6 +31,10 @@ class PackageService
             $packages->whereIn('logistic_number',array_values(array_filter(preg_split('/[,, ]+/is', $params['logistic_number']))));
             unset($params["logistic_number"]);
         }
+        if ($params['is_weighed']?? false) {
+            $packages->whereNotNull('weighed_at');
+            Arr::forget($params, 'is_weighed');
+        }
         $columnQueryRules=[
             'batch_number' => ['like' => ''],
             'created_at_start' => ['alias' => 'created_at','startDate' => " 00:00:00"],

+ 7 - 0
app/Services/RegionService.php

@@ -128,4 +128,11 @@ class RegionService
         }
         return $name;
     }
+
+    public function getSelection($type = null, $columns = ["id","name"])
+    {
+        $regions = Region::query()->select($columns);
+        if ($type)$regions->where("type",$type);
+        return $regions->get();
+    }
 }

+ 1 - 3
app/Services/RejectedBillItemService.php

@@ -10,8 +10,6 @@ class RejectedBillItemService
 {
     use ServiceAppAop;
     protected $modelClass=RejectedBillItem::class;
-    public function insert(array $params){
-        return RejectedBillItem::query()->insert($params);
-    }
+
 
 }

+ 0 - 5
app/Services/ShopService.php

@@ -32,11 +32,6 @@ class ShopService
         return $shop->firstOrCreate($param);
     }
 
-    public function insert(array $params)
-    {
-        return Shop::query()->insert($params);
-    }
-
     public function batchUpdate(array $params)
     {
         return app(BatchUpdateService::class)->batchUpdate('shops',$params);

+ 2 - 0
app/Services/StationRuleBatchService.php

@@ -20,6 +20,8 @@ class StationRuleBatchService
     {
         $batchType = $batch['type'] ?? 'null';
         $ownerId = $batch['owner_id'] ?? 'null';
+        $batch->loadMissing('stationTaskBatch');
+        if($batch['stationTaskBatch'])return null;
         return Cache::remember('stationRuleBatch_batchType_'.$batchType.'_ownerId_'.$ownerId, config('cache.expirations.rarelyChange'),function()use($batch){
             $builder= StationRuleBatch::query()->with('stationType')
                 ->where('owner_id',$batch['owner_id']);

+ 1 - 1
app/Services/StationService.php

@@ -60,7 +60,7 @@ class StationService
         broadcast(new BroadcastToStation($station_id,$json_data));
     }
 
-    function broadcastBinMonitor($station_id, StationTask $stationTask){
+    function broadcastBinMonitor($station_id, ?StationTask $stationTask){
         $stationTask->loadMissing(["taskCommodities.commodity.barcodes","taskCommodities.materialBox","taskBatches.batch"/*,"taskMaterialBoxes.box"*/]);
         $stationTask->toJson();
         $this->broadcast($station_id, $stationTask->toJson());

+ 20 - 18
app/Services/StationTaskBatchService.php

@@ -88,8 +88,8 @@ class StationTaskBatchService
 
     function getAndAttachIds($stationTaskBatches): Collection
     {
-        $md5=is_array($stationTaskBatches)
-            ?$md5=md5(json_encode($stationTaskBatches)):null;
+        $md5=md5(is_array($stationTaskBatches)
+            ?$md5=json_encode($stationTaskBatches):$stationTaskBatches->toJson());
 
         return Cache::remember(
             'StationTaskBatch_'.$md5??md5(json_encode($stationTaskBatches->toArray()))
@@ -101,10 +101,7 @@ class StationTaskBatchService
                 ->get();
         });
     }
-    function insert(array $stationMissionBatches): bool
-    {
-        return StationTaskBatch::query()->insert($stationMissionBatches);
-    }
+
 
     function markManyExcepted(Collection $stationTaskBatches_failed)
     {
@@ -167,9 +164,13 @@ class StationTaskBatchService
             (function () use ($stationTaskBatch) {
                 throw new Exception('找不到料箱:' . json_encode($stationTaskBatch));
             })();
-        $isFetchedFromRobotics
-            = $this->foreignHaiRoboticsService->
-        fetchGroup($toLocation, $taskMaterialBoxes, $groupPrefix);
+        try{
+            $isFetchedFromRobotics
+                = $this->foreignHaiRoboticsService->
+            fetchGroup($toLocation, $taskMaterialBoxes, $groupPrefix);
+        }catch(Exception $e){
+            throw new ErrorException('$stationTaskBatch运行波次机器人任务失败,获取组失败: '.$stationTaskBatch->toJson() . $e->getMessage());
+        }
         ($markNewStatus
             =function()use($isFetchedFromRobotics,$stationTaskBatch){
             $isFetchedFromRobotics?
@@ -179,19 +180,20 @@ class StationTaskBatchService
         return $isFetchedFromRobotics;
     }
 
-    function markProcessing($stationTaskBatches)
+    function markProcessing($stationTaskBatch_orCollection)
     {
-        if (get_class($stationTaskBatches)==StationTaskBatch::class){
-            $stationTaskBatches = collect($stationTaskBatches);
+        if (get_class($stationTaskBatch_orCollection)==StationTaskBatch::class){
+            $stationTaskBatch_orCollection = collect([$stationTaskBatch_orCollection]);
         }
+        $this->markProcessing_byIds(data_get($stationTaskBatch_orCollection, '*.id'));
+    }
+    function markProcessing_byIds($ids)
+    {
+        if(!$ids)$ids=[];
+        if(!is_array($ids))$ids=[$ids];
         StationTaskBatch::query()
-            ->whereIn('id', data_get($stationTaskBatches, '*.id'))
+            ->whereIn('id', $ids)
             ->update(['status'=>'处理中']);
-
-        $this->stationTaskService
-            ->markProcessing_byId(
-                data_get($stationTaskBatches, '*.station_id')
-            );
     }
 
 //    function markFinished($stationTaskBatches)

+ 1 - 7
app/Services/StationTaskChildService.php

@@ -26,11 +26,5 @@ class StationTaskChildService
             return $query->get();
         });
     }
-    public function insert(array $stationMissionBatches): bool
-    {
-        $inserted = StationTaskChild::query()->insert($stationMissionBatches);
-        LogService::log(__METHOD__,__FUNCTION__,json_encode($stationMissionBatches).
-            '||'.json_encode(array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS),0,3)));
-        return $inserted;
-    }
+
 }

+ 16 - 20
app/Services/StationTaskCommodityService.php

@@ -9,6 +9,7 @@ use App\OrderCommodity;
 use App\StationTask;
 use App\StationTaskBatch;
 use App\StationTaskCommodity;
+use App\StationTaskMaterialBox;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Cache;
 use App\Traits\ServiceAppAop;
@@ -63,6 +64,8 @@ class StationTaskCommodityService
 
     }
 
+
+
 //    function getAndAttachIds($taskCommodities): Collection
 //    {
 //        $md5=is_array($taskCommodities)
@@ -101,6 +104,7 @@ class StationTaskCommodityService
             $stationType=$this->stationTypeService->getForCommodity();
             $station=$this->stationService->getStation_byType($stationType['name']);
             $materialBox=$this->materialBoxService->firstOrCreate(['code' => $orderCommodity['location']]);
+            $stationTaskMaterialBoxId=StationTaskMaterialBox::query()->where('station_task_batch_id',$batch['id'])->where('material_box_id',$materialBox['id'])->get('id');
             $stationTaskCommodities_toCreate->push(
                 new StationTaskCommodity([
                     'station_id'=>$station['id'],
@@ -110,34 +114,26 @@ class StationTaskCommodityService
                     'bin_number'=>$orderCommodity['orderBin']['number']??'',
                     'order_id'=>$orderCommodity['order_id'],
                     'station_task_batch_id'=>$batch['id'],
-                    'status'=>'待处理'
+                    'station_task_material_box_id'=>$stationTaskMaterialBoxId,
+                    'status'=>'待处理',
                 ])
             );
         }
-        return $this->insert($stationTaskCommodities_toCreate->toArray());
+        return $this->insert($stationTaskCommodities_toCreate->toArray(),true);
     }
 
-    public function insert(array $taskCommodities): ?Collection
+    function markProcessing($stationTaskCommodity_orCollection)
     {
-        StationTaskCommodity::query()->insert($taskCommodities);
-        return StationTaskCommodity::query()
-            ->whereIn('status', data_get($taskCommodities, '*.status'))
-            ->whereIn('station_task_batch_id', data_get($taskCommodities, '*.station_task_batch_id'))
-            ->whereIn('commodity_id', data_get($taskCommodities, '*.commodity_id'))
-            ->get();
-    }
-    function markProcessing($stationTaskCommodities)
-    {
-        if (get_class($stationTaskCommodities)==StationTaskCommodity::class){
-            $stationTaskCommodities = collect($stationTaskCommodities);
+        if (get_class($stationTaskCommodity_orCollection)==StationTaskCommodity::class){
+            $stationTaskCommodity_orCollection = collect([$stationTaskCommodity_orCollection]);
         }
         StationTaskCommodity::query()
-            ->whereIn('id',data_get($stationTaskCommodities,'*.id'))
+            ->whereIn('id',data_get($stationTaskCommodity_orCollection,'*.id'))
             ->update(['status'=>'处理中']);
-
-        $this->stationTaskService
-            ->markProcessing_byId(
-                data_get($stationTaskCommodities, '*.station_id')
-            );
+    }
+    function markProcessed(Collection $stationTaskCommodities){
+        StationTaskCommodity::query()
+            ->whereIn('id',data_get($stationTaskCommodities,'*.id'))
+            ->update(['status'=>'完成']);
     }
 }

+ 40 - 35
app/Services/StationTaskMaterialBoxService.php

@@ -6,9 +6,11 @@ namespace App\Services;
 
 use App\Batch;
 use App\Exceptions\ErrorException;
+use App\Exceptions\Exception;
 use App\MaterialBox;
 use App\OrderCommodity;
 use App\StationTask;
+use App\StationTaskBatch;
 use App\StationTaskMaterialBox;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Cache;
@@ -43,11 +45,10 @@ class StationTaskMaterialBoxService
     function createByBatches(Collection $batches,Collection $stationTasks_toAttach): Collection
     {
         $this->instant($this->stationTaskService,'StationTaskService');
-        $stationTaskMaterialBoxes = (function () use ($batches) {
+        $stationTaskMaterialBoxes_byBatch = (function () use ($batches) {
             $stationTaskMaterialBoxes_listByBatch = new Collection();
             foreach ($batches as $batch) {
-                $stationTaskMaterialBoxes_listByBatch=
-                    $stationTaskMaterialBoxes_listByBatch->merge(
+                    $stationTaskMaterialBoxes_listByBatch->push(
                     $this->createByBatch($batch)
                 );
             }
@@ -56,9 +57,8 @@ class StationTaskMaterialBoxService
          $this->stationTaskService
             ->registerSubTasks(
                 $stationTasks_toAttach,
-                [$stationTaskMaterialBoxes]);
-        return $stationTaskMaterialBoxes;
-
+                $stationTaskMaterialBoxes_byBatch);
+        return collect(data_get($stationTaskMaterialBoxes_byBatch,'*.*'));
     }
 
     function createByBatch(Batch $batch): ?Collection
@@ -77,16 +77,20 @@ class StationTaskMaterialBoxService
             $stationMaterialBoxes_toCreate->push([
                 'station_id'=>$station['id'],
                 'material_box_id'=>$materialBox['id'],
+                'station_task_batch_id'=>$batch['id'],
                 'status'=>'待处理'
             ]);
         }
-        return $this->insert($stationMaterialBoxes_toCreate->toArray());
+        return $this->insert($stationMaterialBoxes_toCreate->toArray(),true);
     }
 
-    function get(array $kvPairs){
+    function get(array $kvPairs, $with=null){
         ksort($kvPairs);
-        return Cache::remember('StationTaskMaterialBox'.md5(json_encode($kvPairs)), config('cache.expirations.fastChange'), function ()use($kvPairs) {
+        return Cache::remember('StationTaskMaterialBox'.md5(json_encode($kvPairs).json_encode([$with])), config('cache.expirations.fastChange'), function ()use($kvPairs,$with) {
             $query = StationTaskMaterialBox::query();
+            if($with){
+                $query->with($with);
+            }
             foreach ($kvPairs as $column => $value){
                 if (is_array($value))$query->whereIn($column,$value);
                 else $query->where($column,$value);
@@ -95,23 +99,18 @@ class StationTaskMaterialBoxService
         });
     }
 
-    public function insert(array $stationTaskMaterialBoxes): Collection
-    {
-        $inserted=collect();
-        foreach ($stationTaskMaterialBoxes as $stationTaskMaterialBox){
-            $inserted->push(StationTaskMaterialBox::query()->create($stationTaskMaterialBox));
-        }
-        return $inserted;
-    }
 
-    function markHasPut(StationTaskMaterialBox $stationTaskMaterialBox){
+    function markHasTaken(StationTaskMaterialBox $stationTaskMaterialBox){
+        $this->instant($this->stationTaskBatchService,'StationTaskBatchService');
+        $this->instant($this->stationTaskCommodityService,'StationTaskCommodityService');
         try{
             $taskType=$this->getServingTaskType($stationTaskMaterialBox);
             switch ($taskType){
                 case '分波次':
                     $this->markProcessing($stationTaskMaterialBox);
-                    $this->stationTaskBatchService->markProcessing($stationTaskMaterialBox['stationTaskBatch']);
+                    $this->stationTaskBatchService->markProcessing_byIds($stationTaskMaterialBox['station_task_batch_id']);
                     $this->stationTaskCommodityService->markProcessing($stationTaskMaterialBox['stationTaskCommodities']);
+                    $this->stationTaskService->markProcessing_byIds(data_get($stationTaskMaterialBox['stationTaskCommodities'],'*.station_task_id'));
                     break;
                 case '入立库':
 
@@ -123,43 +122,48 @@ class StationTaskMaterialBoxService
         }
     }
 
-    function markTaken($stationTaskMaterialBox){
+    function markPutStored($stationTaskMaterialBox){
         //TODO: 标记 料箱位置(需要其字段存在)$stationTaskMaterialBox['materialBox']['position']
     }
     function markProcessed(StationTaskMaterialBox $stationTaskMaterialBox){
         $stationTaskMaterialBox['status'] = '完成';
         $stationTaskMaterialBox->save();
-        $this->stationService->broadcastBinMonitor($stationTaskMaterialBox['station_id'],$stationTaskMaterialBox['stationTask']);
     }
 
-    function markProcessing($stationTaskMaterialBox)
+    function markProcessing($stationTaskMaterialBox_orBoxes)
     {
-        if (get_class($stationTaskMaterialBox)==StationTaskMaterialBox::class){
-            $stationTaskMaterialBox = collect($stationTaskMaterialBox);
+        $this->instant($this->stationTaskService,'StationTaskService');
+        if (get_class($stationTaskMaterialBox_orBoxes)==StationTaskMaterialBox::class){
+            $stationTaskMaterialBox_orBoxes = collect([$stationTaskMaterialBox_orBoxes]);
         }
         StationTaskMaterialBox::query()
-            ->whereIn('id', data_get($stationTaskMaterialBox, '*.id'))
+            ->whereIn('id', data_get($stationTaskMaterialBox_orBoxes, '*.id'))
             ->update(['status'=>'处理中']);
         $this->stationTaskService
-            ->markProcessing_byId(
-                data_get($stationTaskMaterialBox, '*.station_id')
+            ->markProcessing_byIds(
+                data_get($stationTaskMaterialBox_orBoxes, '*.station_id')
             );
     }
 
-    function excepted($stationTaskMaterialBox_orBox){
-        switch (get_class($stationTaskMaterialBox_orBox)){
+    function excepted($stationTaskMaterialBoxes_orBox){
+        if (get_class($stationTaskMaterialBoxes_orBox)==StationTaskMaterialBox::class){
+            $stationTaskMaterialBoxes_orBox = collect([$stationTaskMaterialBoxes_orBox]);
+        }
+        StationTaskMaterialBox::query()->whereIn('id',data_get($stationTaskMaterialBoxes_orBox,'*.id'))
+            ->update(['status'=>'异常']);
+        switch (get_class($stationTaskMaterialBoxes_orBox)){
             case MaterialBox::class:
             case StationTaskMaterialBox::class:
-            throw new ErrorException('料箱异常'.json_encode($stationTaskMaterialBox_orBox->toJson()));
+            throw new ErrorException('料箱异常'.json_encode($stationTaskMaterialBoxes_orBox->toJson()));
         }
     }
 
     function getServingTaskType(StationTaskMaterialBox $stationTaskMaterialBox): string
     {
-        $stationTaskMaterialBox->loadMissing('station.stationType');
+        $stationTaskMaterialBox->load('station.stationType');
         if($isBatching=(
             $stationTaskMaterialBox['station_task_batch_id'] &&
-            $stationTaskMaterialBox['station']['stationType'] == '料箱监视器')
+            $stationTaskMaterialBox['station']['stationType']['name'] == '料箱监视器')
         ){
             return '分波次';
         }
@@ -169,9 +173,10 @@ class StationTaskMaterialBoxService
         ){
             return '入立库';
         }
-        if($isStoring=false){
-            return '入库';
-        }
+//        if($isStoring=false){
+//            return '入库';
+//        }
         throw new ErrorException('当前类型找不到');
+
     }
 }

+ 14 - 2
app/Services/StationTaskService.php

@@ -61,12 +61,24 @@ class StationTaskService
         $this->stationTaskChildService->insert($taskChildren_toInsert->toArray());
     }
 
-    function markProcessing_byId($stationTaskIds)
+    function markProcessing_byIds($ids)
     {
+        if(!$ids)$ids=[];
+        if(!is_array($ids))$ids=[$ids];
         StationTask::query()
-            ->whereIn('id',$stationTaskIds)
+            ->whereIn('id',$ids)
             ->update(['status'=>'处理中']);
     }
 
+    function markProcessing($stationTask_orCollection)
+    {
+        if (get_class($stationTask_orCollection)==StationTask::class){
+            $stationTask_orCollection = collect([$stationTask_orCollection]);
+        }
+        $this->markProcessing_byIds(
+                data_get($stationTask_orCollection, '*.station_id')
+            );
+    }
+
 
 }

+ 1 - 3
app/Services/StoreCheckingReceiveItemService.php

@@ -11,9 +11,7 @@ class StoreCheckingReceiveItemService
 {
     use ServiceAppAop;
     protected $modelClass=StoreCheckingReceiveItem::class;
-    public function insert(array $params){
-        return StoreCheckingReceiveItem::query()->insert($params);
-    }
+
 
     public function updateFind(StoreCheckingReceiveItem $item, array $values){
         $item->update($values);

+ 3 - 7
app/Services/StoreItemService.php

@@ -7,7 +7,7 @@ use App\Owner;
 use App\Services\common\BatchUpdateService;
 use App\Services\common\DataHandlerService;
 use App\Store;
-use App\StoreItems;
+use App\StoreItem;
 use App\Traits\ServiceAppAop;
 
 
@@ -15,10 +15,6 @@ class StoreItemService
 {
     use ServiceAppAop;
     protected $modelClass=StoreItem::class;
-    public function insert(array $params)
-    {
-        return StoreItems::query()->insert($params);
-    }
 
     public function storeItemCreateByWms($asnHerders)
     {
@@ -240,7 +236,7 @@ class StoreItemService
         if (!$asnDetails) {
             return null;
         }
-        return StoreItems::query()->with('store')->whereIn('store_id', function ($query) use ($asnDetails) {
+        return StoreItem::query()->with('store')->whereIn('store_id', function ($query) use ($asnDetails) {
             $query->from('stores')->select('id')->whereIn('asn_code', array_unique(data_get($asnDetails, '*.asnno')));
         })->get();
     }
@@ -252,7 +248,7 @@ class StoreItemService
             array_push($storeItemIds, $delete_storeItem->id);
         }
         try {
-            StoreItems::query()->whereIn('id', $storeItemIds)->delete();
+            StoreItem::query()->whereIn('id', $storeItemIds)->delete();
             LogService::log(__METHOD__, __FUNCTION__, '删除多余StoreItems ' . count($delete_storeItems) . json_encode($delete_storeItems), null);
         } catch (\Exception $e) {
             LogService::log(__METHOD__, __FUNCTION__, '删除多余StoreItems error' . count($delete_storeItems) . json_encode($delete_storeItems) . $e->getMessage() . $e->getTraceAsString(), null);

+ 1 - 1
app/Services/UnitService.php

@@ -18,7 +18,7 @@ class UnitService
         if (!is_array($column)) {
             $column = [$column];
         }
-        return Unit::query()->select($column)->get();
+        return Unit::query()->orderBy("sequence")->select($column)->get();
     }
 
 }

+ 20 - 0
app/Services/UserWorkgroupService.php

@@ -0,0 +1,20 @@
+<?php
+
+namespace App\Services;
+
+use App\Traits\ServiceAppAop;
+use App\UserWorkgroup;
+
+class UserWorkgroupService
+{
+    use ServiceAppAop;
+    protected $modelClass=UserWorkgroup::class;
+
+    public function getSelection($column = ['id','name']){
+        if (!is_array($column)) {
+            $column = [$column];
+        }
+        return UserWorkgroup::query()->select($column)->get();
+    }
+
+}

+ 56 - 12
app/Services/WaybillService.php

@@ -21,7 +21,7 @@ class WaybillService
      * @return Builder
      */
     private function conditionQuery(array $param){
-        $waybills = Waybill::filterAuthorities()->with(['owner','logistic','originationCity','destinationCity.province',
+        $waybills = Waybill::filterAuthorities()->with(['owner','logistic','originationCity','destinationCity.parent',
             'uploadFile','amountUnit','warehouseWeightUnit','carrierWeightUnit','district',
             'warehouseWeightUnitOther','carrierWeightUnitOther','carType','uploadFile','waybillAuditLogs.user'])
             ->selectRaw('waybills.* ,waybill_on_tops.id top_id ,waybill_on_tops.remark,waybill_on_tops.updated_at top_update')
@@ -29,21 +29,72 @@ class WaybillService
             ->whereNull('waybill_on_tops.deleted_at')
             ->orderBy('waybill_on_tops.updated_at','desc')
             ->orderBy('waybills.id','desc');
+        if ($param["owner_id"] ?? false){
+            $ownerIds = explode(",",$param["owner_id"]);
+            $waybills->where(function ($query)use($ownerIds){
+                /** @var Builder $query */
+                $query->whereIn("owner_id",$ownerIds)->orWhereHas("order",function ($query)use($ownerIds){
+                    /** @var Builder $query */
+                    $query->whereIn("owner_id",$ownerIds);
+                });
+            });
+            unset($param["owner_id"]);
+        }
+        if ($param["destination"] ?? false){
+            $destination = $param["destination"];
+            $waybills->where(function ($query)use($destination){
+                /** @var Builder $query */
+                $query->where("destination","like",$destination."%")->orWhereHas("order",function ($query)use($destination){
+                    /** @var Builder $query */
+                    $query->where("address",'like',$destination."%");
+                });
+            });
+            unset($param["destination"]);
+        }
+        if ($param["recipient"] ?? false){
+            $recipient = $param["recipient"];
+            $waybills->where(function ($query)use($recipient){
+                /** @var Builder $query */
+                $query->where("recipient","like",$recipient."%")->orWhereHas("order",function ($query)use($recipient){
+                    /** @var Builder $query */
+                    $query->where("consignee_name",'like',$recipient."%");
+                });
+            });
+            unset($param["recipient"]);
+        }
+        if ($param["recipient_mobile"] ?? false){
+            $recipientMobile = $param["recipient_mobile"];
+            $waybills->where(function ($query)use($recipientMobile){
+                /** @var Builder $query */
+                $query->where("recipient_mobile","like",$recipientMobile."%")->orWhereHas("order",function ($query)use($recipientMobile){
+                    /** @var Builder $query */
+                    $query->where("consignee_phone",'like',$recipientMobile."%");
+                });
+            });
+            unset($param["recipient_mobile"]);
+        }
+        if ($param["logistic_id"] ?? false){
+            $logisticId = $param["logistic_id"];
+            $waybills->where(function ($query)use($logisticId){
+                /** @var Builder $query */
+                $query->where("logistic_id",$logisticId)->orWhereHas("order",function ($query)use($logisticId){
+                    /** @var Builder $query */
+                    $query->where("logistic_id",$logisticId);
+                });
+            });
+            unset($param["logistic_id"]);
+        }
         $columnQueryRules=[
             'waybill_number' => ['like' => ''],
             'carrier_bill' => ['like' => ''],
-            'owner_id' => ['multi' => ','],
             'wms_bill_number' => ['like' => ''],
             'origination' => ['like' => ''],
-            'destination' => ['like' => ''],
             'source_bill' => ['like' => ''],
             'car_owner_info' => ['like' => ''],
             'created_at_start' => ['alias' => 'created_at' , 'startDate' => ':00'],
             'created_at_end' => ['alias' => 'created_at' , 'endDate' => ':59'],
             'uriType' => ['alias' => 'type'],
             'id' => ['multi' => ','],
-            'recipient' => ['timeLimit' => 15],
-            'recipient_mobile' => ['timeLimit' => 15],
         ];
         $waybills = app(QueryService::class)->query($param,$waybills,$columnQueryRules,"waybills");
         return $waybills;
@@ -83,13 +134,6 @@ class WaybillService
         return DB::transaction(function ()use($request){
             $waybill=new Waybill();
             $inputs = $request->all();
-            if ($inputs["wms_bill_number"]){
-                $order = app("OrderService")->first(["code"=>$inputs["wms_bill_number"]]);
-                if ($order){
-                    $inputs["destination_city_id"] = app("RegionService")->getCity($order->city,$order->province);
-                    $inputs["district_id"] = app("RegionService")->getDistrict($order->district,$order->city);
-                }
-            }
             $inputs['status']='未审核';
             $inputs['waybill_number']=Uuid::uuid1();
             $waybill->fill($inputs);

+ 2 - 2
app/Services/WeighExceptedService.php

@@ -26,7 +26,7 @@ class WeighExceptedService
     }
 
     public function getCreateExceptionSql(array $params){
-        return $this->conditionQuery($params)->where(TABLE.'status',"上传异常")->orWhere(TABLE.'status',"测量异常")
+        return $this->conditionQuery($params)->where(TABLE.'uploaded_to_wms',"异常")->orWhere(TABLE.'status',"测量异常")
             ->leftJoin('orders',TABLE.'order_id','orders.id')
             ->LeftJoin('logistics','orders.logistic_id','logistics.id')
                 ->selectRaw('logistics.name logistic_name')
@@ -39,7 +39,7 @@ class WeighExceptedService
 
     public function getIssuedExceptionSql(array $params){
         return $this->conditionQuery($params)->where(TABLE.'status',"下发异常")->orWhere(TABLE.'status',"记录异常")
-            ->orWhere(TABLE.'status',"已上传异常")
+            ->orWhere(TABLE.'uploaded_to_wms',"异常")
             ->leftJoin('orders',TABLE.'order_id','orders.id')
             ->LeftJoin('logistics','orders.logistic_id','logistics.id')
                 ->selectRaw('logistics.name logistic_name')

+ 22 - 0
app/StationTaskBatch.php

@@ -4,6 +4,8 @@ namespace App;
 
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
+use Illuminate\Database\Eloquent\Relations\HasMany;
+use Illuminate\Database\Eloquent\Relations\HasManyThrough;
 use Illuminate\Database\Eloquent\Relations\HasOne;
 use Illuminate\Database\Eloquent\Relations\MorphOne;
 
@@ -28,4 +30,24 @@ class StationTaskBatch extends Model
     {   //波次
         return $this->belongsTo(Batch::class);
     }
+    function stationTaskCommodities(): HasMany
+    {
+        return $this->hasMany(StationTaskCommodity::class);
+    }
+    function stationTaskMaterialBoxes(): HasMany
+    {
+        return $this->hasMany(StationTaskMaterialBox::class);
+    }
+    function materialBoxes(): HasManyThrough
+    {
+        return $this->hasManyThrough(
+            MaterialBox::class,
+            StationTaskMaterialBox::class,
+            'station_task_batch_id',
+            'id',
+            'id',
+            'material_box_id',
+        );
+    }
+
 }

+ 5 - 5
app/StationTaskMaterialBox.php

@@ -4,8 +4,8 @@ namespace App;
 
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
+use Illuminate\Database\Eloquent\Relations\HasMany;
 use Illuminate\Database\Eloquent\Relations\HasOne;
-use Illuminate\Database\Eloquent\Relations\MorphOne;
 
 use App\Traits\ModelLogChanging;
 
@@ -21,7 +21,7 @@ class StationTaskMaterialBox extends Model
     }
     function station(): BelongsTo
     {
-        return $this->belongsTo(Station::class,"id","station_id");
+        return $this->belongsTo(Station::class);
     }
     function stationTaskBatch(): BelongsTo
     {
@@ -31,9 +31,9 @@ class StationTaskMaterialBox extends Model
     {
         return $this->belongsTo(StationTask::class);
     }
-    function stationTaskCommodities(): HasOne
+    function stationTaskCommodities(): HasMany
     {
-        return $this->hasOne(StationTaskCommodity::class,"station_task_batch_id","station_task_batch_id")
-        ->where('material_box_id',$this['material_box_id']);
+        return $this->hasMany(StationTaskCommodity::class,'station_task_batch_id','station_task_batch_id')
+            ->where('material_box_id',$this['material_box_id']);
     }
 }

+ 1 - 1
app/Store.php

@@ -31,7 +31,7 @@ class Store extends Model
         return $this->belongsTo('App\Warehouse','warehouse_id','id');
     }
     public function storeItems(){
-        return $this->hasMany('App\StoreItems','store_id','id');
+        return $this->hasMany('App\StoreItem','store_id','id');
 }
 
 //    public function getOwnerNameAttribute()

+ 1 - 1
app/StoreItems.php → app/StoreItem.php

@@ -7,7 +7,7 @@ use App\Traits\ModelTimeFormat;
 
 use App\Traits\ModelLogChanging;
 
-class StoreItems extends Model
+class StoreItem extends Model
 {
     use ModelLogChanging;
 

+ 40 - 6
app/Traits/ServiceAppAop.php

@@ -4,6 +4,7 @@
 namespace App\Traits;
 
 
+use App\Services\LogService;
 use Illuminate\Contracts\Foundation\Application;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Cache;
@@ -16,19 +17,19 @@ trait ServiceAppAop
      * 实例化一个service的入口,为了测试方便做出来的,这样测试时可以代入假的柱件替换service的实现
      * 应当在一般性用app的地方换成本方法才可以做到使用柱件
      * @param $targetService
-     * @param $abstract
+     * @param $abstractClassName
      * @return Application|mixed|string
      */
-    public function instant(&$targetService, $abstract){
+    public function instant(&$targetService, $abstractClassName){
         if(!is_string($targetService)){
             if(empty($targetService))
-                $targetService=app($abstract);
+                $targetService=app($abstractClassName);
             return $targetService;
         }
-        if(!is_string($abstract)){
-            $this->$targetService=$abstract;
+        if(!is_string($abstractClassName)){
+            $this->$targetService=$abstractClassName;
         }else{
-            $this->$targetService=app($abstract);
+            $this->$targetService=app($abstractClassName);
         }
         return $targetService;
     }
@@ -73,4 +74,37 @@ trait ServiceAppAop
         $this->clearCache($kvPairs);
         return $this->create($kvPairs);
     }
+
+    /**
+     * $returnInserted 设为true返回插入的内容,是通过插入的字段返查的,所以可能会不准(看字段是否能匹配)
+     * @param array $targetsArrays
+     * @param bool $returnInserted 设为true返回插入的内容
+     * @param bool $createdAtOn
+     * @param bool $updatedAtOn
+     * @return Collection|null
+     */
+    function insert(array $targetsArrays, $returnInserted=false, $createdAtOn=true,$updatedAtOn=true): ?Collection
+    {
+        if($createdAtOn||$updatedAtOn)$now = now();
+        foreach ($targetsArrays as &$target){
+            if($createdAtOn)$target['created_at']= $now;
+            if($updatedAtOn)$target['updated_at']= $now;
+        }
+        ($this->modelClass)::query()->insert($targetsArrays);
+        LogService::log(__METHOD__, __FUNCTION__, json_encode($targetsArrays) .
+            '||' . json_encode(array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 0, 4)));
+        if(!$returnInserted)return null;
+
+        return ($查回插入内容,不保证准=function ()use($targetsArrays,$createdAtOn,$updatedAtOn){
+            $query=($this->modelClass)::query();
+            foreach ($targetsArrays as &$target){
+                $query->orWhere(function($subQuery)use($target){
+                    foreach ($target as $key=>$val){
+                        $subQuery->where($key, $val);
+                    }
+                });
+            }
+            return $query->get();
+        })();
+    }
 }

+ 47 - 20
app/Traits/TestMockSubServices.php

@@ -1,7 +1,28 @@
 <?php
 namespace App\Traits;
 
+use App\MaterialBox;
+use App\Services\MaterialBoxService;
+use App\Services\StationTaskCommodityService;
+
 trait TestMockSubServices{
+    /**
+     * 例子:
+     *  $this->service=$this->subMock([
+     *   'class'=>StationTaskCommodityService::class,
+     *   'subServices'=>[
+     *  [
+     *   'serviceName'=>'materialBoxService',
+     *   'class'=>MaterialBoxService::class,
+     *   'methods'=>[
+     *   'firstOrCreate'=>new MaterialBox(['id'=>1]),
+     *  ],
+     *  ],
+     *  ]
+     * ]);
+     * @param array $serviceDefinition
+     * @return \PHPUnit\Framework\MockObject\MockObject
+     */
     function subMock(array $serviceDefinition){
         $mockingService=$this->createPartialMock(
             $serviceDefinition['class'],
@@ -12,37 +33,43 @@ trait TestMockSubServices{
             foreach ($serviceDefinition['methods'] as $mName=>$mVal){
                 $mockingService->method($mName)->willReturn($mVal);
             }
-
         if(isset($serviceDefinition['subServices']))
-            foreach ($serviceDefinition['subServices'] as $subService){
-                $mockingService->instant(
-                    $subService['serviceName'],
-                    ($subServiceMock=function()use($subService){
-                        $subServiceMock=$this->createPartialMock(
-                            $subService['class'],
-                            array_keys($subService['methods'])
-                        );
-                        if(isset($subService['methods']))
-                            foreach ($subService['methods'] as $methodName=>$methodVal){
-                                $subServiceMock->method($methodName)->willReturn($methodVal);
-                            }
-                        return $subServiceMock;
-                    })()
-                );
-            }
+            $this->registerSubServices($mockingService,$serviceDefinition['subServices']);
         return $mockingService;
     }
 
-    function getTargetIdCirculately($targetArr, $additionMark='', $idName='id'){
+    private function registerSubServices($rootService, $subServices){
+        foreach ($subServices as $subService){
+            $rootService->instant(
+                $subService['serviceName'],
+                ($subServiceMock=function()use($subService){
+                    $subServiceMock=$this->createPartialMock(
+                        $subService['class'],
+                        array_keys($subService['methods'])
+                    );
+                    if(isset($subService['methods']))
+                        foreach ($subService['methods'] as $methodName=>$methodVal){
+                            $subServiceMock->method($methodName)->willReturn($methodVal);
+                        }
+                    if(isset($subService['subServices'])){
+                        $this->registerSubServices($subServiceMock,$subService['subServices']);
+                    }
+                    return $subServiceMock;
+                })()
+            );
+        }
+    }
+
+    function getTargetFieldCirculately($targetArr, $className='', $idName='id'){
         $amount = count($targetArr);
 
         $json_encode = json_encode($targetArr);
-        $iName = 'i_' . md5($json_encode . $additionMark);
+        $iName = 'i_' . md5($json_encode . $className);
         if(!isset($this->data[$iName])){
             $this->data[$iName]=$amount;
         }
         $this->data[$iName]++;
-        if($this->data[$iName]>=$this->batchAmount)
+        if($this->data[$iName]>=$amount)
             $this->data[$iName]=0;
         return $targetArr[$this->data[$iName]][$idName];
     }

+ 1 - 1
app/Unit.php

@@ -13,6 +13,6 @@ class Unit extends Model
 
     use ModelTimeFormat;
     protected $fillable=[
-        'name'
+        'name',"sequence"
     ];
 }

+ 71 - 14
app/Waybill.php

@@ -18,11 +18,47 @@ class Waybill extends Model
     use ModelTimeFormat;
     use SoftDeletes;
     protected $fillable=[
-        'status','type','waybill_number','owner_id','wms_bill_number','origination','destination','recipient','recipient_mobile','charge','ordering_remark',
-        'logistic_id','carrier_bill','origination_city_id','destination_city_id','warehouse_weight','warehouse_weight_unit_id','carrier_weight','carrier_weight_unit_id','carType_id',
-        'car_owner_info','fee','pick_up_fee','other_fee','collect_fee','dispatch_remark','waybill_price_model_id','warehouse_weight_other','warehouse_weight_unit_id_other'
-        ,'carrier_weight_other','carrier_weight_unit_id_other','source_bill','mileage','amount','inquire_tel','amount_unit_id','other_charge','other_charge_remark','deliver_at',
-        "district_id"
+        'status',
+        'type',
+        'waybill_number',
+        'owner_id',
+        'wms_bill_number',
+        'origination',
+        'destination',
+        'recipient',
+        'recipient_mobile',
+        'charge',
+        'ordering_remark',
+        'logistic_id',
+        'carrier_bill',
+        'origination_city_id',
+        'destination_city_id',
+        'warehouse_weight',
+        'warehouse_weight_unit_id',
+        'carrier_weight',
+        'carrier_weight_unit_id',
+        'carType_id',
+        'car_owner_info',
+        'fee',
+        'pick_up_fee',
+        'other_fee',
+        'collect_fee',
+        'dispatch_remark',
+        'waybill_price_model_id',
+        'warehouse_weight_other',
+        'warehouse_weight_unit_id_other',
+        'carrier_weight_other',
+        'carrier_weight_unit_id_other',
+        'source_bill',
+        'mileage',
+        'amount',
+        'inquire_tel',
+        'amount_unit_id',
+        'other_charge',
+        'other_charge_remark',
+        'deliver_at',
+        "district_id",
+        "order_id"
     ];
 
     public function district()
@@ -35,11 +71,13 @@ class Waybill extends Model
     public function logistic(){
         return $this->hasOne('App\Logistic','id','logistic_id');
     }
-    public function originationCity(){
-        return $this->hasOne('App\City','id','origination_city_id');
+    public function originationCity()
+    {   //始发市
+        return $this->hasOne(Region::class,'id','origination_city_id');
     }
-    public function destinationCity(){
-        return $this->hasOne('App\City','id','destination_city_id');
+    public function destinationCity()
+    {   //目的市
+        return $this->hasOne(Region::class,'id','destination_city_id');
     }
     public function wmsCommodities(){
         return $this->hasMany('App\WMSWaybillOrder','OrderNo','wms_bill_number');
@@ -71,9 +109,11 @@ class Waybill extends Model
     public function uploadFile(){
         return $this->hasOne('App\UploadFile','table_id','id')->where('table_name','waybills');
     }
-//    public function getOrderingRemarkAttribute($val){
-//        return
-//    }
+    public function order()
+    {   //订单
+        return $this->belongsTo(Order::class);
+    }
+
 
 
     static public function setWeightByOrderCode($orderCode,$weight){
@@ -92,8 +132,25 @@ class Waybill extends Model
      * @return Builder
      */
     public static function filterAuthorities(){
-        $owner_ids=app('UserService')->getPermittingOwnerIds(auth()->user());
-        return (new static)->newQuery()->whereIn('owner_id',$owner_ids);
+        $ids=app('UserService')->getPermittingOwnerIds(auth()->user());
+        return (new static)->newQuery()->leftJoin("orders","waybills.wms_bill_number","orders.code")
+            ->leftJoin("owners","orders.owner_id","owners.id")
+            ->leftJoin("logistics","orders.logistic_id","logistics.id")
+            ->selectRaw(<<<column
+            owners.name as owner_name,
+            logistics.name as logistic_name,
+            orders.consignee_name as order_consignee_name,
+            orders.consignee_phone as order_consignee_phone,
+            orders.province as order_province,
+            orders.city as order_city,
+            orders.district as order_district,
+            orders.address as order_address
+column
+)
+            ->where(function ($query)use($ids){
+            /** @var Builder  $query */
+            $query->whereIn('waybills.owner_id',$ids)->orWhereIn("orders.owner_id",$ids);
+        });
     }
 
 

+ 6 - 4
app/WaybillPriceModel.php

@@ -28,12 +28,14 @@ class WaybillPriceModel extends Model
         return $this->belongsTo('App\Logistic','logistic_id','id');
     }
 
-    public  function province(){
-        return $this->belongsTo('App\Province','province_id','id');
+    public  function province()
+    {   //省份
+        return $this->belongsTo(Region::class,'province_id','id');
     }
 
-    public  function city(){
-        return $this->belongsTo('App\City','city_id','id');
+    public  function city()
+    {   //城市
+        return $this->belongsTo(Region::class,'city_id','id');
     }
 
     public function unit(){

+ 3 - 3
composer.json

@@ -8,8 +8,7 @@
     ],
     "license": "MIT",
     "require": {
-        "php": "^7.1.3",
-        "ext-bcmath": "*",
+        "php": "^7.2.34",
         "ext-json": "*",
         "ext-mbstring": "*",
         "ext-openssl": "*",
@@ -30,7 +29,8 @@
         "pusher/pusher-php-server": "^4.1",
         "te7a-houdini/laravel-trix": "^2.0",
         "tymon/jwt-auth": "1.*@rc",
-        "yajra/laravel-oci8": "7.0"
+        "yajra/laravel-oci8": "7.0",
+        "ext-bcmath": "*"
     },
     "require-dev": {
         "barryvdh/laravel-debugbar": "^3.2",

+ 4 - 1
config/logging.php

@@ -5,8 +5,11 @@ use Monolog\Handler\SyslogUdpHandler;
 
 return [
 
+    'passing_methods'=>[  //跳过日志的方法
+        'finishSave',
+    ],
 
-    'expire_duration'=>'150', //天数,日志超过时长的就在服务中删除
+    'expire_duration'=>'60', //天数,日志超过时长的就在服务中删除
     /*
     |--------------------------------------------------------------------------
     | Default Log Channel

+ 1 - 1
database/factories/FeatureFactory.php

@@ -6,7 +6,7 @@ use App\Feature;
 use Faker\Generator as Faker;
 
 $factory->define(Feature::class, function (Faker $faker) {
-    $type = ['商品名称','订单类型','承运商','店铺类型'];
+    $type = [0,1,2,3,4,5];
     $logic = ['包含','不包含','等于'];
     return [
         "type" => $type[array_rand($type)],     //类型

+ 1 - 4
database/factories/StationTaskBatchFactory.php

@@ -8,9 +8,6 @@ use Faker\Generator as Faker;
 $factory->define(StationTaskBatch::class, function (Faker $faker) {
     $status = ['待处理','挂起','处理中','完成','异常','取消'];
     return [
-        'batch_id' => factory(\App\Batch::class),
-        'station_id' => factory(\App\Station::class),
-        'station_task_batch_type_id' => factory(\App\StationTaskBatchType::class),
-        "status"=>$status[array_rand($status)],
+        "status"=>'待处理',
     ];
 });

+ 1 - 1
database/factories/StationTaskCommodityFactory.php

@@ -14,6 +14,6 @@ $factory->define(StationTaskCommodity::class, function (Faker $faker) {
         'amount'=>rand(1,1000),
         "bin_number"=>rand(1,24),
         'order_id'=>factory(\App\Order::class),
-        "status"=>$status[array_rand($status)],
+        "status"=>'待处理',
     ];
 });

+ 0 - 0
database/migrations/2021_01_08_112003_add_default_mail_event_role.php


+ 32 - 0
database/migrations/2021_01_28_094833_edit_order_packages_status_add_uploaded_to_wms_enum.php

@@ -0,0 +1,32 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class EditOrderPackagesStatusAddUploadedToWmsEnum extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('order_packages', function (Blueprint $table) {
+            $table->enum('uploaded_to_wms', ['是', '否', '异常'])->default('否')->index();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('order_packages', function (Blueprint $table) {
+            $table->dropColumn('uploaded_to_wms');
+        });
+    }
+}

+ 2 - 5
database/migrations/2021_01_29_161734_add_units_data.php

@@ -7,7 +7,7 @@ use Illuminate\Support\Facades\Schema;
 class AddUnitsData extends Migration
 {
     protected $units = [
-        "件","箱",'单',"日","月","m²","m³"
+        "件","箱",'单',"日","月","m²","m³","件","托"
     ];
     /**
      * Run the migrations.
@@ -17,10 +17,7 @@ class AddUnitsData extends Migration
     public function up()
     {
         foreach ($this->units as $unit){
-            \App\Unit::query()->firstOrCreate(["name"=>$unit],[
-               "name" => $unit,
-               "code" => $unit
-            ]);
+            \App\Unit::query()->firstOrCreate(["name"=>$unit]);
         }
     }
 

+ 48 - 0
database/migrations/2021_02_04_112223_create_owner_fee_detail_logistics_table.php

@@ -0,0 +1,48 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class CreateOwnerFeeDetailLogisticsTable extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::create('owner_fee_detail_logistics', function (Blueprint $table) {
+            $table->id();
+            $table->bigInteger("owner_fee_detail_id")->index()->comment("外键即时账单");
+            $table->integer("amount")->comment("商品数量");
+            $table->string('logistic_bill')->nullable()->comment('快递单号');
+            $table->decimal('volume',8,3)->nullable()->comment('体积');
+            $table->decimal('weight',8,3)->nullable()->comment('重量');
+            $table->decimal('logistic_fee',8,4)->nullable()->comment('物流费');
+        });
+        Schema::table("features",function(Blueprint $table){
+            $table->dropColumn("type");
+        });
+        Schema::table("features",function(Blueprint $table){
+            $table->tinyInteger("type")->default(0)->index()->comment("特征类型");
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table("features",function(Blueprint $table){
+            $table->dropColumn("type");
+        });
+        Schema::table("features",function(Blueprint $table){
+            $table->enum("type",["商品名称","订单类型","承运商","店铺类型"])->index()->comment("特征类型");
+        });
+        Schema::dropIfExists('owner_fee_detail_logistics');
+    }
+}

+ 41 - 0
database/migrations/2021_02_18_105955_change_owner_operation_table.php

@@ -0,0 +1,41 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class ChangeOwnerOperationTable extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('owner_price_operations', function (Blueprint $table) {
+            $table->string("discount_count")->nullable()->comment("减免数")->change();
+            $table->string("total_discount_price")->nullable()->comment("减免总价")->change();
+        });
+        Schema::table('owner_price_operation_items', function (Blueprint $table) {
+            $table->string("discount_price")->nullable()->comment("减免单价")->change();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('owner_price_operations', function (Blueprint $table) {
+            $table->integer("discount_count")->nullable()->comment("减免数")->change();
+            $table->decimal("total_discount_price")->nullable()->comment("减免总价")->change();
+        });
+        Schema::table('owner_price_operation_items', function (Blueprint $table) {
+            $table->integer("discount_price")->nullable()->comment("减免单价")->change();
+        });
+    }
+}
+

+ 40 - 0
database/migrations/2021_02_19_110139_change_owner_operation_owner_table.php

@@ -0,0 +1,40 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class ChangeOwnerOperationOwnerTable extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('owner_price_operation_owner', function (Blueprint $table) {
+            $table->date("discount_date")->nullable()->comment("满减标记日");
+            $table->integer("target_value")->nullable()->comment("目标值");
+        });
+        Schema::table('owner_price_operations', function (Blueprint $table) {
+            $table->dropColumn("discount_date");
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('owner_price_operation_owner', function (Blueprint $table) {
+            $table->dropColumn("discount_date");
+            $table->dropColumn("discount_date");
+        });
+        Schema::table('owner_price_operations', function (Blueprint $table) {
+            $table->date("discount_date")->nullable()->comment("满减标记日");
+        });
+    }
+}

+ 32 - 0
database/migrations/2021_02_19_155516_change_owners_table_add_column_user_workgroup_id.php

@@ -0,0 +1,32 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class ChangeOwnersTableAddColumnUserWorkgroupId extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('owners', function (Blueprint $table) {
+            $table->bigInteger("user_workgroup_id")->nullable()->index()->comment("仓库小组");
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('owners', function (Blueprint $table) {
+            $table->dropColumn("user_workgroup_id");
+        });
+    }
+}

+ 32 - 0
database/migrations/2021_02_20_162232_change_units_table_add_sequence_column.php

@@ -0,0 +1,32 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class ChangeUnitsTableAddSequenceColumn extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('units', function (Blueprint $table) {
+            $table->integer("sequence")->default(0)->comment("排序");
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('units', function (Blueprint $table) {
+            $table->dropColumn("sequence");
+        });
+    }
+}

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