瀏覽代碼

Merge branch 'master' into zzd

# Conflicts:
#	app/Console/Kernel.php
dream 4 年之前
父節點
當前提交
40cdab7767
共有 100 個文件被更改,包括 3201 次插入1733 次删除
  1. 2 0
      .gitignore
  2. 8 7
      .gitlab-ci.yml
  3. 0 1
      app/Authority.php
  4. 60 0
      app/Console/Commands/OrderCountingRecordTask.php
  5. 1 0
      app/Console/Commands/SyncOrderPackageLogisticRouteTask.php
  6. 1 0
      app/Console/Kernel.php
  7. 2 0
      app/Events/BroadcastToStation.php
  8. 45 0
      app/Filters/OrderPackageReceivedSyncRecordFilters.php
  9. 46 0
      app/Filters/OwnerSundryFeeDetailFilters.php
  10. 11 10
      app/Http/Controllers/CacheShelfController.php
  11. 33 3
      app/Http/Controllers/ControlPanelController.php
  12. 50 12
      app/Http/Controllers/DischargeTaskController.php
  13. 5 17
      app/Http/Controllers/LaborCompanyController.php
  14. 10 1
      app/Http/Controllers/LaborReportController.php
  15. 2 2
      app/Http/Controllers/OrderController.php
  16. 85 0
      app/Http/Controllers/OwnerLogisticFeeDetailController.php
  17. 85 0
      app/Http/Controllers/OwnerLogisticFeeReportController.php
  18. 82 0
      app/Http/Controllers/OwnerSundryFeeDetailsController.php
  19. 3 3
      app/Http/Controllers/ProcurementController.php
  20. 2 0
      app/Http/Controllers/RejectedController.php
  21. 23 18
      app/Http/Controllers/RoleController.php
  22. 6 3
      app/Http/Controllers/TestController.php
  23. 3 2
      app/Http/Controllers/WaybillController.php
  24. 21 254
      app/Http/Controllers/api/thirdPart/goodscan/PackageController.php
  25. 1 1
      app/Http/Controllers/api/thirdPart/haiq/LightController.php
  26. 24 21
      app/Http/Controllers/api/thirdPart/hengli/PackageController.php
  27. 37 315
      app/Http/Controllers/api/thirdPart/weight/PackageController.php
  28. 10 0
      app/Http/Requests/DischargeTask/DischargeTaskRequest.php
  29. 41 0
      app/Http/Requests/OwnerSundryFeeDetailRequest.php
  30. 14 0
      app/Http/Requests/Request.php
  31. 83 0
      app/Imports/DischargeTaskImport.php
  32. 58 0
      app/Jobs/LogisticAliJiSuSync.php
  33. 5 2
      app/Jobs/LogisticSFSync.php
  34. 10 5
      app/Jobs/LogisticYDSync.php
  35. 11 5
      app/Jobs/LogisticYTOSync.php
  36. 23 151
      app/Jobs/LogisticZopSync.php
  37. 9 1
      app/Listeners/AddOrUpdateOrderIssuesListener.php
  38. 1 1
      app/Logistic.php
  39. 21 0
      app/Observers/OwnerSundryFeeDetailObserver.php
  40. 14 1
      app/OrderCountingRecord.php
  41. 22 0
      app/OrderPackageReceivedSyncRecord.php
  42. 6 0
      app/Owner.php
  43. 12 0
      app/OwnerFeeDetail.php
  44. 6 0
      app/OwnerFeeDetailLogistic.php
  45. 26 0
      app/OwnerLogisticFeeDetail.php
  46. 14 0
      app/OwnerLogisticFeeReport.php
  47. 70 0
      app/OwnerSundryFeeDetail.php
  48. 20 0
      app/Policies/OwnerSundryFeeDetailPolicy.php
  49. 22 0
      app/Policies/Policy.php
  50. 174 87
      app/Providers/AppServiceProvider.php
  51. 1 0
      app/Providers/AuthServiceProvider.php
  52. 3 0
      app/Role.php
  53. 27 17
      app/Services/BatchService.php
  54. 82 140
      app/Services/CacheShelfService.php
  55. 2 2
      app/Services/DischargeTaskService.php
  56. 15 27
      app/Services/ForeignHaiRoboticsService.php
  57. 3 2
      app/Services/LaborReportService.php
  58. 11 9
      app/Services/LaborReportsCountingRecordService.php
  59. 126 0
      app/Services/LogisticAliJiSuApiService.php
  60. 12 0
      app/Services/LogisticRouteInterface.php
  61. 19 6
      app/Services/LogisticYDService.php
  62. 8 2
      app/Services/LogisticYTOService.php
  63. 90 78
      app/Services/LogisticZopService.php
  64. 242 18
      app/Services/NewOrderCountingRecordService.php
  65. 33 0
      app/Services/OrderPackageReceivedSyncRecordService.php
  66. 38 9
      app/Services/OrderPackageReceivedSyncService.php
  67. 46 25
      app/Services/OrderService.php
  68. 95 0
      app/Services/OwnerLogisticFeeDetailService.php
  69. 13 0
      app/Services/OwnerLogisticFeeReportService.php
  70. 7 1
      app/Services/StationService.php
  71. 1 2
      app/Services/StationTaskMaterialBoxService.php
  72. 4 3
      app/Services/WaybillService.php
  73. 42 0
      app/Services/weight/GoodScanWeightService.php
  74. 49 0
      app/Services/weight/HaoChuangWeightService.php
  75. 45 0
      app/Services/weight/HengLiWeightService.php
  76. 503 0
      app/Services/weight/WeightService.php
  77. 5 0
      app/Station.php
  78. 19 2
      app/User.php
  79. 10 1
      app/Utils/helpers.php
  80. 0 23
      app/library/zop/README.md
  81. 0 60
      app/library/zop/ZopClient.php
  82. 0 20
      app/library/zop/ZopHttpUtil.php
  83. 0 46
      app/library/zop/ZopProperties.php
  84. 0 59
      app/library/zop/ZopRequest.php
  85. 1 5
      composer.json
  86. 158 239
      composer.lock
  87. 13 0
      config/api_logistic.php
  88. 2 2
      config/cache.php
  89. 0 1
      database/factories/OrderCountingRecordFactory.php
  90. 16 0
      database/factories/OrderPackageReceivedSyncRecordFactory.php
  91. 17 0
      database/factories/OwnerLogisticFeeDetailFactory.php
  92. 12 0
      database/factories/OwnerLogisticFeeReportFactory.php
  93. 11 0
      database/factories/OwnerSundryFeeDetailFactory.php
  94. 1 0
      database/factories/StationTaskFactory.php
  95. 6 1
      database/factories/StationTaskMaterialBoxFactory.php
  96. 15 0
      database/factories/StorageFactory.php
  97. 4 3
      database/migrations/2020_11_30_140957_create_station_types_table.php
  98. 8 7
      database/migrations/2021_05_21_131520_add_order_packages_logistic_number_unique.php
  99. 27 0
      database/migrations/2021_05_27_103720_create_ownersundryfeedetails_table.php
  100. 39 0
      database/migrations/2021_05_27_105155_add_authority_settlement_bills.php

+ 2 - 0
.gitignore

@@ -29,4 +29,6 @@ yarn-error.log
 /public/phpMyAdmin4.8.5/
 /public/fonts
 /phpunit.xml
+/serves/excelExportGo/logs
+/serves/excelExportGo/go_build_main_go.exe
 /laravel-echo-server.lock

+ 8 - 7
.gitlab-ci.yml

@@ -8,6 +8,7 @@ cache:
     - vendor/
 
 before_script:
+#配置环境
 #  - sudo cp ci/.envCi .env
 #  - sudo bash ci/installEnv.sh
 
@@ -25,8 +26,8 @@ test:
     - testwas
   script:
     - echo "run test....."
-#    - path=`pwd`
-#    - sudo bash ci/judgePush.sh $path
+    - path=`pwd`
+    - sudo bash ci/judgePush.sh $path
 #    - vendor/bin/phpunit --testsuite=Unit
 
 deploy:
@@ -35,8 +36,8 @@ deploy:
     - testwas
   script:
     - echo "deploy ...."
-#    - cd /var/www/bswas_test && sudo git config --global credential.helper store
-#    - sudo git pull
-#    - sudo bash ci/executeCommand.sh
-#  only:
-#    - master
+    - cd /var/www/bswas_test && sudo git config --global credential.helper store
+    - sudo git pull
+    - sudo bash ci/executeCommand.sh
+  only:
+    - master

+ 0 - 1
app/Authority.php

@@ -34,7 +34,6 @@ class Authority extends Model
         return '';
     }
 
-
     public  static  function  filterRecycle(Collection $authorities)
     {
         $owners = Owner::query()->whereNotNull("deleted_at")->get();

+ 60 - 0
app/Console/Commands/OrderCountingRecordTask.php

@@ -0,0 +1,60 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Services\LogService;
+use App\Services\NewOrderCountingRecordService;
+use Illuminate\Console\Command;
+
+class OrderCountingRecordTask extends Command
+{
+    /**
+     * @var NewOrderCountingRecordService $service
+     */
+    public $service;
+    /**
+     * The name and signature of the console command.
+     *
+     * @var string
+     */
+    protected $signature = 'orderCountingRecordTask';
+
+    /**
+     * The console command description.
+     *
+     * @var string
+     */
+    protected $description = 'Command description';
+
+    /**
+     * Create a new command instance.
+     *
+     * @return void
+     */
+    public function __construct()
+    {
+        parent::__construct();
+    }
+
+    /**
+     * Execute the console command.
+     *
+     * @throws \Exception
+     */
+    public function handle()
+    {
+        LogService::log(OrderCountingRecordTask::class, "订单量统计", '');
+        ini_set('memory_limit', '2226M');
+        $this->service = app('NewOrderCountingRecordService');
+        if (now()->toDateString() == now()->startOfMonth()->toDateString()) {//是否为月初
+            //统计上月的数据
+            $this->service->recordOrder(now()->subMonth()->startOfMonth()->toDateString(), now()->subMonth()->endOfMonth()->toDateString(), '月');
+        }
+        if (now()->toDateString() == now()->startOfYear()->toDateString()) {//是否为年初
+            //统计上年的数据
+            $this->service->recordOrder(now()->subYear()->startofYear()->toDateString(), now()->subYear()->endOfYear()->toDateString(), '年');
+        }
+        //统计前一天的数据
+        $this->service->recordOrder(now()->subDay()->toDateString(), now()->subDay()->toDateString(), '日');
+    }
+}

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

@@ -46,6 +46,7 @@ class SyncOrderPackageLogisticRouteTask extends Command
         LogService::log(SyncOrderPackageLogisticRouteTask::class, "同步快递信息定时任务启动", '');
         ini_set('memory_limit', '2226M');
         $this->service = app('OrderPackageReceivedSyncService');
+        $this->service->syncLogisticRouteByAliJiSu();
         $this->service->syncLogisticRoute();
     }
 }

+ 1 - 0
app/Console/Kernel.php

@@ -80,6 +80,7 @@ class  Kernel extends ConsoleKernel
         $schedule->command('create:weightStatistic')->dailyAt("00:30");
         $schedule->command('sync:carrier')->hourlyAt(1);
         $schedule->command('createProcurementTotalBill')->monthlyOn(1);
+        $schedule->command('orderCountingRecordTask')->dailyAt("1:00");
         //$schedule->command('check:cacheRack')->everyMinute();
     }
 

+ 2 - 0
app/Events/BroadcastToStation.php

@@ -19,6 +19,7 @@ class BroadcastToStation implements ShouldBroadcastNow
      */
     public function __construct(int $id, string $json)
     {
+        app('LogService')->log('海柔','broadcast1',$id.$json);
         $this->id = $id;// 0意味着通用站,所有站都需要收发的意思
         $this->json = $json;
     }
@@ -30,6 +31,7 @@ class BroadcastToStation implements ShouldBroadcastNow
      */
     public function broadcastOn()
     {
+        app('LogService')->log('海柔','broadcast2',$this->id.$this->json);
         return new Channel('station-'.$this->id);
     }
 }

+ 45 - 0
app/Filters/OrderPackageReceivedSyncRecordFilters.php

@@ -0,0 +1,45 @@
+<?php
+
+
+namespace App\Filters;
+
+
+use Illuminate\Http\Request;
+use Illuminate\Database\Query\Builder;
+
+class OrderPackageReceivedSyncRecordFilters
+{
+    protected $request;
+    /**
+     * @var $queryBuilder Builder
+     */
+    protected $queryBuilder;
+    protected $filters = ['start', 'end', 'logistic_name'];
+
+    public function __construct(Request $request)
+    {
+        $this->request = $request;
+    }
+
+    public function apply($builder)
+    {
+        $this->queryBuilder = $builder;
+        $filters = array_filter($this->request->only($this->filters));
+        foreach ($filters as $filter => $value) {
+            if (method_exists($this, $filter)) {
+                $this->$filter($value, $this->queryBuilder);
+            }
+        }
+        return $this->queryBuilder;
+    }
+
+    public function start($start)
+    {
+        $this->queryBuilder->whereDate('recorded_at', '>=', $start);
+    }
+
+    public function end($end)
+    {
+        $this->queryBuilder->whereDate('recorded_at', '<=', $end);
+    }
+}

+ 46 - 0
app/Filters/OwnerSundryFeeDetailFilters.php

@@ -0,0 +1,46 @@
+<?php
+
+
+namespace App\Filters;
+
+use App\Order;
+use App\Services\UserService;
+use Illuminate\Http\Request;
+use Illuminate\Support\Carbon;
+use Illuminate\Support\Str;
+use phpDocumentor\Reflection\Types\Boolean;
+
+class OwnerSundryFeeDetailFilters
+{
+    protected $request;
+    protected $queryBuilder;
+    protected $filters = ['owner_id'];
+
+    public function __construct(Request $request)
+    {
+        $this->request = $request;
+    }
+
+    public function apply($builder)
+    {
+        $this->queryBuilder = $builder;
+        $filters = array_filter($this->request->only($this->filters));
+        foreach ($filters as $filter => $value) {
+            if (method_exists($this, $filter)) {
+                $this->$filter($value, $this->queryBuilder);
+            }
+        }
+        return $this->queryBuilder;
+    }
+
+
+    private function owner_id($owner_id)
+    {
+        if (strpos($owner_id, ',') || strpos($owner_id, ',') || strpos($owner_id, ' ')) {
+            $arr = array_filter(preg_split('/[,, ]+/is', $owner_id));
+            $this->queryBuilder->whereIn('owner_id',$arr);
+        } else {
+            $this->queryBuilder->where('owner_id','like',$owner_id."%");
+        }
+    }
+}

+ 11 - 10
app/Http/Controllers/CacheShelfController.php

@@ -30,16 +30,15 @@ class CacheShelfController extends Controller
     }
 
     /**
-     * 获取缓存货架上的任务列表
+     * 获取缓存货架上的料箱
      * @param Request $request
      * @param string $id
      * @param CacheShelfService $service
      */
-    public function getTasksApi(Request $request,string $id,CacheShelfService $service)
+    public function getChildStationApi(Request $request,string $id,CacheShelfService $service)
     {
-        /** @var Station $station */
-        $station = $service->getChildStation($id);
-        $this->success($station);
+        $stations = $service->getChildStation($id);
+        $this->success($stations);
     }
 
     /**
@@ -48,21 +47,23 @@ class CacheShelfController extends Controller
      * @param CacheShelfService $service
      * @return mixed
      */
-    public function lightOnApi(Request $request,CacheShelfService $service)
+    public function lightOnApi(Request $request,CacheShelfService $service): array
     {
-        if($request['stationCode'] && $request['materialBoxCode'])
-           return $service->createStationTask($request['stationCode'],$request['materialBoxCode']);
+        if($request['stationCode'] && $request['materialBoxCode']){
+            return  $service->bindMaterialBox($request['stationCode'],$request['materialBoxCode']);
+        }
         return ['success' => false,'message' => '参数错误'];
     }
 
     /**
      * @param Request $request
+     * @param CacheShelfService $service
      * @return array|bool[]
      */
-    public function clearTaskApi(Request $request): array
+    public function clearTaskApi(Request $request,CacheShelfService $service): array
     {
         $code = $request['station'];
-        return app(CacheShelfService::class)->clearTask($code);
+        return $service->clearTask($code);
     }
 
 }

+ 33 - 3
app/Http/Controllers/ControlPanelController.php

@@ -3,7 +3,9 @@
 namespace App\Http\Controllers;
 
 use App\Components\AsyncResponse;
+use App\Filters\OrderPackageReceivedSyncRecordFilters;
 use App\OrderPackageCountingRecord;
+use App\OrderPackageReceivedSyncRecord;
 use App\Owner;
 use App\Services\CacheService;
 use App\Services\CheckActiveMenuService;
@@ -49,7 +51,7 @@ class ControlPanelController extends Controller
         $end = Carbon::parse($request->end)->gt(Carbon::now()) ? Carbon::now()->toDateString() : $request->end;
         $ownerIds=$request->owner_ids;
         if (!$ownerIds || in_array('all',$ownerIds)) $ownerIds = $this->getCountingOwnerIds(null);
-        $orderCountingRecords = $orderCountingRecordService->orderCountingRecords($start, $end, $request->unit, $ownerIds);
+        $orderCountingRecords = $orderCountingRecordService->getOrderCountingRecordsApi($start, $end, $request->unit, $ownerIds);
         return compact('orderCountingRecords');
     }
 
@@ -63,7 +65,7 @@ class ControlPanelController extends Controller
         $end = Carbon::parse($request->end)->gt(Carbon::now()) ? Carbon::now()->toDateString() : $request->end;
         $ownerIds=$request->input('owner_ids');
         if (!$ownerIds || in_array('all',$ownerIds)) $ownerIds = $this->getCountingOwnerIds(null);
-        $logisticsCountingRecords = $orderCountingRecordService->logisticsCountingRecords($start, $end, $ownerIds);
+        $logisticsCountingRecords = $orderCountingRecordService->getLogisticRecordsApi($start, $end, $ownerIds);
         return compact('logisticsCountingRecords');
     }
 
@@ -76,7 +78,7 @@ class ControlPanelController extends Controller
         $start = Carbon::parse($request->start)->gt(Carbon::now()) ? Carbon::now()->toDateString() : $request->start;
         $end = Carbon::parse($request->end)->gt(Carbon::now()) ? Carbon::now()->toDateString() : $request->end;
         $ownerIds = $this->getCountingOwnerIds(null);
-        $warehouseCountingRecords = $orderCountingRecordService->warehouseCountingRecords($start, $end, $ownerIds);
+        $warehouseCountingRecords = $orderCountingRecordService->getWareHouseRecordsApi($start, $end, $ownerIds);
         return compact('warehouseCountingRecords');
     }
 
@@ -160,6 +162,34 @@ class ControlPanelController extends Controller
         $this->success(["title"=>$title,"data"=>$data]);
     }
 
+
+    /**
+     * 快递信息同步失败成功占比
+     * @param OrderPackageReceivedSyncRecordFilters $filters
+     * @param Request $request
+     * @return array
+     */
+    public function orderPackageReceivedSyncRecordApi(OrderPackageReceivedSyncRecordFilters $filters, Request $request)
+    {
+        $orderPackageReceivedSyncRecords = OrderPackageReceivedSyncRecord::query()->filter($filters)->get();
+        $data = [];
+        foreach ($orderPackageReceivedSyncRecords as $orderPackageReceivedSyncRecord) {
+            $total = $orderPackageReceivedSyncRecord->succeed_count + $orderPackageReceivedSyncRecord->failed_count;
+            $data[] = [
+                'date' => $orderPackageReceivedSyncRecord->recorded_at,
+                'total'=> $total,
+                'count'=>$orderPackageReceivedSyncRecord->succeed_count,
+                'value' => (int)($orderPackageReceivedSyncRecord->succeed_count / $total*100),
+                'logistic_name' =>$orderPackageReceivedSyncRecord->logistic_name
+            ];
+        }
+        $title = [];
+        foreach ($data as $data_item) {
+            $title[] = $data_item['date'];
+        }
+        return ['success' =>true, 'data' =>['data'=>$data,'title'=>$title]];
+    }
+
     public function exceptionTypeApi(Request $request)
     {
         $ownerIds=$request->owner_ids;

+ 50 - 12
app/Http/Controllers/DischargeTaskController.php

@@ -7,11 +7,16 @@ use App\Facilitator;
 use App\DischargeTask;
 use App\Filters\DischargeTaskFilters;
 use App\Http\Requests\DischargeTask\DischargeTaskRequest;
+use App\Imports\CommodityImport;
+use App\Imports\DischargeTaskImport;
+use App\Owner;
 use App\Services\common\ExportService;
 use App\Services\OwnerService;
 use App\Warehouse;
 use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Facades\Gate;
+use Maatwebsite\Excel\Facades\Excel;
 use Oursdreams\Export\Export;
 use function Sodium\compare;
 
@@ -25,13 +30,18 @@ class DischargeTaskController extends Controller
         if (!Gate::allows('人事管理-卸货-查询')) {
             return redirect(url('/'));
         }
+        if(Gate::allows('人事管理-卸货-货主可见全部')){
+            $owners = Owner::query()->get();
+            $dischargeTasks = DischargeTask::query()->with(['facilitator', 'owner', 'warehouse'])->filter($filters)->orderByDesc('income_at')->paginate($request['paginate'] ?? 50);
+        }else{
+            $owners = app(OwnerService::class)->getAuthorizedOwners();
+            $dischargeTasks = DischargeTask::query()->with(['facilitator', 'owner', 'warehouse'])->filter($filters)->whereIn('owner_id',data_get($owners,'*.id'))->orderByDesc('income_at')->paginate($request['paginate'] ?? 50);
+        }
 
-        $dischargeTasks = DischargeTask::query()->with(['facilitator', 'owner','warehouse'])->filter($filters)->orderByDesc('id')->paginate($request['paginate'] ?? 50);
-        $owners = app(OwnerService::class)->getAuthorizedOwners();
-        $warehouses = Warehouse::query()->select('id','name')->get();
+        $warehouses = Warehouse::query()->select('id', 'name')->get();
         $facilitators = Facilitator::query()->select('name', 'id')->get();
 
-        return view('personnel.discharge.task.index', compact('dischargeTasks', 'owners', 'facilitators','warehouses'));
+        return view('personnel.discharge.task.index', compact('dischargeTasks', 'owners', 'facilitators', 'warehouses'));
     }
 
     // 结算报表
@@ -41,7 +51,7 @@ class DischargeTaskController extends Controller
             return redirect(url('/'));
         }
 
-        $dischargeStatements = DischargeTask::query()->with('facilitator')->filter($filters)->orderByDesc('id')->paginate($request['paginate'] ?? 50);
+        $dischargeStatements = DischargeTask::query()->with('facilitator')->filter($filters)->orderByDesc('income_at')->paginate($request['paginate'] ?? 50);
         $owners = app(OwnerService::class)->getAuthorizedOwners();
         $facilitators = Facilitator::query()->select('name', 'id')->get();
 
@@ -115,13 +125,17 @@ class DischargeTaskController extends Controller
     {
         $this->gate('人事管理-卸货-查询');
 
-        $dischargeTasks = DischargeTask::query()->with(['Facilitator', 'owner'])->filter($filters)->orderByDesc('id')->get();
+        if(Gate::allows('人事管理-卸货-货主可见全部')){
+            $dischargeTasks = DischargeTask::query()->with(['Facilitator', 'owner'])->filter($filters)->orderByDesc('id')->get();
+        }else{
+            $owners = app(OwnerService::class)->getAuthorizedOwners();
+            $dischargeTasks = DischargeTask::query()->with(['Facilitator', 'owner'])->filter($filters)->whereIn('owner_id',data_get($owners,'*.id'))->orderByDesc('id')->get();
+        }
 
         $row = ['日期', '客户名称', '作业名称', '入库单号', '数量', '单位', '单价', '收费', '状态', '备注'];
         $json = app('DischargeTaskService')->getJson($dischargeTasks);
 
         return Export::make($row, $json, "卸货任务");
-        //return app(ExportService::class)->json($row, $json, "卸货任务");
     }
 
     // 结算报表下载
@@ -129,38 +143,62 @@ class DischargeTaskController extends Controller
     {
         $this->gate('人事管理-卸货-结算报表-查询');
 
-        $dischargeTasks = DischargeTask::query()->with(['facilitator', 'owner','warehouse'])->filter($filters)->orderByDesc('id')->get();
+        $dischargeTasks = DischargeTask::query()->with(['facilitator', 'owner', 'warehouse'])->filter($filters)->orderByDesc('id')->get();
 
-        $row = ['日期', '客户名称','仓库', '作业名称', '入库单号', '数量', '单位', '收入单价', '收入合计', '装卸队', '数量', '单位', '支出单价', '支出合计', '状态', '收入备注', '支出备注'];
+        $row = ['日期', '客户名称', '仓库', '作业名称', '入库单号', '数量', '单位', '收入单价', '收入合计', '装卸队', '数量', '单位', '支出单价', '支出合计', '状态', '收入备注', '支出备注'];
         $json = app('DischargeTaskService')->getStatementsJson($dischargeTasks);
 
         return Export::make($row, $json, "卸货结算报表");
         //return app(ExportService::class)->json($row, $json, "卸货结算报表");
     }
 
-    // 回执单
     public function receipt(Request $request)
     {
-        $task = DischargeTask::query()->with(['facilitator', 'owner','warehouse'])->where('id' , $request['id'])->first();
+        $task = DischargeTask::query()->with(['facilitator', 'owner', 'warehouse'])->where('id', $request['id'])->first();
         $task->type = DischargeTask::types[$task->type];
-        return view('personnel.discharge.task.receipt',compact('task'));
+        return view('personnel.discharge.task.receipt', compact('task'));
+    }
+
+    public function importApi(Request $request): array
+    {
+        $this->gate('人事管理-卸货-创建');
+
+        $extension = $request->file()['file']->getClientOriginalExtension();
+        if (in_array($extension, ['xlsx', 'xlsm', 'xltx', 'xltm', 'xls', 'xlt', 'ods', 'ots', 'slk', 'xml', 'gnumeric', 'htm', 'html', 'csv', 'tsv']))
+            return ['success' => false,'message'=>'请检查导入文件是否符合要求'];
+        $extension[0] = strtoupper($extension[0]);
+        try {
+            Excel::import(new DischargeTaskImport(), $request->file()['file']->path(), null, $extension);
+        } catch (\Exception $e) {
+            return ['success' => false, 'message' => ['请检查导入文件是否符合要求']];
+        }
+        if (Cache::has('exception')) {
+            return ['success' => false, 'errors' => Cache::get('exception')];
+        }
+        return ['success' => true];
     }
 
+
     public function show(DischargeTask $dischargeTask)
     {
     }
+
     public function edit(DischargeTask $dischargeTask)
     {
     }
+
     public function update(Request $request, DischargeTask $dischargeTask)
     {
     }
+
     public function store(Request $request)
     {
     }
+
     public function create()
     {
     }
+
     public function destroy(DischargeTask $dischargeTask)
     {
 

+ 5 - 17
app/Http/Controllers/LaborCompanyController.php

@@ -10,11 +10,7 @@ use Illuminate\Support\Facades\Validator;
 
 class LaborCompanyController extends Controller
 {
-    /**
-     * Display a listing of the resource.
-     *
-     * @return Response
-     */
+
     public function index()
     {
         if(!Gate::allows('劳务所-查询')){ return redirect(url('/'));  }
@@ -22,30 +18,21 @@ class LaborCompanyController extends Controller
         return view('maintenance.laborCompany.index',['laborCompanys'=>$laborCompanys]);
     }
 
-    /**
-     * Show the form for creating a new resource.
-     *
-     * @return Response
-     */
+
     public function create()
     {
         if(!Gate::allows('劳务所-录入')){ return redirect(url('/'));  }
         return view('maintenance.laborCompany.create');
     }
 
-    /**
-     * Store a newly created resource in storage.
-     *
-     * @param Request $request
-     * @return Response
-     */
+
     public function store(Request $request)
     {
         if(!Gate::allows('劳务所-录入')){ return redirect(url('/'));  }
         $this->validatorCreate($request->all())->validate();
         $laborCompany=new LaborCompany($request->all());
         $laborCompany->save();
-
+        app('LaborCompanyService')->createAuthority($laborCompany);//创建劳务所创建对应权限
         app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
         return redirect('maintenance/laborCompany/create')->with('successTip',"成功录入劳务所“{$request->input('name')}”");
     }
@@ -97,6 +84,7 @@ class LaborCompanyController extends Controller
         $this->validatorUpdate($request->all())->validate();
         $laborCompany->fill($request->all());
         $laborCompany->update();
+        app('LaborCompanyService')->updateAuthority($laborCompany);
         app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
         return redirect('maintenance/laborCompany/')->with('successTip',"成功修改劳务所“{$laborCompany['name']}”!");
     }

+ 10 - 1
app/Http/Controllers/LaborReportController.php

@@ -63,7 +63,16 @@ class LaborReportController extends Controller
             }
         }
         $totalWorkingHours=$this->getTotalWorkingHours($request->input());
-        $laborCompanies=LaborCompany::query()->get();
+        if($user->isSuperAdmin()|| Gate::allows('劳务所-可见全部')){
+            $laborCompanies=LaborCompany::query()->get();
+        }else{
+            $userId=$user['id'];
+            $laborCompanies=LaborCompany::query()->whereIn('id',function ($query)use($userId){
+                $query->from('role_labor_company')->selectRaw('labor_company_id')->whereIn('role_id',function ($builder)use ($userId){
+                    $builder->from('user_role')->selectRaw('id_role')->where('id_user',$userId);
+                });
+            })->get();
+        }
         $userWorkGroups=UserWorkgroup::query()->select('id','name')->get();
         return view('personnel/laborReport/index',compact('laborReports','userWorkGroups','laborCompanies','laravelEchoPrefix','permittingWorkgroups','paginateParams','tokenOfBroadcastEnterAndLeave','totalWorkingHours'));
     }

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

@@ -336,12 +336,12 @@ sql;
             ->whereIn('orderno',$orderno)
             ->where('sostatus','99')
             ->whereIn('edisendflag',['R','W'])
-                ->where('addwho','==','EDI')
+            ->where('addwho','EDI')
             ->update(['edisendflag'=>'N']);
 
         $failedOrdernos =OracleDOCOrderHeader::query()
             ->whereIn('orderno', $orderno)
-            ->where('edisendflag', '!=', 'N')->pluck('orderno');
+                ->where('edisendflag', '!=', 'N')->pluck('orderno');
 
         $successedOrdernos =OracleDOCOrderHeader::query()
             ->whereIn('orderno', array_diff($orderno,$oldIds))

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

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

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

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

+ 82 - 0
app/Http/Controllers/OwnerSundryFeeDetailsController.php

@@ -0,0 +1,82 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\Filters\OwnerSundryFeeDetailFilters;
+use App\Owner;
+use App\OwnerSundryFeeDetail;
+use Illuminate\Http\Request;
+use App\Http\Requests\OwnerSundryFeeDetailRequest;
+
+class OwnerSundryFeeDetailsController extends Controller
+{
+    public function __construct()
+    {
+        $this->middleware('auth');
+    }
+
+    public function index(Request $request, OwnerSundryFeeDetailFilters $filters)
+    {
+        $paginateParams = $request->input();
+        $owner_sundry_fee_details = OwnerSundryFeeDetail::query()->filter($filters)->with('owner')->orderByDesc('updated_at')->paginate($request->paginate ?? 50);
+        $owners = Owner::all();
+        return view('customer.ownerSundryFee.index', compact('owner_sundry_fee_details', 'paginateParams','owners'));
+    }
+
+    public function show($owner_sundry_fee_detail)
+    {
+        $owner_sundry_fee_detail = OwnerSundryFeeDetail::find($owner_sundry_fee_detail);
+        $owner_sundry_fee_detail->loadMissing('owner');
+        return view('customer.ownerSundryFee.show', compact('owner_sundry_fee_detail'));
+    }
+
+    public function create(OwnerSundryFeeDetail $owner_sundry_fee_detail)
+    {
+        $types = [
+            '材料',
+            '垫付',
+            '人工',
+            '其他',
+        ];
+        $owners = Owner::all();
+        return view('customer.ownerSundryFee.create_and_edit', compact('owner_sundry_fee_detail', 'types','owners'));
+    }
+
+    public function store(OwnerSundryFeeDetailRequest $request)
+    {
+        $owner_sundry_fee_detail = OwnerSundryFeeDetail::create($request->all());
+        return redirect()->route('ownerSundryFeeDetails.index', $owner_sundry_fee_detail->id)->with('success', '创建成功');
+    }
+
+    public function edit($owner_sundry_fee_detail)
+    {
+        $owner_sundry_fee_detail = OwnerSundryFeeDetail::find($owner_sundry_fee_detail);
+        $owner_sundry_fee_detail->loadMissing('owner');
+        $this->authorize('update', $owner_sundry_fee_detail);
+        $types = [
+            '材料',
+            '垫付',
+            '人工',
+            '其他',
+        ];
+        $owners = Owner::all();
+
+        return view('customer.ownerSundryFee.create_and_edit', compact('owner_sundry_fee_detail','types','owners'));
+    }
+
+    public function update(OwnerSundryFeeDetailRequest $request, $owner_sundry_fee_detail)
+    {
+        $owner_sundry_fee_detail = OwnerSundryFeeDetail::find($owner_sundry_fee_detail);
+        $this->authorize('update', $owner_sundry_fee_detail);
+        $owner_sundry_fee_detail->update($request->all());
+        return redirect()->route('ownerSundryFeeDetails.index', $owner_sundry_fee_detail->id)->with('success', '更新成功');
+    }
+
+    public function destroy($owner_sundry_fee_detail)
+    {
+        $owner_sundry_fee_detail = OwnerSundryFeeDetail::find($owner_sundry_fee_detail);
+        $this->authorize('destroy', $owner_sundry_fee_detail);
+        $owner_sundry_fee_detail->delete();
+        return redirect()->route('ownerSundryFeeDetails.index')->with('success', '删除成功');
+    }
+}

+ 3 - 3
app/Http/Controllers/ProcurementController.php

@@ -78,7 +78,7 @@ class ProcurementController extends Controller
                     $build->whereIn('id',$owner_ids);
                 });
             })
-            ->paginate($param['paginate'] ?? 50);
+            ->paginate($paginateParams['paginate'] ?? 50);
         foreach ($procurements as $procurement){
             if ($procurement->procurement_quotations_count>0 && $procurement->status==0) $procurement->status=1;
             if (empty($procurement->procurementDeliveries))continue;
@@ -287,7 +287,7 @@ class ProcurementController extends Controller
                     });
                 });
             })
-            ->paginate($param['paginate'] ?? 50);
+            ->paginate($paginateParams['paginate'] ?? 50);
         $suppliers=Supplier::query()->select('id','name')->get();
         $materials=Material::query()->select('id','name')->get();
         return view('procurement/finance/checkBill',compact('procurementCheckSheets','suppliers','paginateParams','materials'));
@@ -348,7 +348,7 @@ class ProcurementController extends Controller
                 });
             })
             ->where('type',0) //只取采购单
-            ->paginate($param['paginate'] ?? 50);
+            ->paginate($paginateParams['paginate'] ?? 50);
         foreach ($procurements as $procurement){
             if (empty($procurement->procurementDeliveries))continue;
             $procurement->receive_amount=$procurement->procurementDeliveries->sum('amount');

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

@@ -399,6 +399,8 @@ class RejectedController extends Controller
 //        return ['success'=>$re];
     }
     public function export(Request $request){
+        ini_set('max_execution_time',2500);
+        ini_set('memory_limit','1526M');
         if(!Gate::allows('退货管理-查询')){ return '没有权限';  }
         if ($request->checkAllSign){
             $param = $request->input();

+ 23 - 18
app/Http/Controllers/RoleController.php

@@ -3,6 +3,7 @@
 namespace App\Http\Controllers;
 
 use App\Authority;
+use App\LaborCompany;
 use App\Role;
 use Exception;
 use Illuminate\Http\Request;
@@ -13,11 +14,7 @@ use Illuminate\Support\Facades\Validator;
 
 class RoleController extends Controller
 {
-    /**
-     * Display a listing of the resource.
-     *
-     * @return Response
-     */
+
     public function index(Request $request)
     {
         if(!Gate::allows('角色-查询')){ return redirect(url('/'));  }
@@ -42,25 +39,17 @@ class RoleController extends Controller
         return view('maintenance.role.index',['roles'=>$roles]);
     }
 
-    /**
-     * Show the form for creating a new resource.
-     *
-     * @return Response
-     */
+
     public function create()
     {
         if(!Gate::allows('角色-录入')){ return redirect(url('/'));  }
         $authoritiesAll=Authority::orderBy('alias_name','desc')->get();
         $authoritiesAll = Authority::filterRecycle($authoritiesAll);
-        return view('maintenance.role.create',compact('authoritiesAll'));
+        $laborCompanies=LaborCompany::query()->get();
+        return view('maintenance.role.create',compact('authoritiesAll','laborCompanies'));
     }
 
-    /**
-     * Store a newly created resource in storage.
-     *
-     * @param Request $request
-     * @return Response
-     */
+
     public function store(Request $request)
     {
         if(!Gate::allows('角色-录入')){ return redirect(url('/'));  }
@@ -72,6 +61,13 @@ class RoleController extends Controller
             $authorityIdArr=explode(',',$authorityIds);
             $role->authorities()->sync($authorityIdArr);
         }
+        $laborCompanyIds=$request->input('laborCompany')??'';
+        if($laborCompanyIds){
+            $laborCompanyIdArr=explode(',',$laborCompanyIds);
+            $role->laborCompanies()->sync($laborCompanyIdArr);
+        }else{
+            $role->laborCompanies()->sync([]);
+        }
 
         app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
         return redirect('maintenance/role/create')->with('successTip',"成功录入角色“{$request->input('name')}”");
@@ -111,7 +107,9 @@ class RoleController extends Controller
         $authoritiesAll=Authority::orderBy('alias_name','desc')->get();
         $authoritiesAll = Authority::filterRecycle($authoritiesAll);
         $authorities=$role->authorities()->get();
-        return view('maintenance.role.edit',compact('role','authorities','authoritiesAll'));
+        $laborCompanies=LaborCompany::query()->get();
+        $laborCompaniesRole=$role->laborCompanies()->get();
+        return view('maintenance.role.edit',compact('role','authorities','authoritiesAll','laborCompanies','laborCompaniesRole'));
     }
 
     /**
@@ -134,6 +132,13 @@ class RoleController extends Controller
         }else{
             $role->authorities()->sync([]);
         }
+        $laborCompanyIds=$request->laborCompany??'';
+        if($laborCompanyIds){
+            $laborCompanyIdArr=explode(',',$laborCompanyIds);
+            $role->laborCompanies()->sync($laborCompanyIdArr);
+        }else{
+            $role->laborCompanies()->sync([]);
+        }
         app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
         return redirect('maintenance/role/')->with('successTip',"成功修改角色“{$role['name']}”!");
     }

文件差異過大導致無法顯示
+ 6 - 3
app/Http/Controllers/TestController.php


+ 3 - 2
app/Http/Controllers/WaybillController.php

@@ -768,7 +768,7 @@ class WaybillController extends Controller
             'other_fee'=>'sometimes|nullable|min:0|numeric|max:999999',
             'charge'=>'sometimes|nullable|min:0|numeric|max:999999',
             'mileage'=>'nullable|numeric|min:0',
-            'amount'=>'nullable|numeric|min:0',
+            'amount'=>'numeric|min:0',
             'amount_unit_id'=>'required',
             'origination_city_id'=>'sometimes|required|integer',
             'destination_city_id'=>'sometimes|required_without:order_id|integer',
@@ -964,7 +964,7 @@ class WaybillController extends Controller
         if(!Gate::allows('运输管理-运单-按日计算专线费')){return ['success'=>false,'message'=>'没有权限'];}
         $dailyBilling=$request->input('param');
         $waybills=app('waybillService')->dailyBilling($dailyBilling);
-        if ($waybills==false)return ['success'=>false,'message'=>'当前选定发货日期没有任何记录'];
+        if ($waybills=='无数据')return ['success'=>false,'message'=>'当前选定发货日期没有任何记录'];
         if (!isset($waybills))return ['success'=>false,'message'=>'该日有记录未填写重量'];
         return ['success'=>true,'data'=>$waybills];
     }
@@ -974,6 +974,7 @@ class WaybillController extends Controller
         $param=$request->input('param');
         $waybills=app('waybillService')->get($param);
         $total_pick_up_fee=$waybills->sum('pick_up_fee');
+        if ($total_pick_up_fee)$total_pick_up_fee=round($total_pick_up_fee);
         return ['success'=>true,'data'=>$total_pick_up_fee];
     }
 

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

@@ -3,95 +3,48 @@
 
 namespace App\Http\Controllers\api\thirdPart\goodscan;
 
-use App\Events\WeighedEvent;
-use App\Http\Controllers\LogisticNumberFeatureController;
-use App\Jobs\WeightUpdateInstantBill;
-use App\MeasuringMachine;
-use App\OracleDOCOrderHeader;
-use App\Order;
-use App\OrderPackage;
 use App\Services\LogService;
-use App\Services\OrderService;
-use App\Waybill;
-use Carbon\Carbon;
+use App\Services\weight\GoodScanWeightService;
 use Illuminate\Http\Request;
+use Illuminate\Support\Carbon;
 use Illuminate\Support\Facades\Validator;
 
 class PackageController
 {
     public function new_(Request $request)
     {
-        app('LogService')->log(__METHOD__,'GoodScan weightApi add'.__FUNCTION__,json_encode($request->getContent()));
+        app('LogService')->log(__METHOD__, 'GoodScan weightApi add' . __FUNCTION__, json_encode($request->getContent()));
         $requestInput = [];
-        foreach ($request->input() as $key=>$item) {
+        foreach ($request->input() as $key => $item) {
             $requestInput[strtolower($key)] = $item;
         }
 
         $errors = $this->validatorWeight($requestInput)->errors(); // 参数校验
-        $weight = $requestInput['weight']??'';
-        if($weight == '-9.9'){   // 称重异常校验
-            app('LogService')->log(__METHOD__,'GoodScan weightApi (Error)'.__FUNCTION__,'异方接口称重伤上传异常[异常值为-9.9,电子秤故障或未连接]'.json_encode($request->getContent()));
-            return json_encode(['code'=>500,'error'=>'weight=-9.9']);
-        }
-        if(count($errors) > 0){
-            app('LogService')->log(__METHOD__,'error'.__FUNCTION__,json_encode($request->getContent()).'||'.json_encode($errors),null);
-            return json_encode(['code'=>500,'error'=>$errors]);
-        }
 
-        /**
-         * @var MeasuringMachine $measuringMachine
-         * @var OrderPackage $orderPackage
-         * @var OracleDOCOrderHeader $orderHeader
-         * @var Order $order
-         */
+        $weight = $requestInput['weight'] ?? '';
 
-        $measuringMachine = $this->getMeasuringMachine($requestInput['hid']); // 返回设备并启动
-        $orderPackage=$this->getOrderPackageByLogisticNumber($requestInput['code']); // 查询WAS是否有对应的包裹信息
-        if($orderPackage){
-            $result = $this->updateOrderPackage($orderPackage,$requestInput,$measuringMachine); // 更新包裹信息
-            if($result){
-                return json_encode($result);
-            }
-        }else{
-            try {
-                $orderHeader = $this->findOrderHeaderByLogisticNumber($requestInput['code']);// 查询WMS是否有对应的包裹信息
-                if (!$orderHeader) {
-                    return json_encode(['code' => 500, 'error' => '保存时发生错误(未在WMS中找到订单)!'], JSON_UNESCAPED_UNICODE);
-                }
-                $order = $this->createOrderByOrderHeader($orderHeader);
-                $orderPackage = $this->getOrderPackage($requestInput, $measuringMachine, $order);// 返回包裹对象
-                $this->syncOrderPackageLogistic($orderPackage);// 同步包裹订单的承运商
-            } catch (\Exception $e) {
-                app('LogService')->log(__METHOD__,__FUNCTION__,'GoodScan weightApi (Error)'.json_encode($request->getContent()).'||'.json_encode($orderPackage),null);
-                return json_encode(["code"=>500,"error"=>"写入WMS失败!"],JSON_UNESCAPED_UNICODE);
-            }
+        if ($weight == '-9.9') {   // 称重异常校验
+            app('LogService')->log(__METHOD__, 'GoodScan weightApi (Error)' . __FUNCTION__, '异方接口称重伤上传异常[异常值为-9.9,电子秤故障或未连接]' . json_encode($request->getContent()));
+            return json_encode(['code' => 500, 'error' => 'weight=-9.9'], JSON_UNESCAPED_UNICODE);
         }
-        if(!empty($orderPackage->order)){
-            Waybill::setWeightByOrderCode($orderPackage->order->code,$orderPackage->weight);
+
+        if (count($errors) > 0) {
+            app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, json_encode($request->getContent()) . '||' . json_encode($errors), null);
+            return json_encode(['code' => 500, 'error' => $errors], JSON_UNESCAPED_UNICODE);
         }
-        $orderPackage->loadMissing('measuringMachine');
-        event(new WeighedEvent($orderPackage));
-        dispatch(new WeightUpdateInstantBill($orderPackage));
-        $response=["code"=>0,'error'=>'upload success'];
-        app('LogService')->log(__METHOD__,__FUNCTION__,"异方下发写入包裹成功:".json_encode($request->getContent()).'||'.json_encode($response),null);
 
-        return json_encode($response,JSON_UNESCAPED_UNICODE);
-    }
+        /** @var GoodScanWeightService $serivce */
+        $service = app(GoodScanWeightService::class);
+        $response = $service->new($requestInput);
+        if ($response['code'] == 500)
+            LogService::log(__CLASS__, __METHOD__, '称重失败:' . json_encode($response['error']));
+        else if ($response['code'] == 0)
+            LogService::log(__CLASS__, __METHOD__, '称重成功:' . json_encode($requestInput));
 
-    /**
-     * @param string $hid
-     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
-     */
-    public function getMeasuringMachine($hid)
-    {
-        /** @var MeasuringMachine $measuringMachine */
-        $measuringMachine = MeasuringMachine::query()->firstOrCreate(['code'=>$hid]); // 称重设备
-        $measuringMachine->turnOn();
-        $measuringMachine->turnOffInMinutes(30);
-        return $measuringMachine;
+        return json_encode($response, JSON_UNESCAPED_UNICODE);
     }
 
-    public function validatorWeight(array $request)
+    public function validatorWeight(array $request): \Illuminate\Contracts\Validation\Validator
     {
         return Validator::make($request, [
             'code' => ['required', 'max:191'],
@@ -109,190 +62,4 @@ class PackageController
             'string' => ':attribute 应为字符串',
         ], []);
     }
-
-    /**
-     * @param OrderPackage $orderPackage
-     * @param array $params
-     * @param MeasuringMachine $measuringMachine
-     * @return array
-     */
-    public function updateOrderPackage(&$orderPackage,$params,$measuringMachine) //更新包裹信息 前往处理活动波次
-    {
-        $edges=$this->getEdges($params);
-
-        $req_date=\Illuminate\Support\Carbon::now()->format(\Illuminate\Support\Carbon::DEFAULT_TO_STRING_FORMAT);
-        $orderPackage->weight=$params['weight'];
-        $orderPackage->measuring_machine_id=$measuringMachine->id;
-        $orderPackage->length=$edges[0];
-        $orderPackage->width=$edges[1];
-        $orderPackage->height=$edges[2];
-        $orderPackage->weighed_at=$req_date;
-        $orderPackage->bulk=$edges[0]*$edges[1]*$edges[2]/1000;
-        if($orderPackage->isActivityBatch()){
-            $response=$this->activityWaveNoProcessing($orderPackage);
-            if($response)return $response;
-        }
-        $orderPackage->save();
-        return[];
-    }
-
-    /**
-     * @param OrderPackage $orderPackage
-     * @return array
-     */
-    public function activityWaveNoProcessing(&$orderPackage) //处理活动波次
-    {
-        $fluxController = new \App\Http\Controllers\api\thirdPart\flux\PackageController();
-        if($orderPackage->isActivityBatch()){
-            app('LogService')->log(__METHOD__,__FUNCTION__,"依波次号同步所有包裹:".json_encode($orderPackage),null);
-            $params = [
-                'weight'=>$orderPackage['weight'] ?? null,
-                'length'=>$orderPackage['length'] ?? null,
-                'width'=>$orderPackage['width'] ?? null,
-                'height'=>$orderPackage['height'] ?? null,
-                'bulk'=>$orderPackage['bulk'] ?? null,
-                'measuring_machine_id'=>$orderPackage['measuring_machine_id'] ?? null,
-                'weighed_at'=>$orderPackage['weighed_at'] ?? null,
-                'paper_box_id'=>$orderPackage['paper_box_id'] ?? null,
-            ];
-            OrderPackage::query()->where('batch_number',$orderPackage['batch_number'])->update($params);
-            $result=$fluxController->markWMSOnBatch($orderPackage['batch_number'], $orderPackage['weight']);
-            if(!$result['result']){
-                $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->uploaded_to_wms="是";
-                else
-                    $orderPackage->uploaded_to_wms="异常";
-            }catch (\Exception $e){
-                $orderPackage->uploaded_to_wms="否";
-            }
-        }
-        $response=$this->saveOrderPackage($orderPackage);
-        return $response??[];
-    }
-
-    /**
-     * @param OrderPackage $orderPackage
-     * @return array
-     */
-    public function saveOrderPackage(&$orderPackage) //保存修改并
-    {
-        try {
-            $logisticNumberController = new LogisticNumberFeatureController();
-            if (!$orderPackage->order) {
-                $orderPackage->order = new Order();
-            }
-            if (!$orderPackage->order->logistic) {
-                $orderPackage->order->logistic = $logisticNumberController->getLogisticByFeatures($orderPackage->logistic_number);
-            }
-            $orderPackage->save();
-            return [];
-        } catch (\Exception $e) {
-            $response=["msg"=>'称重下发修改时发生错误!',json_encode($e),'code'=>500,'data'=>null];
-            app('LogService')->log(__METHOD__,'GoodScan weightApi (Error)'.__FUNCTION__,json_encode($orderPackage).'||'.json_encode($e),null);
-            return $response;
-        }
-    }
-
-    /**
-     * @param string $logisticNumber
-     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
-     */
-    public function getOrderPackageByLogisticNumber($logisticNumber)
-    {
-        return OrderPackage::query()
-            ->with(['order'=>function($query){
-                $query->with('owner','logistic');
-            }])
-            ->where('logistic_number',$logisticNumber)
-            ->first();
-    }
-
-    /**
-     * @param string $logisticNumber
-     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
-     */
-    public function findOrderHeaderByLogisticNumber($logisticNumber)
-    {
-        return OracleDOCOrderHeader::query()->with('actAllocationDetails','oracleBASCode')
-            ->whereHas('actAllocationDetails',function($query)use($logisticNumber){
-                $query->where('picktotraceid',$logisticNumber);
-            })
-//            ->orWhere('soreference5',$logisticNumber)
-            ->first();
-    }
-
-    /**
-     * @param OracleDOCOrderHeader $orderHeader
-     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
-     */
-    public function createOrderByOrderHeader($orderHeader)
-    {
-        /** @var OrderService $orderService */
-        $orderService=app(OrderService::class);
-        $order_create_params=$orderService->getParamByOrderHeader($orderHeader);
-        $order = $orderService->first(['code'=>$orderHeader->orderno]);
-        if($order)return $order;
-        $order = $orderService->createOrder($order_create_params);
-        app('LogService')->log(__METHOD__,__FUNCTION__,'GoodScan 创建Order',json_encode($order)." || ".$orderHeader);
-        return $order;
-    }
-
-    /**
-     * @param array $requestInput
-     * @param MeasuringMachine $measuringMachine
-     * @param Order $order
-     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
-     */
-    public function getOrderPackage($requestInput,$measuringMachine,$order)
-    {
-//        $weighed_at =$requestInput['time']??Carbon::now();
-        $weighed_at =Carbon::now();
-        $edges=$this->getEdges($requestInput);
-        OrderPackage::query()->create([
-            'order_id'=>$order->id,
-            'logistic_number'=>$requestInput['code'],
-            'measuring_machine_id'=>$measuringMachine->id,
-            'weight'=>$requestInput['weight'],
-            'length'=>$edges[0],
-            'width'=>$edges[1],
-            'height'=>$edges[2],
-            'bulk'=>$edges[0]*$edges[1]*$edges[2],
-            'weighed_at'=>$weighed_at,
-            'status'=>"无",
-        ]);
-        return $this->getOrderPackageByLogisticNumber($requestInput['code']);
-    }
-
-    /**
-     * @param array $requestInput
-     * @return array
-     */
-    public function getEdges($requestInput)
-    {
-        $edges = [$requestInput['l']??0,$requestInput['w']??0,$requestInput['h']??0];
-        rsort($edges);
-        return $edges;
-    }
-
-    /**
-     * @param $orderPackage
-     */
-    public function syncOrderPackageLogistic(&$orderPackage) // 同步订单承运商
-    {
-        $logisticNumberController = new LogisticNumberFeatureController();
-        if (!$orderPackage->order) {
-            $orderPackage->order = new Order();
-        }
-        if (!$orderPackage->order->logistic) {
-            $orderPackage->order->logistic = $logisticNumberController->getLogisticByFeatures($orderPackage->logistic_number);
-        }
-        $orderPackage->save();
-    }
-
 }

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

@@ -56,7 +56,7 @@ class LightController
                 $response['errMsg']=$result['errMsg'];
                 return $response;
             case 'U型线拍灯':
-                $this->foreignHaiRoboticsService->uLineLightPat($station);
+//                $this->foreignHaiRoboticsService->uLineLightPat($station);
         }
 
         return $response;

+ 24 - 21
app/Http/Controllers/api/thirdPart/hengli/PackageController.php

@@ -4,27 +4,33 @@
 namespace App\Http\Controllers\api\thirdPart\hengli;
 
 use App\Http\Controllers\api\thirdPart\weight\WeightBaseController;
+use App\Services\LogService;
+use App\Services\weight\HengLiWeightService;
 use Illuminate\Http\Request;
 
 class PackageController extends WeightBaseController
 {
-    // 参数
-    protected $weight = 'weight';     // 重量
-    protected $length = 'length';     // 长
-    protected $width = 'width';      // 宽
-    protected $height = 'height';     // 高
-    protected $code = 'code';       // 快递单号
-    protected $weight_at = 'weight_at';  // 称重时间
-    protected $hid = 'hid';        // 称重设备id
-    protected $name = 'HengLi';       // 名称
-
     public function new_(Request $request)
     {
-        app('LogService')->log(__METHOD__, $this->name, "记录上传日志:" . json_encode($request->all()) , null);
-        return $this->new($request);
+        $errors = $this->validator($request);
+        if(count($errors)>0){
+            return json_encode(['success' => false,'message' => $errors],JSON_UNESCAPED_UNICODE);
+        }
+
+        $params = $this->conversionRequest($request);
+
+        /** @var HengLiWeightService $service */
+        $service = app(HengLiWeightService::class);
+
+        $response = $service->new($params);
+        if($response['success'])
+            LogService::log(__CLASS__,$service->name,'称重成功!'.json_encode($params));
+        else
+            LogService::log(__CLASS__,$service->name,'称重失败!'.json_encode($request['']).json_encode($params));
+        return json_encode($response,JSON_UNESCAPED_UNICODE);
     }
 
-    public function conversionRequest($request)
+    public function conversionRequest($request): array
     {
         $params = [];
         $arr = $request->all();
@@ -66,27 +72,22 @@ class PackageController extends WeightBaseController
         return str_replace('_', '.', $value);
     }
 
-    // 信息返回
 
-    // 返回称重成功信息
     public function getSuccessMessage($params, $orderPackage): array
     {
         return ['success' => true, 'message' => '称重成功'];
     }
 
-    // 返回包裹未找到异常
     public function getNotFindOrderPackageMessage($params, $orderPackage): string
     {
         return json_encode(['success' => false, 'message' => '未找打包裹信息', JSON_UNESCAPED_UNICODE]);
     }
 
-    // 返回富勒信息未找到异常
     public function getNotFindOrderHeaderMessage($params, $orderPackage): string
     {
         return json_encode(['success' => false, 'message' => '富勒信息未找到'], JSON_UNESCAPED_UNICODE);
     }
 
-    // 返回称重下发错误
     public function getWeightMessage($orderPackage, $e)
     {
         return json_encode(['success' => false, 'message' => $e->getMessage], JSON_UNESCAPED_UNICODE);
@@ -94,18 +95,20 @@ class PackageController extends WeightBaseController
 
     public function validator(Request $request): array
     {
+        /** @var HengLiWeightService $service */
+        $service = app(HengLiWeightService::class);
         $params = $this->conversionRequest($request);
         $errors = [];
-        $weight = $this->getWeightValue($params);
+        $weight = $service->getWeightValue($params);
         if (empty($weight) || $weight == '') {
             $errors['weight'] = '称重重量为空';
         }
-        $code = $this->getCodeValue($params);
+        $code = $service->getCodeValue($params);
         $code = trim($code, "'");
         if (empty($code) || $code == '') {
             $errors['code'] = '快递单号为空';
         }
-        $hid = $this->getValue($this->hid, $params);
+        $hid = $service->getValue($service->hid, $params);
         if (empty($hid) || $hid == '') {
             $errors['hid'] = '称重设备号不能为空';
         }

+ 37 - 315
app/Http/Controllers/api/thirdPart/weight/PackageController.php

@@ -2,335 +2,57 @@
 
 namespace App\Http\Controllers\api\thirdPart\weight;
 
-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;
-use App\Services\OrderService;
-use App\Waybill;
+use App\Services\LogService;
+use App\Services\weight\HaoChuangWeightService;
 use Illuminate\Http\Request;
 use Illuminate\Support\Carbon;
 use Illuminate\Support\Facades\Validator;
 
-
 class PackageController extends Controller
 {
-//    public function new_(Request $requestInitial){
-//        $request=[];
-//        foreach ($requestInitial->all() as $k=>$v){
-//            $request[strtolower($k)]=$v;
-//        }
-//        $reqDate=isset($request['time'])?$request['time']:Carbon::now();
-//        $errors=$this->validatorWeight($request)->errors();
-//
-//        if (count($errors)>0){
-//            app('LogService')->log(__METHOD__,'error'.__FUNCTION__,json_encode($request).'||'.json_encode($errors),null);
-//            $response=["msg"=>$errors,"code"=>500,"data"=>null];
-//            return json_encode($response);
-//        }
-//
-//        $measuringMachine=MeasuringMachine::where('code',$request['id'])->first();
-//        if (!$measuringMachine){
-//            $measuringMachine=new MeasuringMachine([
-//                'name'=>$request['id'],
-//                'code'=>$request['id'],
-//                'status'=>'在线'
-//            ]);
-//            $measuringMachine->save();
-//            app('LogService')->log(__METHOD__,'weightApi(new measuring machine)'.__FUNCTION__,json_encode($request),null);
-//        }else{
-//            $measuringMachineStatus=new MeasuringMachine();
-//            $measuringMachineStatus->changeStatus($measuringMachine);
-//        }
-//        MeasuringMachineQueue::dispatch($measuringMachine)->delay(Carbon::now()->addMinutes(30));
-//
-//        $package=Package::where('logistic_number',$request['barcode'])->first();
-//        if (isset($request['length'])&&isset($request['width'])&&isset($request['height'])){
-//            $length=$request['length'];
-//            $width=$request['width'];
-//            $height=$request['height'];
-//            $max=($length>=($width>=$height?$width:$height)?$length:($width>=$height?$width:$height));
-//            if ($max==$length){
-//                $centre=$width>=$height?$width:$height;
-//                $min=$width<$height?$width:$height;
-//            }elseif ($max==$width){
-//                $centre=$length>=$height?$length:$height;
-//                $min=$length<$height?$length:$height;
-//            }else{
-//                $centre=$width>=$length?$width:$length;
-//                $min=$width<$length?$width:$length;
-//            }
-//        }else{
-//            $max=0;$centre=0;$min=0;
-//        }
-//        $apiController=new \App\Http\Controllers\api\thirdPart\flux\PackageController();
-//        if ($package){
-//            $packageController=new \App\Http\Controllers\PackageController();
-//            $package->fetchPaperBox($max,$centre,$min,$package->owner_id);
-//            //处理活动波次
-//            if ($package->batch_rule&&strstr($package->batch_rule,'组合')){
-//                $packageController->syncBatch($package->batch_number,$request['weight'],$max,$centre,$min,$reqDate,$package['paper_box_id']);
-//            }else{
-//                $package->measuring_machine_id=$measuringMachine->id;
-//                $package->weight=$request['weight'];
-//                $package->length=$max;
-//                $package->width=$centre;
-//                $package->height=$min;
-//                $package->bulk=$max*$centre*$min;
-//                $package->weighed_at=$reqDate;
-//                $package->status="未上传";
-//                app('LogService')->log(__METHOD__,'Batch_'.__FUNCTION__,json_encode($package),null);
-//                $package->save();
-//                $result=$apiController->accomplishToWMS($package);
-//                if ($result['result']){
-//                    if ($package->status=="记录异常")$package->status="已上传异常";
-//                    else $package->status="已上传";
-//                }else{
-//                    $package->status="上传异常";
-//                }
-//                $package->save();
-//            }
-//            if ($package->order_code){
-//                $waybill=Waybill::where('wms_bill_number',$package->order_code)->where('status','!=','已完结')
-//                    ->where('status','!=','无模型')->first();
-//                if ($waybill){
-//                    $waybill->warehouse_weight_other=$package->weight;
-//                    $waybill->warehouse_weight_unit_id_other=1;
-//                    $waybill->update();
-//                }
-//            }
-//            event(new WeighedEvent($package));
-//            $response=["msg"=>"保存成功",
-//                        "code"=>200,
-//                        "data"=>true,
-//                        "serverMsg"=>null,
-//                        "requestor"=>[
-//                                "requestor"=>"1",
-//                                "eventCode"=>"0",
-//                                "reqDate"=>$reqDate,
-//                                "resDate"=>Carbon::now()]
-//                        ];
-//            app('LogService')->log(__METHOD__,'weightApi'.__FUNCTION__,json_encode($request).'|'.json_encode($response),null);
-//            return json_encode($response,JSON_UNESCAPED_UNICODE);
-//        }
-//        if (!$package){
-//            $logisticNumber=$request['barcode'];
-//            $createPackage=new Package([
-//                'logistic_number'=>$logisticNumber,
-//                'delivery_number'=>$logisticNumber,
-//                'measuring_machine_id'=>$measuringMachine->id,
-//                'weight'=>$request['weight'],
-//                'length'=>$max,
-//                'width'=>$centre,
-//                'height'=>$min,
-//                'bulk'=>$max*$centre*$min,
-//                'weighed_at'=>$reqDate,
-//                'status'=>"未下发",
-//            ]);
-//            $createPackage->fetchAllFromOracle();
-//            $createPackage->fetchPaperBox($max, $centre, $min);
-//            $result=$apiController->accomplishToWMS($createPackage);
-//            if(!$result['result']){
-//                app('LogService')->log(__METHOD__,'weightApi'.__FUNCTION__,json_encode($request).'||'.json_encode($createPackage),null);
-//                $response=["msg"=>"写入WMS失败!","code"=>500,"data"=>null];
-//                return json_encode($response,JSON_UNESCAPED_UNICODE);
-//            }
-//            if ($createPackage->save()){
-//                $measuringMachine->touch();
-//                MeasuringMachineQueue::dispatch($measuringMachine)->delay(Carbon::now()->addMinutes(30));
-//                MarkPackageExcepted::dispatch($createPackage)->delay(Carbon::now()->addMinutes(1440));
-//                event(new WeighedEvent($createPackage));
-//                $response=["msg"=>"保存成功",
-//                    "code"=>200,
-//                    "data"=>true,
-//                    "serverMsg"=>null,
-//                    "requestor"=>[
-//                        "requestor"=>"1",
-//                        "eventCode"=>"0",
-//                        "reqDate"=>$reqDate,
-//                        "resDate"=>Carbon::now()]
-//                ];
-//                app('LogService')->log(__METHOD__,'weightApi'.__FUNCTION__,json_encode($request).'||'.json_encode($response),null);
-//                return json_encode($response,JSON_UNESCAPED_UNICODE);
-//            }
-//
-//            $response=["msg"=>"保存时发生错误(未下发)!","code"=>500,"data"=>null];
-//            app('LogService')->log(__METHOD__,'weightApi(ERROR)'.__FUNCTION__,json_encode($request).'||'.json_encode($response),null);
-//            return json_encode($response,JSON_UNESCAPED_UNICODE);
-//        }
-//    }
-
-    public function new_(Request $requestInitial){
-        $request=[];
-        foreach ($requestInitial->all() as $k=>$v){
-            $request[strtolower($k)]=$v;
+    public function new_(Request $requestInitial)
+    {
+        $request = [];
+        foreach ($requestInitial->all() as $k => $v) {
+            $request[strtolower($k)] = $v;
         }
-//        $reqDate=isset($request['time'])?$request['time']:Carbon::now();
-        $reqDate=Carbon::now()->format(Carbon::DEFAULT_TO_STRING_FORMAT);
-        $errors=$this->validatorWeight($request)->errors();
+        $weight_at = Carbon::now()->format(Carbon::DEFAULT_TO_STRING_FORMAT);
+        $errors = $this->validatorWeight($request)->errors();
 
-        if (count($errors)>0){
-            app('LogService')->log(__METHOD__,'error'.__FUNCTION__,json_encode($request).'||'.json_encode($errors),null);
-            return json_encode(["msg"=>$errors,"code"=>500,"data"=>null]);
+        if (count($errors) > 0) {
+            app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, json_encode($request) . '||' . json_encode($errors), null);
+            return json_encode(["msg" => $errors, "code" => 500, "data" => null]);
         }
 
-        $id = $request['id']??'无ID设备';
-        $measuringMachine=MeasuringMachine::query()->firstOrCreate(['code'=> $id]);
-        $measuringMachine->turnOn();
-        $measuringMachine->turnOffInMinutes(30);
+        $request['weight_at'] = $weight_at;
+        /** @var HaoChuangWeightService $service */
+        $service = app(HaoChuangWeightService::class);
+        $response = $service->new($request);
+        if ($response['code'] == 500)
+            LogService::log(__CLASS__, $service->name, '称重失败!' . json_encode($request['msg'] ?? '') . json_encode($request));
+        else
+            LogService::log(__CLASS__, $service->name, '称重成功!' . json_encode($request));
 
-        /** @var OrderPackage $package */
-        $package=OrderPackage::query()->where('logistic_number',$request['barcode'])->first();
-
-        $edges=[$request['length']??0,$request['width']??0,$request['height']??0];
-        rsort($edges);
-        $fluxController=new \App\Http\Controllers\api\thirdPart\flux\PackageController();
-        if ($package){
-            $package['measuring_machine_id']=$measuringMachine->id;
-            $package['weight']=$request['weight'];
-            $package['length']=$edges[0];
-            $package['width']=$edges[1];
-            $package['height']=$edges[2];
-            $package['weighed_at']=$reqDate;
-            $package->fetchAllFromOracle();
-            $package->fetchPaperBox();
-            $package['bulk']=$edges[0]*$edges[1]*$edges[2];
-            if ($package->isActivityBatch()){//处理活动波次
-                app('LogService')->log(__METHOD__,__FUNCTION__,"依波次号同步所有包裹:".json_encode($package),null);
-                $package->unifyThisMeasureUnderSameBatch();
-                $result=$fluxController->markWMSOnBatch($package['batch_number'], $request['weight']);
-                if(!$result['result']){
-                    $package->uploaded_to_wms="异常";
-                }
-            }else{
-                app('LogService')->log(__METHOD__,__FUNCTION__,"写入包裹至WMS:".json_encode($package),null);
-                try{
-                    $result=$fluxController->accomplishToWMS($package);
-                    if ($result['result']){
-                        $package->uploaded_to_wms="是";
-                    }else{
-                        $package->uploaded_to_wms="异常";
-                    }
-                }catch (\Exception $e){
-                    $package->uploaded_to_wms="否";
-                }
-            }
-            try{
-                $package->save();
-                $package->load(['order'=>function($query){
-                    $query->with('owner','logistic');
-                },'paperBox','measuringMachine']);
-                $logisticNumberController = new LogisticNumberFeatureController();
-                if (!$package->order){
-                    $package->order = new Order();
-                    $logistic=$logisticNumberController->getLogisticByFeatures($package->logistic_number);
-                    $package->order->logistic = $logistic;
-                }else{
-                    if(!$package->order->logistic){
-                        $logistic=$logisticNumberController->getLogisticByFeatures($package->logistic_number);
-                        $package->order->logistic_id = $logistic['id'];
-                        $package->order->save();
-                    }
-                }
-            }catch (\Exception $e){
-                $response=["msg"=>"称重下发修改时发生错误!".json_encode($e),"code"=>500,"data"=>null];
-                app('LogService')->log(__METHOD__,'weightApi(ERROR)'.__FUNCTION__,json_encode($request).'||'.json_encode($response).'||'.json_encode($e),null);
-                return json_encode($response,JSON_UNESCAPED_UNICODE);
-            }
-        }
-        if (!$package){
-            $logisticNumber=$request['barcode'];
-            /** @var $orderService OrderService */
-            $orderService = app('OrderService');
-            $order = $orderService->logisticNumberFirstOrCreateOrder($logisticNumber);
-            if (!$order) {
-                $response=["msg"=>"保存时发生错误(未在WMS找到该单)!","code"=>500,"data"=>null];
-                return json_encode($response,JSON_UNESCAPED_UNICODE);
-            }
-            $package=new OrderPackage([
-                'order_id' => $order->id,
-                'logistic_number'=>$logisticNumber,
-                'measuring_machine_id'=>$measuringMachine->id,
-                'weight'=>$request['weight'],
-                'length'=>$edges[0],
-                'width'=>$edges[1],
-                'height'=>$edges[2],
-                'bulk'=>$edges[0]*$edges[1]*$edges[2],
-                'weighed_at'=>$reqDate,
-                'status'=>"无",
-            ]);
-            $package->fetchAllFromOracle();
-            $package->fetchPaperBox();
-            try{
-                $package->save();
-                $package->load(['order'=>function($query){
-                    $query->with('owner','logistic');
-                },'paperBox','measuringMachine']);
-                $logisticNumberController = new LogisticNumberFeatureController();
-                if (!$package->order){
-                    $package->order = new Order();
-                    $logistic=$logisticNumberController->getLogisticByFeatures($package->logistic_number);
-                    $package->order->logistic = $logistic;
-                }else{
-                    if(!$package->order->logistic){
-                        $logistic=$logisticNumberController->getLogisticByFeatures($package->logistic_number);
-                        $package->order->logistic_id = $logistic['id'];
-                        $package->order->save();
-                    }
-                }
-            }catch (\Exception $e){
-                $response=["msg"=>$e->getMessage(),"code"=>500,"data"=>$e->getTraceAsString()];
-                app('LogService')->log(__METHOD__,'weightApi(ERROR)'.__FUNCTION__,json_encode($request).'||'.json_encode($response).'||'.$e->getTraceAsString(),null);
-                return json_encode($response,JSON_UNESCAPED_UNICODE);
-            }
-            $result=$fluxController->accomplishToWMS($package);
-            if(!$package['batch_number'])
-                FetchPackageFromOracle::dispatch($package)->delay(Carbon::now()->addMinutes(1440));
-            if(!$result['result']){
-                app('LogService')->log(__METHOD__,'weightApi'.__FUNCTION__,json_encode($request).'||'.json_encode($package),null);
-                $response=["msg"=>"写入WMS失败!","code"=>500,"data"=>null];
-                return json_encode($response,JSON_UNESCAPED_UNICODE);
-            }
-        }
-        if(!empty($package->order))
-            Waybill::setWeightByOrderCode($package->order->code,$package->weight);
-        if ($package){
-            event(new WeighedEvent($package));
-            dispatch(new WeightUpdateInstantBill($package));
-        }
-        $response=["msg"=>"保存成功",
-            "code"=>200,
-            "data"=>true,
-            "serverMsg"=>null,
-            "requestor"=>[
-                "requestor"=>"1",
-                "eventCode"=>"0",
-                "reqDate"=>$reqDate,
-                "resDate"=>Carbon::now()]
-        ];
-        app('LogService')->log(__METHOD__,__FUNCTION__,"下发写入包裹成功:".json_encode($request).'|'.json_encode($response),null);
-        return json_encode($response,JSON_UNESCAPED_UNICODE);
+        return json_encode($response);
     }
 
-    public function validatorWeight(array $request){
-        $validator=Validator::make($request,[
-            'id'=>['nullable','max:30'],
-            'barcode'=>['required','max:191'],
-            'weight'=>['required','numeric','min:0'],
-            'length'=>['nullable','numeric','min:0'],
-            'width'=>['nullable','numeric','min:0'],
-            'height'=>['nullable','numeric','min:0'],
-        ],[
-            'required'=>':attribute 为必填项',
-            'max'=>':attribute 字符过多或数值过大',
-            'min'=>':attribute 不得为负',
-            'numeric'=>':attribute 应为数字',
-        ],[]);
-        return $validator;
+
+    public function validatorWeight(array $request): \Illuminate\Contracts\Validation\Validator
+    {
+        return Validator::make($request, [
+            'id' => ['nullable', 'max:30'],
+            'barcode' => ['required', 'max:191'],
+            'weight' => ['required', 'numeric', 'min:0'],
+            'length' => ['nullable', 'numeric', 'min:0'],
+            'width' => ['nullable', 'numeric', 'min:0'],
+            'height' => ['nullable', 'numeric', 'min:0'],
+        ], [
+            'required' => ':attribute 为必填项',
+            'max' => ':attribute 字符过多或数值过大',
+            'min' => ':attribute 不得为负',
+            'numeric' => ':attribute 应为数字',
+        ], []);
     }
 
 }

+ 10 - 0
app/Http/Requests/DischargeTask/DischargeTaskRequest.php

@@ -69,6 +69,12 @@ class DischargeTaskRequest extends FormRequest
         'expenditure_unit.required' => '单位为必选项',
         'expenditure_unit_price.required' => '单价为必填项',
     ];
+    protected $uploadApiRule = [
+        'file' => 'required',
+    ];
+    protected $uploadApiMessage = [
+        'file' => 'required',
+    ];
 
     public function authorize(): bool
     {
@@ -88,6 +94,8 @@ class DischargeTaskRequest extends FormRequest
                 return $this->updateApiRules;
             case 'discharge.updateTaskFacilitatorApi':
                 return $this->updateTaskFacilitatorApiRules;
+            case 'discharge.importApi':
+                return $this->uploadApiRule;
             default :
                 return [];
         }
@@ -106,6 +114,8 @@ class DischargeTaskRequest extends FormRequest
                 return $this->updateApiMessage;
             case 'discharge.updateTaskFacilitatorApi':
                 return $this->updateTaskFacilitatorApiMessage;
+            case 'discharge.importApi':
+                return $this->uploadApiMessage;
             default :
                 return [];
         }

+ 41 - 0
app/Http/Requests/OwnerSundryFeeDetailRequest.php

@@ -0,0 +1,41 @@
+<?php
+
+namespace App\Http\Requests;
+
+class OwnerSundryFeeDetailRequest extends Request
+{
+    public function rules()
+    {
+        switch($this->method())
+        {
+            // CREATE
+            case 'POST':
+            {
+                return [
+                    // CREATE ROLES
+                ];
+            }
+            // UPDATE
+            case 'PUT':
+            case 'PATCH':
+            {
+                return [
+                    // UPDATE ROLES
+                ];
+            }
+            case 'GET':
+            case 'DELETE':
+            default:
+            {
+                return [];
+            }
+        }
+    }
+
+    public function messages()
+    {
+        return [
+            // Validation messages
+        ];
+    }
+}

+ 14 - 0
app/Http/Requests/Request.php

@@ -0,0 +1,14 @@
+<?php
+
+namespace App\Http\Requests;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+class Request extends FormRequest
+{
+    public function authorize()
+    {
+    	// Using policy for Authorization
+        return true;
+    }
+}

+ 83 - 0
app/Imports/DischargeTaskImport.php

@@ -0,0 +1,83 @@
+<?php
+
+namespace App\Imports;
+
+use App\DischargeTask;
+use App\Owner;
+use App\Services\DischargeTaskService;
+use App\Warehouse;
+use Illuminate\Support\Carbon;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\Cache;
+use Maatwebsite\Excel\Concerns\ToCollection;
+use Maatwebsite\Excel\Concerns\WithHeadingRow;
+use Maatwebsite\Excel\Imports\HeadingRowFormatter;
+
+HeadingRowFormatter::default('none');
+
+class DischargeTaskImport implements ToCollection, WithHeadingRow
+{
+    /**
+     * @param Collection $collection
+     */
+    public function collection(Collection $collection)
+    {
+        /** @var DischargeTaskService $service */
+        $service = app(DischargeTaskService::class);
+        $exception = [];
+        $numbers = [];
+        foreach ($collection as $row => $item) {
+            $index = $row + 1;
+            $message = '';
+            $owner = Owner::query()->where('name', trim($item['货主']))->first();
+            $waveHouse = Warehouse::query()->where('name', trim($item['仓库']))->first();
+            $type = array_search(trim($item['作业名称']), DischargeTask::types);
+            $unit = array_search(trim($item['单位']), DischargeTask::units);
+
+            if (array_search(trim($item['入库单']), $numbers)) $message .= '入库单号重复;';
+
+            if (!$owner) $message .= '对应货主不存在;';
+
+            if (!$waveHouse) $message .= '对应仓库不存在;';
+
+            if (!$item['入库单'] || strlen(trim('入库单')) == 0) $message .= '未输入入库单;';
+
+            if (!$item['数量'] || strlen(trim('数量')) == 0) $message .= '未输入数量;';
+
+            if (!$item['单价'] || strlen(trim('单价')) == 0) $message .= '未输入单价;';
+
+            if (!$item['单位'] || strlen(trim('单位')) == 0) $message .= '未输入单位;';
+
+            if (isset($type) && $type != 0) $message .= '指定作业类型错误;';
+
+            if (!$item['作业名称']) $message .= '未指定作业类型';
+
+            if (DischargeTask::query()->where('numbers',$item['入库单'])->exists()) $message .= '入库单号已存在;';
+
+            if (strlen($message) > 0) {
+                $exception[] = "第{$index}行卸货任务创建失败:" . $message;
+                continue;
+            }
+            $params = [
+                'owner_id' => $owner->id,
+                'warehouse_id' => $waveHouse->id,
+                'type' => $type,
+                'numbers' => trim($item['入库单']),
+                'income_amount' => $item['数量'],
+                'income_unit_price' => $item['单价'],
+                'income_unit' => $unit,
+                'income_total_cost' => $item['数量'] * $item['单价'],
+                'status' => 0,
+                'income_remark' => $item['备注'],
+                'income_at' => $item['预约日期'] ?formatExcelDateTime($item['预约日期']): Carbon::now()->format(Carbon::DEFAULT_TO_STRING_FORMAT)
+            ];
+            try {
+                $service->createTask($params, false);
+                $numbers[] = trim($item['入库单']);
+            } catch (\Exception $e) {
+                $exception[] = "第{$index}行创建失败:创建异常";
+            }
+        }
+        Cache::put('exception', $exception, 86400);
+    }
+}

+ 58 - 0
app/Jobs/LogisticAliJiSuSync.php

@@ -0,0 +1,58 @@
+<?php
+
+namespace App\Jobs;
+
+use App\Services\LogisticAliJiSuApiService;
+use App\Services\LogService;
+use App\Services\OrderPackageReceivedSyncService;
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
+
+class LogisticAliJiSuSync implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+
+    /**
+     * @var $logisticAliJiSuApiService LogisticAliJiSuApiService
+     * @var $orderPackageReceivedSyncService OrderPackageReceivedSyncService
+     * @var $logistic_number string
+     */
+
+    protected $logistic_number;
+    protected $logisticAliJiSuApiService;
+    protected $orderPackageReceivedSyncService;
+
+    /**
+     * Create a new job instance.
+     *
+     * @param $logistic_number
+     */
+    public function __construct($logistic_number)
+    {
+        $this->logistic_number=$logistic_number;
+    }
+
+    /**
+     * Execute the job.
+     *
+     * @return void
+     */
+    public function handle()
+    {
+        LogService::log(LogisticAliJiSuSync::class, "{$this->logistic_number}-JOB-AliJiSu", '');
+        $this->logisticAliJiSuApiService = app('LogisticAliJiSuApiService');
+        try {
+            $response = $this->logisticAliJiSuApiService->query($this->logistic_number);
+            if ($response && $response->status==0){
+                $format = $this->logisticAliJiSuApiService->format($response);
+                $this->orderPackageReceivedSyncService = app('OrderPackageReceivedSyncService');
+                if (count($format)>0 && $format['logistic_number']??false) $this->orderPackageReceivedSyncService->update([$format]);
+            }
+        } catch (\Exception $e) {
+            app('LogService')->log(__METHOD__, __FUNCTION__, "阿里极速数据同步快递数据 ERROR " . ' || ' . json_encode($this->logistic_number) . ' || ' . json_encode($e->getMessage()) . ' || ' . json_encode($e->getTraceAsString()));
+        }
+    }
+}

+ 5 - 2
app/Jobs/LogisticSFSync.php

@@ -12,6 +12,10 @@ use Illuminate\Queue\SerializesModels;
 
 class LogisticSFSync implements ShouldQueue
 {
+    public $tries = 2;
+
+    public $timeout = 10;
+
     use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
 
     public $logistic_number;
@@ -40,8 +44,7 @@ class LogisticSFSync implements ShouldQueue
      */
     public function handle()
     {
-        ini_set('max_execution_time', 60);
-        LogService::log(LogisticSFSync::class, "{$this->logistic_number}-JOB-SF", '');
+        LogService::log(LogisticSFSync::class, "JOB-SF", $this->logistic_number);
         $this->logisticSFService = app('LogisticSFService');
         $formedData = $this->logisticSFService->get([$this->logistic_number]);
         $this->orderPackageReceivedSyncService = app('OrderPackageReceivedSyncService');

+ 10 - 5
app/Jobs/LogisticYDSync.php

@@ -13,16 +13,22 @@ use Illuminate\Queue\SerializesModels;
 
 class LogisticYDSync implements ShouldQueue
 {
+    public $tries = 2;
+
+    public $timeout = 10;
+
     use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
     /**
-     * @var $logisticYDService LogisticYDService
+     *
      * @var $orderPackageReceivedSyncService OrderPackageReceivedSyncService
      * @var $orderPackageReceivedSyncService OrderPackageReceivedSyncService
      * @var $logistic_number string
      */
 
     protected $logistic_number;
-
+    /**
+     * @var $logisticYDService LogisticYDService
+     */
     protected $logisticYDService;
     protected $orderPackageReceivedSyncService;
 
@@ -43,15 +49,14 @@ class LogisticYDSync implements ShouldQueue
      */
     public function handle()
     {
-        ini_set('max_execution_time', 60);
-        LogService::log(LogisticYDSync::class, "{$this->logistic_number}-JOB-YD", '');
+        LogService::log(LogisticYDSync::class, "JOB-YD", $this->logistic_number);
         $this->logisticYDService = app('LogisticYDService');
         //先订阅订单
         $this->logisticYDService->registerApi([$this->logistic_number]);
         //查询订单路由信息
         $nativeResponse = $this->logisticYDService->query($this->logistic_number);
         //格式化信息
-        $formattedData = $this->logisticYDService->format($nativeResponse);
+        $formattedData = $this->logisticYDService->format($nativeResponse,$this->logistic_number);
         $this->orderPackageReceivedSyncService = app('OrderPackageReceivedSyncService');
         //更新数据
         $this->orderPackageReceivedSyncService->update([$formattedData]);

+ 11 - 5
app/Jobs/LogisticYTOSync.php

@@ -14,7 +14,11 @@ use Illuminate\Queue\SerializesModels;
 
 class LogisticYTOSync implements ShouldQueue
 {
+    public $tries = 2;
+    public $timeout = 10;
+
     use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+
     /**
      * @var $logisticYTOService LogisticYTOService
      * @var $orderPackageReceivedSyncService OrderPackageReceivedSyncService
@@ -22,7 +26,6 @@ class LogisticYTOSync implements ShouldQueue
      */
 
     protected $logistic_number;
-
     protected $logisticYTOService;
     protected $orderPackageReceivedSyncService;
 
@@ -43,12 +46,15 @@ class LogisticYTOSync implements ShouldQueue
      */
     public function handle()
     {
-        ini_set('max_execution_time', 60);
-        LogService::log(LogisticYTOSync::class, "{$this->logistic_number}-JOB-YTO", '');
+        LogService::log(LogisticYTOSync::class, "JOB-YTO", $this->logistic_number);
         $this->logisticYTOService = app('LogisticYTOService');
         $nativeResponse = $this->logisticYTOService->query($this->logistic_number);
-        $formattedData = $this->logisticYTOService->format($nativeResponse);
+        $formattedData = $this->logisticYTOService->format($nativeResponse,$this->logistic_number);
         $this->orderPackageReceivedSyncService = app('OrderPackageReceivedSyncService');
-        $this->orderPackageReceivedSyncService->update([$formattedData]);
+        if (count($formattedData)>0 && $formattedData['logistic_number']??false){
+            $this->orderPackageReceivedSyncService->update([$formattedData]);
+        }else{
+            LogService::log(LogisticYTOService::class, "YTO快递无快递单号异常", $formattedData);
+        }
     }
 }

+ 23 - 151
app/Jobs/LogisticZopSync.php

@@ -2,10 +2,8 @@
 
 namespace App\Jobs;
 
-use App\library\zop\ZopClient;
-use App\library\zop\ZopProperties;
-use App\library\zop\ZopRequest;
-use App\OrderPackage;
+
+use App\Services\LogisticZopService;
 use App\Services\LogService;
 use App\Services\OrderPackageReceivedSyncService;
 use Illuminate\Bus\Queueable;
@@ -13,13 +11,26 @@ use Illuminate\Contracts\Queue\ShouldQueue;
 use Illuminate\Foundation\Bus\Dispatchable;
 use Illuminate\Queue\InteractsWithQueue;
 use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Carbon;
 
 class LogisticZopSync implements ShouldQueue
 {
+    public $tries = 2;
+    public $timeout = 10;
+
     use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
 
+    /**
+     * @var string $logistic_number
+     */
     protected $logistic_number;
+//    /**
+//     * @var LogisticZopService $logistic_zop_service
+//     */
+//    protected $logistic_zop_service;
+    /**
+     * @var  OrderPackageReceivedSyncService $order_package_received_sync_service
+     */
+    protected $order_package_received_sync_service;
 
     /**
      * Create a new job instance.
@@ -29,6 +40,8 @@ class LogisticZopSync implements ShouldQueue
     public function __construct($logistic_number)
     {
         $this->logistic_number = $logistic_number;
+//        $this->logistic_zop_service = app('LogisticZopService');
+        $this->order_package_received_sync_service = app('OrderPackageReceivedSyncService');
     }
 
     /**
@@ -38,151 +51,10 @@ class LogisticZopSync implements ShouldQueue
      */
     public function handle()
     {
-        ini_set('max_execution_time', 60);
-        LogService::log(LogisticZopSync::class, "{$this->logistic_number}-JOB-ZOP", '');
-        $zopResult = [];
-        $response = $this->sentRequestToZT();
-        if(is_null($response)) return;
-        if ($response->status) {
-            $zopResult[] = [
-                'routes' => $response->result,
-                'logisticNum' => $this->logistic_number,
-            ];
-        }
-        $result = $this->transformRoutes($zopResult);
-        /* @var $orderPackageReceivedSyncService OrderPackageReceivedSyncService */
-        $orderPackageReceivedSyncService = app('OrderPackageReceivedSyncService');
-        !empty($result) && $orderPackageReceivedSyncService->update($result);
-    }
-
-    /**
-     * 转换快递路由信息
-     * @param array $routs 快递路由
-     * @return array
-     */
-    public function transformRoutes(array $routs): array
-    {
-        $result = [];
-        foreach ($routs as $route) {
-            $result = $this->transformRouteItem($route, $result);
-        }
-        return $result;
-    }
-
-    /**
-     * @param $route
-     * @param array $result
-     * @return array
-     */
-    private function transformRouteItem($route, array $result): array
-    {
-        $resultItem = [];
-        $resultItem['logistic_number'] = $route['logisticNum'];
-        $itemRoutes = $route['routes'];
-        $lastRoute = null;
-        if (!empty($itemRoutes)) {
-            $lastRoute = $itemRoutes[count($itemRoutes) - 1];
-            $resultItem = $this->getNormalStatusAndReceivedAt($lastRoute, $resultItem);
-            $resultItem['transfer_status'] = $this->getTransferStatus($itemRoutes);
-        } else {
-            $resultItem['status'] = null;
-            $resultItem['transfer_status'] = [];
-        }
-        if (!array_key_exists('status', $resultItem)) {
-            $resultItem['status'] = null;
-            $resultItem['transfer_status'] = [];
-        }
-        try {
-            $orderPackageReceivedSyncService = app('OrderPackageReceivedSyncService');
-            $exceptionData = $orderPackageReceivedSyncService->setExceptionType($resultItem, $lastRoute ? $lastRoute->scanDate / 1000 : null);
-            $resultItem['exception_type'] = $exceptionData['exception_type'];
-            $resultItem['exception'] = $exceptionData['exception'];
-        } catch (\Exception $e) {
-        }
-        if ($resultItem['status'] == null) {
-            unset($resultItem['status']);
-            unset($resultItem['transfer_status']);
-        }
-        //如果没有发现额外的异常,且查询到物流轨迹,将异常置为无
-        if (!array_key_exists('exception', $resultItem)
-            && !array_key_exists('exception_type', $resultItem)
-            && array_key_exists('transfer_status', $resultItem)
-        ) {
-            $resultItem['exception_type'] = '无';
-            $resultItem['exception'] = '否';
-        }
-        $resultItem['routes_length'] = array_key_exists('transfer_status', $resultItem) ? count($resultItem['transfer_status']) : 0;
-        $result[] = $resultItem;
-        return $result;
-    }
-    /**
-     * 正常的状态与签收时间
-     * @param $lastRoute
-     * @param array $resultItem
-     * @return array
-     */
-    private function getNormalStatusAndReceivedAt($lastRoute, array $resultItem): array
-    {
-        switch ($lastRoute->scanType) {
-            case '收件':
-                $resultItem['status'] = '已揽收';
-                break;
-            case '到件':
-            case '发件':
-                $resultItem['status'] = '在途';
-                break;
-            case 'ARRIVAL':
-            case '派件':
-                $resultItem['status'] = '派送中';
-                break;
-            case 'SIGNED':
-            case '签收':
-                $resultItem['status'] = '已收件';
-                $resultItem['received_at'] = Carbon::parse($lastRoute->scanDate / 1000)->toDateTimeString();
-                break;
-            default:
-                $resultItem['status'] = '无';
-                break;
-        }
-        return $resultItem;
-    }
-
-    /**
-     * @param $itemRoutes
-     * @return array
-     */
-    private function getTransferStatus($itemRoutes): array
-    {
-        $transfer_status = [];
-        foreach ($itemRoutes as $item) {
-            $data = [];
-            $data['accept_time'] = Carbon::parse($item->scanDate / 1000)->toDateTimeString();
-            $scanSite = $item->scanSite;
-            $data['accept_address'] = $scanSite->prov . '-' . $scanSite->name;
-            $data['remark'] = $item->scanType;
-
-            $transfer_status[] = $data;
-        }
-        return $transfer_status;
-    }
-
-    /**
-     * 发送请求到中通
-     * @return mixed
-     */
-    private function sentRequestToZT()
-    {
-        $url = config('api_logistic.ZTO.url');
-        $xAppKey = config('api_logistic.ZTO.x-appKey');
-        $appSecret = config('api_logistic.ZTO.appSecret');
-        $properties = new ZopProperties($xAppKey, $appSecret);
-        $client = new ZopClient($properties);
-        $request = new ZopRequest();
-
-        $request->setUrl($url);
-        $request->setBody(json_encode([
-            'billCode' => $this->logistic_number,
-        ],JSON_UNESCAPED_UNICODE));
-        return json_decode($client->execute($request));
+        LogService::log(LogisticZopSync::class, "JOB-ZOP", $this->logistic_number);
+        $logistic_zop_service = new LogisticZopService();
+        $nativeResponse = $logistic_zop_service->query($this->logistic_number);
+        $formatted_data = $logistic_zop_service->format($nativeResponse,$this->logistic_number);
+        $this->order_package_received_sync_service->update([$formatted_data]);
     }
 }

+ 9 - 1
app/Listeners/AddOrUpdateOrderIssuesListener.php

@@ -37,8 +37,16 @@ class AddOrUpdateOrderIssuesListener implements ShouldQueue
                 'exception_type' => '其他',
                 'exception' => '是',
             ]);
+
+        //如果问题件改为 完结订单 吧异常该为无
+        OrderPackage::query()->whereIn('order_id',
+            OrderIssue::query()->whereIn('order_id', $event->order_ids)->where('final_status', '已解决')->pluck('order_id'))
+            ->update([
+                'exception_type' => '无',
+                'exception' => '否',
+            ]);
         //更新统计数据
-        $orderPackageIds = OrderPackage::query()->whereIn('order_id', $order_ids)->pluck('id');
+        $orderPackageIds = OrderPackage::query()->whereIn('order_id', $event->order_ids)->pluck('id');
         event(new UpdateOrderPackageExceptionListenerEvent($orderPackageIds));
     }
 }

+ 1 - 1
app/Logistic.php

@@ -17,7 +17,7 @@ class Logistic extends Model
     use ModelLogChanging;
     use SoftDeletes;
     use ModelTimeFormat;
-    protected $fillable = ['name','code',"type","mobile","remark","delivery_fee","is_bunched","english_name"];
+    protected $fillable = ['name','code',"type","mobile","remark","delivery_fee","is_bunched","english_name",'belong_company'];
 
 
     static function nameById($id){

+ 21 - 0
app/Observers/OwnerSundryFeeDetailObserver.php

@@ -0,0 +1,21 @@
+<?php
+
+namespace App\Observers;
+
+use App\OwnerSundryFeeDetail;
+
+// creating, created, updating, updated, saving,
+// saved,  deleting, deleted, restoring, restored
+
+class OwnerSundryFeeDetailObserver
+{
+    public function creating(OwnerSundryFeeDetail $owner_sundry_fee_detail)
+    {
+        //
+    }
+
+    public function updating(OwnerSundryFeeDetail $owner_sundry_fee_detail)
+    {
+        //
+    }
+}

+ 14 - 1
app/OrderCountingRecord.php

@@ -5,12 +5,25 @@ namespace App;
 use Illuminate\Database\Eloquent\Model;
 
 use App\Traits\ModelLogChanging;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
 
 class OrderCountingRecord extends Model
 {
     use ModelLogChanging;
 
     //
-    protected $fillable = ['owner_id','shop_id' ,'warehouse_id' ,'logistic_id' ,'date_target' ,'counting_unit' ,'amount','year','month','week'];
+    protected $fillable = ['owner_id' ,'warehouse_id' ,'logistic_id' ,'date_target' ,'counting_unit' ,'amount','year','month'];
+
+    public  $timestamps = false;
+
+    public function logistic(): BelongsTo
+    {
+        return $this->belongsTo(Logistic::class);
+    }
+
+    public function warehouse(): BelongsTo
+    {
+        return $this->belongsTo(Warehouse::class);
+    }
 
 }

+ 22 - 0
app/OrderPackageReceivedSyncRecord.php

@@ -0,0 +1,22 @@
+<?php
+
+namespace App;
+
+use Illuminate\Database\Eloquent\Model;
+
+use App\Traits\ModelLogChanging;
+
+class OrderPackageReceivedSyncRecord extends Model
+{
+    use ModelLogChanging;
+
+    //
+    public $fillable = ['logistic_name', 'recorded_at', 'succeed_count', 'failed_count'];
+
+    public $timestamps = false;
+
+    public function scopeFilter($query, $filters)
+    {
+        return $filters->apply($query);
+    }
+}

+ 6 - 0
app/Owner.php

@@ -4,6 +4,7 @@ namespace App;
 
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\HasMany;
 use Illuminate\Support\Facades\Auth;
 
 /**
@@ -209,4 +210,9 @@ class Owner extends Model
             ->select(DB::raw(1))->whereNotNull("operation")
             ->where("operation","!=","");
     }
+
+    public function ownerSundryFeeDetail(): HasMany
+    {
+        return $this->hasMany(OwnerSundryFeeDetail::class);
+    }
 }

+ 12 - 0
app/OwnerFeeDetail.php

@@ -6,6 +6,8 @@ use App\Services\ProcessMethodService;
 use Illuminate\Database\Eloquent\Model;
 
 use App\Traits\ModelLogChanging;
+use Illuminate\Database\Eloquent\Relations\HasMany;
+use Illuminate\Database\Eloquent\Relations\HasOne;
 
 class OwnerFeeDetail extends Model
 {
@@ -61,4 +63,14 @@ class OwnerFeeDetail extends Model
     {   //快递费子项
         return $this->hasMany(OwnerFeeDetailLogistic::class,"owner_fee_detail_id","id");
     }
+
+    public function ownerLogisticFeeDetails(): HasMany
+    {
+        return $this->hasMany(OwnerLogisticFeeDetail::class);
+    }
+
+    public function ownerLogisticFeeDetail(): HasOne
+    {
+        return $this->hasOne(OwnerLogisticFeeDetail::class,'logistic_bill','logistic_bill');
+    }
 }

+ 6 - 0
app/OwnerFeeDetailLogistic.php

@@ -5,6 +5,7 @@ namespace App;
 use Illuminate\Database\Eloquent\Model;
 
 use App\Traits\ModelLogChanging;
+use Illuminate\Database\Eloquent\Relations\HasOne;
 
 class OwnerFeeDetailLogistic extends Model
 {
@@ -20,4 +21,9 @@ class OwnerFeeDetailLogistic extends Model
     {   //快递
         return $this->belongsTo(Logistic::class);
     }
+
+    public function ownerLogisticFeeDetail(): HasOne
+    {
+        return $this->hasOne(OwnerLogisticFeeDetail::class, 'logistic_bill', 'logistic_bill');
+    }
 }

+ 26 - 0
app/OwnerLogisticFeeDetail.php

@@ -0,0 +1,26 @@
+<?php
+
+namespace App;
+
+use Illuminate\Database\Eloquent\Model;
+
+use App\Traits\ModelLogChanging;
+use Illuminate\Database\Eloquent\Relations\HasOne;
+
+class OwnerLogisticFeeDetail extends Model
+{
+    use ModelLogChanging;
+
+    public $fillable = ['owner_fee_detail_id', 'logistic_bill', 'initial_weight', 'initial_weight_price', 'additional_weight', 'additional_price'];
+
+    public function ownerFeeDetail(): HasOne
+    {
+        return $this->hasOne(OwnerFeeDetail::class);
+    }
+
+
+    public function ownerFeeDetailLogistic(): HasOne
+    {
+        return $this->hasOne(OwnerFeeDetailLogistic::class,'logistic_bill', 'logistic_bill');
+    }
+}

+ 14 - 0
app/OwnerLogisticFeeReport.php

@@ -0,0 +1,14 @@
+<?php
+
+namespace App;
+
+use Illuminate\Database\Eloquent\Model;
+
+use App\Traits\ModelLogChanging;
+
+class OwnerLogisticFeeReport extends Model
+{
+    use ModelLogChanging;
+
+    //
+}

+ 70 - 0
app/OwnerSundryFeeDetail.php

@@ -0,0 +1,70 @@
+<?php
+
+namespace App;
+
+use App\Traits\ModelLogChanging;
+use App\Traits\ModelTimeFormat;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
+use Illuminate\Database\Eloquent\Relations\HasOne;
+use Illuminate\Database\Eloquent\SoftDeletes;
+
+class OwnerSundryFeeDetail extends Model
+{
+    use ModelLogChanging;
+    use ModelTimeFormat;
+    use SoftDeletes;
+
+    protected $fillable = ['type', 'fee_explain', 'remark', 'fee', 'changable','owner_id'];
+
+
+    static public $enums = [
+        'type' => [
+            '' => 0,
+            '材料' => 1,
+            '垫付' => 2,
+            '人工' => 3,
+            '其他' => 4,
+        ],
+        'changable' => [
+            '' => 0,
+            '未冻结' => 1,
+            '已冻结' => 2,
+        ],
+    ];
+
+    function __construct(array $attributes = [])
+    {
+        foreach (self::$enums as &$enum) {
+            $enum = $enum + array_flip($enum);
+        }
+        parent::__construct($attributes);
+    }
+
+    public function getTypeAttribute($value)
+    {
+        if (!$value) return '';
+        return self::$enums['type'][$value];
+    }
+
+    public function setTypeAttribute($value)
+    {
+        if (!$value) return 0;
+        $this->attributes['type'] = self::$enums['type'][$value];
+    }
+
+    public function getRouteKey()
+    {
+        return 'id';
+    }
+
+    public function owner(): BelongsTo
+    {
+        return $this->belongsTo(Owner::class);
+    }
+
+    public function scopeFilter($query, $filters)
+    {
+        return $filters->apply($query);
+    }
+}

+ 20 - 0
app/Policies/OwnerSundryFeeDetailPolicy.php

@@ -0,0 +1,20 @@
+<?php
+
+namespace App\Policies;
+
+use App\User;
+use App\OwnerSundryFeeDetail;
+
+class OwnerSundryFeeDetailPolicy extends Policy
+{
+    public function update(User $user, OwnerSundryFeeDetail $owner_sundry_fee_detail)
+    {
+        // return $owner_sundry_fee_detail->user_id == $user->id;
+        return true;
+    }
+
+    public function destroy(User $user, OwnerSundryFeeDetail $owner_sundry_fee_detail)
+    {
+        return true;
+    }
+}

+ 22 - 0
app/Policies/Policy.php

@@ -0,0 +1,22 @@
+<?php
+
+namespace App\Policies;
+
+use Illuminate\Auth\Access\HandlesAuthorization;
+
+class Policy
+{
+    use HandlesAuthorization;
+
+    public function __construct()
+    {
+        //
+    }
+
+    public function before($user, $ability)
+	{
+	    // if ($user->isSuperAdmin()) {
+	    // 		return true;
+	    // }
+	}
+}

+ 174 - 87
app/Providers/AppServiceProvider.php

@@ -3,6 +3,12 @@
 namespace App\Providers;
 
 use App\Http\Controllers\Controller;
+use App\Jobs\LogisticSFSync;
+use App\Jobs\LogisticYDSync;
+use App\Jobs\LogisticYTOSync;
+use App\Jobs\LogisticZopSync;
+use App\LaborCompany;
+use App\Observers\LaborCompanyObserver;
 use App\Services\AuthorityService;
 use App\Services\BatchService;
 use App\Services\CacheService;
@@ -26,8 +32,10 @@ use App\Services\InventoryCompareService;
 use App\Services\LaborReportsCountingRecordService;
 use App\Services\LogisticSFService;
 use App\Services\LogisticYTOService;
+use App\Services\LogisticZopService;
 use App\Services\LogService;
 use App\Services\MaterialBoxService;
+use App\Services\NewOrderCountingRecordService;
 use App\Services\OracleBasCustomerService;
 use App\Services\OracleBasSkuService;
 use App\Services\OracleDocAsnDetailService;
@@ -43,6 +51,7 @@ use App\Services\OracleActAllocationDetailService;
 use App\Services\OrderIssueProcessLogService;
 use App\Services\OrderIssueRejectedBillService;
 use App\Services\OrderIssueService;
+use App\Services\OrderPackageReceivedSyncRecordService;
 use App\Services\OrderPackageReceivedSyncService;
 use App\Services\OrderPackageService;
 use App\Services\OrderService;
@@ -104,9 +113,14 @@ use App\Services\UserWorkgroupService;
 use App\Services\DischargeTaskService;
 use App\Services\DeliveryAppointmentService;
 use App\Services\StationCacheShelfGridService;
+use App\Services\weight\GoodScanWeightService;
+use App\Services\weight\HaoChuangWeightService;
+use App\Services\weight\HengLiWeightService;
 use App\Services\PrintPartService;
 use App\Services\PrintTemplateService;
 use Illuminate\Queue\Events\JobFailed;
+use Illuminate\Queue\Events\JobProcessed;
+use Illuminate\Queue\Events\JobProcessing;
 use Illuminate\Support\Facades\Queue;
 use Illuminate\Support\Facades\Schema;
 use Illuminate\Support\Facades\View;
@@ -119,7 +133,11 @@ use App\Services\OrderPackageExceptionTypeCountingRecordService;
 use App\Services\LogisticYDService;
 use App\Services\ForeignZhenCangService;
 use App\Services\StorageService;
+use App\Services\LogisticAliJiSuApiService;
 use App\Services\CommodityMaterialBoxModelService;
+use App\Services\OwnerLogisticFeeDetailService;
+use App\Services\OwnerLogisticFeeReportService;
+use App\Services\LaborCompanyService;
 
 class AppServiceProvider extends ServiceProvider
 {
@@ -143,7 +161,13 @@ class AppServiceProvider extends ServiceProvider
         //
         Schema::defaultStringLength(191);
         Queue::failing(function (JobFailed $event) {
-            (new Controller())->log(__METHOD__,'EventError_',json_encode($event));
+            (new Controller())->log(__METHOD__, 'EventError_', json_encode($event));
+            $payload = $event->job->payload();
+            $displayName = $payload['displayName'];
+            //快递信息同步失败计数
+            if ($this->isLogisticSyncJob($displayName)) {
+                $this->logisticSyncRecord($displayName, 'failed_count');
+            }
         });
         //扩展身份证验证规则
         Validator::extend('identity_cards', function($attribute, $value, $parameters) {
@@ -160,11 +184,25 @@ class AppServiceProvider extends ServiceProvider
         \Illuminate\Database\Eloquent\Builder::macro('sql', function(){
             return ($this->getQuery()->sql());
         });
+
+        Queue::before(function (JobProcessing $event) {
+
+        });
+        //任务成功后的回调
+        Queue::after(function (JobProcessed $event) {
+            //快递信息同步成功计数
+            $payload = $event->job->payload();
+            $displayName = $payload['displayName'];
+            if ($this->isLogisticSyncJob($displayName)) {
+                $this->logisticSyncRecord($displayName, 'succeed_count');
+            }
+        });
     }
 
     private function loadingService(){
         app()->singleton('AllInventoryService',AllInventoryService::class);
         app()->singleton('AuthorityService',AuthorityService::class);
+        app()->singleton('NewOrderCountingRecordService',NewOrderCountingRecordService::class);
         app()->singleton('BatchService',BatchService::class);
         app()->singleton('BatchUpdateService', BatchUpdateService::class);
         app()->singleton('CacheService',CacheService::class);
@@ -175,8 +213,6 @@ class AppServiceProvider extends ServiceProvider
         app()->singleton('CommodityService', CommodityService::class);
         app()->singleton('ConfigurationService',ConfigurationService::class);
         app()->singleton('CustomerLogService',CustomerLogService::class);
-        app()->singleton('CustomerLogService',CustomerLogService::class);
-        app()->singleton('CustomerLogStatusService',CustomerLogStatusService::class);
         app()->singleton('CustomerLogStatusService',CustomerLogStatusService::class);
         app()->singleton('CustomerService',CustomerService::class);
         app()->singleton('DataHandlerService',DataHandlerService::class);
@@ -189,94 +225,145 @@ class AppServiceProvider extends ServiceProvider
         app()->singleton('FeatureService',FeatureService::class);
         app()->singleton('ForeignHaiRoboticsService',ForeignHaiRoboticsService::class);
         app()->singleton('ForeignZhenCangService',ForeignZhenCangService::class);
-        app()->singleton('InventoryAccountMissionService',InventoryAccountMissionService::class);
-        app()->singleton('InventoryCompareService',InventoryCompareService::class);
-        app()->singleton('InventoryDailyLogService',InventoryDailyLogService::class);
-        app()->singleton('LaborReportsCountingRecordService',LaborReportsCountingRecordService::class);
-        app()->singleton('LogService',LogService::class);
-        app()->singleton('LogisticSFService',LogisticSFService::class);
-        app()->singleton('LogisticService',LogisticService::class);
-        app()->singleton('LogisticYDService',LogisticYDService::class);
-        app()->singleton('LogisticYTOService',LogisticYTOService::class);
-        app()->singleton('MaterialBoxService',MaterialBoxService::class);
-        app()->singleton('OracleActAllocationDetailService',OracleActAllocationDetailService::class);
-        app()->singleton('OracleBasCustomerService',OracleBasCustomerService::class);
-        app()->singleton('OracleBasSkuService',OracleBasSkuService::class);
-        app()->singleton('OracleDocAsnDetailService',OracleDocAsnDetailService::class);
-        app()->singleton('OracleDocOrderHeaderService',OracleDOCOrderHeaderService::class);
-        app()->singleton('OracleDocWaveDetailService',OracleDocWaveDetailService::class);
-        app()->singleton('OrderCommodityAssignService',OrderCommodityAssignService::class);
-        app()->singleton('OrderCommodityService',OrderCommodityService::class);
-        app()->singleton('OrderFreezeService',OrderFreezeService::class);
-        app()->singleton('OrderIssuePerformanceService',OrderIssuePerformanceService::class);
-        app()->singleton('OrderIssueProcessLogService',OrderIssueProcessLogService::class);
-        app()->singleton('OrderIssueRejectedBillService',OrderIssueRejectedBillService::class);
-        app()->singleton('OrderIssueService',OrderIssueService::class);
-        app()->singleton('OrderIssueWorkLoadService',OrderIssueWorkLoadService::class);
-        app()->singleton('OrderPackageCommoditiesService',OrderPackageCommoditiesService::class);
-        app()->singleton('OrderPackageCommoditySerialNumberService',OrderPackageCommoditySerialNumberService::class);
-        app()->singleton('OrderPackageExceptionTypeCountingRecordService',OrderPackageExceptionTypeCountingRecordService::class);
-        app()->singleton('OrderPackageReceivedSyncService',OrderPackageReceivedSyncService::class);
-        app()->singleton('OrderPackageService',OrderPackageService::class);
-        app()->singleton('OrderService',OrderService::class);
-        app()->singleton('OrderTrackingService',OrderTrackingService::class);
-        app()->singleton('OwnerAreaReportService',OwnerAreaReportService::class);
-        app()->singleton('OwnerBillReportService',OwnerBillReportService::class);
-        app()->singleton('OwnerFeeDetailService',OwnerFeeDetailService::class);
-        app()->singleton('OwnerMaterialService',OwnerMaterialService::class);
-        app()->singleton('OwnerMaterialService',OwnerMaterialService::class);
-        app()->singleton('OwnerPriceDirectLogisticService',OwnerPriceDirectLogisticService::class);
-        app()->singleton('OwnerPriceExpressService',OwnerPriceExpressService::class);
-        app()->singleton('OwnerPriceLogisticService',OwnerPriceLogisticService::class);
-        app()->singleton('OwnerPriceOperationItemService',OwnerPriceOperationItemService::class);
-        app()->singleton('OwnerPriceOperationService',OwnerPriceOperationService::class);
-        app()->singleton('OwnerReportService',OwnerReportService::class);
-        app()->singleton('OwnerService',OwnerService::class);
-        app()->singleton('OwnerStoragePriceModelService',OwnerStoragePriceModelService::class);
-        app()->singleton('PackageService',PackageService::class);
-        app()->singleton('PackageStatisticsService',PackageStatisticsService::class);
+        app()->singleton('InventoryAccountMissionService', InventoryAccountMissionService::class);
+        app()->singleton('LogisticZopService', LogisticZopService::class);
+        app()->singleton('InventoryCompareService', InventoryCompareService::class);
+        app()->singleton('InventoryDailyLogService', InventoryDailyLogService::class);
+        app()->singleton('LaborCompanyService',LaborCompanyService::class);
+        app()->singleton('LaborReportsCountingRecordService', LaborReportsCountingRecordService::class);
+        app()->singleton('LogService', LogService::class);
+        app()->singleton('LogisticAliJiSuApiService',LogisticAliJiSuApiService::class);
+        app()->singleton('LogisticSFService', LogisticSFService::class);
+        app()->singleton('LogisticService', LogisticService::class);
+        app()->singleton('LogisticYDService', LogisticYDService::class);
+        app()->singleton('LogisticYTOService', LogisticYTOService::class);
+        app()->singleton('LogisticZopService', LogisticZopService::class);
+        app()->singleton('MaterialBoxService', MaterialBoxService::class);
+        app()->singleton('OracleActAllocationDetailService', OracleActAllocationDetailService::class);
+        app()->singleton('OracleBasCustomerService', OracleBasCustomerService::class);
+        app()->singleton('OracleBasSkuService', OracleBasSkuService::class);
+        app()->singleton('OracleDocAsnDetailService', OracleDocAsnDetailService::class);
+        app()->singleton('OracleDocOrderHeaderService', OracleDOCOrderHeaderService::class);
+        app()->singleton('OracleDocWaveDetailService', OracleDocWaveDetailService::class);
+        app()->singleton('OrderCommodityAssignService', OrderCommodityAssignService::class);
+        app()->singleton('OrderCommodityService', OrderCommodityService::class);
+        app()->singleton('OrderFreezeService', OrderFreezeService::class);
+        app()->singleton('OrderIssuePerformanceService', OrderIssuePerformanceService::class);
+        app()->singleton('OrderIssueProcessLogService', OrderIssueProcessLogService::class);
+        app()->singleton('OrderIssueRejectedBillService', OrderIssueRejectedBillService::class);
+        app()->singleton('OrderIssueService', OrderIssueService::class);
+        app()->singleton('OrderIssueWorkLoadService', OrderIssueWorkLoadService::class);
+        app()->singleton('OrderPackageCommoditiesService', OrderPackageCommoditiesService::class);
+        app()->singleton('OrderPackageCommoditySerialNumberService', OrderPackageCommoditySerialNumberService::class);
+        app()->singleton('OrderPackageExceptionTypeCountingRecordService', OrderPackageExceptionTypeCountingRecordService::class);
+        app()->singleton('OrderPackageReceivedSyncRecordService', OrderPackageReceivedSyncRecordService::class);
+        app()->singleton('OrderPackageReceivedSyncService', OrderPackageReceivedSyncService::class);
+        app()->singleton('OrderPackageService', OrderPackageService::class);
+        app()->singleton('OrderService', OrderService::class);
+        app()->singleton('OrderTrackingService', OrderTrackingService::class);
+        app()->singleton('OwnerAreaReportService', OwnerAreaReportService::class);
+        app()->singleton('OwnerBillReportService', OwnerBillReportService::class);
+        app()->singleton('OwnerFeeDetailService', OwnerFeeDetailService::class);
+        app()->singleton('OwnerLogisticFeeDetailService',OwnerLogisticFeeDetailService::class);
+        app()->singleton('OwnerLogisticFeeReportService',OwnerLogisticFeeReportService::class);
+        app()->singleton('OwnerMaterialService', OwnerMaterialService::class);
+        app()->singleton('OwnerMaterialService', OwnerMaterialService::class);
+        app()->singleton('OwnerPriceDirectLogisticService', OwnerPriceDirectLogisticService::class);
+        app()->singleton('OwnerPriceExpressService', OwnerPriceExpressService::class);
+        app()->singleton('OwnerPriceLogisticService', OwnerPriceLogisticService::class);
+        app()->singleton('OwnerPriceOperationItemService', OwnerPriceOperationItemService::class);
+        app()->singleton('OwnerPriceOperationService', OwnerPriceOperationService::class);
+        app()->singleton('OwnerReportService', OwnerReportService::class);
+        app()->singleton('OwnerService', OwnerService::class);
+        app()->singleton('OwnerStoragePriceModelService', OwnerStoragePriceModelService::class);
+        app()->singleton('PackageService', PackageService::class);
+        app()->singleton('PackageStatisticsService', PackageStatisticsService::class);
         app()->singleton('PrintPartService',PrintPartService::class);
         app()->singleton('PrintTemplateService',PrintTemplateService::class);
-        app()->singleton('ProcessMethodService',ProcessMethodService::class);
-        app()->singleton('ProcessService',ProcessService::class);
-        app()->singleton('ProcessStatisticService',ProcessStatisticService::class);
-        app()->singleton('ProcessesContentService',ProcessesContentService::class);
-        app()->singleton('ProcurementService',ProcurementService::class);
-        app()->singleton('ProcurementTotalBillService',ProcurementTotalBillService::class);
-        app()->singleton('ProcurementWeiXinSendMessageService',ProcurementWeiXinSendMessageService::class);
-        app()->singleton('ProvinceService',ProvinceService::class);
-        app()->singleton('RealtimePendingOrdersService',RealtimePendingOrdersService::class);
-        app()->singleton('RegionService',RegionService::class);
-        app()->singleton('RejectedBillItemService',RejectedBillItemService::class);
-        app()->singleton('RejectedBillService',RejectedBillService::class);
-        app()->singleton('RejectedService',RejectedService::class);
-        app()->singleton('ShopService',ShopService::class);
-        app()->singleton('StationCacheShelfGridService',StationCacheShelfGridService::class);
-        app()->singleton('StationRuleBatchService',StationRuleBatchService::class);
-        app()->singleton('StationService',StationService::class);
-        app()->singleton('StationTaskBatchService',StationTaskBatchService::class);
-        app()->singleton('StationTaskBatchTypeService',StationTaskBatchTypeService::class);
-        app()->singleton('StationTaskChildService',StationTaskChildService::class);
-        app()->singleton('StationTaskCommodityService',StationTaskCommodityService::class);
-        app()->singleton('StationTaskMaterialBoxService',StationTaskMaterialBoxService::class);
-        app()->singleton('StationTaskService',StationTaskService::class);
-        app()->singleton('StationTaskTypeService',StationTaskTypeService::class);
-        app()->singleton('StationTypeBinMonitorService',StationTypeBinMonitorService::class);
-        app()->singleton('StationTypeService',StationTypeService::class);
+        app()->singleton('ProcessMethodService', ProcessMethodService::class);
+        app()->singleton('ProcessService', ProcessService::class);
+        app()->singleton('ProcessStatisticService', ProcessStatisticService::class);
+        app()->singleton('ProcessesContentService', ProcessesContentService::class);
+        app()->singleton('ProcurementService', ProcurementService::class);
+        app()->singleton('ProcurementTotalBillService', ProcurementTotalBillService::class);
+        app()->singleton('ProcurementWeiXinSendMessageService', ProcurementWeiXinSendMessageService::class);
+        app()->singleton('ProvinceService', ProvinceService::class);
+        app()->singleton('RealtimePendingOrdersService', RealtimePendingOrdersService::class);
+        app()->singleton('RegionService', RegionService::class);
+        app()->singleton('RejectedBillItemService', RejectedBillItemService::class);
+        app()->singleton('RejectedBillService', RejectedBillService::class);
+        app()->singleton('RejectedService', RejectedService::class);
+        app()->singleton('ShopService', ShopService::class);
+        app()->singleton('StationCacheShelfGridService', StationCacheShelfGridService::class);
+        app()->singleton('StationRuleBatchService', StationRuleBatchService::class);
+        app()->singleton('StationService', StationService::class);
+        app()->singleton('StationTaskBatchService', StationTaskBatchService::class);
+        app()->singleton('StationTaskBatchTypeService', StationTaskBatchTypeService::class);
+        app()->singleton('StationTaskChildService', StationTaskChildService::class);
+        app()->singleton('StationTaskCommodityService', StationTaskCommodityService::class);
+        app()->singleton('StationTaskMaterialBoxService', StationTaskMaterialBoxService::class);
+        app()->singleton('StationTaskService', StationTaskService::class);
+        app()->singleton('StationTaskTypeService', StationTaskTypeService::class);
+        app()->singleton('StationTypeBinMonitorService', StationTypeBinMonitorService::class);
+        app()->singleton('StationTypeService', StationTypeService::class);
         app()->singleton('StorageService',StorageService::class);
-        app()->singleton('StoreCheckingReceiveItemService',StoreCheckingReceiveItemService::class);
-        app()->singleton('StoreCheckingReceiveService',StoreCheckingReceiveService::class);
-        app()->singleton('StoreItemService',StoreItemService::class);
-        app()->singleton('StoreService',StoreService::class);
-        app()->singleton('SupplierService',SupplierService::class);
-        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);
+        app()->singleton('StoreCheckingReceiveItemService', StoreCheckingReceiveItemService::class);
+        app()->singleton('StoreCheckingReceiveService', StoreCheckingReceiveService::class);
+        app()->singleton('StoreItemService', StoreItemService::class);
+        app()->singleton('StoreService', StoreService::class);
+        app()->singleton('SupplierService', SupplierService::class);
+        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);
+        app()->singleton('GoodScanWeightService',GoodScanWeightService::class);
+        app()->singleton('HaoChuangWeightService',HaoChuangWeightService::class);
+        app()->singleton('HengLiWeightService',HengLiWeightService::class);
+        app()->singleton('InventoryAccountMissionService',InventoryAccountMissionService::class);
     }
 
+    /**
+     * 快递同步接口 同步情况统计
+     */
+    private function logisticSyncRecord($displayName, $column_name): void
+    {
+
+
+        /**
+         * @var OrderPackageReceivedSyncRecordService $orderPackageReceivedSyncRecordService
+         */
+        $orderPackageReceivedSyncRecordService = app('OrderPackageReceivedSyncRecordService');
+        switch ($displayName) {
+            case LogisticZopSync::class:
+                $orderPackageReceivedSyncRecordService->createOrIncrementSucceededCount('中通', now()->toDateString(), $column_name);
+                break;
+            case LogisticSFSync::class:
+                $orderPackageReceivedSyncRecordService->createOrIncrementSucceededCount('顺丰', now()->toDateString(), $column_name);
+                break;
+            case LogisticYDSync::class:
+                $orderPackageReceivedSyncRecordService->createOrIncrementSucceededCount('韵达', now()->toDateString(), $column_name);
+                break;
+            case LogisticYTOSync::class:
+                $orderPackageReceivedSyncRecordService->createOrIncrementSucceededCount('圆通', now()->toDateString(), $column_name);
+                break;
+            default:
+                $orderPackageReceivedSyncRecordService->createOrIncrementSucceededCount('其他', now()->toDateString(), $column_name);
+        }
+    }
 
+    /**
+     * 判断当前任务类型是否为快递信息同步
+     * @param $displayName
+     * @return bool
+     */
+    private function isLogisticSyncJob($displayName): bool
+    {
+        return ($displayName == LogisticZopSync::class)
+            || ($displayName == LogisticSFSync::class)
+            || ($displayName == LogisticYDSync::class)
+            || ($displayName == LogisticYTOSync::class);
+    }
 }

+ 1 - 0
app/Providers/AuthServiceProvider.php

@@ -22,6 +22,7 @@ class AuthServiceProvider extends ServiceProvider
      * @var array
      */
     protected $policies = [
+		 \App\OwnerSundryFeeDetail::class => \App\Policies\OwnerSundryFeeDetailPolicy::class,
         // 'App\Model' => 'App\Policies\ModelPolicy',
         CustomerLog::class => CustomerLogPolice::class,
 

+ 3 - 0
app/Role.php

@@ -19,4 +19,7 @@ class Role extends Model
     function authorities(){
         return $this->belongsToMany('App\Authority','authority_role','id_role','id_authority');
     }
+    function laborCompanies(){
+        return $this->belongsToMany('App\LaborCompany','role_labor_company','role_id','labor_company_id');
+    }
 }

+ 27 - 17
app/Services/BatchService.php

@@ -65,6 +65,7 @@ class BatchService
      */
     public function assignTasks($batches)
     {
+        app('LogService')->log('海柔','assignTasks1',json_encode($batches));
         try{
             $batches = collect($batches);
 
@@ -76,39 +77,48 @@ class BatchService
 
             $stationTaskBatches=null;
             $stationTasks=null;
+            app('LogService')->log('海柔','assignTasks2',json_encode($batches));
             $batches_shouldProcess = $this->stationRuleBatchService->getBatches_shouldProcess($batches); //按规则过滤需要的波次
             if($batches_shouldProcess->isEmpty()) return;
-            $stationTaskMaterialBoxes_occupied = $this->stationTaskMaterialBoxService->getOccupied_byBatches($batches_shouldProcess); //按规则过滤需要的波次
-            if($stationTaskMaterialBoxes_occupied->isNotEmpty()) {
-                foreach ($batches_shouldProcess as $batch){
-                    Cache::tags(['波次防重叠'.$batch['id']])->flush();
-                }
-                BatchTaskJob::dispatch($batches_shouldProcess)
-                    ->delay(now()->addMinutes(1));    //因为料箱被占用了,所以将任务推迟1分钟后尝试
-                return;
-            }
+//            $stationTaskMaterialBoxes_occupied = $this->stationTaskMaterialBoxService->getOccupied_byBatches($batches_shouldProcess); //过滤料箱被占用的波次
+//            app('LogService')->log('海柔','assignTasks2.5',json_encode($stationTaskMaterialBoxes_occupied));
+//            if($stationTaskMaterialBoxes_occupied->isNotEmpty()) {
+//                foreach ($batches_shouldProcess as $batch){
+//                    Cache::tags(['波次防重叠'.$batch['id']])->flush();
+//                }
+//                BatchTaskJob::dispatch($batches_shouldProcess)
+//                    ->delay(now()->addMinutes(1));    //因为料箱被占用了,所以将任务推迟1分钟后尝试
+//                return;
+//            }
+            app('LogService')->log('海柔','assignTasks3',json_encode($batches_shouldProcess));
             DB::transaction(function ()use($batches,&$stationTaskBatches,&$batches_shouldProcess,&$stationTasks){
                 $stationTasks =  $this->stationTaskService->create($batches_shouldProcess->count()); //生成总任务
                 $stationTaskBatches=$this->stationTaskBatchService->createByBatches($batches_shouldProcess,$stationTasks); //注册波次任务
                 $stationTaskMaterialBoxes=$this->stationTaskMaterialBoxService->createByBatches($batches_shouldProcess,$stationTasks); //注册料箱任务
                 $stationTaskCommodities=$this->stationTaskCommodityService->createByBatches($batches_shouldProcess,$stationTasks); //注册商品任务
+                app('LogService')->log('海柔','assignTasks4',json_encode($batches_shouldProcess));
             });
-
-            $stationTasks->loadMissing([
-                "stationTaskCommodities.commodity.barcodes",
-                "stationTaskCommodities.materialBox",
-                "stationTaskBatches.batch.owner",
-                "stationTaskMaterialBoxes.materialBox",
-            ]);
-            $jsonStationTasks=json_encode($stationTasks);
+            foreach ($stationTasks as &$stationTask){
+                $stationTask->loadMissing([
+                    "stationTaskCommodities.commodity.barcodes",
+                    "stationTaskCommodities.materialBox",
+                    "stationTaskBatches.batch.owner",
+                    "stationTaskMaterialBoxes.materialBox",
+                ]);
+            }
+            app('LogService')->log('海柔','assignTasks5',json_encode($stationTasks,true).json_encode($batches_shouldProcess));
+            $jsonStationTasks=json_encode($stationTasks,true);
             broadcast(new BroadcastToStation(BroadcastToStation::ALL_STATION, $jsonStationTasks));
+            app('LogService')->log('海柔','assignTasks6',$jsonStationTasks.json_encode($batches_shouldProcess));
 //            $ran=$this->stationTaskBatchService->runMany($stationTaskBatches);//执行波次任务
         }catch(Exception $e){
+            app('LogService')->log('海柔','assignTasks7',json_encode($batches));
             $batchesJson='';
             foreach ($batches as $batch){
                 $batchesJson.=json_encode($batch);
                 Cache::tags(['波次防重叠'.$batch['id']])->flush();
             }
+            app('LogService')->log('海柔','assignTasks8',json_encode($batches));
             throw new ErrorException('注册任务失败: '. $batchesJson . $e->getMessage().json_encode($e->getTrace()));
         }
     }

+ 82 - 140
app/Services/CacheShelfService.php

@@ -7,9 +7,11 @@ use App\Exceptions\ErrorException;
 use App\MaterialBox;
 use App\Station;
 use App\StationTask;
+use App\StationTaskChild;
 use App\StationTaskChildren;
 use App\StationTaskMaterialBox;
 use App\StationType;
+use App\Storage;
 use App\Traits\ServiceAppAop;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Http;
@@ -40,7 +42,7 @@ class   CacheShelfService
      */
     public function getChildStation($id)
     {
-        return Station::query()->where('parent_id',$id)->with('parent','pendingStationTask.stationTaskMaterialBoxes.materialBox')->get();
+        return Station::query()->where('parent_id', $id)->with('storage.materialBox')->get();
     }
 
 
@@ -49,6 +51,7 @@ class   CacheShelfService
      * @param $locCode
      * @param $PTLAction
      * @return array|bool[]
+     * @throws \Exception
      */
     public function lightOffTask($locCode, $PTLAction): array
     {
@@ -59,128 +62,88 @@ class   CacheShelfService
         };
         try {
             $bool = $this->putBinToStore($station);                         // 推送任务
-            if($bool){
-                LogService::log(__CLASS__,'lightOffTask','code' .' true'. $locCode.json_encode($station));
+            if ($bool) {
+                LogService::log(__CLASS__, 'lightOffTask', 'code' . ' true' . $locCode . json_encode($station));
                 return ['success' => true];
-            }else{
-                return ['success' => false,'errMsg' => '机器人推送失败'];
+            } else {
+                return ['success' => false, 'errMsg' => '机器人推送失败'];
             }
         } catch (ErrorException $e) {
-            LogService::log(__FUNCTION__,'缓存架推送任务失败',json_encode($e->getMessage()));
-            return ['success' => false,'errMsg' => $e->getMessage()];
+            LogService::log(__FUNCTION__, '缓存架推送任务失败', json_encode($e->getMessage()));
+            return ['success' => false, 'errMsg' => $e->getMessage()];
         }
     }
 
     /**
      * 推任务至海柔机器人
      * @param  $station
-     * @return bool
+     * @return array
      * @throws ErrorException
+     * @throws \Exception
      */
-    public function putBinToStore($station): bool
+    public function putBinToStore($station): array
     {
-        $this->instant($this->stationTaskMaterialBoxService, 'StationTaskMaterialBoxService');
         $this->instant($this->foreignHaiRoboticsService, 'ForeignHaiRoboticsService');
         $this->instant($this->stationService, 'StationService');
-        $this->instant($this->stationTaskService, 'StationTaskService');
-        $this->instant($this->stationTaskChildService, 'StationTaskChildService');
 
-        /** @var StationTaskMaterialBox $takeStationTaskMaterialBox */
-        $takeStationTaskMaterialBox = $station['pendingStationTask']['stationTaskMaterialBoxes']->first();
-        $formStation = $this->stationService->getStation_byType('立库');
+        /** @var MaterialBox $materialbox */
+        $materialBox = $station->storage->materialbox;
+
+        $formStation = $this->stationService->getStation_byType('立库');          // 立库
+
+        $stationTask = StationTask::query()->create(['station_id' => $formStation['id'], 'status' => '待处理']);   // 生成任务
 
-        // 查询是否有待处理的入库任务
-        $putStationTaskMaterialBox = StationTaskMaterialBox::query()->where([
+        /** @var StationTaskMaterialBox $stationTaskMaterialBox */
+        $stationTaskMaterialBox = StationTaskMaterialBox::query()->create([
             'station_id' => $formStation['id'],
-            'material_box_id' => $takeStationTaskMaterialBox['material_box_id'],
+            'material_box_id' => $materialBox['id'],
             'status' => '待处理',
-        ])->first();
-
-        // 创建入立库任务
-        if(!$putStationTaskMaterialBox){
-            $stationTask = $this->stationTaskService->create(1);               // 生成站任务
-            $this->stationTaskService->registerStations($stationTask,[$formStation['id']]);   // 注册站任务站
-            /** @var StationTaskMaterialBox $putStationTaskMaterialBox */
-            $putStationTaskMaterialBox = $this->stationTaskMaterialBoxService->create([
-                'station_id' => $formStation['id'],
-                'material_box_id' => $takeStationTaskMaterialBox['material_box_id'],
-                'status' => '待处理',
-            ]);
-            $putStationTaskMaterialBox['station_task_id'] = $stationTask->first()['id'];
-            $putStationTaskMaterialBox['type'] = '放';
-            $putStationTaskMaterialBox->update();
-
-            $params = [[
-                'station_task_id'=>$stationTask->first()['id'],
-                'station_taskable_type'=>StationTaskMaterialBox::class,
-                'station_taskable_id'=>$putStationTaskMaterialBox['id']
-            ]];
+            'station_task_id' => $stationTask['id'],
+            'type' => '放',
+        ]);
 
-            $this->stationTaskChildService->insert($params);    // 任务任务注册
-        }
+        StationTaskChildren::query()->create([
+            'station_task_id' => $stationTask['id'],
+            'station_taskable_type' => StationTaskMaterialBox::class,
+            'station_taskable_id' => $stationTaskMaterialBox['id']
+        ]);
 
-        // 推立库任务
-        $isSuccess =  $this->foreignHaiRoboticsService->putBinToStore_fromCacheShelf($putStationTaskMaterialBox,$station['code']);
-        if($isSuccess) $this->stationTaskMaterialBoxService->set($takeStationTaskMaterialBox,['status' => '处理中']);  // 任务推送成功 标记站任务为处理中
-        else {
-            $materialBoxCode = $station['pendingStationTask']['stationTaskMaterialBoxes']->first()->code ?? '';
-            $this->_stationCacheBroadCast($station->code,0,'error');
-            $this->_stationCacheLightOn($station->code,$materialBoxCode,'拍灯重试任务');
-        }
-        return $isSuccess;
+        $bool = $this->foreignHaiRoboticsService->putBinToStore_fromCacheShelf($stationTaskMaterialBox, $station['code']);
+        return $bool ? ['success' => true] : ['success' => false];
     }
 
     /**
-     * 创建站任务和料箱任务
+     * 缓存架和料箱的绑定
      * @param $stationCode
      * @param $materialBoxCode
      * @return array
      */
-    public function createStationTask($stationCode,$materialBoxCode): array
+    public function bindMaterialBox($stationCode, $materialBoxCode): array
     {
-        $this->instant($this->stationTaskService, 'StationTaskService');
-        $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
-        $this->instant($this->stationTaskChildService,'StationTaskChildService');
+        $station = Station::query()->with('storage')->where('code', $stationCode)->first();
 
-        $station = Station::query()->where('code' , $stationCode)->first();
-        if(!$station){
+        if (!$station) {
             $arr = [];
-            preg_match('/^HAI([\w]+)/',$stationCode,$arr);
+            preg_match('/^HAI([\w]+)/', $stationCode, $arr);
             $parentCode = $arr[1] ?? '';
-            $stationType = StationType::query()->where('name','缓存架')->first();
-            $parentStation = Station::query()->firstOrCreate(['code'=>$parentCode],['station_type_id'=>$stationType['id']]);
-            $station = Station::query()->firstOrCreate(['code' => $stationCode,'parent_id'=>$parentStation['id']],['name'=>$stationCode,'station_type_id' => $stationType['id']]);
+            $stationType = StationType::query()->where('name', '缓存架')->first();
+            $parentStation = Station::query()->firstOrCreate(['code' => $parentCode], ['station_type_id' => $stationType['id']]);
+            $station = Station::query()->firstOrCreate(['code' => $stationCode, 'parent_id' => $parentStation['id']], ['name' => $stationCode, 'station_type_id' => $stationType['id']]);
         }
 
         $materialBox = MaterialBox::query()->firstOrCreate(['code' => $materialBoxCode]);
 
-        $station->load('pendingStationTask.stationTaskMaterialBoxes.materialBox');
-        if($station->pendingStationTask){
-            if($station['pendingStationTask']['stationTaskMaterialBoxes']->first()->materialBox->code == $materialBoxCode){
-                $response = $this->_stationCacheLightOn($stationCode,$materialBoxCode,'任务重试');
-                if($response->code) return ['success'=>true,'message' =>  '任务重试'];
-                return ['success'=>true,'message' =>  '任务重试失败'];
-            }
-            return ['success' => false,'message' => '当前已有进行重的任务'];
-        }
+        $storage = $station->storage ?? Storage::query()->firstOrCreate(['station_id' => $station['id']]);
 
-        $stationTask = $this->stationTaskService->create(1);                                                       // 生成站任务
-        $stationTaskMaterialBox = $this->stationTaskMaterialBoxService->createByStationAndMaterialBox($station,$materialBox);     // 创建料箱任务
-        $this->stationTaskService->registerStations($stationTask,[$station['id']]);                                               // 注册站任务站
-        $stationTaskMaterialBox['station_task_id'] = $stationTask->first()['id'];
-        $stationTaskMaterialBox->update();
-        $params = [[
-                'station_task_id'=>$stationTask->first()['id'],
-                'station_taskable_type'=>StationTaskMaterialBox::class,
-                'station_taskable_id'=>$stationTaskMaterialBox['id']
-            ]];
-        $this->stationTaskChildService->insert($params);                                                                        // 任务任务注册
-
-        $body = $this->_stationCacheLightOn($stationCode,$materialBoxCode);
-        if($body->code == 200)return ['success'=>true];
-        return ['success' => false,'message' => '机器人亮灯异常'];
+        $result = $this->_stationCacheLightOn($station['code'],$materialBoxCode);
+        if($result['code'] == 200){
+            $storage->update(['material_box_id' => $materialBox['id'],'status' => 1]);
+            return ['success' => true];
+        }
+        return ['success' => false,'message' => $result['errMsg']];
     }
 
+
     /**
      * 控制格口亮灯
      * @param $locCode
@@ -189,13 +152,13 @@ class   CacheShelfService
      * @param string $color
      * @return mixed
      */
-    public function _stationCacheLightOn($locCode,$materialCode = null,$title = 'title' ,string $color = '1')
+    public function _stationCacheLightOn($locCode, $materialCode = null, $title = 'title', string $color = '1')
     {
         $params = [
             "areaCode" => "1004",
             'locCode' => $locCode,
             'PTLAction' => 1,
-            'PTLSettings' => ['color'=> $color, 'frequency'  =>1],
+            'PTLSettings' => ['color' => $color, 'frequency' => 1],
             "displayInfo" => [
                 "detail01" => $materialCode,
                 "detail02" => "detail02",
@@ -252,8 +215,9 @@ class   CacheShelfService
      * @param $locCode
      * @return mixed
      */
-    public function _stationCacheLightOff($locCode){
-        if(!$locCode)return null;
+    public function _stationCacheLightOff($locCode)
+    {
+        if (!$locCode) return null;
         $params = [
             "areaCode" => "1004",
             'locCode' => $locCode,
@@ -269,84 +233,62 @@ class   CacheShelfService
      * @param $PTLAction
      * @param string $type
      */
-    public function _stationCacheBroadCast($locCode, $PTLAction,string $type = 'success')
+    public function _stationCacheBroadCast($locCode, $PTLAction, string $type = 'success')
     {
-        if($PTLAction == 0){
-            $station = Station::query()->with('parent')->where('code',$locCode)->first();
+        if (!$locCode) return;
+        if ($PTLAction == 0) {
+            $station = Station::query()->with('parent')->where('code', $locCode)->first();
 
-            $json = json_encode( [
+            $json = json_encode([
                 'station_id' => $station['parent']['id'],
-                'code'  => $station['parent']['code'],
+                'code' => $station['parent']['code'],
                 'gird_id' => $station['id'],
                 'grid_code' => $station['code'],
-                'type' => $type
+                'type' => $type,
+                'status' => 0
             ]);
-            broadcast(new BroadcastToStation($station['parent_id'],$json));
+            broadcast(new BroadcastToStation($station['parent_id'], $json));
         }
     }
 
     /**
-     * 根据立库任务完成 缓存架任务 和 入立架任务
-     * @param StationTaskMaterialBox $putStationTaskMaterial
+     * 根据立库任务完成对storage进行修改
+     * @param StationTaskMaterialBox $stationTaskMaterial
      */
-    public function putStationTaskMaterialBoxProcess(StationTaskMaterialBox $putStationTaskMaterial)
+    public function putStationTaskMaterialBoxProcess(StationTaskMaterialBox $stationTaskMaterial)
     {
-        $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
-
-        $takeStationTaskMaterialBox = StationTaskMaterialBox::query()->with('station','stationTask')->where('material_box_id',$putStationTaskMaterial['material_box_id'])->whereIn('station_id',function($query){
-            $query->from('stations')->selectRaw('id')->whereIn('station_type_id',function($query){
-                $query->from('station_types')->selectRaw('id')->where('name','缓存架');
-            });
-        })->where('status','处理中')->first();
-
-        if(!$takeStationTaskMaterialBox)return ;
-        $this->stationTaskMaterialBoxService->set($takeStationTaskMaterialBox, [
-            'status' => '完成'
-        ]);
+        $this->instant($this->stationTaskMaterialBoxService, 'StationTaskMaterialBoxService');
 
-        // 缓存架任务
-        if($takeStationTaskMaterialBox->stationTask)$takeStationTaskMaterialBox->stationTask->update(['status' => '完成']);
-        // 入立架任务
-        if($putStationTaskMaterial->stationTask)$putStationTaskMaterial->stationTask->update(['status' => '完成']);
+        $storage = Storage::query()->where('material_box_id', $stationTaskMaterial['material_box_id'])->where('status',1)->first();
+        if($storage)$storage->update(['status' => 0, 'material_box_id' => null]);
 
-        $this->_stationCacheLightOff($takeStationTaskMaterialBox->station->code ?? null);  //海柔格口灭灯
-        $this->_stationCacheBroadCast($takeStationTaskMaterialBox->station->code, 0);    //通知缓存架任务完成
+        $this->_stationCacheLightOff($stationTaskMaterial->station->code ?? null);  //海柔格口灭灯
+        $this->_stationCacheBroadCast($stationTaskMaterial->station->code ?? null, 0);    //通知缓存架任务完成
     }
 
     /**
      * 取消任务
      * @param $stationCode
      * @return array
+     * @throws \Exception
      */
     public function clearTask($stationCode): array
     {
-        $station = Station::query()->with(['currentStationTask.stationTaskMaterialBoxes.materialBox',
-            'pendingStationTask.stationTaskMaterialBoxes.materialBox'])
-            ->where('code',$stationCode)->first();
+        $station = Station::query()->with('storage')->where('code', $stationCode)->first();
 
-        if($station->currentStationTask)return ['success' => false,'message' => '当前任务正在执行','data'=>$stationCode];
-        if($station->pendingStationTask->stationTaskMaterialBoxes->count() == 0){
-            $station->pendingStationTask->delete();
-            return ['success' => true];
-        }
-
-        $taskStationTaskMaterialBox = $station->pendingStationTask->stationTaskMaterialBoxes->first() ?? null;
-        $stationTaskMaterialBoxes = StationTaskMaterialBox::query()->with('stationTask')
-            ->where('material_box_id',$taskStationTaskMaterialBox['material_box_id'])
-            ->where('station_id','!=',$station->pendingStationTask['id'])
-            ->get();
+        if (!$station) return ['success' => false, 'message' => '传入参数异常,找不到对应的缓存架记录'];
 
-        foreach ($stationTaskMaterialBoxes as $stationTaskMaterialBox) {
-            if($stationTaskMaterialBox->stationTask){
-                StationTaskChildren::query()->where([
-                    'station_task_id' => $stationTaskMaterialBox->stationTask['id'],
-                    'station_taskable_type'=>StationTaskMaterialBox::class,
-                    'station_taskable_id'=>$stationTaskMaterialBox['id']])->delete();
-
-                $stationTaskMaterialBox->stationTask->delete();
+        $stationTaskMaterialBox = StationTaskMaterialBox::query()->where('material_box_id',$station['storage']['material_box_id'])->first();
+        if($stationTaskMaterialBox ){
+            if($stationTaskMaterialBox->status == '处理中')
+                return ['success' => false, 'message' => '当前缓存架任务正在处理中'];
+            else{
+                $stationTaskMaterialBox->delete();
             }
-            $stationTaskMaterialBox->delete();
         }
+
+        $station->storage->update(['status' => 0,'material_box_id' => null]);
+
         return ['success' => true];
     }
 }

+ 2 - 2
app/Services/DischargeTaskService.php

@@ -72,7 +72,7 @@ class DischargeTaskService
     }
 
     // 创建卸货任务
-    public function createTask(array $param): array
+    public function createTask(array $param,bool $loadMissing = true): array
     {
         if (isset($param['id'])) unset($param['id']);
         if (empty($param['income_total_cost'])) $param['income_total_cost'] = $param['income_unit_price'] * $param['income_amount'];
@@ -80,7 +80,7 @@ class DischargeTaskService
         if (empty($param['status'])) $param['status'] = 0;
 
         $dischargeTask = DischargeTask::query()->create($param);
-        $dischargeTask->loadMissing('facilitator', 'owner','warehouse');
+        if($loadMissing)$dischargeTask->loadMissing('facilitator', 'owner','warehouse');
 
         return ['success' => true, 'data' => $dischargeTask];
     }

+ 15 - 27
app/Services/ForeignHaiRoboticsService.php

@@ -168,7 +168,7 @@ class ForeignHaiRoboticsService
     ): bool
     {
         LogService::log('海柔请求','markBinProcessed1.1',
-            '');
+            $binCode.'|'.$success.'|'.$exception.'|'.$is_in_plan);
         $this->instant($this->stationService,'StationService');
         $this->instant($this->materialBoxService,'MaterialBoxService');
         $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
@@ -205,21 +205,21 @@ class ForeignHaiRoboticsService
                     ->first();
             })();
             LogService::log('海柔请求','markBinProcessed1.6',
-                json_encode($stationTaskMaterialBox));
+                json_encode($stationTaskMaterialBox).'|'.$binCode);
             if(!$stationTaskMaterialBox){
                 throw new ErrorException($binCode.'该料箱没有安排在处理队列中.');
             }
             LogService::log('海柔请求','markBinProcessed1.7',
-                json_encode($stationTaskMaterialBox));
+                json_encode($stationTaskMaterialBox).'|'.$binCode);
 
-            DB::transaction(function ()use($stationTaskMaterialBox){
+            DB::transaction(function ()use($stationTaskMaterialBox,$binCode){
                 $stationTaskMaterialBox_next=
                     $this->stationTaskMaterialBoxService
                         ->processNextQueued($stationTaskMaterialBox); //找到队列中下一个料箱,并标记为处理中
                 $this->stationTaskCommoditiesService
                     ->markProcessed($stationTaskMaterialBox['stationTaskCommodities']);
                 LogService::log('海柔请求','markBinProcessed1.8',
-                    json_encode($stationTaskMaterialBox));
+                    json_encode($stationTaskMaterialBox).'|'.$binCode);
                 if($stationTaskMaterialBox_next)
                     $this->stationTaskCommoditiesService
                         ->markProcessing($stationTaskMaterialBox_next['stationTaskCommodities']);//因为上边商品任务被标记完成了,所以这里要将队列中找出正在处理的料箱对应的标记为“处理中”
@@ -230,26 +230,26 @@ class ForeignHaiRoboticsService
                 if($notProcessedBoxTasks->isEmpty()){
                     $this->instant($this->stationTaskService,'StationTaskService');
                     LogService::log('海柔请求','markBinProcessed1.81',
-                        json_encode($stationTaskMaterialBox['stationTaskBatch']));
+                        json_encode($stationTaskMaterialBox['stationTaskBatch']).'|'.$binCode);
                     $stationTaskMaterialBox->loadMissing('stationTaskBatch');
                     $this->stationTaskBatchService->markProcessed($stationTaskMaterialBox['stationTaskBatch']);
                     LogService::log('海柔请求','markBinProcessed1.82',
-                        json_encode($stationTaskMaterialBox['stationTaskBatch']));
+                        json_encode($stationTaskMaterialBox['stationTaskBatch']).'|'.$binCode);
                     $this->stationTaskService->markProcessed($stationTaskMaterialBox['stationTask']);
                 }
                 $this->storeBox($stationTaskMaterialBox)
                     ?true
                     :(function(){throw new ErrorException('呼叫机器人回收U型线料箱失败');})();
                 LogService::log('海柔请求','markBinProcessed1.9',
-                    json_encode($stationTaskMaterialBox));
+                    json_encode($stationTaskMaterialBox).'|'.$binCode);
                 $this->stationService->broadcastBinMonitor($stationTaskMaterialBox['station_id'],$stationTaskMaterialBox['stationTask']);
                 LogService::log('海柔请求','markBinProcessed1.99',
-                    json_encode($stationTaskMaterialBox));
+                    json_encode($stationTaskMaterialBox).'|'.$binCode);
             });
-
             return true;
         }catch (\Exception $e){
-
+            LogService::log('海柔请求','markBinProcessed E1',
+                $binCode);
             $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
             $this->instant($this->materialBoxService,'MaterialBoxService');
             $box=$this->materialBoxService->firstOrCreate(['code'=>$binCode]);
@@ -269,6 +269,8 @@ class ForeignHaiRoboticsService
             );
             $this->controlHaiRobot($dataToPost,collect([$stationTaskMaterialBox_toStore]),'输送线入立架');
 
+            LogService::log('海柔请求','markBinProcessed E2',
+                $binCode);
             $stationTaskMaterialBox = $stationTaskMaterialBox_toStore??$materialBox??null;
             if($stationTaskMaterialBox && get_class($stationTaskMaterialBox)==MaterialBox::class){
                 $stationTaskMaterialBox = StationTaskMaterialBox::query()
@@ -322,26 +324,12 @@ class ForeignHaiRoboticsService
     public function putBinToStore_fromCacheShelf(?StationTaskMaterialBox $stationTaskMaterialBox,
                                                  string $formLocation): bool
     {
-        LogService::log('海柔请求','putBinToStore_fromCacheShelf1', '');
-        LogService::log('海柔请求','putBinToStore_fromCacheShelf2', json_encode($stationTaskMaterialBox));
-
-        $dataToPost=$this->makeJson_move(
-            collect([$stationTaskMaterialBox]),
-            '缓存架入立架',
-            $formLocation,
-            ''
-        );
-        LogService::log('海柔请求','putBinToStore_fromCacheShelf3', json_encode($dataToPost));
+        $dataToPost=$this->makeJson_move(collect([$stationTaskMaterialBox]), '缓存架入立架', $formLocation, '');
 
         $controlSuccess = $this->controlHaiRobot($dataToPost,collect([$stationTaskMaterialBox]),'缓存架入立架');
-        LogService::log('海柔请求','putBinToStore_fromCacheShelf4', 'controlHaiRobot '. json_encode($controlSuccess));
-
         if($controlSuccess){
             $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
-            $this->stationTaskMaterialBoxService->set($stationTaskMaterialBox,[
-                'status' => '处理中',
-            ]);
-            LogService::log('海柔请求','putBinToStore_fromCacheShelf5', 'controlHaiRobot '. json_encode($stationTaskMaterialBox));
+            $this->stationTaskMaterialBoxService->set($stationTaskMaterialBox,['status' => '处理中']);
         }
         return $controlSuccess;
     }

+ 3 - 2
app/Services/LaborReportService.php

@@ -55,11 +55,12 @@ class LaborReportService
         if((Gate::allows('人事管理-临时工报表-可见全部组')||Gate::allows('人事管理-门卫审核')) && !($params["user_workgroup_id"] ?? false)){
             $laborReports->where(function ($query)use($user){
                 $query->whereIn('labor_reports.user_workgroup_id',$user?$user->getPermittingWorkgroupIds(Gate::allows('人事管理-临时工报表-可见全部组')):[])
+                    ->whereIn('labor_reports.labor_company_id',$user?$user->getPermittingLaborCompanyIdsAttribute():[])
                     ->orWhereNull('labor_reports.user_workgroup_id');
             });
         }else{
-            $laborReports->whereIn('labor_reports.user_workgroup_id',
-                $user?$user->getPermittingWorkgroupIds(Gate::allows('人事管理-临时工报表-可见全部组')):[]);
+            $laborReports->whereIn('labor_reports.user_workgroup_id',$user?$user->getPermittingWorkgroupIds(Gate::allows('人事管理-临时工报表-可见全部组')):[])
+                ->whereIn('labor_reports.labor_company_id',$user?$user->getPermittingLaborCompanyIdsAttribute():[]);
         }
         $laborReports = app(QueryService::class)->query($params,$laborReports,$columnQueryRules,'labor_reports');
         return $laborReports;

+ 11 - 9
app/Services/LaborReportsCountingRecordService.php

@@ -6,25 +6,27 @@ namespace App\Services;
 
 use App\LaborReport;
 use Carbon\Carbon;
-use DateTime;
-use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Str;
-use Ramsey\Uuid\Type\Integer;
 use App\Traits\ServiceAppAop;
 
 
 class LaborReportsCountingRecordService
 {
     use ServiceAppAop;
-    protected $modelClass=LaborReportsCountingRecord::class;
+
+    private $ttl;
+
     public function __construct(LaborReport $laborReport)
     {
+        $this->ttl = config('cache.expirations.commonFrequent');
         $laborReport::$withoutAppends = false;
     }
+
     public function userGroupsCount($start, $end)
     {
-        $resultByCache = Cache::remember('userGroupsCount_' . $start . '_' . $end, 600, function () use ($start, $end) {
+
+        $resultByCache = Cache::remember('userGroupsCount_' . $start . '_' . $end, $this->ttl, function () use ($start, $end) {
             return LaborReport::query()->selectRaw('user_workgroup_id,count(user_workgroup_id) amount')
                 ->with('userWorkgroup', 'laborReportStatus')
                 ->whereDate('created_at', '>=', $start)
@@ -103,7 +105,7 @@ class LaborReportsCountingRecordService
                 break;
             case '年';
                 foreach (Carbon::parse($start)->yearsUntil($end, 1)->toArray() as $item) {
-                    $dataArray[] = $item->year.'';
+                    $dataArray[] = $item->year . '';
                 }
                 break;
             default:
@@ -127,7 +129,7 @@ class LaborReportsCountingRecordService
                 $dataList->each(function ($item) use ($unit) {
                     $date = $item->date_target;
                     $key = 'laborReportsCountingRecords_' . $date . '_' . $unit;
-                    Cache::put($key, $item);
+                    Cache::put($key, $item, $this->ttl);
                 });
                 break;
             case '月':
@@ -143,7 +145,7 @@ class LaborReportsCountingRecordService
                 $dataList->each(function ($item) use ($unit) {
                     $date = $item->date_target;
                     $key = 'laborReportsCountingRecords_' . $date . '_' . $unit;
-                    Cache::put($key, $item);
+                    Cache::put($key, $item, $this->ttl);
                 });
                 break;
             case '年':
@@ -158,7 +160,7 @@ class LaborReportsCountingRecordService
                 $dataList->each(function ($item) use ($unit) {
                     $date = $item->date_target;
                     $key = 'laborReportsCountingRecords_' . $date . '_' . $unit;
-                    Cache::put($key, $item);
+                    Cache::put($key, $item, $this->ttl);
                 });
                 break;
             default:

+ 126 - 0
app/Services/LogisticAliJiSuApiService.php

@@ -0,0 +1,126 @@
+<?php
+
+namespace App\Services;
+
+use App\Traits\ServiceAppAop;
+
+class LogisticAliJiSuApiService
+{
+    use ServiceAppAop;
+
+    public function query($logistic_number)
+    {
+        $app_code = config('api_logistic.AliJiSu.prod.app-code');
+        $type = config('api_logistic.AliJiSu.prod.type');
+        $host = config('api_logistic.AliJiSu.prod.search.host');
+        $path = config('api_logistic.AliJiSu.prod.search.path');
+        $method = config('api_logistic.AliJiSu.prod.method');
+        $headers = array();
+        array_push($headers, "Authorization:APPCODE " . $app_code);
+        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
+        $query='number='.$logistic_number.'&type='.$type;
+        $bodys = "null";
+        $url = $host . $path . "?" . $query;
+//        $response = Http::withHeaders($headers)->get($url);
+//        return json_decode($response->body());
+
+        $curl = curl_init();
+        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
+        curl_setopt($curl, CURLOPT_URL, $url);
+        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
+        curl_setopt($curl, CURLOPT_FAILONERROR, false);
+        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
+//        curl_setopt($curl, CURLOPT_HEADER, true);
+        if (1 == strpos("$".$host, "https://"))
+        {
+            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
+            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
+        }
+        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
+        return json_decode(curl_exec($curl));
+    }
+
+    public function format($response): array
+    {
+        $result = [];
+        if (!isset($response)) {return [];}
+        else {
+            try {
+                if ($response->result->number??false)$result['logistic_number'] = $response->result->number;
+            } catch (\Exception $e) {
+                LogService::log(LogisticYTOService::class, "AliJiSu快递信息异常", $response);
+            }
+            $list=$response->result->list;
+            if (!empty($list) && is_array($list)) {
+                $lastNativeRoute = $list[0];
+                $result['status'] = $this->getStatus($response);
+                if ($result['status'] == '已收件') $result['received_at'] = $lastNativeRoute->time;
+                $result['transfer_status'] = $this->getTransferStatus($list);
+                $result['routes_length'] = array_key_exists('transfer_status', $result) ? count($result['transfer_status']) : 0;
+                $orderPackageReceivedSyncService = app('OrderPackageReceivedSyncService');
+                $exceptionData = $orderPackageReceivedSyncService->setExceptionType($result, $lastNativeRoute ? $lastNativeRoute->time : null);
+                $result['exception_type'] = $exceptionData['exception_type'];
+                $result['exception'] = $exceptionData['exception'];
+
+            } else {
+                $result['status'] = null;
+                $result['transfer_status'] = [];
+            }
+            if (!array_key_exists('exception', $result)
+                && !array_key_exists('exception_type', $result)
+                && array_key_exists('transfer_status', $result)
+            ) {
+                $result['exception_type'] = '无';
+                $result['exception'] = '否';
+            }
+            if (!array_key_exists('status', $result)) {
+                $result['status'] = null;
+                $result['transfer_status'] = [];
+            }
+            return $result;
+        }
+    }
+    /**
+     * @param $nativeData
+     * @return string
+     */
+    private function getStatus($nativeData): string
+    {
+        $status = null;
+        switch ($nativeData->result->deliverystatus) {
+            case '1':
+                $status = '在途';
+                break;
+            case '2':
+                $status = '派送中';
+                break;
+            case '3':
+                $status = '已收件';
+                break;
+            case '4':
+                $status = '派送异常';
+                break;
+            default:
+                $status = '无';
+        }
+        return $status;
+    }
+    /**
+     * @param $nativeRoutes
+     * @return array
+     */
+    private function getTransferStatus($nativeRoutes): array
+    {
+        $transferStatus = [];
+        foreach ($nativeRoutes as $nativeRoute) {
+            $item = [];
+            $item['accept_time'] = $nativeRoute->time;
+            $item['accept_address'] = $nativeRoute->status;
+            $item['remark'] = "";
+            $transferStatus[] = $item;
+        }
+        return $transferStatus;
+    }
+
+
+}

+ 12 - 0
app/Services/LogisticRouteInterface.php

@@ -0,0 +1,12 @@
+<?php
+
+
+namespace App\Services;
+
+
+interface LogisticRouteInterface
+{
+    public function query($logistic_number);
+
+    public function format($nativeResponse,$logistic_number);
+}

+ 19 - 6
app/Services/LogisticYDService.php

@@ -64,8 +64,12 @@ class LogisticYDService
             'req-time' => now()->timestamp,
             "Content-Type" => "application/json"
         ];
-        $response = Http::withHeaders($headers)->withBody($json_body, 'application/json')->post($this->url);
-        return json_decode($response);
+        try {
+            $response = Http::withHeaders($headers)->withBody($json_body, 'application/json')->post($this->url);
+            return json_decode($response);
+        } catch (\GuzzleHttp\Exception\RequestException $e) {
+            LogService::log(LogisticYDService::class, "韵达-registerApi", $logistic_numbers);
+        }
     }
 
     public function query($logistic_number)
@@ -83,14 +87,23 @@ class LogisticYDService
             'req-time' => now()->timestamp,
             "Content-Type" => "application/json"
         ];
-        $response = Http::withHeaders($headers)->withBody(json_encode($body, JSON_UNESCAPED_UNICODE), 'application/json')->post($this->url);
+        try {
+            $response = Http::withHeaders($headers)->withBody(json_encode($body, JSON_UNESCAPED_UNICODE), 'application/json')->post($this->url);
+        } catch (\GuzzleHttp\Exception\RequestException $e) {
+            LogService::log(LogisticYDService::class, "韵达-query", $logistic_number);
+            return null;
+        }
         return json_decode($response->body());
     }
 
-    public function format($nativeResponse)
+    public function format($nativeResponse, $logistic_number)
     {
-        if ($nativeResponse->code != '0000' || $nativeResponse->data->result=="false") {
-            return [];
+        if (is_null($nativeResponse) || $nativeResponse->code != '0000' || $nativeResponse->data->result == "false") {
+            return [
+                'logistic_number' => $logistic_number,
+                'exception_type' => '揽件异常',
+                'exception' => '是',
+            ];
         } else {
             $nativeData = $nativeResponse->data;
             try {

+ 8 - 2
app/Services/LogisticYTOService.php

@@ -42,10 +42,16 @@ class LogisticYTOService
         return json_decode($response->body());
     }
 
-    public function format($response): array
+    public function format($response,$logistic_number): array
     {
         $result = [];
-        if (is_object($response) && $response->code=='1001') {return [];}
+        if (is_object($response) && $response->code=='1001') {
+            return [
+                'logistic_number' => $logistic_number,
+                'exception_type' => '揽件异常',
+                'exception' => '是',
+            ];
+        }
         else {
             try {
                 if (is_array($response))$result['logistic_number'] = $response[0]->waybill_No;

+ 90 - 78
app/Services/LogisticZopService.php

@@ -3,101 +3,113 @@
 
 namespace App\Services;
 
-
-use App\library\zop\ZopClient;
-use App\library\zop\ZopProperties;
-use App\library\zop\ZopRequest;
+use App\OrderPackage;
 use Carbon\Carbon;
+use Illuminate\Support\Facades\Http;
 
-class LogisticZopService
+class LogisticZopService implements LogisticRouteInterface
 {
 
-
-    /**
-     * 获取中通快递路由信息
-     * @param array $logisticNums
-     * @return array
-     */
-    public function get(array $logisticNums): array
+    public function query($logistic_number)
     {
-        $result = [];
-
         $url = config('api_logistic.ZTO.url');
         $xAppKey = config('api_logistic.ZTO.x-appKey');
         $appSecret = config('api_logistic.ZTO.appSecret');
+        $body = json_encode([
+            'billCode' => $logistic_number,
+        ], JSON_UNESCAPED_UNICODE);
+        $data_digest = base64_encode(md5($body . $appSecret, TRUE));
+        $headers = [
+            'Content-Type' => 'application/json; charset=UTF-8',
+            'x-companyid' => $xAppKey,
+            'x-datadigest' => $data_digest,
+        ];
+        $response = Http::withHeaders($headers)->withBody($body, 'application/json')->post($url);
+        return json_decode($response->body());
+    }
 
-        $properties = new ZopProperties($xAppKey, $appSecret);
-        $client = new ZopClient($properties);
-        $request = new ZopRequest();
-
-        $request->setUrl($url);
-        foreach ($logisticNums as $logisticNum) {
-            $request->setBody(json_encode([
-                'billCode' => $logisticNum,
-            ]));
-            $response = json_decode($client->execute($request));
+    public function format($nativeResponse,$logistic_number)
+    {
+        $order_package = OrderPackage::query()->where('logistic_number', $logistic_number)->first();
+        $result = [
+            'logistic_number' => $logistic_number,
+            'exception_type' => $order_package->exception_type,
+            'exception' => $order_package->exception,
+            'status' => $order_package->status,
+            'transfer_status' => $order_package->transfer_status,
+            'received_at' => $order_package->received_at,
+        ];
+        $nativeRoutes = $nativeResponse->result??[];
+        if (empty($nativeRoutes)) {
+            $result['exception_type'] = '揽件异常';
+            $result['exception'] = '是';
+            return $result;
+        }
+        $lastRoute = $nativeRoutes[count($nativeRoutes) - 1]??[];
+        list($status, $received_at) = $this->getNormalStatusAndReceivedAt($lastRoute);
+        $result['status'] = $status;
+        $result['received_at'] = $received_at;
+        $result['transfer_status'] = $this->getTransferStatus($nativeRoutes);
+        $result['routes_length'] = count($result['transfer_status']);
+        /**
+         * @var $orderPackageReceivedSyncService OrderPackageReceivedSyncService
+         */
+        $orderPackageReceivedSyncService = app('OrderPackageReceivedSyncService');
+        $lastRouteDate = Carbon::parse($lastRoute->scanDate / 1000)->addHours(8)->toDateTimeString();
+        $exceptionData = $orderPackageReceivedSyncService->setExceptionType($result, $lastRouteDate);
+        $result['exception_type'] = $exceptionData['exception_type'];
+        $result['exception'] = $exceptionData['exception'];
+        return $result;
+    }
 
-            if ($response->status) {
-                $result[] = [
-                    'routes' => $response->result,
-                    'logisticNum' => $logisticNum,
-                ];
-            } else {
-//                throw new WarningException("单号没有查询到快递路由信息','LogisticZopService->get->{$logisticNum}");
-            }
+    /**
+     * 正常的状态与签收时间
+     */
+    private function getNormalStatusAndReceivedAt($lastRoute): array
+    {
+        $status = null;
+        $received_at = null;
+        switch ($lastRoute->scanType) {
+            case '收件':
+                $status = '已揽收';
+                break;
+            case '到件':
+            case '发件':
+                $status = '在途';
+                break;
+            case 'ARRIVAL':
+            case '派件':
+                $status = '派送中';
+                break;
+            case 'SIGNED':
+            case '签收':
+                $status = '已收件';
+                $received_at = Carbon::parse($lastRoute->scanDate / 1000)->addHours(8)->toDateTimeString();
+                break;
+            default:
+                $status = '无';
+                break;
         }
-        return $this->transformRoutes($result);
+        return array($status, $received_at);
     }
 
+
     /**
-     * 转换快递路由信息
-     * @param array $routs 快递路由
+     * @param $nativeRoutes
      * @return array
      */
-    public function transformRoutes(array $routs): array
+    private function getTransferStatus($nativeRoutes): array
     {
-        $result = [];
-        foreach ($routs as $route) {
-            $resultItem = [];
-            $resultItem['logistic_number'] = $route['logisticNum'];
-            $itemRoutes = $route['routes'];
-            if (empty($itemRoutes)) {
-                continue;
-            }
-            $lastRoute = $itemRoutes[count($itemRoutes) - 1];
-            switch ($lastRoute->scanType) {
-                case '收件':
-                    $resultItem['status'] = '已揽收';
-                    break;
-                case '到件':
-                case '发件':
-                    $resultItem['status'] = '在途';
-                    break;
-                case 'ARRIVAL':
-                case '派件':
-                    $resultItem['status'] = '派送中';
-                    break;
-                case 'SIGNED':
-                case '签收':
-                    $resultItem['status'] = '已收件';
-                    $resultItem['received_at'] = Carbon::parse($lastRoute->scanDate / 1000)->toDateTimeString();
-                    break;
-                default:
-                    break;
-            }
-            $transfer_status = [];
-            foreach ($itemRoutes as $item) {
-                $data = [];
-                $data['accept_time'] = Carbon::parse($item->scanDate / 1000)->toDateTimeString();
-                $scanSite = $item->scanSite;
-                $data['accept_address'] = $scanSite->prov . '-' . $scanSite->name;
-                $data['remark'] = $item->scanType;
-
-                $transfer_status[] = $data;
-            }
-            $resultItem['transfer_status'] = $transfer_status;
-            $result[] = $resultItem;
+        $transfer_status = [];
+        foreach ($nativeRoutes as $item) {
+            $data = [];
+            $data['accept_time'] = Carbon::parse($item->scanDate / 1000)->addHours(8)->toDateTimeString();
+            $scanSite = $item->scanSite;
+            $data['accept_address'] = $scanSite->prov . '-' . $scanSite->name;
+            $data['remark'] = $item->desc;
+            $transfer_status[] = $data;
         }
-        return $result;
+        return $transfer_status;
     }
+
 }

+ 242 - 18
app/Services/NewOrderCountingRecordService.php

@@ -9,6 +9,7 @@ use App\Order;
 use App\OrderCountingRecord;
 use App\Warehouse;
 use Carbon\Carbon;
+use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Support\Arr;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Cache;
@@ -18,7 +19,9 @@ use App\Traits\ServiceAppAop;
 class NewOrderCountingRecordService
 {
     use ServiceAppAop;
-    protected $modelClass=NewOrderCountingRecord::class;
+
+    protected $modelClass = OrderCountingRecord::class;
+
     public function orderCountingRecordsFromCache($start, $end, $unit, $ownerIds)
     {
         $dataList = collect();
@@ -86,22 +89,22 @@ class NewOrderCountingRecordService
     {
         $key = 'warehouseCountingRecords_' . $start . '_' . $end . '_' . json_encode($ownerIds);
         return Cache::remember($key, config('cache.expirations.warehouseCountingRecords'), function () use ($start, $end, $ownerIds) {
-        $dataList = collect();
-        $resultOrders = $this->get($start, $end, '日', $ownerIds);
-        $resultOrders->groupBy('warehouse_id')->each(function ($item) use (&$dataList) {
-            $counter = $item->reduce(function ($sum, $item) {
-                return $sum + $item->amount;
-            }, 0);
-            $warehouse = Warehouse::query()->find($item[0]->warehouse_id);
+            $dataList = collect();
+            $resultOrders = $this->get($start, $end, '日', $ownerIds);
+            $resultOrders->groupBy('warehouse_id')->each(function ($item) use (&$dataList) {
+                $counter = $item->reduce(function ($sum, $item) {
+                    return $sum + $item->amount;
+                }, 0);
+                $warehouse = Warehouse::query()->find($item[0]->warehouse_id);
 
-            $dataList->push([
-                'value' => $counter,
-                'warehouse_id' => $item[0]->warehouse_id,
-                'name' => $warehouse ? $warehouse->name : '仓库为空',
-                'code' => $warehouse ? $warehouse->code : 'NULL',
-            ]);
-        });
-        return $dataList;
+                $dataList->push([
+                    'value' => $counter,
+                    'warehouse_id' => $item[0]->warehouse_id,
+                    'name' => $warehouse ? $warehouse->name : '仓库为空',
+                    'code' => $warehouse ? $warehouse->code : 'NULL',
+                ]);
+            });
+            return $dataList;
         });
     }
 
@@ -378,7 +381,7 @@ class NewOrderCountingRecordService
                 'logistic_id' => $order->logistic_id,
                 'date_target' => $order->date_target,
                 'counting_unit' => $unit,
-                'amount' => $order->amounts,
+                'amount' => $order->amounts??0,
                 'week' => $year . '-' . $week,
                 'month' => $year . '-' . $month,
                 'year' => $year . '',
@@ -475,10 +478,231 @@ class NewOrderCountingRecordService
     private function getTtl($dateStr, $unit)
     {
         if ($this->isNotCurrentDate($dateStr, $unit)) {
-            $ttl = config('cache.expirations.forever');//非当前日期的缓存为永久
+            LogService::log('NewOrderCountingRecordService', '缓存设置为永久', $dateStr);
+            $ttl = config('cache.expirations.orderCountingRecord');//非当前日期的缓存为永久
         } else {
+            LogService::log('NewOrderCountingRecordService', '缓存设置为临时', $dateStr);
             $ttl = config('cache.expirations.orderCountingRecord');//当前日期缓存为1800s
         }
         return $ttl;
     }
+
+
+    //TODO 控制台重构
+
+    public function getWareHouseRecordsApi($start, $end, $ownerIds): array
+    {
+        $orderCountingRecords = OrderCountingRecord::query()
+            ->selectRaw("sum(amount) as value ,warehouse_id")
+            ->with('warehouse:id,name,code')
+            ->whereBetween('date_target', [$start, $end])
+            ->whereIn('owner_id', $ownerIds)
+            ->groupBy('warehouse_id')
+            ->get();
+        $result = [];
+        foreach ($orderCountingRecords as $orderCountingRecord) {
+            $result[] = [
+                'logistic_id' => $orderCountingRecord->warehouse_id,
+                'value' => $orderCountingRecord->value,
+                'name' => $orderCountingRecord->warehouse->name ?? '',
+                'code' => $orderCountingRecord->warehouse->code ?? '',
+            ];
+        }
+        return $result;
+    }
+
+    public function getLogisticRecordsApi($start, $end, $ownerIds): array
+    {
+        $orderCountingRecords = OrderCountingRecord::query()
+            ->selectRaw("sum(amount) as value ,logistic_id")
+            ->with('logistic:id,name')
+            ->whereBetween('date_target', [$start, $end])
+            ->whereIn('owner_id', $ownerIds)
+            ->groupBy('logistic_id')
+            ->get();
+        $result = [];
+        foreach ($orderCountingRecords as $orderCountingRecord) {
+            $result[] = [
+                'logistic_id' => $orderCountingRecord->logistic_id,
+                'value' => $orderCountingRecord->value,
+                'name' => $orderCountingRecord->logistic->name ?? '',
+            ];
+        }
+        return $result;
+    }
+
+    /**
+     * 查询订单量趋势
+     * @param $start string
+     * @param $end string
+     * @param $unit string
+     * @param $ownerIds array
+     * @return Builder[]|\Illuminate\Database\Eloquent\Collection
+     */
+    public function getOrderCountingRecordsApi(string $start, string $end, string $unit, array $ownerIds)
+    {
+        $orderCountingRecords = OrderCountingRecord::query()
+            ->selectRaw("sum(amount) as counter ,date_target")
+            ->whereBetween('date_target', [$start, $end])
+            ->where('counting_unit', $unit)
+            ->whereIn('owner_id', $ownerIds)
+            ->groupBy('date_target')
+            ->get()->toArray();
+        if (now()->toDateString() == $end) {//查询时间包含当天
+            switch ($unit) {
+                case '日':
+                    //查询当天统计
+                    $startDateTime = Carbon::parse($end)->startOfDay()->toDateTimeString();
+                    $endDateTime = Carbon::parse($end)->endOfDay()->toDateTimeString();
+                    break;
+                case '月':
+                    //查询当月统计
+                    $startDateTime = Carbon::parse($end)->startOfMonth()->startOfDay()->toDateTimeString();
+                    $endDateTime = Carbon::parse($end)->endOfMonth()->endOfDay()->toDateTimeString();
+                    break;
+                case '年':
+                    //查询当年统计
+                    $startDateTime = Carbon::parse($end)->startOfYear()->startOfDay()->toDateTimeString();
+                    $endDateTime = Carbon::parse($end)->endOfYear()->endOfDay()->toDateTimeString();
+                    break;
+            }
+            $order = Order::query()
+                ->selectRaw("count(1) as amounts ,DATE_FORMAT(created_at,'%Y-%m-%d') as date_target")
+                ->whereBetween('created_at', [$startDateTime, $endDateTime])
+                ->where('wms_status', '订单完成')
+                ->whereIn('owner_id', $ownerIds)
+                ->groupBy('date_target')
+                ->first();
+            $orderCountingRecords[] = [
+                "counter" => $order->amounts??0,
+                "date_target" => $order->date_target,
+            ];
+        }
+        return $orderCountingRecords;
+    }
+
+    /**
+     * 统计订单量 从$start 开始统计 默认截止到当前日期的前一天
+     * @param $start string
+     * @param null $end string
+     * @param $unit string
+     */
+    public function recordOrder(string $start, $end = null, string $unit = '日')
+    {
+        switch ($unit) {
+            case '日':
+                $this->recordByDay($start, $end, $unit);
+                break;
+            case'月':
+                $this->recordByMonth($start, $end, $unit);
+                break;
+            case'年':
+                $this->recordByYear($start, $end, $unit);
+                break;
+            default:
+        }
+    }
+
+    /**
+     * 清空统计缓存
+     */
+    public function clearCacheOrderRecord()
+    {
+
+    }
+
+    /**
+     * 日统计
+     * @param string $start
+     * @param $end
+     * @param string $unit
+     */
+    public function recordByDay(string $start, $end = null, string $unit = '日'): void
+    {
+        $startDateTime = Carbon::parse($start)->startOfDay()->toDateTimeString();
+        if (is_null($end)) {
+            $end = now()->subDay()->endOfDay();
+        }
+        $endDateTime = Carbon::parse($end)->endOfDay()->toDateTimeString();
+        $orders = Order::query()
+            ->selectRaw("owner_id,warehouse_id,logistic_id,count(1) as amounts ,DATE_FORMAT(created_at,'%Y-%m-%d') as date_target")
+            ->whereBetween('created_at', [$startDateTime, $endDateTime])
+            ->where('wms_status', '订单完成')
+            ->groupBy('owner_id', 'warehouse_id', 'logistic_id', 'date_target')
+            ->get();
+        $insertData = [];
+        foreach ($orders as $order) {
+            $insertData[] = [
+                'owner_id' => $order->owner_id,
+                'warehouse_id' => $order->warehouse_id,
+                'logistic_id' => $order->logistic_id,
+                'date_target' => $order->date_target,
+                'counting_unit' => $unit,
+                'amount' => $order->amounts??0,
+                'year' => Carbon::parse($order->date_target)->year,
+                'month' => Carbon::parse($order->date_target)->year . '-' . Carbon::parse($order->date_target)->month,
+            ];
+        }
+        $insertDataChunked = array_chunk($insertData, 2000);
+        foreach ($insertDataChunked as $items) {
+            OrderCountingRecord::query()->insertOrIgnore($items);
+        }
+    }
+
+
+    public function recordByMonth(string $start, $end = null, $unit = '月')
+    {
+        $startDate = Carbon::parse($start)->startOfMonth()->toDateString();
+        if (is_null($end)) {
+            $end = now()->subMonth()->endOfDay();
+        }
+        $endDate = Carbon::parse($end)->endOfDay()->toDateString();
+        $orderCountingRecords = OrderCountingRecord::query()
+            ->selectRaw("owner_id,warehouse_id,logistic_id,sum(amount) as amount_sum,month,year,date_target")
+            ->whereBetween('date_target', [$startDate, $endDate])
+            ->where('counting_unit', '日')
+            ->groupBy('owner_id', 'warehouse_id', 'logistic_id', 'month', 'date_target')
+            ->get();
+        $insertData = [];
+        foreach ($orderCountingRecords as $orderCountingRecord) {
+            $insertData[] = [
+                'owner_id' => $orderCountingRecord->owner_id,
+                'warehouse_id' => $orderCountingRecord->warehouse_id,
+                'logistic_id' => $orderCountingRecord->logistic_id,
+                'counting_unit' => $unit,
+                'date_target' => Carbon::parse($orderCountingRecord->date_target)->startOfMonth()->toDateString(),
+                'amount' => $orderCountingRecord->amount_sum,
+                'year' => $orderCountingRecord->year,
+                'month' => $orderCountingRecord->month,
+            ];
+        }
+        OrderCountingRecord::query()->insertOrIgnore($insertData);
+    }
+
+    public function recordByYear(string $start, $end = null, $unit = '年')
+    {
+        $startYear = Carbon::parse($start)->year;
+        if (is_null($end)) {
+            $end = now()->subYear()->toDateString();
+        }
+        $endYear = Carbon::parse($end)->year;
+        $orderCountingRecords = OrderCountingRecord::query()
+            ->selectRaw("owner_id,warehouse_id,logistic_id,sum(amount) as amount_sum,year,date_target")
+            ->whereBetween('year', [$startYear, $endYear])
+            ->groupBy('owner_id', 'warehouse_id', 'logistic_id', 'year')
+            ->get();
+        $insertData = [];
+        foreach ($orderCountingRecords as $orderCountingRecord) {
+            $insertData[] = [
+                'owner_id' => $orderCountingRecord->owner_id,
+                'warehouse_id' => $orderCountingRecord->warehouse_id,
+                'logistic_id' => $orderCountingRecord->logistic_id,
+                'counting_unit' => $unit,
+                'date_target' => Carbon::parse($orderCountingRecord->date_target)->startOfYear()->toDateString(),
+                'amount' => $orderCountingRecord->amount_sum,
+                'year' => $orderCountingRecord->year,
+            ];
+        }
+        OrderCountingRecord::query()->insertOrIgnore($insertData);
+    }
 }

+ 33 - 0
app/Services/OrderPackageReceivedSyncRecordService.php

@@ -0,0 +1,33 @@
+<?php
+
+namespace App\Services;
+
+use App\Traits\ServiceAppAop;
+use App\OrderPackageReceivedSyncRecord;
+
+class OrderPackageReceivedSyncRecordService
+{
+    use ServiceAppAop;
+
+    protected $modelClass = OrderPackageReceivedSyncRecord::class;
+
+    /**
+     * @param $logistic_name string 成员商名称
+     * @param $recorded_at string 统计日期
+     * @param $column_name string 操作列名称 succeed_count or failed_count
+     */
+    public function createOrIncrementSucceededCount(string $logistic_name, string $recorded_at, string $column_name)
+    {
+        $orderPackageReceivedSyncRecord = OrderPackageReceivedSyncRecord::query()->where('logistic_name', $logistic_name)->whereDate('recorded_at', $recorded_at)->first();
+
+        if (is_null($orderPackageReceivedSyncRecord)) {
+            OrderPackageReceivedSyncRecord::query()->create([
+                'logistic_name' => $logistic_name,
+                'recorded_at' => $recorded_at,
+                $column_name => 1,
+            ]);
+        } else {
+            $orderPackageReceivedSyncRecord->increment($column_name);
+        }
+    }
+}

+ 38 - 9
app/Services/OrderPackageReceivedSyncService.php

@@ -4,6 +4,7 @@
 namespace App\Services;
 
 
+use App\Jobs\LogisticAliJiSuSync;
 use App\Jobs\LogisticSFSync;
 use App\Jobs\LogisticYDSync;
 use App\Jobs\LogisticYTOSync;
@@ -26,8 +27,8 @@ class OrderPackageReceivedSyncService
      */
     public function syncLogisticRoute()
     {
+        ini_set('max_execution_time', 2 * 60 * 60);
         LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法", '');
-        ini_set('max_execution_time', 60 * 60);
         //初始化时间 2020-12-31 23:59:59
         $initDate = Carbon::parse(config('api_logistic.init_date'));
         $query = OrderPackage::query()
@@ -48,7 +49,7 @@ class OrderPackageReceivedSyncService
             //sf
             if (array_key_exists('SF', $logisticNumbers)) {
                 $SFLogisticNumbers = $logisticNumbers['SF'];
-                LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-SF", '');
+                LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-SF", $SFLogisticNumbers);
                 foreach ($SFLogisticNumbers as $logisticNumber) {
                     LogisticSFSync::dispatch($logisticNumber);
                 }
@@ -56,7 +57,7 @@ class OrderPackageReceivedSyncService
             //更新中通
             if (array_key_exists('ZTO', $logisticNumbers)) {
                 $ZTOLogisticNumbers = $logisticNumbers['ZTO'];
-                LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-ZTO", '');
+                LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-ZTO", $ZTOLogisticNumbers);
                 foreach ($ZTOLogisticNumbers as $logisticNumber) {
                     LogisticZopSync::dispatch($logisticNumber);
                 }
@@ -64,7 +65,7 @@ class OrderPackageReceivedSyncService
             //更新韵达
             if (array_key_exists('YUNDA', $logisticNumbers)) {
                 $YDLogisticNumbers = $logisticNumbers['YUNDA'];
-                LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-YUNDA", '');
+                LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-YUNDA", $YDLogisticNumbers);
                 foreach ($YDLogisticNumbers as $logistic_number) {
                     LogisticYDSync::dispatch($logistic_number);
                 }
@@ -72,7 +73,7 @@ class OrderPackageReceivedSyncService
             //更新圆通
             if (array_key_exists('YTO', $logisticNumbers)) {
                 $YTOLogisticNumbers = $logisticNumbers['YTO'];
-                LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-YTO", '');
+                LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-YTO", $YTOLogisticNumbers);
                 foreach ($YTOLogisticNumbers as $logistic_number) {
                     LogisticYTOSync::dispatch($logistic_number);
                 }
@@ -80,6 +81,25 @@ class OrderPackageReceivedSyncService
         });
     }
 
+    public function syncLogisticRouteByAliJiSu()
+    {
+        ini_set('max_execution_time', 60);
+        LogService::log(OrderPackageReceivedSyncService::class, "阿里同步快递信息定时方法", '');
+        $query = OrderPackage::query()
+            ->select(['logistic_number', 'order_id'])
+            ->whereIn('order_id',function ($query){
+                $query->from('orders')->selectRaw('id')->whereIn('logistic_id',function ($builder){
+                    $builder->from('logistics')->selectRaw('id')->where('type','!=','物流')->whereNotIn('belong_company',['顺丰','中通','韵达','圆通']);
+                });
+            });
+        $query = $query->where('sent_at', '>=', now()->subDays(20))
+            ->whereNull('received_at');
+        $query->chunk(200, function ($orderPackages) {
+            foreach ($orderPackages as $orderPackage){
+                if ($orderPackage && $orderPackage->logistic_number)LogisticAliJiSuSync::dispatch($orderPackage->logistic_number);
+            }
+        });
+    }
     /**
      * 根据传递的承运商与快递单号更新快递信息
      * @param array $logisticNumbers 快递单号
@@ -141,12 +161,17 @@ class OrderPackageReceivedSyncService
                     unset($data['exception']);
                 }
             } catch (Exception $e) {
-                LogService::log(OrderPackageReceivedSyncService::class, "标记问题件不需要更新异常状态失败", $data['logistic_number'].'-'.json_encode($e));
+                LogService::log(OrderPackageReceivedSyncService::class, "标记问题件不需要更新异常状态失败", $data['logistic_number'] . '-' . json_encode($e));
+            }
+            //如果已经收货,将异常更新为正常
+            if (array_key_exists('received_at', $data)) {
+                $data['exception_type'] = '无';
+                $data['exception'] = '否';
             }
             if (isset($data['status'])) $orderPackage->status = $data['status'];
             if (isset($data['received_at'])) $orderPackage->received_at = $data['received_at'];
             if (isset($data['exception'])) $orderPackage->exception = $data['exception'];
-            if (isset($data['transfer_status'])&&!empty($data['transfer_status'])) $orderPackage->transfer_status = $data['transfer_status'];
+            if (isset($data['transfer_status']) && !empty($data['transfer_status'])) $orderPackage->transfer_status = $data['transfer_status'];
             if (isset($data['exception_type'])) $orderPackage->exception_type = $data['exception_type'];
             $orderPackage->save();
         }
@@ -165,6 +190,7 @@ class OrderPackageReceivedSyncService
             try {
                 $logisticCode = $orderPackage->order->logistic->code;
             } catch (Exception $e) {
+                LogService::log(OrderPackageReceivedSyncService::class, "快递同步按照承运商分组异常", $orderPackage->id);
                 continue;
             }
             $key = config('api_logistic.logistic.' . $logisticCode);
@@ -184,6 +210,9 @@ class OrderPackageReceivedSyncService
      */
     public function setExceptionType(array $data, $lastRouteDate): array
     {
+        //设置默认异常为否
+        $data['exception_type'] = '无';
+        $data['exception'] = '否';
         $logistic_number = $data['logistic_number'];
         /** @var OrderPackage $orderPackage */
         $orderPackage = OrderPackage::query()->with('order')->where('logistic_number', $logistic_number)->first();
@@ -296,7 +325,7 @@ class OrderPackageReceivedSyncService
             $conclusion |= ($last_routed_duration > $SHORT_RESPONSE_HOURS && $last_routed_duration < $LONG_RESPONSE_HOURS) ? $IS_SHORT_NO_RESPONSE : 0;
             $conclusion |= ($last_routed_duration > $LONG_RESPONSE_HOURS) ? $IS_LONG_NO_RESPONSE : 0;
             $conclusion |= ($last_routed_duration > $SENDING_RESPONSE_HOURS && $data['status'] == '派送中') ? $IS_SENDING_NO_RESPONSE : 0;
-            $conclusion |= ($delivered_duration > $HAVEN_SECOND_GOT_HOURS && $data['routes_length'] < 3) ? $IS_SECOND_ROUTE_HAVE : 0;//超过指定时间,路由信息小于两
+            $conclusion |= ($delivered_duration > $HAVEN_SECOND_GOT_HOURS && $data['routes_length'] < 3) ? $IS_SECOND_ROUTE_HAVE : 0;//和出库时间比较 超过指定时间,路由信息小于三
             return $conclusion;
         })();
         switch ($conclusion) {
@@ -323,7 +352,7 @@ class OrderPackageReceivedSyncService
         }
         if ($conclusion
             == ($conclusion | $IS_SECOND_ROUTE_HAVE)) {
-            $data['exception_type'] = '件异常';
+            $data['exception_type'] = '件异常';
             $data['exception'] = '是';
 
         }

+ 46 - 25
app/Services/OrderService.php

@@ -176,23 +176,6 @@ class OrderService
                 $sql.=")";
             }
         }
-        if ($soreference1){
-            $arr=array_values(array_filter(preg_split('/[,, ]+/is', $soreference1)));
-            if (count($arr)==1){
-                $sql.=" and soreference1 like '".$soreference1."%'";
-            }
-            if (count($arr)>1){
-                $sql.=" and soreference1 in (";
-                foreach ($arr as $index=>$str){
-                    if ($index==0){
-                        $sql.="'".$str."'";
-                        continue;
-                    }
-                    $sql.=",'".$str."'";
-                }
-                $sql.=")";
-            }
-        }
 //        if ($waveno)$sql.=" and WaveNo like '".$waveno."%'";
         if ($waveno)$sql=$this->sqlSearchWay($sql,$waveno,'WaveNo');
         if ($issuepartyname)$sql.=" and issuepartyname like '".$issuepartyname."%'";
@@ -230,8 +213,25 @@ class OrderService
             }
         }
         if ($edisendflag2) $sql.=" and edisendflag2 like '".$edisendflag2."%'";
-
         if ($edisendflag) $sql.=" and edisendflag like '".$edisendflag."%'";
+        if ($soreference1){
+            $arr=array_values(array_filter(preg_split('/[,, ]+/is', $soreference1)));
+            if (count($arr)==1){
+                $sql.=" and soreference1 like '".$soreference1."%'";
+            }
+            if (count($arr)>1 && !strpos($soreference1,'%')){
+                $sql.=" and soreference1 in (";
+                foreach ($arr as $index=>$str){
+                    if ($index==0){
+                        $sql.="'".$str."'";
+                        continue;
+                    }
+                    $sql.=",'".$str."'";
+                }
+                $sql.=")";
+            }
+            if ($params['soreference']) $sql.=" and soreference1 like '".$params['soreference']."'";
+        }
         return $sql;
     }
 
@@ -247,7 +247,7 @@ class OrderService
             if ($ordernos)$params['ordernos'] = $ordernos;
             else return null;
         }
-        $sql="select ACT_ALLOCATION_DETAILS.CHECKTIME,DOC_ORDER_HEADER.addtime,DOC_ORDER_HEADER.C_PROVINCE,DOC_ORDER_HEADER.C_CITY,DOC_ORDER_HEADER.C_DISTRICT,DOC_ORDER_HEADER.C_CONTACT,DOC_ORDER_HEADER.OrderNo,DOC_ORDER_HEADER.SOStatus,DOC_ORDER_HEADER.WAREHOUSEID,DOC_ORDER_HEADER.CustomerID
+        $sql="SELECT * FROM (select ACT_ALLOCATION_DETAILS.CHECKTIME,DOC_ORDER_HEADER.addtime,DOC_ORDER_HEADER.C_PROVINCE,DOC_ORDER_HEADER.C_CITY,DOC_ORDER_HEADER.C_DISTRICT,DOC_ORDER_HEADER.C_CONTACT,DOC_ORDER_HEADER.OrderNo,DOC_ORDER_HEADER.SOStatus,DOC_ORDER_HEADER.WAREHOUSEID,DOC_ORDER_HEADER.CustomerID as header_customer_id
         ,DOC_ORDER_HEADER.C_Tel2,DOC_ORDER_HEADER.C_Tel1,DOC_ORDER_HEADER.CarrierName,DOC_ORDER_HEADER.IssuePartyName,DOC_ORDER_HEADER.EDIREMARKS2,
        DOC_ORDER_HEADER.WaveNo,DOC_ORDER_HEADER.SOReference1
         ,NVL(ACT_ALLOCATION_DETAILS.PICKTOTRACEID,DOC_ORDER_HEADER.soreference5) as soreference5,DOC_ORDER_HEADER.EDISENDFLAG2,DOC_ORDER_HEADER.EDISendTime2,DOC_ORDER_HEADER.Notes,DOC_ORDER_HEADER.ERPCANCELFLAG,
@@ -298,7 +298,7 @@ class OrderService
                       DOC_ORDER_HEADER.Picking_Print_Flag,DOC_ORDER_HEADER.EDISENDFLAG,DOC_ORDER_HEADER.ReleaseStatus,DOC_ORDER_HEADER.C_Address1,
                       DOC_ORDER_HEADER.OrderTime,DOC_Order_Details.CustomerID,DOC_Order_Details.SKU,DOC_Order_Details.QtyOrdered,DOC_Order_Details.LOTNUM,
                       DOC_Order_Details.LineStatus,DOC_Order_Details.OrderLineNo,order_code.codename_c,order_detail_code.codename_c,BAS_Customer.descr_c,
-                      BAS_SKU.Alternate_SKU1,BAS_SKU.Descr_C ORDER BY DOC_ORDER_HEADER.ADDTIME desc";
+                      BAS_SKU.Alternate_SKU1,BAS_SKU.Descr_C ORDER BY DOC_ORDER_HEADER.ADDTIME desc)";
         return $sql;
     }
 
@@ -323,7 +323,28 @@ class OrderService
             $params['codename_c_end'] = "62";
         }
 
-        $sql = $this->getSql($params,$params['page'] ?? 1, $params['paginate'] ?? 50);
+        if ($params['soreference1']??false){
+            $arr=array_values(array_filter(preg_split('/[,, ]+/is', $params['soreference1'])));
+            if (count($arr)==1){
+                $params['soreference']='';$sql = $this->getSql($params,$params['page'] ?? 1, $params['paginate'] ?? 50);
+            }
+            if (count($arr)>1 && !strpos($params['soreference1'],'%')){
+                $params['soreference']='';$sql = $this->getSql($params,$params['page'] ?? 1, $params['paginate'] ?? 50);
+            }
+            if (count($arr)>1 && strpos($params['soreference1'],'%')){
+                foreach ($arr as $index=>$str){
+                    if ($index==0){
+                        $params['soreference']=$str; $sql=$this->getSql($params,$params['page'] ?? 1, $params['paginate'] ?? 50); continue;
+                    }
+                    $params['soreference']=$str;
+                    $sql.=" union ".$this->getSql($params,$params['page'] ?? 1, $params['paginate'] ?? 50);
+                }
+            }
+        }else{
+            $params['soreference']='';
+            $sql = $this->getSql($params,$params['page'] ?? 1, $params['paginate'] ?? 50);
+        }
+
         if ($sql)$orders=DB::connection('oracle')->select(DB::raw($sql));
         else $orders = [];
         return $this->orderFormat($orders);
@@ -1195,15 +1216,15 @@ sql
             "outer_table_name"  => "orders",
             "work_tax_fee"      => $workTaxFee,
             "logistic_tax_fee"  => $logistic_fee ? $logisticTaxFee : null,
-       ]);
-       if ($detail){
+        ]);
+        if ($detail){
             foreach ($items as &$item)$item["owner_fee_detail_id"] = $detail->id;
             if (count($items)>1)OwnerFeeDetailLogistic::query()->insert($items);
             $this->setOrderQuantity($order->owner_id,$order->logistic_id);
             Cache::put("owner_fee_details:orders_".$order->id,1,86400);
             return true;
-       }
-       return false;
+        }
+        return false;
     }
 
     public function getMonthTotal($ownerId = null, $month = null)

+ 95 - 0
app/Services/OwnerLogisticFeeDetailService.php

@@ -0,0 +1,95 @@
+<?php
+
+namespace App\Services;
+
+use App\OwnerFeeDetail;
+use App\Traits\ServiceAppAop;
+use App\OwnerLogisticFeeDetail;
+use Carbon\Carbon;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Support\Collection;
+
+class OwnerLogisticFeeDetailService
+{
+    use ServiceAppAop;
+
+    /**
+     * @var $modelClass  OwnerLogisticFeeDetail
+     */
+    protected $modelClass = OwnerLogisticFeeDetail::class;
+
+    //插入数据 ServiceAppAop的 insert 方法 支持批量
+
+    /**
+     * 根据货主查询 和时间段查询
+     * @param string $owner_id
+     * @param string $start
+     * @param string $end
+     * @return array
+     */
+    public function getDetails(string $owner_id, string $start, string $end): array
+    {
+        $ownerFeeDetailIds = OwnerFeeDetail::query()->selectRaw('id')
+            ->where('type', '发货')
+            ->where('outer_table_name', 'orders')
+            ->whereHas('logistic', function (Builder $query) {
+                $query->where('type', '快递');
+            })
+            ->where('owner_id', $owner_id)
+            ->where('worked_at', '>=', Carbon::parse($start)->startOfDay())
+            ->where('worked_at', '<=', Carbon::parse($end)->endOfDay())->pluck('id');
+        $ownerLogisticFeeDetails = OwnerLogisticFeeDetail::query()->with(['ownerFeeDetail.logistic', 'ownerFeeDetailLogistic'])->whereIn('owner_fee_detail_id', $ownerFeeDetailIds)->paginate();
+        dd($ownerLogisticFeeDetails);
+
+//         $ownerFeeDetails = OwnerFeeDetail::query()
+//            ->with(['ownerLogisticFeeDetail:id,logistic_bill,initial_weight_price,additional_price', 'items.logistic:id,name','items.ownerLogisticFeeDetail:id,logistic_bill,initial_weight_price,additional_price', 'logistic:id,name,type'])
+//            ->where('type', '发货')
+//            ->where('outer_table_name', 'orders')
+//            ->whereHas('logistic', function (Builder $query) {
+//                $query->where('type', '快递');
+//            })
+//            ->where('owner_id', $owner_id)
+//            ->where('worked_at', '>=', Carbon::parse($start)->startOfDay())
+//            ->where('worked_at', '<=', Carbon::parse($end)->endOfDay())
+//            ->get();
+//        $result = [];
+//        foreach ($ownerFeeDetails as $ownerFeeDetail) {
+//            if ($ownerFeeDetail->items->count()==0) {//只有一个包裹
+//                $result[] = [
+//                    'logistic_name' => $ownerFeeDetail->logistic->name ?? '',//快递公司
+//                    'province' => $ownerFeeDetail->province,//省份
+//                    'logistic_bill' => $ownerFeeDetail->logistic_bill ?? '',//快递单号
+//                    'weight' => $ownerFeeDetail->weight,//重量
+//                    'logistic_fee' => $ownerFeeDetail->logistic_fee,//快递费
+//                    'initial_weight_price' => $ownerFeeDetail->ownerLogisticFeeDetail->initial_weight_price ?? '',//首重价格
+//                    'additional_price' => $ownerFeeDetail->ownerLogisticFeeDetail->additional_price ?? '',//续重价格
+//                ];
+//            } else {//多个包裹
+//                foreach ($ownerFeeDetail->items as $ownerFeeDetailLogistic) {
+//                    $result[] = [
+//                        'logistic_name' => $ownerFeeDetail->logistic->name ?? '',//快递公司
+//                        'province' => $ownerFeeDetail->province,//省份
+//                        'logistic_bill' => $ownerFeeDetailLogistic->logistic_bill,//快递单号
+//                        'weight' => $ownerFeeDetailLogistic->weight,//重量
+//                        'logistic_fee' => $ownerFeeDetailLogistic->logistic_fee,//快递费
+//                        'initial_weight_price' => $ownerFeeDetailLogistic->ownerLogisticFeeDetail->initial_weight_price ?? '',//首重价格
+//                        'additional_price' => $ownerFeeDetailLogistic->ownerLogisticFeeDetail->additional_price ?? '',//续重价格
+//                    ];
+//                }
+//            }
+//        }
+        $result = [];
+        foreach ($ownerLogisticFeeDetails->items() as $ownerLogisticFeeDetail) {
+                $result[] = [
+                    'logistic_name' => $ownerLogisticFeeDetail->ownerFeeDetail->logistic->name ?? '',//快递公司
+                    'province' => $ownerLogisticFeeDetail->ownerFeeDetail->province,//省份
+                    'logistic_bill' => $ownerLogisticFeeDetail->logistic_bill ?? '',//快递单号
+                    'weight' => $ownerLogisticFeeDetail->ownerFeeDetailLogistic->weight,//重量
+                    'logistic_fee' => $ownerLogisticFeeDetail->ownerFeeDetailLogistic->logistic_fee,//快递费
+                    'initial_weight_price' => $ownerLogisticFeeDetail->initial_weight_price ?? '',//首重价格
+                    'additional_price' => $ownerLogisticFeeDetail->additional_price ?? '',//续重价格
+                ];
+        }
+        return $result;
+    }
+}

+ 13 - 0
app/Services/OwnerLogisticFeeReportService.php

@@ -0,0 +1,13 @@
+<?php 
+
+namespace App\Services;
+
+use App\Traits\ServiceAppAop;
+use App\OwnerLogisticFeeReport;
+
+class OwnerLogisticFeeReportService
+{
+    use ServiceAppAop;
+    protected $modelClass=OwnerLogisticFeeReport::class;
+
+}

+ 7 - 1
app/Services/StationService.php

@@ -61,16 +61,20 @@ class StationService
 
 
     function broadcast($station_id, ?StationTask $stationTask){
+        LogService::log('海柔请求in2','broadcast',
+            $station_id.'|'.json_encode($stationTask));
         if($stationTask)
             $json = $stationTask->toJson();
         else
             $json =[];
-        LogService::log('海柔请求','broadcastBinMonitor',
+        LogService::log('海柔请求done2','broadcast',
             $station_id.'|'.$json);
         broadcast(new BroadcastToStation($station_id, $json));
     }
 
     function broadcastBinMonitor($station_id, ?StationTask $stationTask){
+        LogService::log('海柔请求in1','broadcastBinMonitor',
+            $station_id.'|'.json_encode($stationTask));
         if(!$stationTask)return;
         $this->instant($this->stationTaskService,'StationTaskService');
         if($stationTask['status']=='完成')
@@ -82,6 +86,8 @@ class StationService
                 "stationTaskBatches.batch",
                 "stationTaskMaterialBoxes.materialBox",
             ]);
+        LogService::log('海柔请求done1','broadcastBinMonitor',
+            $station_id.'|'.json_encode($stationTask));
         $this->broadcast($station_id, $stationTask);
     }
 

+ 1 - 2
app/Services/StationTaskMaterialBoxService.php

@@ -172,7 +172,6 @@ class StationTaskMaterialBoxService
                     $stationTaskMaterialBox->materialBox->update();
                     break;
                 case '入立库':
-                    $this->taskCompleted($stationTaskMaterialBox);
                     $this->cacheShelfService->putStationTaskMaterialBoxProcess($stationTaskMaterialBox);
                     $stationTaskMaterialBox->materialBox['status']='在立库';
                     $stationTaskMaterialBox->materialBox->update();
@@ -181,13 +180,13 @@ class StationTaskMaterialBoxService
                     $this->storageService->checkMark($stationTaskMaterialBox); //检查标记并做一些特殊处理
                     break;
                 case '入缓存架':
-                    $this->taskCompleted($stationTaskMaterialBox);
                     $stationTaskMaterialBox->materialBox['status']='在缓存架';
                     $stationTaskMaterialBox->materialBox->update();
                     $this->storageService->putCacheShelf($stationTaskMaterialBox);
                     break;
                 default:;
             }
+            $this->taskCompleted($stationTaskMaterialBox);
         }catch (\Exception $e){
             throw new ErrorException('放置料箱出错');
         }

+ 4 - 3
app/Services/WaybillService.php

@@ -171,12 +171,13 @@ class WaybillService
             ->orderBy('waybill_on_tops.updated_at','desc')
             ->orderBy('waybills.id','desc')
             ->where('waybills.type','专线')
+            ->where('waybills.amount','>',0)
             ->where('waybills.deliver_at','like',$param['screenDate'].'%')
             ->get();
-        if ($waybills->isEmpty()) return false;
+        if ($waybills->isEmpty()) return '无数据';
         foreach ($waybills as $waybill){
             if (!$waybill['carrier_weight_other'] && !$waybill['carrier_weight']) return null;
-            if (!$waybill['carrier_weight_other']) $waybill['carrier_weight_other']=($waybill['carrier_weight']/0.004);
+            if (!$waybill['carrier_weight_other'] || $waybill['carrier_weight_other']<=0) $waybill['carrier_weight_other']=($waybill['carrier_weight']/0.25*100);
         }
         $daily_total_weight=$waybills->sum('carrier_weight_other');
         $updateParams = [['id','pick_up_fee','updated_at']];
@@ -184,7 +185,7 @@ class WaybillService
             $waybill['pick_up_fee']=round(($waybill->carrier_weight_other/$daily_total_weight)*$param['billing']);
             $updateParams[] = [
                 'id' => $waybill->id,
-                'pick_up_fee' => (($waybill->carrier_weight_other/$daily_total_weight)*$param['billing']),
+                'pick_up_fee' =>(($waybill->carrier_weight_other/$daily_total_weight)*$param['billing']),
                 'updated_at' => Carbon::now()->toDateTimeString(),
             ];
         }

+ 42 - 0
app/Services/weight/GoodScanWeightService.php

@@ -0,0 +1,42 @@
+<?php
+
+namespace App\Services\weight;
+
+
+class GoodScanWeightService extends WeightService
+{
+    public $weight = 'weight';       // 重量
+    public $length = 'l';            // 长
+    public $width = 'w';             // 宽
+    public $height = 'h';            // 高
+    public $code = 'code';           // 快递单号
+    public $weight_at = 'time'; // 称重时间
+    public $hid = 'hid';             // 称重设备id
+    public $name = 'GoodScan';          // 名称
+
+    public function getSuccessMessage($params, $orderPackage): array
+    {
+        return ["code" => 0, 'error' => 'upload success'];
+    }
+
+    public function getNotFindOrderPackageMessage($params, $orderPackage): array
+    {
+        return ['code' => 500, 'error' => '未找打包裹信息'];
+    }
+
+    public function getNotFindOrderHeaderMessage($params, $orderPackage): array
+    {
+        return ['code' => 500, 'error' => '保存时发生错误(未在WMS中找到订单)!'];
+    }
+
+    public function getWeightMessage($orderPackage, $e): array
+    {
+        return ['code' => 500, 'error' => $e->getMessage];
+    }
+
+    public function getWriteWasFailMessage($params, $orderPackage): array
+    {
+        return ["code" => 500, "error" => "写入WMS失败!"];
+    }
+
+}

+ 49 - 0
app/Services/weight/HaoChuangWeightService.php

@@ -0,0 +1,49 @@
+<?php
+
+namespace App\Services\weight;
+
+
+use Illuminate\Support\Carbon;
+
+class HaoChuangWeightService extends WeightService
+{
+    public $weight = 'weight';     // 重量
+    public $length = 'length';     // 长
+    public $width = 'width';      // 宽
+    public $height = 'height';     // 高
+    public $code = 'barcode';       // 快递单号
+    public $weight_at = 'weight_at';  // 称重时间
+    public $hid = 'id';        // 称重设备id
+    public $name = 'HaoChuang';       // 名称
+
+    public function getSuccessMessage($params, $orderPackage): array
+    {
+        return ['code' => 200, 'msg' => '保存成功', 'data' => true, 'serverMsg' => null,
+            "requestor" => [
+                "requestor" => "1",
+                "eventCode" => "0",
+                "reqDate" => $orderPackage->weighed_at ?? Carbon::now()->format(Carbon::DEFAULT_TO_STRING_FORMAT),
+                "resDate" => Carbon::now()
+            ]];
+    }
+
+    public function getNotFindOrderPackageMessage($params, $orderPackage): array
+    {
+        return ['code' => 500, 'msg' => '未找打包裹信息', 'data' => null];
+    }
+
+    public function getNotFindOrderHeaderMessage($params, $orderPackage): array
+    {
+        return ['code' => 500, 'msg' => '富勒信息未找到', 'data' => null];
+    }
+
+    public function getWeightMessage($orderPackage, $e): array
+    {
+        return ['code' => 500, 'msg' => '称重下发修改时发生错误'.json_encode($e), 'data' => null];
+    }
+
+    public function getWriteWasFailMessage($params,$orderPackage): array
+    {
+        return ['code' => 500 ,'msg' => '写入Was包裹失败!', 'data' => null];
+    }
+}

+ 45 - 0
app/Services/weight/HengLiWeightService.php

@@ -0,0 +1,45 @@
+<?php
+
+namespace App\Services\weight;
+
+
+
+class HengLiWeightService extends WeightService
+{
+    // 参数
+    public $weight = 'weight';     // 重量
+    public $length = 'length';     // 长
+    public $width = 'width';      // 宽
+    public $height = 'height';     // 高
+    public $code = 'code';       // 快递单号
+    public $weight_at = 'weight_at';  // 称重时间
+    public $hid = 'hid';        // 称重设备id
+    public $name = 'HengLi';       // 名称
+
+    public function getWeightValue($params)
+    {
+        $value = $this->getValue($this->weight, $params);
+        return str_replace('_', '.', $value);
+    }
+
+    public function getSuccessMessage($params, $orderPackage): array
+    {
+        return ['success' => true, 'message' => '称重成功'];
+    }
+
+    public function getNotFindOrderPackageMessage($params, $orderPackage): array
+    {
+        return ['success' => false, 'message' => '未找打包裹信息'];
+    }
+
+    public function getNotFindOrderHeaderMessage($params, $orderPackage): array
+    {
+        return ['success' => false, 'message' => '富勒信息未找到'];
+    }
+
+    public function getWeightMessage($orderPackage, $e): array
+    {
+        return ['success' => false, 'message' => $e->getMessage];
+    }
+
+}

+ 503 - 0
app/Services/weight/WeightService.php

@@ -0,0 +1,503 @@
+<?php
+
+namespace App\Services\weight;
+
+
+use App\Events\WeighedEvent;
+use App\Http\Controllers\api\thirdPart\flux\PackageController;
+use App\Jobs\WeightUpdateInstantBill;
+use App\MeasuringMachine;
+use App\OracleActAllocationDetails;
+use App\OracleDOCOrderHeader;
+use App\OrderPackage;
+use App\Services\OrderService;
+use App\Waybill;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Support\Carbon;
+
+class WeightService
+{
+    public $weight = '';     // 重量
+    public $length = '';     // 长
+    public $width = '';      // 宽
+    public $height = '';     // 高
+    public $code = '';       // 快递单号
+    public $weight_at = '';  // 称重时间
+    public $hid = '';        // 称重设备id
+    public $name = '';       // 名称
+
+    public function new(array $params): array
+    {
+        $params = $this->conversionParams($params);
+        return $this->weightOrderPackage($params);
+    }
+
+    /**
+     * 参数转换
+     * @param array $params
+     * @return array
+     */
+    public function conversionParams(array $params): array
+    {
+        return $params;
+    }
+
+    /**
+     * 包裹称重
+     * @param array $params
+     * @return array
+     */
+    public function weightOrderPackage(array $params): array
+    {
+
+        // 2.获取快递单号
+        $logistic_number = $this->getCodeValue($params);
+
+        if (!$logistic_number) return $this->getLogisticNumberIsNullMessage($params);
+        // 3、获取称重设备
+        $measuringMachine = $this->getMeasuringMachine($params);
+        /** @var OrderPackage $orderPackage */
+        $orderPackage = $this->getOrderPackageByCode($logistic_number);
+
+        // 4、快递单号对应的OrderPackage
+        if (is_null($orderPackage)) {
+            /** @var OracleDOCOrderHeader $orderHeader */
+            $orderHeader = $this->findOrderHeaderByLogisticNumber($logistic_number);
+            if (is_null($orderHeader)) {
+                return $this->getNotFindOrderHeaderMessage($params, $orderPackage);
+            }
+            try {
+                $order = $this->createOrderByOrderHeader($orderHeader);
+                $orderPackage = $this->createOrderPackage($params, $measuringMachine, $order);
+            } catch (\Exception $e) {
+                return $this->getWriteWasFailMessage($params, $orderPackage);
+            }
+        }
+
+
+        // 5、更新包裹信息
+        $bool = $this->updateOrderPackage($orderPackage, $params, $measuringMachine);
+        // 6、称重时间
+        if ($bool) $this->afterApply($orderPackage);
+        else {
+            app('LogService')->log(__METHOD__, $this->name, '写入WAS失败! (Error)', $logistic_number, null);
+            return $this->getUpdatePackageMessage($orderPackage);
+        }
+
+        // 7、处理波次信息 推送至WMS称重信息
+        try {
+            $this->activityWaveNoProcessing($orderPackage);
+        } catch (\Exception $e) {
+            return $this->getWeightMessage($orderPackage, $e);
+        }
+
+        return $this->getSuccessMessage($params, $orderPackage);
+    }
+
+
+// region ---消息返回
+
+    /**
+     * 称重成功
+     * @param $params
+     * @param $orderPackage
+     * @return array
+     */
+    public function getSuccessMessage($params, $orderPackage): array
+    {
+        return ['success' => true, 'message' => '称重成功'];
+    }
+
+    /**
+     * 没有找到对应的包裹信息
+     * @param $params
+     * @param $orderPackage
+     * @return array
+     */
+    public function getNotFindOrderPackageMessage($params, $orderPackage): array
+    {
+        return ['success' => false, 'message' => '未找打包裹信息'];
+    }
+
+    /**
+     * 富勒信息对应快递单号错误
+     * @param $params
+     * @param $orderPackage
+     * @return array
+     */
+    public function getNotFindOrderHeaderMessage($params, $orderPackage): array
+    {
+        return ['success' => false, 'message' => '富勒信息未找到'];
+    }
+
+    /**
+     * 称重下发修改错误
+     * @param $orderPackage
+     * @param $e
+     * @return array
+     */
+    public function getWeightMessage($orderPackage, $e): array
+    {
+        return ['success' => false, 'message' => $e->getMessage];
+    }
+
+    /**
+     * 更新包裹信息异常错误返回
+     * @param $orderPackage
+     * @return array
+     */
+    public function getUpdatePackageMessage($orderPackage): array
+    {
+        return ['success' => false, 'message' => '更新包裹信息出现异常'];
+    }
+
+    /**
+     * 快递单号过滤后为空
+     * @param $params
+     * @return array
+     */
+    public function getLogisticNumberIsNullMessage($params): array
+    {
+        return ['success' => false, 'message' => '快递单号过滤后为空'];
+    }
+
+    /**
+     * 写入Was失败信息
+     * @param $params
+     * @param $orderPackage
+     * @return array
+     */
+    public function getWriteWasFailMessage($params, $orderPackage): array
+    {
+        return ['success' => false, 'message' => '写入was失败!'];
+    }
+
+// endregion
+
+//  region ---称重完成之后的操作
+
+    /**
+     * 称重完成后的后续操作
+     * @param OrderPackage $orderPackage
+     */
+    public function afterApply(OrderPackage $orderPackage)
+    {
+        $orderPackage->loadMissing(['order' => function ($query) {
+            $query->with('owner', 'logistic');
+        }, 'measuringMachine', 'paperBox']);
+        event(new WeighedEvent($orderPackage));                 // 称重信息播报
+        dispatch(new WeightUpdateInstantBill($orderPackage));   // 及时订单
+        if(!empty($orderPackage->order)){
+            Waybill::setWeightByOrderCode($orderPackage->order->code,$orderPackage['weight']);
+        }
+    }
+
+// endregion
+
+// region  ---参数获取
+    /**
+     * 重量
+     * @param $params
+     * @return mixed|null
+     */
+    public function getWeightValue($params)
+    {
+        return $this->getValue($this->weight, $params);
+    }
+
+    /**
+     * 高
+     * @param $params
+     * @return mixed|null
+     */
+    public function getHeightValue($params)
+    {
+        return $this->getValue($this->height, $params);
+    }
+
+    /**
+     * 长
+     * @param $params
+     * @return mixed|null
+     */
+    public function getLengthValue($params)
+    {
+        return $this->getValue($this->length, $params);
+    }
+
+    /**
+     * 宽
+     * @param $params
+     * @return mixed|null
+     */
+    public function getWidthValue($params)
+    {
+        return $this->getValue($this->width, $params);
+    }
+
+    /**
+     * 获取快递单号
+     * @param $params
+     * @return mixed|null
+     */
+    public function getCodeValue($params)
+    {
+        return $this->getValue($this->code, $params);
+    }
+
+    /**
+     * 称重时间
+     * @param $params
+     * @return mixed|null
+     */
+    public function getWeightAtValue($params)
+    {
+        return $this->getValue($this->weight_at, $params);
+    }
+
+    /**
+     * 获取参数
+     * @param $name
+     * @param $param
+     * @return mixed|null
+     */
+    public function getValue($name, $param)
+    {
+        $names = explode(',', $name);
+        $value = array_reduce($names, function ($data, $key) {
+            if (isset($data[$key])) $data = $data[$key];
+            else $data = [];
+            return $data;
+        }, $param);
+        if (is_array($value) && count($value) == 0) return null;
+        return $value;
+    }
+
+    /**
+     * 体积参数排序
+     * @param $params
+     * @return array
+     */
+    public function getEdges($params): array
+    {
+        $length = $this->getLengthValue($params);
+        $height = $this->getHeightValue($params);
+        $width = $this->getWidthValue($params);
+        $edges = [$length ?? 0, $width ?? 0, $height ?? 0];
+        rsort($edges);
+        return $edges;
+    }
+
+// endregion
+
+//  region ---包裹
+
+    /**
+     * 获取单号对应的包裹
+     * @param $code
+     * @return Builder|Model|object|null
+     */
+    public function getOrderPackageByCode($code)
+    {
+        return OrderPackage::query()
+            ->with(['order' => function ($query) {
+                /** @var Builder $query */
+                $query->with('owner', 'logistic');
+            }])->where('logistic_number', $code)->first();
+    }
+
+    /**
+     * 更新包裹信息
+     * @param OrderPackage $orderPackage
+     * @param $params
+     * @param $measuringMachine
+     * @return bool
+     */
+    public function updateOrderPackage(OrderPackage $orderPackage, $params, $measuringMachine): bool
+    {
+        $edges = $this->getEdges($params);
+        $req_date = Carbon::now()->toDateTimeString();
+        $orderPackage['weight'] = $this->getWeightValue($params);
+        $orderPackage['measuring_machine_id'] = $measuringMachine['id'];
+        $orderPackage['length'] = $edges[0];
+        $orderPackage['width'] = $edges[1];
+        $orderPackage['height'] = $edges[2];
+        $orderPackage['weighed_at'] = $req_date;
+        $orderPackage['bulk'] = $edges[0] * $edges[1] * $edges[2];
+        return $orderPackage->save();
+    }
+
+    /**
+     * 创建包裹信息
+     * @param $params
+     * @param $measuringMachine
+     * @param $order
+     * @return Builder|Model|object|null
+     */
+    public function createOrderPackage($params, $measuringMachine, $order)
+    {
+        $weighed_at = Carbon::now()->format(Carbon::DEFAULT_TO_STRING_FORMAT);
+        $edges = $this->getEdges($params);
+        OrderPackage::query()->create([
+            'order_id' => $order->id,
+            'logistic_number' => $this->getCodeValue($params),
+            'measuring_machine_id' => $measuringMachine->id,
+            'weight' => $this->getWeightValue($params),
+            'length' => $edges[0],
+            'width' => $edges[1],
+            'height' => $edges[2],
+            'bulk' => $edges[0] * $edges[1] * $edges[2],
+            'weighed_at' => $weighed_at,
+            'status' => "无",
+        ]);
+        return $this->getOrderPackageByCode($this->getCodeValue($params));
+    }
+
+//  endregion
+
+//  region ---称重设备
+
+    /**
+     * 称重机获取
+     * @param $params
+     * @return MeasuringMachine
+     */
+    public function getMeasuringMachine($params): MeasuringMachine
+    {
+        $hid = $this->getValue($this->hid, $params);
+        /** @var MeasuringMachine $measuringMachine */
+        $measuringMachine = MeasuringMachine::query()->firstOrCreate(['code' => $hid], ['name' => $hid]); // 称重设备
+        $measuringMachine->turnOn();
+        $measuringMachine->turnOffInMinutes(30);
+        return $measuringMachine;
+    }
+//  endregion
+
+// region ---wms操作
+
+    /**
+     * 根据快递单号找到对应的WMS订单信息
+     * @param $code
+     * @return Builder|Model|object|null
+     */
+    public function findOrderHeaderByLogisticNumber($code)
+    {
+        $query = OracleActAllocationDetails::query()->select('OrderNO')->where('PickToTraceId', $code);
+        $orderHeader = OracleDOCOrderHeader::query()->with('actAllocationDetails', 'oracleBASCode')->whereIn('OrderNO', $query)->first();
+        if ($orderHeader == null) {
+            $orderHeader = OracleDOCOrderHeader::query()->with('actAllocationDetails', 'oracleBASCode')->where('SOReference5', $code)->first();
+        }
+        return $orderHeader;
+    }
+
+    /**
+     * 同步wms订单信息
+     * @param $orderHeader
+     * @return Builder|Model|object
+     */
+    public function createOrderByOrderHeader($orderHeader)
+    {
+        /** @var OrderService $orderService */
+        $orderService = app(OrderService::class);
+        $order_create_params = $orderService->getParamByOrderHeader($orderHeader);
+        $order = $orderService->first(['code' => $orderHeader->orderno]);
+        if ($order) return $order;
+        $order = $orderService->createOrder($order_create_params);
+        app('LogService')->log(__METHOD__, $this->name, ' 创建Order', json_encode($order) . " || " . $orderHeader);
+        return $order;
+    }
+
+    /**
+     * 活动波次处理
+     * @param $orderPackage
+     */
+    public function activityWaveNoProcessing(&$orderPackage)
+    {
+        $fluxController = new PackageController();
+        if ($orderPackage->isActivityBatch()) {
+            app('LogService')->log(__METHOD__, $this->name . " 依波次号同步所有包裹", json_encode($orderPackage), null);
+            OrderPackage::query()->where('batch_number', $orderPackage['batch_number'])->update([
+                'weight' => $orderPackage['weight'] ?? null,
+                'length' => $orderPackage['length'] ?? null,
+                'width' => $orderPackage['width'] ?? null,
+                'height' => $orderPackage['height'] ?? null,
+                'bulk' => $orderPackage['bulk'] ?? null,
+                'measuring_machine_id' => $orderPackage['measuring_machine_id'] ?? null,
+                'weighed_at' => $orderPackage['weighed_at'] ?? null,
+                'paper_box_id' => $orderPackage['paper_box_id'] ?? null,
+            ]);
+            $result = $fluxController->markWMSOnBatch($orderPackage['batch_number'], $orderPackage['weight']);
+            if (!$result['result']) {
+                $orderPackage->uploaded_to_wms = "异常";
+            }
+        } else {
+            app('LogService')->log(__METHOD__, $this->name . " 写入包裹至WMS异常", json_encode($orderPackage), null);
+            try {
+                $result = $fluxController->accomplishToWMS($orderPackage);
+                if ($result['result'] == 'success') $orderPackage->uploaded_to_wms = "是";
+                else $orderPackage->uploaded_to_wms = "异常";
+            } catch (\Exception $e) {
+                $orderPackage->uploaded_to_wms = "否";
+            }
+        }
+        $orderPackage->save();
+    }
+// endregion
+
+// region ---上传快递单号处理
+
+    /**
+     * 快递单号处理
+     *
+     * @param $code
+     * @return string
+     */
+    public function processCode($code): string
+    {
+
+        /** 如果是$code 是数组处理 */
+        if (is_array($code)) {
+            return $this->processCodeArr($code);
+        }
+        return $this->processCodeStr($code);
+    }
+
+    /**
+     *  快递单号 array 处理
+     *
+     * @param array $code
+     * @return mixed|string
+     */
+    public function processCodeArr(array $code): string
+    {
+        usort($code, function ($codeA, $codeB) {
+            if (strlen($codeA) == strlen($codeB)) return 0;
+            return strlen($codeA) > strlen($codeB) ? 1 : -1;
+        });
+        return $code[0];
+    }
+
+    /**
+     * 快递单号 string 处理
+     *
+     * @param $code
+     * @return string|null
+     */
+    public function processCodeStr($code): ?string
+    {
+        $codes = [];
+        preg_match_all('/[\w]+/', $code, $codes);
+        if (count($codes) == 0) return $code;
+        $codes = array_unique(array_filter(array_shift($codes), function ($item) {
+            return strlen($item) > 8;
+        }));
+        usort($codes, function ($a, $b) {
+            if (strlen($a) == strlen($b)) return 0;
+            return strlen($a) < strlen($b) ? 1 : -1;
+        });
+        return $codes[0] ?? null;
+    }
+
+// endregion
+}

+ 5 - 0
app/Station.php

@@ -49,4 +49,9 @@ class Station extends Model
             ->where('status','=','待处理');
     }
 
+    public function storage(): HasOne
+    {
+        return $this->hasOne(Storage::class);
+    }
+
 }

+ 19 - 2
app/User.php

@@ -98,8 +98,7 @@ class User extends Authenticatable
 
     function authorities(){
         $authorities = new Collection([]);
-        $user=User::query()->where('id',$this['id'])->with('roles.authorities')->first();
-        $user->roles->each(function ($role)use(&$authorities){
+        $this->roles->each(function ($role)use(&$authorities){
             if($role->authorities){
                 if(!$authorities){
                     $authorities=$role->authorities;
@@ -139,4 +138,22 @@ class User extends Authenticatable
         }
         return $workgroupIds;
     }
+    function getPermittingLaborCompanyIdsAttribute(): array
+    {
+        $labor_company_ids=array();
+        if($this->isSuperAdmin()||Gate::allows('劳务所-可见全部')){
+            $laborCompanies=LaborCompany::all();
+        }else{
+           $userId=$this['id'];
+           $laborCompanies=LaborCompany::query()->whereIn('id',function ($query)use($userId){
+               $query->from('role_labor_company')->selectRaw('labor_company_id')->whereIn('role_id',function ($builder)use ($userId){
+                   $builder->from('user_role')->selectRaw('id_role')->where('id_user',$userId);
+               });
+           })->get();
+        }
+        $laborCompanies->each(function (LaborCompany $laborCompany) use (&$labor_company_ids) {
+            array_push($labor_company_ids, $laborCompany['id']);
+        });
+        return array_unique($labor_company_ids);
+    }
 }

+ 10 - 1
app/Utils/helpers.php

@@ -3,6 +3,8 @@
 use Carbon\Carbon;
 use Illuminate\Database\Eloquent\Model;
 
+const DAY_TO_MILLI_SECONDS  = 1000*60*60*24;
+
 function formatExcelDate(int $timestamp)
 {
     $diff = intval($timestamp);
@@ -11,6 +13,13 @@ function formatExcelDate(int $timestamp)
     return $day->toDateString();
 }
 
+function formatExcelDateTime(float $timestamp): string
+{
+    $today = new Carbon('1900-01-01');
+    $day = $today->addMilliseconds(intval($timestamp*DAY_TO_MILLI_SECONDS))->subDays(2);
+    return $day->toDateTimeString();
+}
+
 function diff($array1,$array2,string $identification,array $mapping,bool $intactDetached = false):array
 {
     $changes = [
@@ -48,4 +57,4 @@ function diff($array1,$array2,string $identification,array $mapping,bool $intact
         }else $changes['detached'][] = array_keys($map);
     }
     return $changes;
-}
+}

+ 0 - 23
app/library/zop/README.md

@@ -1,23 +0,0 @@
-# 中通开放平台SDK(php版)
-
-## 使用方式
-
-```php
-use App\library\zop\ZopClient;
-use App\library\zop\ZopProperties;
-use App\library\zop\ZopRequest;
-
-// ZopProperties类的构造方法接收两个参数,分别是companyid和key,都需要注册中通开放平台后到个人中心查看
-$properties = new ZopProperties("kfpttestCode", "kfpttestkey==");
-$client = new ZopClient($properties);
-
-$request = new ZopRequest();
-$request->setUrl("http://58.40.16.120:9001/submitOrderCode");
-$request->setData('{"data":{"content":{"branchId":"","buyer":"","collectMoneytype":"CNY","collectSum":"12.00","freight":"10.00","id":"xfs2018031500002222333","orderSum":"0.00","orderType":"1","otherCharges":"0.00","packCharges":"1.00","premium":"0.50","price":"126.50","quantity":"2","receiver":{"address":"育德路XXX号","area":"501022","city":"四川省,XXX,XXXX","company":"XXXX有限公司","email":"yyj@abc.com","id":"130520142097","im":"yangyijia-abc","mobile":"136*****321","name":"XXX","phone":"010-222***89","zipCode":"610012"},"remark":"请勿摔货","seller":"","sender":{"address":"华新镇华志路XXX号","area":"310118","city":"上海,上海市,青浦区","company":"XXXXX有限公司","email":"ll@abc.com","endTime":1369033200000,"id":"131*****010","im":"1924656234","mobile":"1391***5678","name":"XXX","phone":"021-87***321","startTime":1369022400000,"zipCode":"610012"},"size":"12,23,11","tradeId":"2701843","type":"1","typeId":"","weight":"0.753"},"datetime":"2018-3-30 12:00:00","partner":"test","verify":"ZTO123"}}');
-
-echo $client->execute($request);
-```
-
-## 其他
-1. 该项目刚创建,功能还很不完善,如有问题请提issue
-2. 由于中通开放平台各个接口返回值格式没有统一,所以未封装返回值,未来可能会做封装

+ 0 - 60
app/library/zop/ZopClient.php

@@ -1,60 +0,0 @@
-<?php
-
-
-namespace App\library\zop;
-use App\library\zop\ZopHttpUtil;
-use Illuminate\Support\Facades\Http;
-
-class ZopClient
-{
-    private $zopProperties;
-
-    private $httpClient;
-    /**
-     * ZopClient constructor.
-     * @param $zopProperties
-     */
-    public function __construct($zopProperties)
-    {
-        $this->zopProperties = $zopProperties;
-        $this->httpClient = new ZopHttpUtil();
-    }
-
-    public function execute($zopRequest)
-    {
-        if($zopRequest->getBody()==null) {
-            $url = $zopRequest->getUrl();
-            $params = $zopRequest->getParams();
-            $fixedParams = array();
-            foreach ($params as $k => $v) {
-                if (gettype($v) != "string") {
-                    $fixedParams += [$k => json_encode($v)];
-                } else {
-                    $fixedParams += [$k => $v];
-                }
-            }
-            $str_to_digest = "";
-            foreach ($fixedParams as $k => $v) {
-                $str_to_digest = $str_to_digest .$k ."=" .$v ."&";
-            }
-            $str_to_digest = substr($str_to_digest, 0, -1) .$this->zopProperties->getKey();
-            $data_digest = base64_encode(md5($str_to_digest, TRUE));
-            $headers = array(
-                "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
-                "x-companyid: " . $this->zopProperties->getCompanyid(),
-                "x-datadigest: " . $data_digest
-            );
-            return $this->httpClient->post($url, $headers, http_build_query($fixedParams), 2000);
-        } else {
-            $url = $zopRequest->getUrl();
-            $body = $zopRequest->getBody();
-            $str_to_digest = $body . $this->zopProperties->getKey();
-            $data_digest = base64_encode(md5($str_to_digest, TRUE));
-            return Http::withHeaders([
-                'Content-Type' => 'application/json; charset=UTF-8',
-                'x-companyid' => $this->zopProperties->getCompanyid(),
-                'x-datadigest' => $data_digest,
-            ])->withBody(json_encode((array)json_decode($body), JSON_UNESCAPED_UNICODE), 'application/json')->post($url)->body();
-        }
-    }
-}

+ 0 - 20
app/library/zop/ZopHttpUtil.php

@@ -1,20 +0,0 @@
-<?php
-
-namespace App\library\zop;
-
-class ZopHttpUtil
-{
-    public function post($url, $headers, $querystring, $timeout)
-    {
-        $ch = curl_init();
-        curl_setopt($ch, CURLOPT_URL, $url);//设置链接
-        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
-        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);//设置HTTP头
-        curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式
-        curl_setopt($ch, CURLOPT_TIMEOUT_MS, $timeout);
-        curl_setopt($ch, CURLOPT_POSTFIELDS, $querystring);
-        $response = curl_exec($ch);
-        return $response;
-    }
-
-}

+ 0 - 46
app/library/zop/ZopProperties.php

@@ -1,46 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: choco
- * Date: 6/13/18
- * Time: 5:47 PM
- */
-namespace App\library\zop;
-
-
-class ZopProperties
-{
-    private $companyid;
-    private $key;
-
-    /**
-     * ZopProperties constructor.
-     * @param $companyid
-     * @param $key
-     */
-    public function __construct($companyid, $key)
-    {
-        $this->companyid = $companyid;
-        $this->key = $key;
-    }
-
-    /**
-     * @return mixed
-     */
-    public function getCompanyid()
-    {
-        return $this->companyid;
-    }
-
-    /**
-     * @return mixed
-     */
-    public function getKey()
-    {
-        return $this->key;
-    }
-
-
-
-
-}

+ 0 - 59
app/library/zop/ZopRequest.php

@@ -1,59 +0,0 @@
-<?php
-
-namespace App\library\zop;
-
-
-class ZopRequest
-{
-    private $url;
-    private $params = Array();
-    private $body;
-
-    public function addParam($k, $v)
-    {
-        $this->params += [$k => $v];
-    }
-
-    /**
-     * @param mixed $url
-     */
-    public function setUrl($url)
-    {
-        $this->url = $url;
-    }
-
-    public function setData($data)
-    {
-        $this->params = json_decode($data);
-    }
-
-    public function setBody($body)
-    {
-        $this->body = $body;
-    }
-
-    public function getBody()
-    {
-        return $this->body;
-    }
-
-
-
-    /**
-     * @return mixed
-     */
-    public function getUrl()
-    {
-        return $this->url;
-    }
-
-    /**
-     * @return array
-     */
-    public function getParams()
-    {
-        return $this->params;
-    }
-
-
-}

+ 1 - 5
composer.json

@@ -66,11 +66,7 @@
             "database/factories"
         ],
         "files": [
-            "app/Utils/helpers.php",
-            "app/library/zop/ZopClient.php",
-            "app/library/zop/ZopHttpUtil.php",
-            "app/library/zop/ZopProperties.php",
-            "app/library/zop/ZopRequest.php"
+            "app/Utils/helpers.php"
         ]
     },
     "autoload-dev": {

文件差異過大導致無法顯示
+ 158 - 239
composer.lock


+ 13 - 0
config/api_logistic.php

@@ -152,6 +152,19 @@ return [
             ],
         ],
     ],
+    'AliJiSu' => [
+        'prod' => [
+            'app-key' => '203946797',
+            'app-secret' => '5jlb4OfKkVFAbEXa7ebvnSQt5wCLQqWb',
+            'app-code' => '531dca65c4df41bfaa0c58cb52f444db',
+            'type' => 'auto',
+            'method' => 'GET',
+            'search' => [
+                'host' => 'https://jisukdcx.market.alicloudapi.com',
+                'path' => '/express/query',
+            ],
+        ],
+    ],
     'init_date' => '2021-05-17 23:59:59',
     'days' => 2,
 ];

+ 2 - 2
config/cache.php

@@ -16,8 +16,8 @@ return [
 
         'owners'=>20,           //模型Owner
         'orderCountingRecord'=>1800,           //模型Owner
-        'logisticsCountingRecords'=>86400,           //快递饼图缓存时间
-        'warehouseCountingRecords'=>86400,           //仓库饼图缓存时间
+        'logisticsCountingRecords'=>1800,           //快递饼图缓存时间
+        'warehouseCountingRecords'=>1800,           //仓库饼图缓存时间
     ],
     /*
     |--------------------------------------------------------------------------

+ 0 - 1
database/factories/OrderCountingRecordFactory.php

@@ -14,7 +14,6 @@ use Illuminate\Database\Eloquent\Factory;
 $factory->define(OrderCountingRecord::class, function (Faker $faker) {
     return [
         'owner_id' => $faker->numberBetween(0, 100),
-        'shop_id' => $faker->numberBetween(0, 100),
         'warehouse_id' => $faker->numberBetween(0, 100),
         'logistic_id' => $faker->numberBetween(0, 100),
         'date_target' => Carbon::now()->toDateString(),

+ 16 - 0
database/factories/OrderPackageReceivedSyncRecordFactory.php

@@ -0,0 +1,16 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OrderPackageReceivedSyncRecord;
+use Faker\Generator as Faker;
+
+$factory->define(OrderPackageReceivedSyncRecord::class, function (Faker $faker) {
+    $logistic_names = ['中通', '顺丰', '韵达', '圆通', '其他'];
+    return [
+        'logistic_name' => $faker->randomElement($logistic_names),
+        'recorded_at' => now()->toDateString(),
+        'succeed_count' => random_int(10000, 20000),
+        'failed_count' => random_int(10000, 20000),
+    ];
+});

+ 17 - 0
database/factories/OwnerLogisticFeeDetailFactory.php

@@ -0,0 +1,17 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OwnerLogisticFeeDetail;
+use Faker\Generator as Faker;
+
+$factory->define(OwnerLogisticFeeDetail::class, function (Faker $faker) {
+    return [
+        'owner_fee_detail_id'=>random_int(1,100),
+        'logistic_bill'=>$faker->uuid,
+        'initial_weight'=>random_int(1,100),
+        'initial_weight_price'=>random_int(1,100),
+        'additional_weight'=>random_int(1,100),
+        'additional_price' => random_int(1, 100),
+    ];
+});

+ 12 - 0
database/factories/OwnerLogisticFeeReportFactory.php

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

+ 11 - 0
database/factories/OwnerSundryFeeDetailFactory.php

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

+ 1 - 0
database/factories/StationTaskFactory.php

@@ -9,5 +9,6 @@ $factory->define(StationTask::class, function (Faker $faker) {
     $status = ['待处理','挂起','处理中','完成','异常','取消'];
     return [
         "status"=>'待处理',
+        'station_id' => 0
     ];
 });

+ 6 - 1
database/factories/StationTaskMaterialBoxFactory.php

@@ -7,6 +7,11 @@ use Faker\Generator as Faker;
 
 $factory->define(StationTaskMaterialBox::class, function (Faker $faker) {
     return [
-        'status'=>'待处理'
+        'station_id' => 0,
+        'material_box_id' => 0,
+        'status'=>'待处理',
+        'type' => 0,
+        'station_task_batch_id' =>0 ,
+        'station_task_id' => 0
     ];
 });

+ 15 - 0
database/factories/StorageFactory.php

@@ -0,0 +1,15 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use Faker\Generator as Faker;
+
+$factory->define(\App\Storage::class, function (Faker $faker) {
+    return [
+        "station_id" => rand(0,10),
+        "material_box_id" =>  rand(0,10),
+        "commodity_id" => 0 ,
+        "amount" => 0,
+        "status" => 0,
+    ];
+});

+ 4 - 3
database/migrations/2020_11_30_140957_create_station_types_table.php

@@ -1,5 +1,6 @@
 <?php
 
+use App\StationType;
 use Illuminate\Database\Migrations\Migration;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Support\Facades\Schema;
@@ -18,9 +19,9 @@ class CreateStationTypesTable extends Migration
             $table->string('name')->index();
             $table->timestamps();
         });
-        \App\StationType::query()->firstOrCreate(['name'=>'料箱出货口']);
-        \App\StationType::query()->firstOrCreate(['name'=>'料箱入货口']);
-        \App\StationType::query()->firstOrCreate(['name'=>'料箱监视器']);
+        StationType::query()->firstOrCreate(['name'=>'料箱出货口']);
+        StationType::query()->firstOrCreate(['name'=>'料箱入货口']);
+        StationType::query()->firstOrCreate(['name'=>'料箱监视器']);
     }
 
     /**

+ 8 - 7
database/migrations/2021_05_21_131520_add_order_packages_logistic_number_unique.php

@@ -13,9 +13,10 @@ class AddOrderPackagesLogisticNumberUnique extends Migration
      */
     public function up()
     {
-        Schema::table('order_packages', function (Blueprint $table) {
-            $table->string('logistic_number')->unique()->change();
-        });
+//        Schema::table('order_packages', function (Blueprint $table) {
+//            //
+//            $table->string('logistic_number')->unique()->change();
+//        });
     }
 
     /**
@@ -25,9 +26,9 @@ class AddOrderPackagesLogisticNumberUnique extends Migration
      */
     public function down()
     {
-        Schema::table('order_packages', function (Blueprint $table) {
-            //
-            $table->dropUnique(['logistic_number']);
-        });
+//        Schema::table('order_packages', function (Blueprint $table) {
+//            //
+//            $table->dropUnique(['logistic_number']);
+//        });
     }
 }

+ 27 - 0
database/migrations/2021_05_27_103720_create_ownersundryfeedetails_table.php

@@ -0,0 +1,27 @@
+<?php
+
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Database\Migrations\Migration;
+
+class CreateOwnerSundryFeeDetailsTable extends Migration
+{
+	public function up()
+	{
+		Schema::create('owner_sundry_fee_details', function(Blueprint $table) {
+            $table->increments('id');
+            $table->integer('owner_id')->comment('货主ID');
+            $table->integer('type')->unsigned()->comment('作业类型');
+            $table->string('fee_explain')->nullable()->comment('费用描述');
+            $table->string('remark')->nullable()->comment('备注');
+            $table->decimal('fee')->default(0)->comment('收费金额');
+            $table->integer('changable')->unsigned()->default(1)->comment('冻结状态');
+            $table->softDeletes();
+            $table->timestamps();
+        });
+	}
+
+	public function down()
+	{
+		Schema::drop('owner_sundry_fee_details');
+	}
+}

+ 39 - 0
database/migrations/2021_05_27_105155_add_authority_settlement_bills.php

@@ -0,0 +1,39 @@
+<?php
+
+use App\Authority;
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class AddAuthoritySettlementBills extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+//        Authority::query()->firstOrCreate(["name" => "结算管理-结算账单"],["alias_name"=>"结算管理-结算账单"]);
+//        Authority::query()->firstOrCreate(["name" => "结算管理-结算账单-杂项费"],["alias_name"=>"结算管理-结算账单-杂项费"]);
+
+        Authority::query()->firstOrCreate(["name" => "项目管理-杂项费-查询"],["alias_name"=>"项目管理-杂项费-查询"]);
+        Authority::query()->firstOrCreate(["name" => "项目管理-杂项费-录入"],["alias_name"=>"项目管理-杂项费-录入"]);
+        Authority::query()->firstOrCreate(["name" => "项目管理-杂项费-编辑"],["alias_name"=>"项目管理-杂项费-编辑"]);
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+//        Authority::query()->where('name', '结算管理-结算账单')->delete();
+//        Authority::query()->where('name', '结算管理-结算账单-杂项费')->delete();
+
+        Authority::query()->where('name', '项目管理-杂项费-查询')->delete();
+        Authority::query()->where('name', '项目管理-杂项费-录入')->delete();
+        Authority::query()->where('name', '项目管理-杂项费-编辑')->delete();
+    }
+}

部分文件因文件數量過多而無法顯示