Sfoglia il codice sorgente

Merge branch 'master' into 缓存架格式修改

# Conflicts:
#	app/Http/Controllers/DischargeTaskController.php
ajun 4 anni fa
parent
commit
2c4993a2a4
100 ha cambiato i file con 2436 aggiunte e 1475 eliminazioni
  1. 2 0
      .gitignore
  2. 2 18
      app/Console/Commands/CheckCacheRackStorage.php
  3. 3 11
      app/Console/Commands/SyncBatchTask.php
  4. 45 0
      app/Filters/OrderPackageReceivedSyncRecordFilters.php
  5. 46 0
      app/Filters/OwnerSundryFeeDetailFilters.php
  6. 30 0
      app/Http/Controllers/ControlPanelController.php
  7. 30 55
      app/Http/Controllers/CustomerController.php
  8. 30 4
      app/Http/Controllers/DeliveryAppointmentController.php
  9. 5 3
      app/Http/Controllers/DischargeTaskController.php
  10. 2 1
      app/Http/Controllers/FacilitatorController.php
  11. 2 1
      app/Http/Controllers/FacilitatorExternalController.php
  12. 23 7
      app/Http/Controllers/InventoryAccountController.php
  13. 14 8
      app/Http/Controllers/InventoryCompareController.php
  14. 41 35
      app/Http/Controllers/InventoryController.php
  15. 3 5
      app/Http/Controllers/LaborReportController.php
  16. 27 10
      app/Http/Controllers/OrderController.php
  17. 2 26
      app/Http/Controllers/OrderIssueController.php
  18. 12 11
      app/Http/Controllers/OrderIssuePerformanceController.php
  19. 2 1
      app/Http/Controllers/OrderTrackingController.php
  20. 82 0
      app/Http/Controllers/OwnerSundryFeeDetailsController.php
  21. 76 4
      app/Http/Controllers/PackageLogisticController.php
  22. 24 55
      app/Http/Controllers/PriceModelController.php
  23. 66 0
      app/Http/Controllers/PrintPartController.php
  24. 49 0
      app/Http/Controllers/PrintTemplateController.php
  25. 14 8
      app/Http/Controllers/ProcessController.php
  26. 3 1
      app/Http/Controllers/ProcessStatisticController.php
  27. 7 8
      app/Http/Controllers/ProcurementController.php
  28. 29 17
      app/Http/Controllers/RejectedController.php
  29. 163 26
      app/Http/Controllers/StorageController.php
  30. 2 10
      app/Http/Controllers/StoreCheckingReceiveController.php
  31. 7 1
      app/Http/Controllers/StoreController.php
  32. 67 63
      app/Http/Controllers/TestController.php
  33. 14 8
      app/Http/Controllers/WaveController.php
  34. 85 68
      app/Http/Controllers/WaybillController.php
  35. 23 8
      app/Http/Controllers/WaybillFinancialSnapshotsController.php
  36. 22 30
      app/Http/Controllers/WeighController.php
  37. 21 16
      app/Http/Controllers/WeighExceptedController.php
  38. 15 2
      app/Http/Controllers/api/thirdPart/haiq/StorageController.php
  39. 41 0
      app/Http/Requests/OwnerSundryFeeDetailRequest.php
  40. 14 0
      app/Http/Requests/Request.php
  41. 4 1
      app/Jobs/LogisticSFSync.php
  42. 4 1
      app/Jobs/LogisticYDSync.php
  43. 5 1
      app/Jobs/LogisticYTOSync.php
  44. 23 150
      app/Jobs/LogisticZopSync.php
  45. 31 0
      app/Jobs/ResetInstantBill.php
  46. 9 1
      app/Listeners/AddOrUpdateOrderIssuesListener.php
  47. 5 0
      app/MaterialBox.php
  48. 21 0
      app/Observers/OwnerSundryFeeDetailObserver.php
  49. 22 0
      app/OrderPackageReceivedSyncRecord.php
  50. 6 0
      app/Owner.php
  51. 1 0
      app/OwnerFeeDetail.php
  52. 70 0
      app/OwnerSundryFeeDetail.php
  53. 20 0
      app/Policies/OwnerSundryFeeDetailPolicy.php
  54. 22 0
      app/Policies/Policy.php
  55. 15 0
      app/PrintPart.php
  56. 14 0
      app/PrintTemplate.php
  57. 160 85
      app/Providers/AppServiceProvider.php
  58. 1 0
      app/Providers/AuthServiceProvider.php
  59. 13 3
      app/Services/BatchService.php
  60. 27 0
      app/Services/DeliveryAppointmentService.php
  61. 94 14
      app/Services/ForeignHaiRoboticsService.php
  62. 12 0
      app/Services/LogisticRouteInterface.php
  63. 1 1
      app/Services/LogisticYDService.php
  64. 1 1
      app/Services/LogisticYTOService.php
  65. 87 77
      app/Services/LogisticZopService.php
  66. 32 3
      app/Services/MaterialBoxService.php
  67. 33 0
      app/Services/OrderPackageReceivedSyncRecordService.php
  68. 16 3
      app/Services/OrderPackageReceivedSyncService.php
  69. 50 32
      app/Services/OrderService.php
  70. 2 2
      app/Services/OwnerAreaReportService.php
  71. 0 7
      app/Services/OwnerPriceDirectLogisticService.php
  72. 0 8
      app/Services/OwnerPriceExpressService.php
  73. 0 7
      app/Services/OwnerPriceLogisticService.php
  74. 26 18
      app/Services/OwnerPriceOperationService.php
  75. 46 53
      app/Services/OwnerService.php
  76. 0 4
      app/Services/OwnerStoragePriceModelService.php
  77. 13 0
      app/Services/PrintPartService.php
  78. 13 0
      app/Services/PrintTemplateService.php
  79. 4 2
      app/Services/RejectedBillService.php
  80. 2 1
      app/Services/RejectedService.php
  81. 7 1
      app/Services/StationService.php
  82. 1 1
      app/Services/StationTaskBatchService.php
  83. 61 0
      app/Services/StorageService.php
  84. 17 8
      app/Services/WaybillService.php
  85. 4 0
      app/Station.php
  86. 14 3
      app/Storage.php
  87. 3 3
      app/Waybill.php
  88. 0 23
      app/library/zop/README.md
  89. 0 60
      app/library/zop/ZopClient.php
  90. 0 20
      app/library/zop/ZopHttpUtil.php
  91. 0 46
      app/library/zop/ZopProperties.php
  92. 0 59
      app/library/zop/ZopRequest.php
  93. 7 0
      bootstrap/cache/packages.php
  94. 20 18
      bootstrap/cache/services.php
  95. 2 5
      composer.json
  96. 195 232
      composer.lock
  97. 15 0
      config/database.php
  98. 16 0
      database/factories/OrderPackageReceivedSyncRecordFactory.php
  99. 11 0
      database/factories/OwnerSundryFeeDetailFactory.php
  100. 13 0
      database/factories/PrintPartFactory.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

+ 2 - 18
app/Console/Commands/CheckCacheRackStorage.php

@@ -6,7 +6,7 @@ use App\Station;
 use App\StationTask;
 use App\StationTaskMaterialBox;
 use Illuminate\Console\Command;
-use Illuminate\Database\Eloquent\Collection;
+use Illuminate\Support\Collection;
 
 class CheckCacheRackStorage extends Command
 {
@@ -46,22 +46,6 @@ class CheckCacheRackStorage extends Command
                 ->where("status","!=","完成")->whereIn("station_id",Station::query()->select("id")->where("station_type_id",5)
                     ->whereNotNull("parent_id"))->groupBy("station_id"))
             ->get();
-        foreach ($stations as $station){
-            $box = app("MaterialBoxService")->getAnEmptyBox();
-            if (!$box)continue;
-            $task = StationTask::query()->create([
-                'status' => "待处理",
-                'station_id' => $station->id,
-            ]);
-            $collection = new Collection();
-            $collection->append(StationTaskMaterialBox::query()->create([
-                'station_id' => $station->id,
-                'material_box_id'=>$box->id,
-                'status'=>"待处理",
-                'type' => '取',
-                'station_task_id' => $task->id,
-            ]));
-            app("ForeignHaiRoboticsService")->fetchGroup($station->code,$collection,'','立架出至缓存架');
-        }
+        app("StorageService")->paddingCacheShelf($stations);
     }
 }

+ 3 - 11
app/Console/Commands/SyncBatchTask.php

@@ -2,8 +2,6 @@
 
 namespace App\Console\Commands;
 
-use App\Exceptions\ErrorException;
-use App\Exceptions\Exception;
 use App\Jobs\BatchTaskJob;
 use App\Order;
 use App\OrderBin;
@@ -157,7 +155,6 @@ sql;
         if (count($details) < 1)return;
         $map = [];
         $nos = [];
-        $ods = [];
         $orderCodes = [];
         $seqnos = [];
         $batchMapping = [];
@@ -166,7 +163,6 @@ sql;
             else {
                 $map[$detail->waveno] = [$detail->orderno];
                 $nos[] = $detail->waveno;
-                $ods[] = $detail->orderno;
             }
             $orderCodes[] = $detail->orderno;
             $seqnos[$detail->orderno] = $detail->seqno;
@@ -174,12 +170,14 @@ sql;
         }
         $orders = Order::query()->select("id","batch_id","code")->whereIn("code",$orderCodes)->get();
         if (count($orderCodes) != count($orders))LogService::log(__CLASS__,"格口号-订单存在差异",json_encode($orderCodes));
+        $existOrder = [];
         if ($orders){
             $orderIds = [];
             $orderMap = [];
             foreach ($orders as $order){
                 $orderIds[] = $order->id;
                 $orderMap[$order->id] = $seqnos[$order->code];
+                $existOrder[$order->code] = $order->batch_id;
             }
             $updateBin = [["id","number"]];
             $insertBin = [];
@@ -227,15 +225,11 @@ sql;
             $batches = $this->batchService->get(["code"=>$nos]);
         }
         $updateOrder = [["code","batch_id"]];
-        $existOrder = [];
         $updatingBatches = [];
-        foreach (Order::query()->select("code","batch_id")->whereNotNull("batch_id")->whereIn("code",$ods)->get() as $item){
-            $existOrder[$item->code] = $item->batch_id;
-        }
         foreach ($batches as $batch){
             $mark = false;
             foreach ($map[$batch->code] as $on){
-                if (!isset($existOrder[$on]) || $existOrder[$on]!=$batch->id){
+                if ((!isset($existOrder[$on])) || $existOrder[$on]!=$batch->id){
                     $updateOrder[] = [
                         "code"=>$on,
                         "batch_id"=>$batch->id
@@ -250,11 +244,9 @@ sql;
             app("OrderService")->batchUpdate($updateOrder);//反向修改订单
             LogService::log(__METHOD__,"波次同步-修改订单波次号",json_encode($updateOrder));
             app("BatchService")->checkBatchOrderInfo($updatingBatches);
-            LogService::log(__METHOD__,"修改过的波次_",json_encode($updatingBatches));
             LogService::log(__METHOD__,"波次注册一入口",json_encode($updatingBatches));
             BatchTaskJob::dispatch($updatingBatches);    //在这里为波次注册队列任务!
         }
-
         if ($map){
             $waveCodes = array_keys($map);
             $waves = $this->service->get(["waveno"=>$waveCodes],["waveno"=>"in"]);

+ 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."%");
+        }
+    }
+}

+ 30 - 0
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;
@@ -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;

+ 30 - 55
app/Http/Controllers/CustomerController.php

@@ -26,6 +26,7 @@ use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
 use Illuminate\Support\Facades\Validator;
+use Oursdreams\Export\Export;
 
 class CustomerController extends Controller
 {
@@ -85,14 +86,7 @@ class CustomerController extends Controller
                 $report->ownerBillReport ? (string)$report->ownerBillReport->updated_at : '',
             ];
         }
-        $post = Http::post(config('go.export.url'),['type'=>'base','data'=>json_encode(["row"=>$column,"list"=>$list],JSON_UNESCAPED_UNICODE)]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=客户项目报表-".date('ymdHis').'.xlsx',
-        ]);
+        return Export::make($column,$list,"客户项目报表");
     }
 
     public function projectIndex()
@@ -146,14 +140,7 @@ class CustomerController extends Controller
                 $owner->description
             ];
         }
-        $post = Http::post(config('go.export.url'),['type'=>'base','data'=>json_encode(["row"=>$column,"list"=>$list],JSON_UNESCAPED_UNICODE)]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=客户报表-".date('ymdHis').'.xlsx',
-        ]);
+        return Export::make($column,$list,"客户报表");
     }
 
     public function projectCreate()
@@ -299,15 +286,7 @@ class CustomerController extends Controller
                 $area->accounting_area,
             ];
         }
-
-        $post = Http::post(config('go.export.url'),['type'=>'base','data'=>json_encode(["row"=>$column,"list"=>$list],JSON_UNESCAPED_UNICODE)]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=项目面积报表-".date('ymdHis').'.xlsx',
-        ]);
+        return Export::make($column,$list,"项目面积报表");
     }
 
     public function financeInstantBill(Request $request)
@@ -328,22 +307,22 @@ class CustomerController extends Controller
         if ($request->checkAllSign)unset($params['checkAllSign']);
         else $params = ["id"=>$request->data];
         $sql = app('OwnerFeeDetailService')->getSql($params);
-
-        $row = ["客户", "项目", "作业时间", "类型","店铺", "单号(发/收/退/提)", "收件人", "收件人电话", "商品数量",
-            "物流/快递单号", "体积", "重量", "承运商", "操作费", "物流费", "合计"];
-        $column = ["customer_name", "owner_name", "worked_at", "type","shop_name", "operation_bill", "consignee_name", "consignee_phone", "commodity_amount",
-            "logistic_bill", "volume", "weight", "logistic_name", "work_fee", "logistic_fee", "total"];
         $rule = ["work_fee"=>"mysqlDate"];
 
-        $post = Http::post(config('go.export.url'),['type'=>'unify','sql'=>$sql, 'connection'=>'mysql',
-            'row'=>json_encode($row,JSON_UNESCAPED_UNICODE), 'column'=>json_encode($column), 'rule'=>json_encode($rule)]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=即时账单记录-".date('ymdHis').'.xlsx',
-        ]);
+        $e = new Export();
+        $e->setMysqlConnection(config('database.connections.mysql.host'),
+            config('database.connections.mysql.port'),config('database.connections.mysql.database')
+            ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
+        $e->setFileName("即时账单记录");
+        return $e->sql($sql,[
+            "customer_name"=>"客户","owner_name"=>"项目",
+            "worked_at"=>"作业时间","type"=>"类型",
+            "shop_name"=>"店铺","operation_bill"=>"单号(发/收/退/提)",
+            "consignee_name"=>"收件人","consignee_phone"=>"收件人电话",
+            "commodity_amount"=>"商品数量","logistic_bill"=>"物流/快递单号",
+            "volume"=>"体积","weight"=>"重量","logistic_name"=>"承运商",
+            "work_fee"=>"操作费","logistic_fee"=>"物流费","total"=>"合计"
+        ],$rule)->direct();
     }
 
     public function financeBillConfirmation(Request $request)
@@ -388,15 +367,7 @@ class CustomerController extends Controller
                 $bill->confirmed == '是' ? '已确认' : '未确认',
             ];
         }
-
-        $post = Http::post(config('go.export.url'),['type'=>'base','data'=>json_encode(["row"=>$column,"list"=>$list],JSON_UNESCAPED_UNICODE)]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=客户账单报表-".date('ymdHis').'.xlsx',
-        ]);
+        return Export::make($column,$list,"客户账单报表");
     }
 
     public function updateBillReport(Request $request)
@@ -581,27 +552,31 @@ class CustomerController extends Controller
         $owner = request("owner");
         $sql = <<<sql
 SELECT owner_id,SUM(IFNULL(work_fee,0)) AS work_fee,SUM(IFNULL(logistic_fee,0)) AS logistic_fee 
-FROM owner_fee_details WHERE worked_at LIKE ? 
+FROM owner_fee_details WHERE worked_at LIKE ? AND ((type = '发货' AND logistic_fee IS NOT NULL AND work_fee IS NOT NULL) OR (type <> '发货' AND work_fee IS NOT NULL))
 sql;
         if ($owner && count($owner)>0){
             $sql.=" AND owner_id IN (''";
             foreach ($owner as $o)$sql .=",'{$o}'";
             $sql.=")";
         }
-        $sql .= " AND ((type = '发货' AND logistic_fee IS NOT NULL AND work_fee IS NOT NULL) OR (type <> '发货' AND work_fee IS NOT NULL))  GROUP BY owner_id";
+        $sql .= " GROUP BY owner_id";
 
         $billDetails = DB::select(DB::raw($sql),[$month."%"]);
 
-        $areas = OwnerAreaReport::query()->with("ownerStoragePriceModel")->where("counting_month","like",$month."%")->get();
+        $areas = OwnerAreaReport::query()->with(["ownerStoragePriceModel.timeUnit","ownerStoragePriceModel.taxRate"])->where("counting_month","like",$month."%")->get();
         $map = [];
+        $mapTax = [];
         foreach($areas as $area){
-            if (isset($map[$area->owner_id."_".$area->counting_month])){
+            $key = $area->owner_id."_".$area->counting_month;
+            if (isset($map[$key])){
                 if (!$area->ownerStoragePriceModel)continue;
-                $map[$area->owner_id."_".$area->counting_month] += app('OwnerStoragePriceModelService')
+                list($money,$taxFee) = app('OwnerStoragePriceModelService')
                     ->calculationAmount($area->ownerStoragePriceModel,$area->accounting_area,$area->owner_id,$area->counting_month);
+                $map[$key] += $money;
+                $mapTax[$key] += $taxFee;
             }else{
                 if (!$area->ownerStoragePriceModel)continue;
-                $map[$area->owner_id."_".$area->counting_month] = app('OwnerStoragePriceModelService')
+                list($map[$key],$mapTax[$key]) = app('OwnerStoragePriceModelService')
                     ->calculationAmount($area->ownerStoragePriceModel,$area->accounting_area,$area->owner_id,$area->counting_month);
             }
         }
@@ -612,7 +587,7 @@ sql;
                 $key = $bill->owner_id."_".$month;
                 OwnerBillReport::query()->where("owner_id",$bill->owner_id)
                     ->where("counting_month",$month."-01")
-                    ->update(["work_fee"=>$bill->work_fee,"logistic_fee"=>$bill->logistic_fee,"storage_fee"=>$map[$key] ?? 0]);
+                    ->update(["work_fee"=>$bill->work_fee,"logistic_fee"=>$bill->logistic_fee,"storage_fee"=>$map[$key] ?? 0,"storage_tax_fee"   => $mapTax[$key] ?? 0]);
             }
         }
         $this->success();

+ 30 - 4
app/Http/Controllers/DeliveryAppointmentController.php

@@ -20,6 +20,7 @@ use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Validator;
+use Oursdreams\Export\Export;
 
 class DeliveryAppointmentController extends Controller
 {
@@ -369,7 +370,7 @@ class DeliveryAppointmentController extends Controller
                 $data->created_at
             ];
         }
-        return app(ExportService::class)->json($row,$list,"预约记录");
+        return Export::make($row,$list,"预约记录");
     }
 
     private function carList($period,$date,$warehouse)
@@ -514,7 +515,7 @@ html;
     }
 
     /**
-     * 验证预约码
+     * 验证预约码  允许当日产能满足后的逾期
      *
      */
     public function checkAppointment()
@@ -524,15 +525,24 @@ html;
         if (!$number)return ["status"=>417];
         $period = app("DeliveryAppointmentService")->getPeriod();
         if ($period===false)return ["status"=>416]; //非法时段扫码
+        $mark = false;
+        mark:
         $car = DeliveryAppointmentCar::query()->whereNull("delivery_time")->where("status",0)
             ->where("appointment_number",$number)->whereHas("deliveryAppointment",function (Builder $query)use($period){
                 $query->where("appointment_date",date("Y-m-d"))
-                ->where("date_period",$period)->where("status",0);
+                ->where("date_period",$period)->whereIn("status",[0,3]);
             })->first();
+        if (!$car && $period===1){$period = 0;$mark = true;goto mark;}
+        if ($mark && $car){
+            $car->load("deliveryAppointment");
+            $available = app("DeliveryAppointmentService")->getAvailableCapacity($car->deliveryAppointment->appointment_date,$car->deliveryAppointment->date_period,$car->deliveryAppointment->warehouse_id);
+            if ($available<$car->deliveryAppointment->capacity)$car = null;
+        }
         if (!$car)return ["status"=>417];
         $car->update(["delivery_time"=>date("Y-m-d H:i:s"),"status"=>1]);
         /** @var DeliveryAppointmentCar $car */
-        event(new DeliveryAppointmentEvent($car));
+        if ($mark)DeliveryAppointment::query()->where("id",$car->delivery_appointment_id)->update(["status" => 0]);
+        else event(new DeliveryAppointmentEvent($car));
         return ["status"=>200,"k"=>$car->delivery_appointment_id];
     }
 
@@ -552,6 +562,7 @@ html;
      */
     public function unloading()
     {
+        $this->gate("入库管理-入库预约-预约管理-卸货完成");
         if (!request("id"))$this->error("非法参数");
         /** @var DeliveryAppointmentCar|\stdClass $car */
         $car = DeliveryAppointmentCar::query()->find(request("id"));
@@ -562,6 +573,21 @@ html;
         $this->success();
     }
 
+    /**
+     * 管理员代替签到
+     */
+    public function signIn()
+    {
+        $this->gate("入库管理-入库预约-预约管理-签到");
+        if (!request("id"))$this->error("非法参数");
+        /** @var DeliveryAppointmentCar|\stdClass $car */
+        $car = DeliveryAppointmentCar::query()->find(request("id"));
+        if (!$car || !$car->deliveryAppointment)$this->error("单据不存在");
+        $car->update(["status"=>1]);
+        event(new DeliveryAppointmentEvent($car));
+        $this->success();
+    }
+
     /**
      * 产能维护
      * */

+ 5 - 3
app/Http/Controllers/DischargeTaskController.php

@@ -12,11 +12,11 @@ use App\Imports\DischargeTaskImport;
 use App\Services\common\ExportService;
 use App\Services\OwnerService;
 use App\Warehouse;
-use Carbon\Carbon;
 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;
 
 class DischargeTaskController extends Controller
@@ -123,7 +123,8 @@ class DischargeTaskController extends Controller
         $row = ['日期', '客户名称', '作业名称', '入库单号', '数量', '单位', '单价', '收费', '状态', '备注'];
         $json = app('DischargeTaskService')->getJson($dischargeTasks);
 
-        return app(ExportService::class)->json($row, $json, "卸货任务");
+        return Export::make($row, $json, "卸货任务");
+        //return app(ExportService::class)->json($row, $json, "卸货任务");
     }
 
     // 结算报表下载
@@ -136,7 +137,8 @@ class DischargeTaskController extends Controller
         $row = ['日期', '客户名称', '仓库', '作业名称', '入库单号', '数量', '单位', '收入单价', '收入合计', '装卸队', '数量', '单位', '支出单价', '支出合计', '状态', '收入备注', '支出备注'];
         $json = app('DischargeTaskService')->getStatementsJson($dischargeTasks);
 
-        return app(ExportService::class)->json($row, $json, "卸货结算报表");
+        return Export::make($row, $json, "卸货结算报表");
+        //return app(ExportService::class)->json($row, $json, "卸货结算报表");
     }
 
     public function receipt(Request $request)

+ 2 - 1
app/Http/Controllers/FacilitatorController.php

@@ -13,6 +13,7 @@ use App\Services\FacilitatorService;
 use Illuminate\Database\Eloquent\Collection;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Gate;
+use Oursdreams\Export\Export;
 
 class FacilitatorController extends Controller
 {
@@ -116,7 +117,7 @@ class FacilitatorController extends Controller
 
         $json = app('DischargeTaskService')->getFacilitatorStatementsJson($facilitatorStatements);
 
-        return app(ExportService::class)->json($row, $json, "装卸队对账单报表");
+        return Export::make($row, $json, "装卸队对账单报表");
     }
 
 

+ 2 - 1
app/Http/Controllers/FacilitatorExternalController.php

@@ -11,6 +11,7 @@ use App\Services\DischargeTaskService;
 use App\Services\FacilitatorService;
 use Illuminate\Database\Eloquent\Collection;
 use Illuminate\Http\Request;
+use Oursdreams\Export\Export;
 
 class FacilitatorExternalController extends Controller
 {
@@ -55,7 +56,7 @@ class FacilitatorExternalController extends Controller
         $row = ['日期', '装卸队', '数量', '单位', '单价', '总金额合计'];
         $json = app('DischargeTaskService')->getFacilitatorStatementsJson($facilitatorStatements);
 
-        return app(ExportService::class)->json($row, $json, "卸货结算报表");
+        return Export::make($row, $json, "卸货结算报表");
     }
 
 }

+ 23 - 7
app/Http/Controllers/InventoryAccountController.php

@@ -411,14 +411,30 @@ class InventoryAccountController extends Controller
         if (!Gate::allows("库存管理-盘点")) {
             return redirect(url('/'));
         }
-        $post = Http::post(config('go.export.url'), ['type' => 'inventoryAccountMission', 'data' => $request->data]);
-        if ($post->status() == 500) {
-            throw new Exception($post->header("Msg"));
+        $list = [];
+        foreach (json_decode($request->data,true) as $item){
+            $list[] = [
+                $item["location"],
+                $item["commodity_name"],
+                $item["commodity_barcode"],
+                $item["commodity_sku"],
+                $item["produced_at"],
+                $item["valid_at"],
+                $item["batch_number"],
+                $item["stock_person"],
+                $item["erp_type_position"],
+                $item["quality"],
+                $item["stored_amount"],
+                $item["valid_amount"],
+                $item["verified_amount"],
+                $item["re_checked_amount"],
+                $item["difference_amount"],
+                $item["occupied_amount"],
+                $item["mark"],
+            ];
         }
-        return response($post, 200, [
-            "Content-type" => "application/octet-stream",
-            "Content-Disposition" => "attachment; filename=库存盘点记录-" . date('ymdHis') . '.xlsx',
-        ]);
+        return \Oursdreams\Export\Export::make(["库位","产品名","商品条码","商品编码","生产日期","失效日期","批号","盘点人","ERP属性仓","质量状态","库存数量",
+            "可用数量","盘点数量","复盘数量","复盘差异","分配数量","状态"],$list,"库存盘点记录");
     }
 
     public function searchCommodityByBarcode(Request $request)

+ 14 - 8
app/Http/Controllers/InventoryCompareController.php

@@ -12,6 +12,7 @@ use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
 use Maatwebsite\Excel\Facades\Excel;
+use Oursdreams\Export\Export;
 
 class InventoryCompareController extends Controller
 {
@@ -138,13 +139,18 @@ class InventoryCompareController extends Controller
         }else{
             $sql=app('InventoryCompareService')->getSql(['id'=>$request->data]);
         }
-        $post = Http::post(config('go.export.url'),['type'=>'inventoryCompare','sql'=>$sql]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=库存对比记录-".date('ymdHis').'.xlsx',
-        ]);
+        $e = new Export();
+        $e->setMysqlConnection(config('database.connections.mysql.host'),
+            config('database.connections.mysql.port'),config('database.connections.mysql.database')
+            ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
+        $e->setFileName("库存对比记录");
+        return $e->sql($sql,[
+            "owner_name"=>"货主","mission_code"=>"任务号",
+            "created_at"=>"生产时间","commodity_name"=>"商品名称",
+            "commodity_sku"=>"商品编码","commodity_barcode_code"=>"商品条码",
+            "custom_location"=>"属性仓","quality"=>"质量状态",
+            "amount_in_sys"=>"宝时库存","amount_in_compare"=>"参考库存",
+            "differ"=>"差值"
+        ])->direct();
     }
 }

+ 41 - 35
app/Http/Controllers/InventoryController.php

@@ -12,6 +12,7 @@ use Exception;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
+use Oursdreams\Export\Export;
 
 class InventoryController extends Controller
 {
@@ -52,17 +53,19 @@ class InventoryController extends Controller
             $params = $request->input();
             unset($params['checkAllSign']);
             $sql=app('inventoryService')->getSql($request->input());
-            $post = Http::post(config('go.export.url'),['type'=>'inventory','sql'=>$sql]);
-        }else {
-            $post = Http::post(config('go.export.url'), ['type' => 'inventory', 'data' => $request->data]);
-        }
-        if ($post->status() == 500){
-            throw new \Exception($post->header("Msg"));
-        }
-        return response($post, 200, [
-            "Content-type" => "application/octet-stream",
-            "Content-Disposition" => "attachment; filename=库存记录-" . date('ymdHis') . '.xlsx',
-        ]);
+            $e = new Export();
+            $e->setOracleConnection(config('database.connections.oracle.host'),
+                config('database.connections.oracle.port'),config('database.connections.oracle.database')
+                ,config('database.connections.oracle.username'),config('database.connections.oracle.password'));
+            $e->setFileName("动库报表");
+            return $e->sql($sql,[
+                "货主"=>"货主","库位"=>"库位",
+                "产品编码"=>"产品编码","产品条码"=>"产品条码",
+                "商品名称"=>"商品名称","属性仓"=>"属性仓",
+                "质量状态"=>"质量状态","失效日期"=>"失效日期",
+                "批号"=>"批号","移出数量"=>"移出数量","移入数量"=>"移入数量"
+            ])->direct();
+        }else return "暂时关闭,如需开启请联系管理员";
     }
     public function exportAllInventory(Request $request){
         if(!Gate::allows("库存管理-库存")){ return redirect(url('/'));  }
@@ -70,17 +73,19 @@ class InventoryController extends Controller
             $params = $request->input();
             unset($params['checkAllSign']);
             $sql=app('AllInventoryService')->getSql($request->input());
-            $post = Http::post(config('go.export.url'),['type'=>'allInventory','sql'=>$sql]);
-        }else{
-            $post = Http::post(config('go.export.url'),['type'=>'allInventory','data'=>$request->data]);
-        }
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=全部库存-".date('ymdHis').'.xlsx',
-        ]);
+            $e = new Export();
+            $e->setOracleConnection(config('database.connections.oracle.host'),
+                config('database.connections.oracle.port'),config('database.connections.oracle.database')
+                ,config('database.connections.oracle.username'),config('database.connections.oracle.password'));
+            $e->setFileName("全部库存");
+            return $e->sql($sql,[
+                "货主"=>"货主","库位"=>"库位",
+                "产品编码"=>"产品编码","产品条码"=>"产品条码",
+                "商品名称"=>"商品名称","属性仓"=>"属性仓",
+                "质量状态"=>"质量状态","失效日期"=>"失效日期",
+                "批号"=>"批号"
+            ])->direct();
+        }else return "暂时关闭,如需开启请联系管理员";
     }
 
     /*
@@ -119,19 +124,20 @@ class InventoryController extends Controller
 
         }else $sql=app('InventoryDailyLogService')->getSql(['id'=>$request->data]);
 
-        $row = ["货主","日期","商品名称","商品编码","商品条码","属性仓","在库数量","长","宽","高","体积","总占用体积","总毛重"];
-        $column = ["owner_name", "created_at", "commodity_name", "commodity_sku", "commodity_barcode_code","depository_name",
-            "amount", "commodity_length", "commodity_width", "commodity_height", "commodity_volumn", "volumn_occupied", "gross_weight"];
         $rule = ["created_at"=> "mysqlDate"];
-        $post = Http::post(config('go.export.url'),['type'=>'unify','sql'=>$sql, 'connection'=>'mysql',
-            'row'=>json_encode($row,JSON_UNESCAPED_UNICODE), 'column'=>json_encode($column), 'rule'=>json_encode($rule)]);
-
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=库存体积记录-".date('ymdHis').'.xlsx',
-        ]);
+        $e = new Export();
+        $e->setMysqlConnection(config('database.connections.mysql.host'),
+            config('database.connections.mysql.port'),config('database.connections.mysql.database')
+            ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
+        $e->setFileName("库存体积");
+        return $e->sql($sql,[
+            "owner_name"=>"货主","created_at"=>"日期",
+            "commodity_name"=>"商品名称","commodity_sku"=>"商品编码",
+            "commodity_barcode_code"=>"商品条码","depository_name"=>"属性仓",
+            "amount"=>"在库数量","commodity_length"=>"长",
+            "commodity_width"=>"宽","commodity_height"=>"高",
+            "commodity_volumn"=>"体积","volumn_occupied"=>"总占用体积",
+            "gross_weight"=>"总毛重"
+        ],$rule)->direct();
     }
 }

+ 3 - 5
app/Http/Controllers/LaborReportController.php

@@ -5,7 +5,6 @@ namespace App\Http\Controllers;
 use App\Events\ClockoutEvent;
 use App\Events\GuardAuditEvent;
 use App\Events\TeamAuditEvent;
-use App\Exports\Export;
 use App\LaborCompany;
 use App\LaborReport;
 use App\LaborReportStatus;
@@ -14,12 +13,10 @@ use App\Services\LaborReportService;
 use App\UserDutyCheck;
 use App\UserWorkgroup;
 use Carbon\Carbon;
-use Exception;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\Gate;
-use Illuminate\Support\Facades\Http;
-use Maatwebsite\Excel\Facades\Excel;
+use Oursdreams\Export\Export;
 
 class LaborReportController extends Controller
 {
@@ -113,7 +110,8 @@ class LaborReportController extends Controller
                 $laborReport->remark,
             ];
         }
-        return app(ExportService::class)->json($row,$list,"临时工报表记录");
+        return Export::make($row,$list,"临时工报表记录");
+        //return app(ExportService::class)->json($row,$list,"临时工报表记录");
     }
 
     //门卫打卡审核

+ 27 - 10
app/Http/Controllers/OrderController.php

@@ -17,6 +17,7 @@ use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
+use Oursdreams\Export\Export;
 
 class OrderController extends Controller
 {
@@ -62,14 +63,30 @@ class OrderController extends Controller
         }else{
             $req["sql"] = $orderService->getSql($request->input());
         }
-        $post = Http::post(config('go.export.url'),$req);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=订单记录-".date('ymdHis').'.xlsx',
-        ]);
+        $e = new Export();
+        $e->setOracleConnection(config('database.connections.oracle.host'),
+            config('database.connections.oracle.port'),config('database.connections.oracle.database')
+        ,config('database.connections.oracle.username'),config('database.connections.oracle.password'));
+        if ($is_merge && $is_merge == 'true'){
+            $e->setMergeFormat([
+                "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P",
+                "Q","R","S","Z","AA","AB","AC","AD"
+            ]);
+            $e->setDatum("ORDERNO");
+        } else $e->setWarpTextFormat();
+        $e->setFileName("订单记录-".date('ymdHis'));
+        return $e->sql($req["sql"],[
+            "ORDERNO"=>"编号","ORDERCODENAME"=>"订单状态",
+            "NOTES"=>"备注","ADDTIME"=>"接口下发时间",
+            "ISSUEPARTYNAME"=>"店铺名称","CUSTOMER_DESCR_C"=>"客户",
+            "SOREFERENCE1"=>"客户订单号","CARRIERNAME"=>"承运人",
+            "SOREFERENCE5"=>"快递单号","C_CONTACT"=>"收货人名称","C_TEL2"=>"收货人电话",
+            "C_PROVINCE"=> "省","C_CITY"=>"市","C_DISTRICT"=>"区","C_ADDRESS1"=>"收货人地址",
+            "WAVENO"=>"波次编号","WAREHOUSEID"=>"仓库","EDISENDFLAG2"=>"快递获取标记","EDISENDTIME2"=>"快递获取时间",
+            "SKU"=>"产品代码","ALTERNATE_SKU1"=>"产品条码","ORDERDETAILCODENAME"=>"明细状态","DESCR_C"=> "产品名称",
+            "QTYORDERED"=>"订单数量","CHECKTIME"=>"复核时间","ERPCANCELFLAG"=>"接口取消标记",
+            "PICKING_PRINT_FLAG"=>"拣货单打印标记","EDISENDFLAG"=>"接口回传标记","EDIREMARKS2"=>"接口回传异常备注",
+            "RELEASESTATUS"=>"订单冻结"],["ADDTIME"=>"date","EDISENDTIME2"=>"date"])->direct();
     }
 
     public function createRejectedBill(Request $request){
@@ -319,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))

+ 2 - 26
app/Http/Controllers/OrderIssueController.php

@@ -32,6 +32,7 @@ use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
 use Illuminate\Support\Facades\Validator;
 use Maatwebsite\Excel\Facades\Excel;
+use Oursdreams\Export\Export;
 
 class OrderIssueController extends Controller
 {
@@ -135,31 +136,6 @@ class OrderIssueController extends Controller
         }
     }
 
-    public function exportOrderIssue(Request $request)
-    {
-        ini_set('max_execution_time', 2500);
-        ini_set('memory_limit', '1526M');
-        if (!Gate::allows('订单管理-问题件-查询')) {
-            return redirect(url('/'));
-        }
-        if ($request->checkAllSign){
-            $params = $request->input();
-            unset($params['checkAllSign']);
-
-            $sqlList = app('OrderIssueService')->getSqlList($params);
-        }else{
-            $sqlList = app('OrderIssueService')->getSqlList(['id'=>$request->data,"is_handle"=>true]);
-        }
-        $post = Http::post(config('go.export.url'),['type'=>'orderIssue','sqlList'=>json_encode($sqlList),'createFormat'=>'merge']);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=订单问题件-".date('ymdHis').'.xlsx',
-        ]);
-    }
-
     public function excelImport()
     {
         if (!Gate::allows('订单管理-问题件-导入')) {
@@ -699,7 +675,7 @@ class OrderIssueController extends Controller
 //                $order_issue->userOwnerGroup->name ?? '',
             ];
         }
-        return app(ExportService::class)->json($row,$json,"订单问题件");
+        return Export::make($row,$json,"订单问题件");
     }
 
     public function recycleBin(Request $request)

+ 12 - 11
app/Http/Controllers/OrderIssuePerformanceController.php

@@ -8,6 +8,7 @@ use Illuminate\Http\Request;
 use Exception;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
+use Oursdreams\Export\Export;
 
 class OrderIssuePerformanceController extends Controller
 {
@@ -35,17 +36,17 @@ class OrderIssuePerformanceController extends Controller
         /** @var OrderIssuePerformanceService  $orderIssuePerformanceService */
         $orderIssuePerformanceService = app(OrderIssuePerformanceService::class);
         $sql = $orderIssuePerformanceService->getSql($request->all());
-        $row = ['客服','客户','创建数','处理数','完结数','总数'];
-        $column = ['userName','ownerName','created','process','end','sumNumber'];
-        $post = Http::post(config('go.export.url'),['type'=>'unify','sql'=>$sql, 'connection'=>'mysql',
-            'row'=>json_encode($row,JSON_UNESCAPED_UNICODE), 'column'=>json_encode($column)]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=客服绩效-".date('ymdHis').'.xlsx',
-        ]);
+
+        $e = new Export();
+        $e->setMysqlConnection(config('database.connections.mysql.host'),
+            config('database.connections.mysql.port'),config('database.connections.mysql.database')
+            ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
+        $e->setFileName("客服绩效");
+        return $e->sql($sql,[
+            "userName"=>"客服","ownerName"=>"客户",
+            "created"=>"创建数","process"=>"处理数",
+            "end"=>"完结数","sumNumber"=>"总数",
+        ])->direct();
     }
 
     public function workLoadPage(Request $request)

+ 2 - 1
app/Http/Controllers/OrderTrackingController.php

@@ -13,6 +13,7 @@ use Exception;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Gate;
 use Intervention\Image\Facades\Image;
+use Oursdreams\Export\Export;
 use Ramsey\Uuid\Uuid;
 
 class OrderTrackingController extends Controller
@@ -222,7 +223,7 @@ class OrderTrackingController extends Controller
                 $orderTracking->remark,
             ];
         }
-        return app(ExportService::class)->json($row,$list,'订单跟踪件');
+        return Export::make($row,$list,'订单跟踪件');
     }
 
     public function destroyImg(Request $request)

+ 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', '删除成功');
+    }
+}

+ 76 - 4
app/Http/Controllers/PackageLogisticController.php

@@ -3,12 +3,13 @@
 namespace App\Http\Controllers;
 
 use App\Events\UpdateOrderPackageExceptionListenerEvent;
+use App\Exceptions\Exception;
 use App\Filters\OrderPackageFilters;
 use App\Logistic;
 use App\OrderPackage;
 use App\Owner;
+use App\Services\common\ExportService;
 use App\Services\UserService;
-use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Http\Request;
 
 class PackageLogisticController extends Controller
@@ -30,7 +31,7 @@ class PackageLogisticController extends Controller
         $orderPackages = OrderPackage::query()
             ->filter($filters)
             ->whereIn('owner_id', $owner_ids)->with(['order.logistic', 'order.owner', 'order.issue' => function ($query) {
-                $query->with(['issueType', 'logs'=>function($query) {
+                $query->with(['issueType', 'logs' => function ($query) {
                     $query->with('user')->orderBy('created_at', 'DESC');
                 }]);
             }])->orderByDesc('id')->paginate($request->paginate ?? 50);
@@ -56,14 +57,14 @@ class PackageLogisticController extends Controller
     public function batchUpdate(Request $request)
     {
         $data = [];
-        if (array_key_exists('exception_type',$request->all())) {
+        if (array_key_exists('exception_type', $request->all())) {
             if ('无' == $request->input('exception_type')) {
                 $data['exception_type'] = $request->input('exception_type');
                 $data['exception'] = "否";
             } else {
                 $data['exception_type'] = $request->input('exception_type');
             }
-        }else if (array_key_exists('status',$request->all())) {
+        } else if (array_key_exists('status', $request->all())) {
             $data['status'] = $request->input('status');
         }
         $logistic_numbers = $request->input('logistic_numbers');
@@ -71,4 +72,75 @@ class PackageLogisticController extends Controller
         //更新统计数据
         event(new UpdateOrderPackageExceptionListenerEvent($logistic_numbers));
     }
+
+    /**
+     * @throws Exception
+     */
+    public function export(Request $request, OrderPackageFilters $filters)
+    {
+        /** @var UserService $userService */
+        $userService = app('UserService');
+        $owner_ids = $userService->getPermittingOwnerIds(auth()->user());
+        $query = OrderPackage::query()
+            ->filter($filters)
+            ->whereIn('owner_id', $owner_ids)
+            ->with(['order.logistic', 'order.owner', 'order.issue' => function ($query) {
+                $query->with(['issueType', 'logs' => function ($query) {
+                    $query->with('user')->orderBy('created_at', 'DESC');
+                }]);
+            }]);
+        if ($request->exists('checkAllSign')) {
+            $orderPackages = $query->orderByDesc('id')->get();
+        } else {
+            $orderPackages = $query
+                ->whereIn('logistic_number', explode(',', $request['data']))
+                ->orderByDesc('id')->get();
+        }
+        $row = ["异常类型", "单号", "状态", "快递公司", "货主", "省份", "发出日期", "收货日期", "称重日期", "快递路由", "客服备注", "情况说明", "问题类别", "说明", "操作者", "时间",];
+        $json = [];
+        foreach ($orderPackages as $orderPackage) {
+            $transfer_status = "";
+            if (is_array($orderPackage->transfer_status) && !empty($orderPackage->transfer_status)) {
+                foreach ($orderPackage->transfer_status as $transfer) {
+                    $transferItemStr = "";
+                    $transferItemStr = $transferItemStr . $transfer['accept_address'] . "   " . $transfer['remark'] . "   " . $transfer['accept_time'];
+                    $transfer_status = $transfer_status . $transferItemStr . ",\r\n";
+                }
+            }
+            $remark = "";
+            if (is_array($orderPackage->remark) && !empty($orderPackage->remark)) {
+                foreach ($orderPackage->remark as $remarkItem) {
+                    $remark = $remark . $remarkItem . ",\r\n";
+                }
+            }
+            $logsContent = "";
+            $users = "";
+            $logCreatedAt = "";
+            if ($orderPackage->order && $orderPackage->order->issue) {
+                foreach ($orderPackage->order->issue->logs as $log) {
+                    $logsContent = $logsContent . $log->content . ",\r\n";
+                    $users = $users . $log->user->name . ",\r\n";
+                    $logCreatedAt = $logCreatedAt . $log->created_at . ",\r\n";
+                }
+            }
+            $data = [
+                $orderPackage->exception_type,
+                $orderPackage->logistic_number,
+                $orderPackage->status,
+                $orderPackage->order->logistic->name,
+                $orderPackage->order->owner->name,
+                $orderPackage->order->province,
+                $orderPackage->sent_at,
+                $orderPackage->received_at,
+                $orderPackage->weighed_at,
+                $transfer_status,
+                $remark,
+                $logsContent,
+                $users,
+                $logCreatedAt,
+            ];
+            $json[] = $data;
+        }
+        return app(ExportService::class)->json($row, $json, "包裹快递");
+    }
 }

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

@@ -18,7 +18,6 @@ use App\OwnerPriceOperationItem;
 use App\OwnerPriceSystem;
 use App\OwnerStoragePriceModel;
 use App\Services\common\BatchUpdateService;
-use App\Services\common\ExportService;
 use App\Services\common\QueryService;
 use App\Services\LogService;
 use App\Services\OwnerPriceOperationItemService;
@@ -30,6 +29,7 @@ use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Validator;
 use Maatwebsite\Excel\Facades\Excel;
+use Oursdreams\Export\Export;
 
 class PriceModelController extends Controller
 {
@@ -55,8 +55,7 @@ class PriceModelController extends Controller
         $this->storageValidator($request->input())->validate();
         /** @var OwnerStoragePriceModel $model */
         $model = app('OwnerStoragePriceModelService')->create($request->input());
-        $result = $model->owners()->sync(explode(",",$request->input("owner_id")));
-        app("OwnerService")->refreshRelevance($result["attached"],0);
+        $model->owners()->sync(explode(",",$request->input("owner_id")));
         LogService::log(__METHOD__,"计费模型-创建仓储计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
         return response()->redirectTo('maintenance/priceModel/storage')->with('successTip',"创建成功!");
     }
@@ -92,9 +91,7 @@ class PriceModelController extends Controller
             $service->update(["id"=>$id],$values);
             $model = new OwnerStoragePriceModel();
             $model->id = $id;
-            $result = $model->owners()->sync(explode(",",request("owner_id")));
-            app("OwnerService")->refreshRelevance($result["attached"],0);
-            app("OwnerService")->refreshRelevance($result["detached"],0,true);
+            $model->owners()->sync(explode(",",request("owner_id")));
         }else $service->copy($model,$values,explode(",",request("owner_id")));
         return response()->redirectTo('maintenance/priceModel/storage')->with('successTip',"更新成功!");
     }
@@ -321,11 +318,7 @@ class PriceModelController extends Controller
         }
         //录入中间表
         /** @var OwnerPriceOperation $ownerPriceOperation */
-        if ($request->input("owner_id")){
-            $result = $ownerPriceOperation->owners()->sync($request->input("owner_id"));
-            app("OwnerService")->refreshRelevance($result["attached"],1);
-            app("OwnerService")->refreshRelevance($result["detached"],1,true);
-        }
+        if ($request->input("owner_id"))$ownerPriceOperation->owners()->sync($request->input("owner_id"));
         LogService::log(__METHOD__,"计费模型-录入作业计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
         return response()->redirectTo("maintenance/priceModel/operation")->with("successTip","创建“".$request->input("name")."”成功");
     }
@@ -381,11 +374,7 @@ class PriceModelController extends Controller
             }
             //录入中间表
             /** @var OwnerPriceOperation $model */
-            if ($request->input("owner_id")){
-                $result = $model->owners()->sync(request("owner_id"));
-                app("OwnerService")->refreshRelevance($result["attached"],1);
-                app("OwnerService")->refreshRelevance($result["detached"],1,true);
-            }
+            if ($request->input("owner_id"))$model->owners()->sync(request("owner_id"));
         }else $service->copy($model,$obj,request("owner_id"),request("items"),false);
         LogService::log(__METHOD__,"计费模型-修改作业计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
         return response()->redirectTo("maintenance/priceModel/operation")->with("successTip","修改“".$request->input("name")."”成功");
@@ -516,9 +505,7 @@ class PriceModelController extends Controller
             "initial_weight" => $request->input("initial_weight"),
             "additional_weight" => $request->input("additional_weight"),
         ]);
-        $result = $model->owners()->sync($request->input("owner_id"));
-        app("OwnerService")->refreshRelevance($result["attached"],2);
-        app("OwnerService")->refreshRelevance($result["detached"],2,true);
+        $model->owners()->sync($request->input("owner_id"));
         $model->logistics()->sync($request->input("logistic_id"));
         LogService::log(__METHOD__,"计费模型-录入快递计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
         return response()->redirectTo("maintenance/priceModel/express")->with("successTip","录入“".$request->input("name")."”成功");
@@ -550,9 +537,7 @@ class PriceModelController extends Controller
             app("OwnerPriceExpressService")->update(["id"=>$id],$values);
             $model = new OwnerPriceExpress();
             $model->id = $id;
-            $result = $model->owners()->sync($request->input("owner_id"));
-            app("OwnerService")->refreshRelevance($result["attached"],2);
-            app("OwnerService")->refreshRelevance($result["detached"],2,true);
+            $model->owners()->sync($request->input("owner_id"));
             $model->logistics()->sync($request->input("logistic_id"));
         }else app("OwnerPriceExpressService")->copy($model,$values,$request->input("owner_id"),$request->input("logistic_id"));
         LogService::log(__METHOD__,"计费模型-修改快递计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
@@ -637,9 +622,7 @@ class PriceModelController extends Controller
             "other_unit_id" => $request->input("other_unit_id"),
             "other_unit_range" => $request->input("other_unit_range"),
         ]);
-        $result = $model->owners()->sync($request->input("owner_id"));
-        app("OwnerService")->refreshRelevance($result["attached"],3);
-        app("OwnerService")->refreshRelevance($result["detached"],3,true);
+        $model->owners()->sync($request->input("owner_id"));
         $model->logistics()->sync($request->input("logistic_id"));
         LogService::log(__METHOD__,"计费模型-录入物流计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
         return response()->redirectTo("maintenance/priceModel/logistic")->with("successTip","创建“".$request->input("name")."”成功");
@@ -675,9 +658,7 @@ class PriceModelController extends Controller
             app("OwnerPriceLogisticService")->update(["id"=>$id],$values);
             $model = new OwnerPriceLogistic();
             $model->id = $id;
-            $result = $model->owners()->sync($request->input("owner_id"));
-            app("OwnerService")->refreshRelevance($result["attached"],3);
-            app("OwnerService")->refreshRelevance($result["detached"],3,true);
+            $model->owners()->sync($request->input("owner_id"));
             $model->logistics()->sync($request->input("logistic_id"));
         }else app("OwnerPriceLogisticService")->copy($model,$values,$request->input("owner_id"),$request->input("logistic_id"));
 
@@ -722,7 +703,7 @@ class PriceModelController extends Controller
                 $detail->additional_weight_price,
             ];
         }
-        return app(ExportService::class)->json($row,$list,"快递计费模型");
+        return Export::make($row,$list,"快递计费模型");
     }
 
     public function logisticImport(Request $request)
@@ -794,7 +775,7 @@ class PriceModelController extends Controller
                 $detail->rate ? $detail->rate."%" : '',
             ];
         }
-        return app(ExportService::class)->json($row,$list,"物流计费模型");
+        return Export::make($row,$list,"物流计费模型");
     }
 
     public function logisticUpdateDetail(Request $request)
@@ -954,9 +935,7 @@ class PriceModelController extends Controller
             "name" => $request->input("name"),
             "base_km" => $request->input("base_km"),
         ]);
-        $result = $model->owners()->sync($request->input("owner_id"));
-        app("OwnerService")->refreshRelevance($result["attached"],4);
-        app("OwnerService")->refreshRelevance($result["detached"],4,true);
+        $model->owners()->sync($request->input("owner_id"));
         LogService::log(__METHOD__,"计费模型-录入直发车计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
         return response()->redirectTo("maintenance/priceModel/directLogistic")->with("successTip","创建“".$request->input("name")."”成功");
     }
@@ -995,9 +974,7 @@ class PriceModelController extends Controller
             app("OwnerPriceDirectLogisticService")->update(["id"=>$id],$values);
             $model = new OwnerPriceDirectLogistic();
             $model->id = $id;
-            $result = $model->owners()->sync($request->input("owner_id"));
-            app("OwnerService")->refreshRelevance($result["attached"],4);
-            app("OwnerService")->refreshRelevance($result["detached"],4,true);
+            $model->owners()->sync($request->input("owner_id"));
         }else app("OwnerPriceDirectLogisticService")->copy($model,$values,request("owner_id"));
         LogService::log(__METHOD__,"计费模型-修改直发车计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
         return response()->redirectTo("maintenance/priceModel/directLogistic")->with("successTip","修改“".$request->input("name")."”成功");
@@ -1119,7 +1096,7 @@ class PriceModelController extends Controller
 
     public function apiStoreStorage()
     {
-        $this->gate("项目管理-仓储-录入");
+        $this->gate("计费模型-仓储-录入");
         $errors = $this->storageValidator(request()->input())->errors();
         if (count($errors)>0)$this->success(["errors"=>$errors]);
 
@@ -1146,7 +1123,6 @@ class PriceModelController extends Controller
         }else{
             $model = app('OwnerStoragePriceModelService')->create($values);
             DB::insert(DB::raw("INSERT INTO owner_storage_price_model_owner VALUES(?,?)"),[$model->id,request("owner_id")]);
-            app("OwnerService")->refreshRelevance(request("owner_id"),0);
             $this->success($model->id);
         }
     }
@@ -1225,7 +1201,6 @@ class PriceModelController extends Controller
                 }
                 app("OwnerPriceOperationItemService")->insert($params["items"]);
                 DB::insert(DB::raw("INSERT INTO owner_price_operation_owner(owner_price_operation_id,owner_id) VALUES(?,?)"),[$model->id,request("owner_id")]);
-                app("OwnerService")->refreshRelevance(request("owner_id"),1);
                 DB::commit();
             });
         }
@@ -1300,7 +1275,6 @@ class PriceModelController extends Controller
                 }
                 OwnerPriceExpressProvince::query()->insert($params["items"]);
                 DB::insert(DB::raw("INSERT INTO owner_price_express_owner VALUES(?,?)"),[$model->id,request("owner_id")]);
-                app("OwnerService")->refreshRelevance(request("owner_id"),2);
                 /** @var OwnerPriceExpress $model */
                 $model->logistics()->syncWithoutDetaching(request("logistics"));
                 DB::commit();
@@ -1382,7 +1356,6 @@ class PriceModelController extends Controller
                 foreach ($params["items"] as &$param)$param["owner_price_logistic_id"] = $model->id;
                 OwnerPriceLogisticDetail::query()->insert($params["items"]);
                 DB::insert(DB::raw("INSERT INTO owner_price_logistic_owner VALUES(?,?)"),[$model->id,request("owner_id")]);
-                app("OwnerService")->refreshRelevance(request("owner_id"),3);
                 /** @var OwnerPriceLogistic $model */
                 $model->logistics()->syncWithoutDetaching(request("logistics"));
                 DB::commit();
@@ -1447,7 +1420,6 @@ class PriceModelController extends Controller
                 foreach ($items as &$item)$item["owner_price_direct_logistic_id"] = $model->id;
                 OwnerPriceDirectLogisticCar::query()->insert($items);
                 DB::insert(DB::raw("INSERT INTO owner_price_direct_logistic_owner VALUES(?,?)"),[$model->id,request("owner_id")]);
-                app("OwnerService")->refreshRelevance(request("owner_id"),4);
                 DB::commit();
             });
         }
@@ -1807,11 +1779,12 @@ class PriceModelController extends Controller
         /** @var \stdClass|Owner $owner */
         $owner = new Owner();
         $owner->id = $ownerId;
+        $response = null;
         switch (request("type")){
             case "storage":
                 app("OwnerStoragePriceModelService")->auditOrRecover(request("isAudit"),$ownerId);//priceModelAuditOrRecoverQuery
                 $owner->load("ownerStoragePriceModels");
-                $this->success($owner->ownerStoragePriceModels);
+                $response = $owner->ownerStoragePriceModels;
                 break;
             case "operation":
                 app("OwnerPriceOperationService")->auditOrRecover(request("isAudit"),$ownerId);
@@ -1834,7 +1807,7 @@ class PriceModelController extends Controller
                         }
                     }
                 }
-                $this->success($owner->ownerPriceOperations);
+                $response = $owner->ownerPriceOperations;
                 break;
             case "express":
                 app("OwnerPriceExpressService")->auditOrRecover(request("isAudit"),$ownerId);
@@ -1842,7 +1815,7 @@ class PriceModelController extends Controller
                     /** @var Builder $query */
                     $query->with(["details","logistics"]);
                 }]);
-                $this->success($owner->ownerPriceExpresses);
+                $response = $owner->ownerPriceExpresses;
                 break;
             case "logistic":
                 app("OwnerPriceLogisticService")->auditOrRecover(request("isAudit"),$ownerId);
@@ -1850,7 +1823,7 @@ class PriceModelController extends Controller
                     /** @var Builder $query */
                     $query->with(["details","logistics"]);
                 }]);
-                $this->success($owner->ownerPriceLogistics);
+                $response = $owner->ownerPriceLogistics;
                 break;
             case "directLogistic":
                 app("OwnerPriceDirectLogisticService")->auditOrRecover(request("isAudit"),$ownerId);
@@ -1859,18 +1832,14 @@ class PriceModelController extends Controller
                 break;
             case "system":
                 $result = app(QueryService::class)->priceModelAuditOrRecoverQuery(request("isAudit"),OwnerPriceSystem::query(),$ownerId,null,true);
-                if ($result["delete"]){
-                    OwnerPriceSystem::destroy($result["delete"]);
-                    app("OwnerService")->refreshRelevance($ownerId,5,true);
-                }
-                if ($result["update"]){
-                    OwnerPriceSystem::query()->whereIn("id",$result["update"])->update(["operation"=>null,"target_id"=>null]);
-                    app("OwnerService")->refreshRelevance($ownerId,5);
-                }
+                if ($result["delete"])OwnerPriceSystem::destroy($result["delete"]);
+                if ($result["update"])OwnerPriceSystem::query()->whereIn("id",$result["update"])->update(["operation"=>null,"target_id"=>null]);
                 $owner->load("ownerPriceSystem");
-                $this->success($owner->ownerPriceSystem);
+                $response = $owner->ownerPriceSystem;
                 break;
         }
+        app("OwnerService")->refreshRelevance($ownerId);
+        $this->success($response);
     }
 
     /**

+ 66 - 0
app/Http/Controllers/PrintPartController.php

@@ -0,0 +1,66 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\Components\AsyncResponse;
+use App\Order;
+use App\PrintPart;
+use App\PrintTemplate;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Http;
+
+class PrintPartController extends Controller
+{
+    use AsyncResponse;
+    public function index(Request $request)
+    {
+        $printParts = PrintPart::query()->paginate($request['paginate'] ?? 50);
+        return view('/maintenance/expressPrinting/part/index',compact('printParts'));
+    }
+
+    public function create(Request $request)
+    {
+        return view('/maintenance/expressPrinting/part/create');
+    }
+
+    public function storeApi(Request $request): \Illuminate\Http\RedirectResponse
+    {
+        PrintPart::query()->create($request->all());
+        $this->success('添加成功');
+    }
+
+    public function destroyApi(Request $request)
+    {
+        $printPart = PrintPart::query()->find($request['id']);
+        $printPart->delete();
+        $this->success('删除成功');
+    }
+
+    public function print(Request $request)
+    {
+        $template = PrintTemplate::query()->where('name','test-快递单号打印')->first();
+        $items = Order::query()->whereIn('code',["SO190628000378","SO190628000347"])->with('packages')->get();
+        return view("maintenance.expressPrinting.print.index",compact("template",'items'));
+    }
+
+    public function printTemplateApi(Request $request)
+    {
+        $file = $request->file("blob");
+        $content = $file->getContent();
+        $content = base64_encode($content);
+        $files = $request->file("blobs");
+
+        $content = [
+            "type" => "print",
+            "aliasName"=>"admin",
+            "printerName"=>"admin123",
+            "content" => $content
+        ];
+        if(!$files)return Http::post("http://127.0.0.1:3000",$content);
+        $contents = [];
+        foreach ($files as $item) {
+            $contents[] = base64_encode($item->getContent());
+        }
+        return Http::post("http://127.0.0.1:3000",['file'=>$content,'files'=>$contents]);
+    }
+}

+ 49 - 0
app/Http/Controllers/PrintTemplateController.php

@@ -0,0 +1,49 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\Components\AsyncResponse;
+use App\PrintPart;
+use App\PrintTemplate;
+use Illuminate\Http\Request;
+
+class PrintTemplateController extends Controller
+{
+    use AsyncResponse;
+    public function index(Request $request)
+    {
+        $templates = PrintTemplate::all();
+        return view('/maintenance/expressPrinting/template/index',compact('templates'));
+    }
+
+    public function create(Request $request)
+    {
+        $printParts = PrintPart::all();
+        return view('/maintenance/expressPrinting/template/create',compact('printParts'));
+    }
+
+
+    public function storeApi(Request $request)
+    {
+        $data = [
+            'name' =>$request['name'],
+            'value'=>json_encode($request['value'])
+        ];
+        $printTemplate = PrintTemplate::query()->create($data);
+        $this->success(['data' => $printTemplate]);
+    }
+
+    public function updateApi(Request $request)
+    {
+
+    }
+
+    public function destroyApi(Request $request)
+    {
+        $printTemplate = PrintTemplate::query()->find($request['id']);
+        $printTemplate->delete();
+        $this->success('删除成功');
+    }
+
+
+}

+ 14 - 8
app/Http/Controllers/ProcessController.php

@@ -30,6 +30,7 @@ use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
 use Illuminate\Support\Facades\Validator;
+use Oursdreams\Export\Export;
 use Ramsey\Uuid\Uuid;
 
 class ProcessController extends Controller
@@ -1106,14 +1107,19 @@ class ProcessController extends Controller
             unset($params['checkAllSign']);
             $sql = app('ProcessService')->getSql($params);
         }else $sql = app('ProcessService')->getSql(["id"=>$request->data]);
-        $post = Http::post(config('go.export.url'),['type'=>'process','sql'=>$sql]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=二次加工记录-".date('ymdHis').'.xlsx',
-        ]);
+        $e = new Export();
+        $e->setMysqlConnection(config('database.connections.mysql.host'),
+            config('database.connections.mysql.port'),config('database.connections.mysql.database')
+            ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
+        $e->setFileName("二次加工记录-".date('ymdHis'));
+        return $e->sql($sql,[
+            "code"=>"任务号","owner_name"=>"货主",
+            "process_method_name"=>"加工类型","amount"=>"预期数量",
+            "completed_amount"=>"实际数量","status"=>"状态",
+            "remark"=>"加工备注","unit_price"=>"单价",
+            "created_at"=>"提交日期","content_bill_type"=>"单据类型","content_wms_code"=>"单据号",
+            "commodity_sku"=> "商品编码","commodity_name"=>"商品名称","commodity_barcode_code"=>"商品条码",
+            "content_amount"=>"本次数量","process_balance_remark"=>"结算备注"])->direct();
     }
 
     public function validatorProcessContent(array $processContent){

+ 3 - 1
app/Http/Controllers/ProcessStatisticController.php

@@ -9,6 +9,7 @@ use Exception;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
+use Oursdreams\Export\Export;
 
 class ProcessStatisticController extends Controller
 {
@@ -59,6 +60,7 @@ class ProcessStatisticController extends Controller
                 $process->process->balance_remark ?? "",
             ];
         }
-        return app(ExportService::class)->json($row,$list,"二次加工统计记录");
+        return Export::make($row,$list,"二次加工统计记录");
+        //return app(ExportService::class)->json($row,$list,"二次加工统计记录");
     }
 }

+ 7 - 8
app/Http/Controllers/ProcurementController.php

@@ -14,14 +14,12 @@ use App\Jobs\ProcurementEnquiry;
 use App\Jobs\ProcurementReceive;
 use App\Jobs\ProcurementWaitConfirmInform;
 use App\Material;
-use App\Owner;
 use App\Procurement;
 use App\ProcurementCheckSheet;
 use App\ProcurementDeliverie;
 use App\ProcurementTotalBill;
 use App\Services\common\ExportService;
 use App\Services\ConfigurationService;
-use App\Services\LogService;
 use App\Services\OwnerMaterialService;
 use App\Services\ProcurementService;
 use App\Services\ProcurementTotalBillService;
@@ -32,6 +30,7 @@ use Illuminate\Support\Carbon;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\Gate;
 use Matrix\Builder;
+use Oursdreams\Export\Export;
 
 class ProcurementController extends Controller
 {
@@ -399,7 +398,7 @@ class ProcurementController extends Controller
         }
         $procurementStatus=Procurement::status;
         $procurementType=Procurement::type;
-        $row = ['采购编号','项目','单据类型','采购公司','耗材编号','耗材','尺寸大小','特殊要求','材质规格','采购数量','销售单价(元)','送货数量','销售总价(元)','采购单状态','联系方式'];
+        $row = ['采购编号','项目','单据类型','采购公司','耗材编号','耗材','尺寸大小','特殊要求','材质规格','采购数量','销售单价(元)','送货数量','销售总价(元)','采购单状态','供应商联系方式'];
         $list = [];
         foreach ($procurements as $procurement){
             $list[] = [
@@ -417,10 +416,10 @@ class ProcurementController extends Controller
                 $procurement->deliver_amount ?  $procurement->deliver_amount :'',//送货数量
                 $procurement->unit_price*$procurement->amount,//销售总价=销售数量*销售单价
                 is_null($procurement->status) ? '' :$procurementStatus[$procurement->status],
-                $procurement->ownerMaterial->owner->customer ? $procurement->ownerMaterial->owner->customer->phone :'',
+                $procurement->supplier->phone ? $procurement->supplier->phone :'',
             ];
         }
-        return app(ExportService::class)->json($row,$list,"采购管理-采购报表记录");
+        return Export::make($row,$list,"采购管理-采购报表记录");
     }
     //对账单报表导出
     public function checkBillExport(Request $request,ProcurementCheckSheetFilters $filters){
@@ -459,7 +458,7 @@ class ProcurementController extends Controller
                 is_null($procurementCheckSheet->status) ? '' :$procurementCheckSheetStatus[$procurementCheckSheet->status],
             ];
         }
-        return app(ExportService::class)->json($row,$list,"采购管理-对账单报表记录");
+        return Export::make($row,$list,"采购管理-对账单报表记录");
     }
     //采购账单导出
     public function procurementBillExport(Request $request,ProcurementFilters $filters){
@@ -512,7 +511,7 @@ class ProcurementController extends Controller
                 is_null($procurement->status) ? '' :$procurementStatus[$procurement->status],
             ];
         }
-        return app(ExportService::class)->json($row,$list,"采购账单报表记录");
+        return Export::make($row,$list,"采购账单报表记录");
     }
     //月账单报表导出
     public function procurementTotalBillExport(Request $request){
@@ -539,6 +538,6 @@ class ProcurementController extends Controller
                 $procurementTotalBill->status ? $procurementTotalBillStatus[$procurementTotalBill->status] :'',
             ];
         }
-        return app(ExportService::class)->json($row,$list,"采购管理-月账单报表记录");
+        return Export::make($row,$list,"采购管理-月账单报表记录");
     }
 }

+ 29 - 17
app/Http/Controllers/RejectedController.php

@@ -24,11 +24,11 @@ use Illuminate\Http\Response;
 use Illuminate\Routing\Redirector;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\Gate;
-use Illuminate\Support\Facades\Http;
 use Illuminate\Support\Facades\Validator;
 use Illuminate\View\View;
 use Maatwebsite\Excel\Facades\Excel;
 use function foo\func;
+use Oursdreams\Export\Export;
 
 class RejectedController extends Controller
 {
@@ -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();
@@ -407,14 +409,21 @@ class RejectedController extends Controller
             $param = ["id"=>$request->data];
         }
         $sql = app('RejectedService')->getSql($param);
-        $post = Http::post(config('go.export.url'),['type'=>'rejected','sql'=>$sql]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=退货单列表-".date('ymdHis').'.xlsx',
-        ]);
+
+        $e = new Export();
+        $e->setMysqlConnection(config('database.connections.mysql.host'),
+            config('database.connections.mysql.port'),config('database.connections.mysql.database')
+            ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
+        $e->setFileName("退货单列表-".date('ymdHis'));
+        return $e->sql($sql,[
+            "created_at"=>"日期","checked_numbers"=>"审核号",
+            "owner_name"=>"客户名称","order_number"=>"订单号",
+            "sender"=>"姓名","mobile_sender"=>"手机",
+            "logistic_number"=>"原单单号","logistic_number_return"=>"退回单号","logistic_name"=>"退回公司",
+            "fee_collected"=>"到付费用","loaded"=>"是否入库",
+            "item_barcode"=>"商品条码","item_name"=>"商品名称",
+            "item_amount"=>"商品数量","quality_label_name"=>"商品质量","operator_name"=>"录入人"
+        ])->direct();
     }
 
 
@@ -500,14 +509,17 @@ class RejectedController extends Controller
     public function exportAnalyze(Request $request){
         $searchParams = $this->getAnalyzeSearchParams($request);
         $sql = RejectedAnalyzeOwner::getQuerySQL($searchParams);
-        $post = Http::post(config('go.export.url'),['type'=>'rejectedStatistics','sql'=>$sql]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=退货统计记录单-".date('ymdHis').'.xlsx',
-        ]);
+
+        $e = new Export();
+        $e->setMysqlConnection(config('database.connections.mysql.host'),
+            config('database.connections.mysql.port'),config('database.connections.mysql.database')
+            ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
+        $e->setFileName("退货统计记录单");
+        return $e->sql($sql,[
+            "owner_name"=>"货主名","bounce_amount"=>"退件单数",
+            "check_amount"=>"审核单数","uncheck_amount"=>"未审核单数",
+            "in_storage_count"=>"入库单数","not_in_storage_count"=>"未入库单数",
+        ])->direct();
     }
 
     public function apiGetRejectedByLogisticNumberReturn(Request $request){

+ 163 - 26
app/Http/Controllers/StorageController.php

@@ -3,6 +3,13 @@
 namespace App\Http\Controllers;
 
 use App\Components\AsyncResponse;
+use App\MaterialBox;
+use App\Services\LogService;
+use App\Station;
+use App\StationTask;
+use App\StationTaskMaterialBox;
+use App\Storage;
+use App\ValueStore;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\DB;
 
@@ -15,25 +22,59 @@ class StorageController extends Controller
         $asn = \request("asn");
         $ide = \request("ide");
         $barCode = \request("barCode");
-        $amount = \request("amount");
+        $amount = (int)\request("amount");
+        //check info
         if (!$asn || !$ide || !$barCode || !$amount)$this->error("信息不完整");
+        $fromLocation = app("MaterialBoxService")->getBoxLocation($ide);
+        if (!$fromLocation)$this->error("海柔无此库位信息");
+        $box = MaterialBox::query()->select("id")->where("code",$ide)->first();
+        if (!$box)$this->error("WAS无此料箱");
+
+        //get flux
         $sql = <<<sql
 SELECT * FROM DOC_ASN_DETAILS LEFT JOIN BAS_SKU ON DOC_ASN_DETAILS.CUSTOMERID = BAS_SKU.CUSTOMERID AND DOC_ASN_DETAILS.SKU = BAS_SKU.SKU
-WHERE asnno = ? AND (ALTERNATE_SKU1 = ? OR ALTERNATE_SKU2 = ?)
-sql;
-        $asn = DB::connection("oracle")->selectOne(DB::raw($sql),[$asn,$barCode,$barCode]);
-        if (!$asn || $asn->receivedqty_each<$amount)$this->error("ASN不存在或数量异常");
-        $sql = <<<sql
-SELECT fmlotnum,fmlocation,toid FROM ACT_TRANSACTION_LOG WHERE transactiontype = 'IN' AND fmcustomerid = ? AND fmsku = ? AND docno = ? AND doclineno = ? AND doctype = 'ASN' AND pa_flag = 'Y'
+LEFT JOIN TSK_TASKLISTS ON DOC_ASN_DETAILS.ASNNO = TSK_TASKLISTS.DOCNO AND DOC_ASN_DETAILS.ASNLINENO = TSK_TASKLISTS.DOCLINENO
+WHERE ASNNO = ? AND (ALTERNATE_SKU1 = ? OR ALTERNATE_SKU2 = ? OR ALTERNATE_SKU3 = ?) AND RECEIVEDQTY >= ?
+  AND TASKPROCESS = '00' AND TASKTYPE = 'PA'
 sql;
-        $act = DB::connection("oracle")->selectOne(DB::raw($sql),[$asn->customerid,$asn->sku,$asn->asnno,$asn->asnlineno]);
-        if (!$act)$this->error("没有入库记录");
+        $asns = DB::connection("oracle")->select(DB::raw($sql),[$asn,$barCode,$barCode,$barCode,$amount]);
+        if (!$asns)$this->error("ASN不存在或上架数量与入库数量不符");
+        $nums = [];
+        $result = null;
+        foreach ($asns as $index=>$asn){
+            if ((int)$asn->fmqty == $amount){$result=$index;break;}
+            $nums[] = (int)$asn->fmqty;
+        }
+        //flux上架
+        if ($result!==null)$this->fluxPA($asns[$result],$ide,$amount);
+        else{
+            $result = $this->twoSum($nums,$amount);
+            if (!$result)$this->error("无法匹配入库记录,检查您的上架数量");
+            DB::connection("oracle")->transaction(function ()use($result,$asns,$ide){
+                foreach ($result as $index){
+                    $this->fluxPA($asns[$index],$ide,(int)$asns[$index]->fmqty);
+                }
+            });
+        }
+        //亮灯
+        app("CacheShelfService")->_stationCacheLightOn($fromLocation,$ide);
+        //建立入库任务
+        if (!app("ForeignHaiRoboticsService")->putWareHousing($fromLocation,'',$box->id))$this->error("错误库位或库位已被下达任务");
+        //占用库位 应在任务完成后释放
+        app("StorageService")->markOccupy($fromLocation);
+        $this->success();
+    }
+
+    public function fluxPA($asn,$ide,$amount)
+    {
+        if (!$asn->taskid)$this->error("ASN单无此入库信息,禁止上架");
+
         $sql = <<<sql
 SELECT * FROM inv_lot_loc_id  WHERE lotnum = ? AND traceid = ? AND customerid= ?  and sku = ?
 sql;
-        $inv = DB::connection("oracle")->select(DB::raw($sql),[$act->fmlotnum,$act->toid,$asn->customerid,$asn->sku]);
-        if (!$inv)$this->error("余量与入库不符");
-        DB::transaction(function ()use($inv,$amount,$ide,$asn,$act){
+        $inv = DB::connection("oracle")->select(DB::raw($sql),[$asn->fmlotnum,$asn->plantoid,$asn->customerid,$asn->sku]);
+        if (count($inv)==0)$this->error("余量与入库不符");
+        DB::connection("oracle")->transaction(function ()use($inv,$amount,$ide,$asn,&$who){
             $db = DB::connection("oracle");
             $qty = $amount;
             foreach ($inv as $in){
@@ -51,18 +92,14 @@ sql;
                     $qty = $qty-$in->qty;
                 }
             }
-            if ($qty!=0){
-                $db->rollBack();
-                $this->error("上架数量与入库数量不符");
-            }
-            $db->delete(DB::raw("DELETE FROM inv_lot_loc_id WHERE lotnum = ? AND traceid = ? AND traceid != '*'"),[
+            $db->delete(DB::raw("DELETE FROM inv_lot_loc_id WHERE lotnum = ? AND traceid = ? AND traceid != '*'  AND qty = 0"),[
                 $inv[0]->lotnum,$inv[0]->traceid
             ]);
-            $inv = $db->selectOne(DB::raw("SELECT * FROM inv_lot_loc_id WHERE lotnum = ? AND locationid = ? AND customerid = ? AND sku = ? AND traceid = '*' FOR UPDATE"),[
+            $invHistory = $db->selectOne(DB::raw("SELECT * FROM inv_lot_loc_id WHERE lotnum = ? AND locationid = ? AND customerid = ? AND sku = ? AND traceid = '*' FOR UPDATE"),[
                 $inv[0]->lotnum,$ide,$inv[0]->customerid,$inv[0]->sku
             ]);
             $who = 'WAS'.(Auth::user() ? '-'.Auth::user()["name"] : '');
-            if ($inv)$db->update(DB::raw("UPDATE inv_lot_loc_id SET qty = qty+? WHERE lotnum = ? AND locationid = ? AND traceid = '*'"),[
+            if ($invHistory)$db->update(DB::raw("UPDATE inv_lot_loc_id SET qty = qty+? WHERE lotnum = ? AND locationid = ? AND traceid = '*'"),[
                 (int)$amount,$inv[0]->lotnum,$ide
             ]);
             else $db->insert(DB::raw("INSERT INTO inv_lot_loc_id VALUES(?,?,'*',?,?,?,0,0,0,0,0,0,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,0,0,0,0,0,'*',0,null)"),[
@@ -70,18 +107,118 @@ sql;
                 date("Y-m-d H:i:s"),$who
             ]);
             $sql = <<<sql
-INSERT INTO ACT_TRANSACTION_LOG VALUES(?,'PA',?,?,?,?,'ASN',?,?,?,?,?,?,?,?,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss')),?,
-TO_DATE(?,'yyyy-mm-dd hh24:mi:ss')),?,0,0,0,0,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,?,null,null,null,'*',?,?,?,?,?,?,?,
+INSERT INTO ACT_TRANSACTION_LOG VALUES(?,'PA',?,?,?,?,'ASN',?,?,?,?,?,?,?,?,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,
+TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,0,0,0,0,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?,?,null,null,null,'*',?,?,?,?,?,?,?,
 ?,?,?,?,?,'N',null,?,?,?,?,?,?,?,null,null)
 sql;
+            $trid = $this->getTrNumber();
             $db->insert(DB::raw($sql),[
-                'WA'.date('ymdHis').substr(\request("asn"),-2).rand(0,9),$asn->customerid,$asn->sku,
-                $asn->asnno,$asn->asnlineno,$inv[0]->lotnum,$act->fmlocation,$act->toid,$asn->packid,$asn->uom,$amount,$amount,$act->status,date("Y-m-d H:i:s"),$who,
+                $trid,$asn->customerid,$asn->sku,
+                $asn->asnno,$asn->asnlineno,$inv[0]->lotnum,$asn->fmlocation,$asn->plantoid,$asn->packid,$asn->uom,$amount,$amount,'99',date("Y-m-d H:i:s"),$who,
                 date("Y-m-d H:i:s"),$who,date("Y-m-d H:i:s"),$asn->customerid,$asn->sku,$ide,$who,$asn->packid,$asn->uom,$amount,$amount,$inv[0]->lotnum,
-                'QC_TASKID',$act->qc_sequence,$act->qc_flag,'*',$act->pa_sequence,$act->warehouseid,$act->userdefine1,$act->userdefine2,
-                $act->userdefine3,$act->userdefine4,$act->userdefine5,$act->edisendflag
+                '*','0','N','*',$asn->taskid_sequence,$asn->warehouseid,$asn->userdefine1,$asn->userdefine2,
+                $asn->userdefine3,$asn->userdefine4,$asn->userdefine5,'O'
+            ]);
+            $this->setTrNumber();
+            $sql = <<<sql
+update TSK_TASKLISTS set TASKPROCESS = '99',REASONCODE = 'OK',PLANTOLOCATION = ?,PLANLOGICALTOSEQUENCE = ?,
+CREATE_TRANSACTIONID = ?,OPENWHO = ?,OPENTIME = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),
+ CLOSEWHO = ?,CLOSETIME = ?,EDITTIME = ?,EDITWHO = ?
+ where taskid = ? AND TASKID_SEQUENCE = ?
+sql;
+            $db->update(DB::raw($sql),[
+                $ide,$ide,$trid,$who,date("Y-m-d H:i:s"),$who,date("Y-m-d H:i:s"),date("Y-m-d H:i:s"),$who,$asn->taskid,$asn->taskid_sequence
             ]);
         });
-        //成功后应去修改ASN状态及数量
+        //成功后应去修改ASN状态及数量 暂时不知上架后ASN应为状态
+        /*        $sql = <<<sql
+        UPDATE doc_asn_details SET linestatus = ?,edittime = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),editwho = ? WHERE asnno = ? AND asnlineno = ?
+        sql;*/
+        //if ($asn->expectedqty>$asn->receivedqty && $asn->linestatus!='30')DB::connection("oracle")->update(DB::raw($sql),['30',date("Y-m-d H:i:s"),$who,$asn->asnno,$asn->asnlineno]);
+        if ($asn->expectedqty==$asn->receivedqty && $asn->linestatus=='40'){
+            //DB::connection("oracle")->update(DB::raw($sql),['40',date("Y-m-d H:i:s"),$who,$asn->asnno,$asn->asnlineno]);
+            $check = DB::connection("oracle")->selectOne(DB::raw("SELECT 1 FROM DOC_ASN_DETAILS WHERE ASNNO = ? AND LINESTATUS != '40'"),[$asn->asnno]);
+            if (!$check){
+                $logs = DB::connection("oracle")->select(DB::raw("SELECT SUM(FMQTY) qty,TRANSACTIONTYPE FROM ACT_TRANSACTION_LOG WHERE DOCNO = ? AND TRANSACTIONTYPE IN ('PA','IN') GROUP BY TRANSACTIONTYPE"),[$asn->asnno]);
+                $paQty = 0;
+                $inQty = 0;
+                foreach ($logs as $log){
+                    if ($log->transactiontype == 'IN')$inQty = $log->qty;
+                    else $paQty = $log->qty;
+                }
+                if ($paQty == $inQty){
+                    DB::connection("oracle")->update(DB::raw("UPDATE DOC_ASN_HEADER SET asnstatus = '99',edittime = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),editwho = ? WHERE asnno = ?"),
+                        [date("Y-m-d H:i:s"),$who,$asn->asnno]);
+                    DB::connection("oracle")->update(DB::raw("UPDATE DOC_ASN_DETAILS SET linestatus = '99',edittime = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),editwho = ? WHERE asnno = ?"),
+                        [date("Y-m-d H:i:s"),$who,$asn->asnno]);
+                }
+            }
+        }
+    }
+
+    /**
+     * @param Integer[] $nums
+     * @param Integer $target
+     * @return Integer[]|null
+     */
+    function twoSum($nums, $target) {
+        $map=[];
+        for($i=0;$i<count($nums);$i++){
+            $complement=$target-$nums[$i];
+            if(array_key_exists($complement,$map)){
+                return [$map[$complement],$i];
+            }
+            $map[$nums[$i]]=$i;
+        }
+        return null;
+    }
+
+    function getTrNumber()
+    {
+        $val = ValueStore::query()->select("value")->where("name","flux_tr_number")->first();
+        if (!$val)$val = ValueStore::query()->create(["name"=>"flux_tr_number","value"=>'0']);
+        $max = $val->value+1;
+        $number = sprintf("%09d", $max);
+        return 'W'.$number;
+    }
+
+    function setTrNumber()
+    {
+        ValueStore::query()->select("value")->where("name","flux_tr_number")->update(["value"=>DB::raw("flux_tr_number+1")]);
+    }
+
+    /**
+     * 重置缓存架指定格口
+     */
+    public function resetCacheShelf()
+    {
+        $boxes = request("boxes");
+        //清理任务
+        $data = '';
+        $station = Station::query()->select("id")->whereIn("code",$boxes);
+        $occupy = Storage::query()->with("station:id,code")->whereIn("station_id",$station)->where("status",1)->get();
+        foreach ($occupy as $item){
+            unset($boxes[array_search($item->station->code,$boxes)]);
+            $data .= '“'.$item->station->code.'”,';
+        }
+        if ($occupy->count()>0){
+            $data .= "存在任务待处理,无法释放";
+            $boxes = array_values($boxes);
+            $station = Station::query()->select("id")->whereIn("code",$boxes);
+        }
+        $task = StationTask::query()->select("id")->where("status","!=",'完成')->whereIn("station_id",$station);
+        StationTaskMaterialBox::query()->where("status","!=",'完成')->whereIn("station_task_id",$task)->update([
+            "status" => "完成"
+        ]);
+        StationTask::query()->where("status","!=",'完成')->whereIn("station_id",$station)->update([
+            "status" => "完成"
+        ]);
+        //清理库存
+        Storage::query()->whereIn("station_id",$station)->update([
+            "status" => 0,"material_box_id" => null, "commodity_id" => null, "amount" => 0,
+        ]);
+        //重新调取料箱
+        app("StorageService")->paddingCacheShelf($station->get());
+        $this->success(["data"=>$data,"boxes"=>$boxes]);
     }
 }

+ 2 - 10
app/Http/Controllers/StoreCheckingReceiveController.php

@@ -14,6 +14,7 @@ use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
 use Maatwebsite\Excel\Facades\Excel;
+use Oursdreams\Export\Export;
 
 class StoreCheckingReceiveController extends Controller
 {
@@ -246,16 +247,7 @@ class StoreCheckingReceiveController extends Controller
                 $item->unique_code,
             ];
         }
-        $post = Http::post(config('go.export.url'),['type'=>'base','data'=>json_encode([
-            'row'=>$row,'list'=>$list
-        ],JSON_UNESCAPED_UNICODE)]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=盘收任务详情-".date('ymdHis').'.xlsx',
-        ]);
+        return Export::make($row,$list,"盘收任务单");
     }
 
     public function resetAmount(Request $request){

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

@@ -6,6 +6,8 @@ use App\Depository;
 use App\Owner;
 use App\Services\common\BatchUpdateService;
 use App\Services\StoreService;
+use App\Station;
+use App\Storage;
 use App\Store;
 use App\StoreItem;
 use App\Warehouse;
@@ -438,6 +440,10 @@ class StoreController extends Controller
      */
     public function cacheRackStorage()
     {
-        return \view("store.inStorage.cacheRackStorage");
+        $stations = Station::query()->select("id")->where("parent_id",6);
+        $storages = Storage::query()->with("station:id,code")->whereIn("station_id",$stations)->where(function (Builder $query){
+            $query->whereNotNull("material_box_id")->orWhere("status",1);
+        })->get();
+        return \view("store.inStorage.cacheRackStorage",compact("storages"));
     }
 }

+ 67 - 63
app/Http/Controllers/TestController.php

@@ -47,10 +47,17 @@ use App\ProcurementDeliverie;
 use App\ProcurementQuotation;
 use App\ProcurementTotalBill;
 use App\RejectedBillItem;
+use App\Services\BatchService;
 use App\Services\CacheService;
 use App\Services\CommodityService;
 use App\Services\common\BatchUpdateService;
 use App\Services\common\DataHandlerService;
+use App\Services\common\QueryService;
+use App\Services\DeliveryAppointmentService;
+use App\Services\DocWaveHeaderService;
+use App\Services\FeatureService;
+use App\Services\InventoryCompareService;
+use App\Services\LogisticService;
 use App\Services\LogisticZopService;
 use App\Services\LogService;
 use App\Services\OracleDOCOrderHeaderService;
@@ -74,9 +81,30 @@ use App\UserDetail;
 use App\UserDutyCheck;
 use App\ValueStore;
 use Carbon\Carbon;
+use Carbon\CarbonPeriod;
+use ChangeColumnOrderIdToOrderIssues;
+use Doctrine\DBAL\Exception\DatabaseObjectExistsException;
+use Doctrine\DBAL\Query\QueryBuilder;
+use GuzzleHttp\Client;
+use Illuminate\Database\Connection;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\QueryException;
+use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\Cache;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Hash;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Redis;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Str;
+use Maatwebsite\Excel\Facades\Excel;
+use Mockery\Mock;
+use Oursdreams\Export\Export;
+use Overtrue\LaravelPinyin\Facades\Pinyin;
+use PhpMyAdmin\Server\Status\Data;
+use Ramsey\Collection\Collection;
 use Zttp\Zttp;
 
 class TestController extends Controller
@@ -93,70 +121,21 @@ class TestController extends Controller
     {
         return call_user_func([$this, $method], $request);
     }
-    public function createCacheRack()
-    {
-        $stations = [
-            "HAIB1-01-02","HAIB1-01-03",
-            "HAIB1-02-01","HAIB1-02-03",
-            "HAIB1-03-01","HAIB1-03-02","HAIB1-03-03"
-        ];
-        foreach ($stations as $station){
-            Station::query()->create([
-                "parent_id" => 6,
-                "name" => $station,
-                "code" => $station,
-                "station_type_id" => 5,
-            ]);
-        }
-        dd("OK");
-    }
     public function test()
     {
-        $orders = Order::query()->where("wms_status","订单完成")->whereBetween("updated_at",["2021-05-21 12:00:00","2021-05-21 23:59:00"])
-            ->whereNotIn("id",OwnerFeeDetail::query()->select("outer_id")->where("outer_table_name","orders")
-                ->whereBetween("worked_at",["2021-05-21 12:00:00","2021-05-21 23:59:00"]))->get();
-        foreach ($orders->chunk(50) as $or){
-            dispatch(new OrderCreateInstantBill($or));
-        }
-        dd("推进数:".count($orders));
-        $asnno = "ASN2105141388";
-        $query = DB::raw("SELECT b.ALTERNATE_SKU1,h.WAREHOUSEID,h.asnno,d.ASNLINENO,d.SKUDESCRC,h.CUSTOMERID,d.SKU,d.PACKID,d.RECEIVEDQTY_EACH,d.EXPECTEDQTY_EACH,d.LOTATT01,d.LOTATT02,d.lotatt04,".
-            "d.lotatt05,d.lotatt08,d.USERDEFINE1,d.USERDEFINE2,d.USERDEFINE3,d.USERDEFINE4,d.USERDEFINE5,d.RECEIVINGLOCATION FROM DOC_ASN_DETAILS d ".
-            " LEFT JOIN BAS_SKU b ON d.CUSTOMERID = b.CUSTOMERID AND d.SKU = b.SKU INNER JOIN DOC_ASN_HEADER h ON d.ASNNO = h.ASNNO WHERE h.ASNNO = ?");
-        $detail = DB::connection("oracle")->selectOne($query,[$asnno]);
-        //dd($detail);
-        $ser = new StoreService();
-        $result = $ser->warehousing(array(
-            "IN_Warehouse" => $detail->warehouseid ?? '',
-            "In_ASNNo_C" => $detail->asnno ?? '',
-            "In_ASNLineNo_C" => $detail->asnlineno ?? '',
-            "In_New_TraceID_C" => (string)rand(100,999),
-            "In_CustomerID" => $detail->customerid ?? '',
-            "In_SKU" => $detail->sku ?? '',
-            "In_ReceivedQty" => (string)((int)$detail->expectedqty_each - (int)$detail->receivedqty_each) ?? '',
-            "In_PackID" => $detail->packid ?? '',
-            "In_LotAtt01_C" => $detail->lotatt01 ?? '',
-            "In_LotAtt02_C" => $detail->lotatt02 ?? '',
-            "In_LotAtt04_C" => $detail->lotatt04 ?? '',
-            "In_LotAtt05_C" => $detail->lotatt05 ?? '',
-            "In_LotAtt08_C" => $detail->lotatt08 ?? '',
-            "In_UserDefine1" => $detail->userdefine1 ?? '',
-            "In_UserDefine2" => $detail->userdefine2 ?? '',
-            "In_UserDefine3" => $detail->userdefine3 ?? '',
-            "In_UserDefine4" => $detail->userdefine4 ?? '',
-            "In_UserDefine5" => $detail->userdefine5 ?? '',
-            "In_FMLocation"  => 'STAGE' . $detail->warehouseid,
-            "In_TOLocation_C" => 'STAGE' . $detail->warehouseid,//'IDE0000001',
-        ));
-       dd($result);
-        /*$order = Order::query()->where("code","SO210511005663")->first();
-        $ser = new OrderService();
-        $ser->createInstantBill($order);
-        dd();*/
-        $store = Store::query()->find(173382);dd($store->load("storeItems.commodity"));
-        $ser = new StoreService();
-        $ser->createInstantBill($store);
-        dd($store);
+        StationTask::destroy([1278,1279,1280,1282,1283]);
+        StationTaskMaterialBox::destroy([18405,18406,18407,18409,18410]);
+        dd("OK");
+        $s = Station::query()->select("id")->where("parent_id",6)->whereNotIn("code",[
+            "HAIB1-01-01","HAIB1-03-01","HAIB1-03-03"
+        ]);
+        dd($s->get());
+        $t = StationTask::query()->select("id")->where("status",'待处理')
+            ->whereIn("station_id",$s);
+        StationTask::query()->where("status",'待处理')
+            ->whereIn("station_id",$s)->update(["status"=>"完成"]);
+        StationTaskMaterialBox::query()->whereIn("station_task_id",$t)->update(["status"=>"完成"]);
+        dd("OK");
     }
     public function orderCreateBill()
     {
@@ -196,7 +175,7 @@ class TestController extends Controller
                 "type" => null,
                 "wms_type" => "09.[BAOSHI]\u622a\u5355\u6ce2\u6b21\u3010\u65e0\u5907\u6ce8\u3011",
                 "wms_status" => "\u90e8\u5206\u6536\u8d27",
-                "wms_created_at" => "0000-00-00 00=>00=>00",
+                "wms_created_at" => "0000-00-00 00=>00 =>00",
                 "created_at" => "2021-03-12T09=>10=>44.000000Z",
                 "updated_at" => "2021-03-12T09=>10=>44.000000Z",
                 "remark" => null,
@@ -1506,4 +1485,29 @@ TEXT;
             ]);
         }
     }
+
+    public function testPrint(Request $request)
+    {
+        return (new PrintPartController())->print($request);
+    }
+
+    public function testSendCon(Request $request)
+    {
+        $content = [
+            "type" => "getClients",
+            "aliasName" => "test",
+            "printerName" => "打印机5",
+        ];
+        $post = Http::post("http://127.0.0.1:3000", $content);
+        $body = json_decode($post->body(),true);
+        $body['msg'] = json_decode($body['msg'],true);
+        dd(json_decode($post->body()),$post->body(),$body);
+    }
+
+
+    public function zop_test(Request $request)
+    {
+        $logistic_number = $request->logistic_number;
+        \App\Jobs\LogisticZopSync::dispatchNow($logistic_number);
+    }
 }

+ 14 - 8
app/Http/Controllers/WaveController.php

@@ -13,6 +13,7 @@ use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
+use Oursdreams\Export\Export;
 
 class WaveController extends Controller
 {
@@ -71,14 +72,19 @@ class WaveController extends Controller
 
     public function exportExcelOnParams(Request $request){
         $sql = app("WaveService")->getSql($request);
-        $post = Http::post(config('go.export.url'),['type'=>'orderWave','sql'=>$sql]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=波次记录-".date('ymdHis').'.xlsx',
-        ]);
+        $e = new Export();
+        $e->setOracleConnection(config('database.connections.oracle.host'),
+            config('database.connections.oracle.port'),config('database.connections.oracle.database')
+            ,config('database.connections.oracle.username'),config('database.connections.oracle.password'));
+        $e->setFileName("波次记录");
+        return $e->sql($sql,[
+            "WAVENO"=>"波次号","CODENAME_C"=>"波次状态",
+            "WAVERULE"=>"波次规则","DESCR"=>"波次描述",
+            "DESCR_C"=>"承运人","ADDWHO"=>"操作员",
+            "ADDTIME"=>"创建时间","pickerPrint"=>"拣货单打印人",
+            "pickerPrintTime"=>"拣货单打印时间","expressPrinting"=>"快递单号打印人",
+            "expressPrintTime"=>"快递单号打印时间"
+        ])->direct();
     }
     public function repairBatch()
     {

+ 85 - 68
app/Http/Controllers/WaybillController.php

@@ -7,7 +7,6 @@ use App\CarType;
 use App\Components\AsyncResponse;
 use App\Region;
 use App\Services\CarTypeService;
-use App\Services\common\ExportService;
 use App\Services\LogisticService;
 use App\Services\OwnerService;
 use App\Services\UnitService;
@@ -24,7 +23,6 @@ use App\WaybillPayoff;
 use App\WaybillFinancialExcepted;
 use App\WaybillFinancialSnapshot;
 use Carbon\Carbon;
-use Exception;
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Collection;
 use Illuminate\Database\Eloquent\Model;
@@ -32,10 +30,10 @@ use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Gate;
-use Illuminate\Support\Facades\Http;
 use Illuminate\Support\Facades\Storage;
 use Illuminate\Support\Facades\Validator;
 use Intervention\Image\Facades\Image;
+use Oursdreams\Export\Export;
 use Ramsey\Uuid\Uuid;
 
 class WaybillController extends Controller
@@ -166,6 +164,11 @@ class WaybillController extends Controller
             $waybillPayoffService->updateOrCreate($waybillPayoffParam);
         }
         app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
+        WaybillAuditLog::query()->create([
+            'waybill_id'=>$id,
+            'audit_stage'=>'发起调度',
+            'user_id'=>Auth::id(),
+        ]);
         return redirect('transport/waybill/index')->with('successTip','运单“'.$waybill->waybill_number.'”调度成功');
     }
 
@@ -487,51 +490,47 @@ class WaybillController extends Controller
     }
 
     public function upload(Request $request){
-        if(!Gate::allows('运输管理-运单-图片上传')){ return '没有权限';  }
-        $file=$request->file('file');
-        $waybill_number=$request->input('waybill_number');
-        $waybill=Waybill::query()->where('waybill_number',$waybill_number)->first();
-        if (!$waybill){
-            return ['success'=>false,'error'=>"未找到该运单!"];
-        }
-        if ($waybill->upload_file_url){
-            return ['success'=>false,'error'=>"该运单已存在照片!"];
-        }
-        if (!$file){
-            return ['success'=>false,'error'=>"照片不得为空!"];
-        }
-        if (!$file->isValid()){
-            return ['success'=>false,'error'=>"找不到照片!"];
-        }
-        $tmpFile = $file->getRealPath();
-        if (! is_uploaded_file($tmpFile)) {
-            return ['success'=>false,'error'=>"文件错误!"];
-        }
-        $fileExtension=$file->getClientOriginalExtension();
-        // 5.存储, 生成一个随机文件名
-        $fileName = date('ymd').'-'.Uuid::uuid1();//thumbnail common bulky
-        $thumbnailName=storage_path('app/public/files/'.$fileName.'-thumbnail.'.$fileExtension);
-        $commonName=storage_path('app/public/files/'.$fileName.'-common.'.$fileExtension);
-        $bulkyName=storage_path('app/public/files/'.$fileName.'-bulky.'.$fileExtension);
-        $result=move_uploaded_file ($tmpFile ,$bulkyName);
-        if ($result){
-            $img=Image::make($bulkyName);
-            if ($img->height() > $img->width())
-                $img->heighten(250)->save($commonName);
-            else $img->widen(250)->save($commonName);
-            $img->heighten(28)->save($thumbnailName);
-            $uploadFile=new UploadFile([
-                "table_name"=>"waybills",
-                "table_id"=>$waybill->id,
-                "url"=>'/files/'.$fileName,
-                "type"=>$fileExtension,
-            ]);
-            if ($uploadFile->save())
-                app('LogService')->log(__METHOD__,'图片上传',json_encode($request),Auth::user()['id']);
-            $uploadFile->url=asset('/storage'.$uploadFile->url);
-            return ['success'=>true,'data'=>$uploadFile];
+        $this->gate("运输管理-运单-图片上传");
+        $files=$request->file("files");
+        if (!$files)$this->error("未传递照片");
+        $id=$request->input('id');
+        $waybill=Waybill::query()->find($id);
+        if (!$waybill)$this->error("未找到该运单!");
+        $res = [];
+        foreach ($files as $file){
+            if (!$file->isValid()){
+                return ['success'=>false,'error'=>"找不到照片!"];
+            }
+            $tmpFile = $file->getRealPath();
+            if (! is_uploaded_file($tmpFile)) {
+                return ['success'=>false,'error'=>"文件错误!"];
+            }
+            $fileExtension=$file->getClientOriginalExtension();
+            // 5.存储, 生成一个随机文件名
+            $fileName = date('ymd').'-'.Uuid::uuid1();//thumbnail common bulky
+            $thumbnailName=storage_path('app/public/files/'.$fileName.'-thumbnail.'.$fileExtension);
+            $commonName=storage_path('app/public/files/'.$fileName.'-common.'.$fileExtension);
+            $bulkyName=storage_path('app/public/files/'.$fileName.'-bulky.'.$fileExtension);
+            $result=move_uploaded_file ($tmpFile ,$bulkyName);
+            if ($result){
+                $img=Image::make($bulkyName);
+                if ($img->height() > $img->width())
+                    $img->heighten(250)->save($commonName);
+                else $img->widen(250)->save($commonName);
+                $img->heighten(28)->save($thumbnailName);
+                /** @var UploadFile|\stdClass $uploadFile */
+                $uploadFile=new UploadFile([
+                    "table_name"=>"waybills",
+                    "table_id"=>$waybill->id,
+                    "url"=>'/files/'.$fileName,
+                    "type"=>$fileExtension,
+                ]);
+                if ($uploadFile->save())
+                    app('LogService')->log(__CLASS__,'运输图片上传',json_encode($request),Auth::user()['id']);
+                $res[] = $uploadFile;
+            }else $this->error("图片存储失败,检查服务器状态");
         }
-        return ['success'=>false,'error'=>"图片保存失败!"];
+        $this->success($res);
     }
 
     //批量上传图片
@@ -560,9 +559,9 @@ class WaybillController extends Controller
             $number[] = $num;
             $mapping[$num] = $index;
         }
-        $waybills = Waybill::query()->select("id","source_bill")->doesntHave("uploadFile")->whereIn('source_bill',$number)->get();
+        $waybills = Waybill::query()->select("id","source_bill")->whereIn('source_bill',$number)->get();
         foreach (array_diff($number,array_column($waybills->toArray(),"source_bill")) as $diff){
-            $errors[] = "“".$diff."”不存在运单或已存在照片";
+            $errors[] = "“".$diff."”不存在运单";
             unset($images[$mapping[$diff]]);
         }
         $insert = [];
@@ -592,16 +591,17 @@ class WaybillController extends Controller
             ];
         }
         if ($insert)UploadFile::query()->insert($insert);
-        $waybills->load("uploadFile");
+        $waybills->load("uploadFiles");
         $this->success(["errors"=>$errors,"data"=>$waybills]);
     }
 
     //删除照片
     public function deleteImg(Request $request){
-        if(!Gate::allows('运输管理-运单-图片删除')){ return '没有权限';  }
-        $ids=$request->input('ids');
-        $uploadFiles=UploadFile::where('table_name','waybills')->whereIn('table_id',$ids)->get();
-        foreach ($uploadFiles as $uploadFile){
+        $this->gate("运输管理-运单-图片删除");
+        $query=UploadFile::query()->where('table_name','waybills');
+        if ($request->input("url"))$query = $query->where('table_id',$request->input("id"))->where("url",$request->input("url"));
+        else $query = $query->whereIn('table_id',$request->input("id"));
+        foreach ($query->get() as $uploadFile){
             $bulky=storage_path('app/public/'.$uploadFile->url.'-bulky.'.$uploadFile->type);
             $common=storage_path('app/public/'.$uploadFile->url.'-common.'.$uploadFile->type);
             $thumbnail=storage_path('app/public/'.$uploadFile->url.'-thumbnail.'.$uploadFile->type);
@@ -609,9 +609,9 @@ class WaybillController extends Controller
                 unlink($bulky);unlink($common);unlink($thumbnail);
             }
         }
-        UploadFile::where('table_name','waybills')->whereIn('table_id',$ids)->delete();
+        $query->delete();
         app('LogService')->log(__METHOD__,'图片删除',json_encode($request),Auth::user()['id']);
-        return ['success'=>true];
+        $this->success();
     }
 
     public function export(){
@@ -623,7 +623,7 @@ class WaybillController extends Controller
         /** @var Collection $waybills */
         $row = [
             "运单类型", "货主", "上游单号", "wms订单号", "运单号", "运输收费",
-            "其他收费", "其他收费备注", "始发地", "目的地", "承运商", "承运商单号",
+            "其他收费", "其他收费备注", "始发地", "目的地","下单备注", "承运商", "承运商单号",
             "仓库计抛", "承运商计抛", "仓库计重", "承运商计重", "车型", "车辆信息",
             "计件", "里程数", "运费(元)", "提货费(元)", "其他费用(元)", "发货时间",
             "调度备注", "创建时间"
@@ -641,6 +641,7 @@ class WaybillController extends Controller
                 $waybill->other_charge_remark,
                 $waybill->origination,
                 $waybill->order->address ?? $waybill->destination,
+                $waybill->ordering_remark,
                 $waybill->logistic->name ?? "",
                 $waybill->carrier_bill,
                 $waybill->warehouse_weight,
@@ -659,7 +660,7 @@ class WaybillController extends Controller
                 $waybill->created_at,
             ];
         });
-        return app(ExportService::class)->json($row,$list,"运输记录单");
+        return Export::make($row,$list,"运输记录单");
     }
 
     public function deliveringExport(Request $request){
@@ -670,14 +671,20 @@ class WaybillController extends Controller
         }else{
             $sql = app('waybillService')->getDeliveringSql(['id'=>$request->data]);
         }
-        $post = Http::post(config('go.export.url'),['type'=>'waybillDelivering','sql'=>$sql]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=发运列表-".date('ymdHis').'.xlsx',
-        ]);
+        $e = new Export();
+        $e->setMysqlConnection(config('database.connections.mysql.host'),
+            config('database.connections.mysql.port'),config('database.connections.mysql.database')
+            ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
+        $e->setFileName("发运报表");
+        return $e->sql($sql,[
+            "created_at"=>"日期","carrier_name"=>"承运商",
+            "waybill_number"=>"宝时运单号","origination"=>"提货仓",
+            "owner_name"=>"货主","warehouse_weight_other"=>"预估重量",
+            "warehouse_weight"=>"预估体积","status"=>"状态",
+            "carrier_bill"=>"专线运单号","inquire_tel"=>"查件电话",
+            "amount"=>"件数","carrier_weight_other"=>"重量",
+            "carrier_weight"=>"体积"
+        ])->direct();
     }
 
     //发运
@@ -761,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',
@@ -824,6 +831,11 @@ class WaybillController extends Controller
         if(!GAte::allows('运输管理-运单-删除')){return['success'=>0,'status'=>'没有权限'];}
         if(is_null($id)){return ['success'=>'0','status'=>'传入id为空'];}
         $result =  Waybill::where('id',$id)->delete();
+        WaybillAuditLog::query()->create([
+            'waybill_id'=>$id,
+            'audit_stage'=>'删除运单',
+            'user_id'=>Auth::id(),
+        ]);
         return ['success'=>$result,'status'=>$result];
     }
 
@@ -853,6 +865,11 @@ class WaybillController extends Controller
             $waybill->restore();
         });
         app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
+        foreach ($ids as $id) WaybillAuditLog::query()->create([
+            'waybill_id'=>$id,
+            'audit_stage'=>'恢复运单',
+            'user_id'=>Auth::id(),
+        ]);
         return ['success'=>'true','waybills'=>$waybills];
     }
     // 修改运费
@@ -947,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];
     }

+ 23 - 8
app/Http/Controllers/WaybillFinancialSnapshotsController.php

@@ -51,13 +51,28 @@ class WaybillFinancialSnapshotsController extends Controller
         }else{
             $sql = app('WaybillFinancialService')->getSql(['waybill_id'=>$request->data]);
         }
-        $post = Http::post(config('go.export.url'),['type'=>'waybillFinancial','sql'=>$sql]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=财务报表-".date('ymdHis').'.xlsx',
-        ]);
+        $e = new \Oursdreams\Export\Export();
+        $e->setMysqlConnection(config('database.connections.mysql.host'),
+            config('database.connections.mysql.port'),config('database.connections.mysql.database')
+            ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
+        $e->setFileName("财务报表");
+        return $e->sql($sql,[
+            "type"=>"运单类型","waybill_number"=>"运单号",
+            "owner_name"=>"货主","wms_bill_number"=>"WMS单号",
+            "origination"=>"始发地","destination"=>"目的地",
+            "recipient"=>"收件人","recipient_mobile"=>"收件人电话",
+            "charge"=>"收费(元)","ordering_remark"=>"下单备注",
+            "carrier"=>"承运商","carrier_bill"=>"承运商单号",
+            "origination_city"=>"始发市","destination_city"=>"目的市",
+            "warehouse_weight"=>"仓库计数(抛)","warehouse_weight_other"=>"仓库计数二",
+            "carrier_weight"=>"承运商计数(抛)","carrier_weight_other"=>"承运商计数二",
+            "car_type_name"=>"车型","car_owner_info"=>"车辆信息",
+            "fee"=>"运费(元)","pick_up_fee"=>"提货费(元)",
+            "other_fee"=>"其他费用(元)","collect_fee"=>"到付金额(元)",
+            "dispatch_remark"=>"调度备注","auditLog_user_name"=>"终审人员",
+            "created_at"=>"运单创建时间","total_receivable"=>"应收款(元)",
+            "total_expense"=>"应付款(元)","gross_margin"=>"毛利(元)",
+            "gross_profit_rate"=>"毛利率","snapshotCreated_at"=>"报表生成时间",
+        ])->direct();
     }
 }

+ 22 - 30
app/Http/Controllers/WeighController.php

@@ -2,6 +2,7 @@
 
 namespace App\Http\Controllers;
 
+use App\MeasuringMachine;
 use App\OrderPackage;
 use App\PaperBox;
 use App\Services\OrderPackageService;
@@ -9,12 +10,11 @@ use App\Services\OwnerService;
 use App\Services\PackageService;
 use App\Services\PackageStatisticsService;
 use Carbon\Carbon;
-use Exception;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\Gate;
-use Illuminate\Support\Facades\Http;
 use Illuminate\Support\Facades\Validator;
+use Oursdreams\Export\Export;
 
 
 class WeighController extends Controller
@@ -26,7 +26,8 @@ class WeighController extends Controller
         /** @var PackageService $application */
         $application = app('PackageService');
         $packages = $application->paginate($request);
-        return view('package.weigh.index',['packages'=>$packages,'owners'=>$ownerService->getIntersectPermitting(),'paginateParams'=>$paginateParams]);
+        $measuringMachines = MeasuringMachine::query()->get();
+        return view('package.weigh.index',['packages'=>$packages,"measuringMachines"=>$measuringMachines,'owners'=>$ownerService->getIntersectPermitting(),'paginateParams'=>$paginateParams]);
     }
 
     public function create()
@@ -144,12 +145,10 @@ class WeighController extends Controller
 
     public function statistics(Request $request){
         $packages = app('PackageStatisticsService')->get($request->input());
-        $owners=app('OwnerService')->getIntersectPermitting();
+        $owners=app('OwnerService')->get([],null,false);
         $logistics=app('LogisticService')->getSelection();
         $ownerTemp = [];
-        foreach ($owners as $owner){
-            $ownerTemp[$owner->id] = $owner->name;
-        }
+        foreach ($owners as $owner)$ownerTemp[$owner->id] = $owner->name;
         $ps = [];
         $logisticsTemp = [];
         foreach ($packages as $package){
@@ -162,7 +161,7 @@ class WeighController extends Controller
                     $package->logistic_id => $package->count,
                     "sum" => (int)$package->count,
                     "owner_id" => $package->owner_id,
-                    "owner_name" => $ownerTemp[$package->owner_id]
+                    "owner_name" => $ownerTemp[$package->owner_id] ?? '未知',
                 ];
             }
         }
@@ -184,20 +183,20 @@ class WeighController extends Controller
         }else{
             $sql=app('PackageService')->getSql(['id'=>$request->data]);
         }
-        $row = ["货主","快递单号","波次号","订单号","物流公司","设备","重(KG)","长(mm)","宽(mm)","高(mm)","体积(mm³)","纸箱","状态","波次规则","称重时间","收件人","收件人电话"];
-        $column = ["owner_name", "logistic_number", "batch_number", "order_code", "logistic_name","measuring_machine_name",
-            "weight", "length", "width", "height", "bulk", "paper_box_name", "status","batch_rule","weighed_at","order_consignee_name","order_consignee_phone"];
-        $rule = ["weighed_at"=> "mysqlDate"];
-        $post = Http::post(config('go.export.url'),['type'=>'unify','sql'=>$sql, 'connection'=>'mysql',
-            'row'=>json_encode($row,JSON_UNESCAPED_UNICODE), 'column'=>json_encode($column), 'rule'=>json_encode($rule)]);
-
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=包裹信息-".date('ymdHis').'.xlsx',
-        ]);
+        $e = new Export();
+        $e->setMysqlConnection(config('database.connections.mysql.host'),
+            config('database.connections.mysql.port'),config('database.connections.mysql.database')
+            ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
+        $e->setFileName("财务报表");
+        return $e->sql($sql,[
+            "owner_name"=>"货主", "logistic_number"=>"快递单号",
+            "batch_number"=>"波次号", "order_code"=>"订单号", "logistic_name"=>"物流公司",
+            "measuring_machine_name"=>"设备",
+            "weight"=>"重(KG)", "length"=>"长(cm)", "width"=>"宽(cm)", "height"=>"高(cm)",
+            "bulk"=>"体积(cm³)", "paper_box_name"=>"纸箱", "status"=>"状态","batch_rule"=>"波次规则",
+            "weighed_at"=>"称重时间",
+            "order_consignee_name"=>"收件人","order_consignee_phone"=>"收件人电话"
+        ])->direct();
     }
     protected function validator(Request $request){
         $validator=Validator::make($request->input(),[
@@ -282,14 +281,7 @@ class WeighController extends Controller
             }
             $list[] = $row;
         }
-        $post = Http::post(config('go.export.url'),['type'=>'base','data'=>json_encode(["row"=>$column,"list"=>$list],JSON_UNESCAPED_UNICODE)]);
-        if ($post->status() == 500){
-            throw new Exception($post->header("Msg"));
-        }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=称重统计信息单-".date('ymdHis').'.xlsx',
-        ]);
+        return Export::make($column,$list,"称重统计单");
     }
 
 }

+ 21 - 16
app/Http/Controllers/WeighExceptedController.php

@@ -8,6 +8,7 @@ use Exception;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
+use Oursdreams\Export\Export;
 
 class WeighExceptedController extends Controller
 {
@@ -33,34 +34,38 @@ class WeighExceptedController extends Controller
 
    public function export($type ,Request $request){
        if(!Gate::allows('称重管理-查看异常')){ return redirect(url('/'));  }
+       $e = new Export();
+       $e->setMysqlConnection(config('database.connections.mysql.host'),
+           config('database.connections.mysql.port'),config('database.connections.mysql.database')
+           ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
        if ($type == 'indexIssued'){
+           $e->setFileName("称重异常记录单");
            if ($request->checkAllSign){
                $params = $request->input();
                unset($params['checkAllSign']);
                $sql = app('WeighExceptedService')->getIssuedExceptionSql($params);
            }else $sql=app('WeighExceptedService')->getIssuedExceptionSql(['id'=>$request->data]);
-           $post = Http::post(config('go.export.url'),['type'=>'packageIssuedException','sql'=>$sql]);
-           if ($post->status() == 500){
-               throw new Exception($post->header("Msg"));
-           }
-           return response($post,200, [
-               "Content-type"=>"application/octet-stream",
-               "Content-Disposition"=>"attachment; filename=下发异常记录-".date('ymdHis').'.xlsx',
-           ]);
+           $mapping = [
+               "logistic_number"=>"快递单号","logistic_name"=>"承运商",
+               "measuring_machine_name"=>"设备","weigh_time"=>"称重时间",
+               "weight"=>"重(KG)","length"=>"长(CM)",
+               "width"=>"宽(CM)","height"=>"高(CM)","bulk"=>"体积(CM³)",
+               "paper_box_name"=>"纸箱","status"=>"异常类型"
+           ];
        }else{
+           $e->setFileName("下发异常记录单");
            if ($request->checkAllSign){
                $params = $request->input();
                unset($params['checkAllSign']);
                $sql = app('WeighExceptedService')->getCreateExceptionSql($params);
            }else $sql=app('WeighExceptedService')->getCreateExceptionSql(['id'=>$request->data]);
-           $post = Http::post(config('go.export.url'),['type'=>'packageCreateException','sql'=>$sql]);
-           if ($post->status() == 500){
-               throw new Exception($post->header("Msg"));
-           }
-           return response($post,200, [
-               "Content-type"=>"application/octet-stream",
-               "Content-Disposition"=>"attachment; filename=录入异常记录-".date('ymdHis').'.xlsx',
-           ]);
+           $mapping = [
+               "logistic_number"=>"快递单号","created_at"=>"下发时间",
+               "delivery_number"=>"发货单号","batch_number"=>"波次号",
+               "batch_rule"=>"波次规则","recipient"=>"收件人",
+               "recipient_mobile"=>"收件人电话","logistic_name"=>"承运商","status"=>"异常类型"
+           ];
        }
+       return $e->sql($sql,$mapping)->direct();
    }
 }

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

@@ -322,11 +322,24 @@ class StorageController
         }
         $response = Http::post(config('api.haiq.storage.moveBin'),$post);
         $responseBody = $response->body();
+        $result = ['status'=>'失败'];
         LogService::log(__CLASS__,__METHOD__,$responseBody);
-        $responseBody = strstr($responseBody,'200')?'请求出库料箱"'.implode(',',$codes).'"成功':$responseBody;
+        if(strstr($responseBody,'200')){
+            $responseJson=json_decode($responseBody,true);
+            $result = ['status'=>'成功'];
+            $responseBody = '取料箱成功:' . implode(',', $codes);
+            $data0part = $responseJson['data'][0]??[];
+            if(($data0part['code']??'')==10007
+                && count($data0part['datas']??[])>0){
+                $responseBody = '以下料箱不在库内,无法取出:' . implode(',', $data0part['datas']??[]).
+                '| 成功取出料箱:'.implode(',', array_diff($codes, $data0part['datas']??[]));
+                $result = ['status'=>'部分成功'];
+            }
+        }
         if(strstr($responseBody,'成功')){
             MaterialBox::query()->whereIn('code',$codes)->update(['status'=>'在出库中']);
         }
-        return ['result'=> $responseBody];
+        $result['result']=$responseBody;
+        return $result;
     }
 }

+ 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;
+    }
+}

+ 4 - 1
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,7 +44,6 @@ class LogisticSFSync implements ShouldQueue
      */
     public function handle()
     {
-        ini_set('max_execution_time', 60);
         LogService::log(LogisticSFSync::class, "{$this->logistic_number}-JOB-SF", '');
         $this->logisticSFService = app('LogisticSFService');
         $formedData = $this->logisticSFService->get([$this->logistic_number]);

+ 4 - 1
app/Jobs/LogisticYDSync.php

@@ -13,6 +13,10 @@ use Illuminate\Queue\SerializesModels;
 
 class LogisticYDSync implements ShouldQueue
 {
+    public $tries = 2;
+
+    public $timeout = 10;
+
     use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
     /**
      * @var $logisticYDService LogisticYDService
@@ -43,7 +47,6 @@ class LogisticYDSync implements ShouldQueue
      */
     public function handle()
     {
-        ini_set('max_execution_time', 60);
         LogService::log(LogisticYDSync::class, "{$this->logistic_number}-JOB-YD", '');
         $this->logisticYDService = app('LogisticYDService');
         //先订阅订单

+ 5 - 1
app/Jobs/LogisticYTOSync.php

@@ -14,7 +14,12 @@ 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
@@ -43,7 +48,6 @@ class LogisticYTOSync implements ShouldQueue
      */
     public function handle()
     {
-        ini_set('max_execution_time', 60);
         LogService::log(LogisticYTOSync::class, "{$this->logistic_number}-JOB-YTO", '');
         $this->logisticYTOService = app('LogisticYTOService');
         $nativeResponse = $this->logisticYTOService->query($this->logistic_number);

+ 23 - 150
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');
     }
 
     /**
@@ -39,150 +52,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->order_package_received_sync_service->update([$formatted_data]);
     }
 }

+ 31 - 0
app/Jobs/ResetInstantBill.php

@@ -8,12 +8,14 @@ use App\OwnerFeeDetail;
 use App\OwnerFeeDetailLogistic;
 use App\Process;
 use App\Province;
+use App\RejectedBill;
 use App\Services\CacheService;
 use App\Services\OwnerPriceDirectLogisticService;
 use App\Services\OwnerPriceExpressService;
 use App\Services\OwnerPriceLogisticService;
 use App\Services\OwnerPriceOperationService;
 use App\Store;
+use App\StoreRejected;
 use App\Waybill;
 use Illuminate\Bus\Queueable;
 use Illuminate\Contracts\Queue\ShouldQueue;
@@ -191,6 +193,35 @@ class ResetInstantBill implements ShouldQueue
                     "work_tax_fee" => $taxFee
                 ]);
                 break;
+            case "rejected_bills":
+                $rejectedBill = RejectedBill::query()->find($this->detail->outer_id);
+                /** @var \stdClass $rejectedBill */
+                $number = array_column(StoreRejected::query()->where("logistic_number_return",$rejectedBill->logistic_number_return)->get()->toArray(),"store_id");
+
+                foreach (Store::query()->with("storeItems")->whereIn("id",$number)->get() as $store){
+                    /** @var OwnerPriceOperationService $service */
+                    $service = app("OwnerPriceOperationService");
+                    list($id,$money,$taxFee) = $service->matching($store, Feature::MAPPING["store"], $store->owner_id, "入库",0);
+                    $bill = OwnerFeeDetail::query()->where("outer_id",$store->id)->where("outer_table_name","stores")->first();
+                    if ($bill) $bill->update([
+                        "work_fee" => $money,
+                        "owner_price_operation_id" => $id,
+                        "outer_id" => $rejectedBill->id,
+                        "outer_table_name" => "rejected_bills",
+                    ]); else app("OwnerFeeDetailService")->create([
+                        "owner_id" => $store->owner_id,
+                        "worked_at" => $store->created_at,
+                        "type" => "收货",
+                        "operation_bill" => $store->asn_code,
+                        "commodity_amount" => array_sum(array_column($store->storeItems->toArray(), "amount")),
+                        "work_fee" => $money,
+                        "owner_price_operation_id" => $id,
+                        "created_at" => date('Y-m-d H:i:s'),
+                        "outer_id" => $rejectedBill->id,
+                        "outer_table_name" => "rejected_bills",
+                        "work_tax_fee" => $taxFee,
+                    ]);
+                }
         }
     }
 }

+ 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));
     }
 }

+ 5 - 0
app/MaterialBox.php

@@ -43,4 +43,9 @@ class MaterialBox extends Model
         if(!$value)return 0;
         $this->attributes['status']=self::$enums['status'][$value];
     }
+
+    public function stationTaskMaterialBoxes()
+    {   //料箱任务
+        return $this->hasMany(StationTaskMaterialBox::class,"material_box_id","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)
+    {
+        //
+    }
+}

+ 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);
+    }
 }

+ 1 - 0
app/OwnerFeeDetail.php

@@ -33,6 +33,7 @@ class OwnerFeeDetail extends Model
         "work_tax_fee",     //作业税费
         "logistic_tax_fee", //物流税费
         "province",         //省份
+        "owner_price_operation_id" //引用的作业模型
     ];
     public $timestamps = false;
 

+ 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;
+	    // }
+	}
+}

+ 15 - 0
app/PrintPart.php

@@ -0,0 +1,15 @@
+<?php
+
+namespace App;
+
+use Illuminate\Database\Eloquent\Model;
+
+use App\Traits\ModelLogChanging;
+
+class PrintPart extends Model
+{
+    use ModelLogChanging;
+
+    //
+    protected $fillable = ['name','value'];
+}

+ 14 - 0
app/PrintTemplate.php

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

+ 160 - 85
app/Providers/AppServiceProvider.php

@@ -3,6 +3,10 @@
 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\Services\AuthorityService;
 use App\Services\BatchService;
 use App\Services\CacheService;
@@ -26,6 +30,7 @@ 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\OracleBasCustomerService;
@@ -43,6 +48,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,7 +110,11 @@ use App\Services\UserWorkgroupService;
 use App\Services\DischargeTaskService;
 use App\Services\DeliveryAppointmentService;
 use App\Services\StationCacheShelfGridService;
+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;
@@ -116,6 +126,7 @@ use App\Services\OrderPackageCommoditySerialNumberService;
 use App\Services\OrderPackageExceptionTypeCountingRecordService;
 use App\Services\LogisticYDService;
 use App\Services\ForeignZhenCangService;
+use App\Services\StorageService;
 
 class AppServiceProvider extends ServiceProvider
 {
@@ -139,7 +150,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) {
@@ -156,6 +173,19 @@ 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(){
@@ -184,91 +214,136 @@ 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('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('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('LogisticZopService', LogisticZopService::class);
+        app()->singleton('InventoryAccountMissionService', InventoryAccountMissionService::class);
+        app()->singleton('InventoryCompareService', InventoryCompareService::class);
+        app()->singleton('InventoryDailyLogService', InventoryDailyLogService::class);
+        app()->singleton('LaborReportsCountingRecordService', LaborReportsCountingRecordService::class);
+        app()->singleton('OrderPackageReceivedSyncRecordService', OrderPackageReceivedSyncRecordService::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('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('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);
     }
 
+    /**
+     * 快递同步接口 同步情况统计
+     */
+    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,
 

+ 13 - 3
app/Services/BatchService.php

@@ -10,6 +10,7 @@ use App\OracleActAllocationDetails;
 use App\Order;
 use App\OrderCommodity;
 use App\Owner;
+use App\Station;
 use Exception;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Cache;
@@ -74,6 +75,7 @@ class BatchService
             $this->instant($this->stationTaskMaterialBoxService,'StationTaskMaterialBoxService');
 
             $stationTaskBatches=null;
+            $stationTasks=null;
             $batches_shouldProcess = $this->stationRuleBatchService->getBatches_shouldProcess($batches); //按规则过滤需要的波次
             if($batches_shouldProcess->isEmpty()) return;
             $stationTaskMaterialBoxes_occupied = $this->stationTaskMaterialBoxService->getOccupied_byBatches($batches_shouldProcess); //按规则过滤需要的波次
@@ -85,14 +87,22 @@ class BatchService
                     ->delay(now()->addMinutes(1));    //因为料箱被占用了,所以将任务推迟1分钟后尝试
                 return;
             }
-            DB::transaction(function ()use($batches,&$stationTaskBatches,&$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); //注册商品任务
             });
-
-//            broadcast(new BroadcastToStation(BroadcastToStation::ALL_STATION, $json));
+            foreach ($stationTasks as &$stationTask){
+                $stationTask->loadMissing([
+                    "stationTaskCommodities.commodity.barcodes",
+                    "stationTaskCommodities.materialBox",
+                    "stationTaskBatches.batch.owner",
+                    "stationTaskMaterialBoxes.materialBox",
+                ]);
+            }
+            $jsonStationTasks=json_encode($stationTasks);
+            broadcast(new BroadcastToStation(BroadcastToStation::ALL_STATION, $jsonStationTasks));
 //            $ran=$this->stationTaskBatchService->runMany($stationTaskBatches);//执行波次任务
         }catch(Exception $e){
             $batchesJson='';

+ 27 - 0
app/Services/DeliveryAppointmentService.php

@@ -7,6 +7,7 @@ use App\DeliveryAppointmentDetail;
 use App\Services\common\QueryService;
 use App\Traits\ServiceAppAop;
 use App\DeliveryAppointment;
+use App\Warehouse;
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Support\Facades\Auth;
 use phpDocumentor\Reflection\Types\Integer;
@@ -171,4 +172,30 @@ class DeliveryAppointmentService
         }])->find($id);
         if ($delivery->cars_count == 0)$delivery->update(["status"=>2]);
     }
+
+    /**
+     * 获取指定时段可用产能
+     *
+     * @param string $date
+     * @param int $period
+     * @param integer $warehouseId
+     *
+     * @return double
+     */
+    public function getAvailableCapacity($date,$period,$warehouseId)
+    {
+        $result = DeliveryAppointment::query()->selectRaw("appointment_date,date_period,SUM(capacity) AS capacity")
+            ->where("appointment_date",$date)
+            ->where("date_period",$period)
+            ->where("warehouse_id",$warehouseId)
+            ->where("status",0)
+            ->groupBy(["appointment_date","date_period"])
+            ->lockForUpdate()->first();
+        if (!$result)return 0;
+        /** @var \stdClass $warehouse */
+        $warehouse = Warehouse::query()->find($warehouseId);
+        if (!$warehouse)return 0;
+        $total = $warehouse->production_capacity*DeliveryAppointment::HOUR[$period];
+        return $total-$result->capacity;
+    }
 }

+ 94 - 14
app/Services/ForeignHaiRoboticsService.php

@@ -5,8 +5,11 @@ namespace App\Services;
 
 
 use App\Exceptions\ErrorException;
+use App\Exceptions\Exception;
 use App\MaterialBox;
+use App\Station;
 use App\StationCacheShelfGrid;
+use App\StationTask;
 use App\StationTaskMaterialBox;
 use Carbon\Carbon;
 use Illuminate\Support\Collection;
@@ -61,16 +64,7 @@ class ForeignHaiRoboticsService
     ): array
     {
         $timestampSuffix = microtime(true);
-        $taskMode=(function()use($modeName){
-            switch ($modeName){
-                case '输送线入立架': return 1;
-                case '立架出至输送线': return 2;
-                case '移动立架内位置': return 3;
-                case '缓存架入立架':
-                case '立架出至缓存架': return 6;
-                default: throw new \Exception('发至海柔的移料箱请求,模式不存在');
-            }
-        })();
+        $taskMode=$this->getTaskMode($modeName);
         $bins=$taskMaterialBoxes->map(function (StationTaskMaterialBox $taskMaterialBox)use($timestampSuffix,$fromLocation,$toLocation){
             return [
                 "taskCode"  =>$taskMaterialBox['id'].'_'.$timestampSuffix,
@@ -88,10 +82,50 @@ class ForeignHaiRoboticsService
         ]];
     }
 
+    private function makeJson_move_multi(
+        Collection $taskMaterialBoxes,
+        string $modeName,
+        string $fromLocation='',
+        Collection $toLocations=null,
+        $groupId=''
+        , $priority=10
+        , $isSequenced=1
+    ): array
+    {
+        if(!$toLocations||($toLocations->count()!=$taskMaterialBoxes->count()))throw new Exception('toLocation中的元素数量必须和料箱任务一致');
+        $timestampSuffix = microtime(true);
+        $taskMode=$this->getTaskMode($modeName);
+        $bins=$taskMaterialBoxes->map(function (StationTaskMaterialBox $taskMaterialBox,$i)use($timestampSuffix,$fromLocation,$toLocations){
+            return [
+                "taskCode"  =>$taskMaterialBox['id'].'_'.$timestampSuffix,
+                "binCode"   => $taskMaterialBox['materialBox']['code'],
+                "fromLocCode" => $fromLocation??'',
+                "toLocCode" => $toLocations[$i],
+            ];
+        });
+        return [[
+            "taskMode"  =>$taskMode,
+            "bins"=>$bins,
+            "groupCode"=>$groupId.'_'.$timestampSuffix,
+            "priority"=>$priority,
+            "sequenceFlag"=>$isSequenced,
+        ]];
+    }
+
+    private function getTaskMode($modeName){
+        switch ($modeName){
+            case '输送线入立架': return 1;
+            case '立架出至输送线': return 2;
+            case '立架出至缓存架':
+            case '移动立架内位置': return 3;
+            case '缓存架入立架':return 6;
+            default: throw new \Exception('发至海柔的移料箱请求,模式不存在');
+        }
+    }
+
+
     public function fetchGroup($toLocation, Collection $taskMaterialBoxes, $groupIdPrefix='',$mode='立架出至输送线'): bool
     {
-        LogService::log(__METHOD__,'runMany','波次任务分配6.r5f0:');
-        LogService::log(__METHOD__,'runMany','波次任务分配6.r5f1:'.json_encode($toLocation).json_encode($taskMaterialBoxes).json_encode($groupIdPrefix));
         $dataToPost=$this->makeJson_move(
             $taskMaterialBoxes,
             $mode,
@@ -99,8 +133,27 @@ class ForeignHaiRoboticsService
             $toLocation??'',
             $groupIdPrefix
         );
-        LogService::log(__METHOD__,'runMany','波次任务分配6.r5f2:'.json_encode($dataToPost));
-        return $this->controlHaiRobot($dataToPost,$taskMaterialBoxes,'立架出至输送线');
+        return $this->controlHaiRobot($dataToPost,$taskMaterialBoxes,$mode);
+    }
+
+    /**
+     * @param Collection $toLocations   //库位和料箱任务一一对应,一个库位对应一个料箱
+     * @param Collection $taskMaterialBoxes
+     * @param string $groupIdPrefix
+     * @param string $mode
+     * @return bool
+     * @throws ErrorException
+     */
+    public function fetchGroup_multiLocation(Collection $toLocations, Collection $taskMaterialBoxes, $groupIdPrefix='',$mode='立架出至输送线'): bool
+    {
+        $dataToPost=$this->makeJson_move_multi(
+            $taskMaterialBoxes,
+            $mode,
+            '',
+            $toLocations,
+            $groupIdPrefix
+        );
+        return $this->controlHaiRobot($dataToPost,$taskMaterialBoxes,$mode);
     }
 
     public function moveBin(){
@@ -444,4 +497,31 @@ class ForeignHaiRoboticsService
         return $isSuccess;
     }
 
+    /**
+     * put cache rack box to warehousing(将缓存架料箱入库)
+     *
+     * @param string $fromLocation
+     * @param string $toLocation
+     * @param integer $boxId
+     *
+     * @return bool
+     */
+    public function putWareHousing(string $fromLocation, string $toLocation, $boxId):bool
+    {
+        $station = Station::query()->select("id")->where("code",$fromLocation)->first();
+        if (!$station)return false;
+        if (StationTask::query()->select("id")->where("status","!=",'完成')->where("station_id",$station->id)->first())return false;
+        /** @var \stdClass $task */
+        $task = StationTask::query()->create([
+            'status' => "待处理",
+            'station_id' => $station->id,
+        ]);
+        StationTaskMaterialBox::query()->create([
+            'station_id' => $station->id,
+            'material_box_id'=>$boxId,
+            'status'=>"待处理",
+            'type' => '放',
+            'station_task_id' => $task->id,
+        ]);
+    }
 }

+ 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);
+}

+ 1 - 1
app/Services/LogisticYDService.php

@@ -89,7 +89,7 @@ class LogisticYDService
 
     public function format($nativeResponse)
     {
-        if ($nativeResponse->code != '0000' || $nativeResponse->data->result=="false") {
+        if (is_null($nativeResponse) || $nativeResponse->code != '0000' || $nativeResponse->data->result == "false") {
             return [];
         } else {
             $nativeData = $nativeResponse->data;

+ 1 - 1
app/Services/LogisticYTOService.php

@@ -52,7 +52,7 @@ class LogisticYTOService
             } catch (\Exception $e) {
                 LogService::log(LogisticYTOService::class, "YTO快递信息异常", $response);
             }
-            if (!empty($response)) {
+            if (!empty($response) && is_array($response)) {
                 $lastNativeRoute = $response[count($response) - 1];
                 $result['status'] = $this->getStatus($lastNativeRoute);
                 if ($result['status'] == '已收件') $result['received_at'] = $lastNativeRoute->upload_Time;

+ 87 - 77
app/Services/LogisticZopService.php

@@ -3,101 +3,111 @@
 
 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();
+    public function format($nativeResponse)
+    {
+        if (is_null($nativeResponse)||isEmpty($nativeResponse->result)) {//返回的结果为空,或者路由为[] 直接返回就好
+            return [];
+        }
+        $nativeRoutes = $nativeResponse->result;
+        $this->logistic_number = $nativeRoutes[0]->billCode;
+        $order_package = OrderPackage::query()->where('logistic_number', $this->logistic_number)->first();
 
-        $request->setUrl($url);
-        foreach ($logisticNums as $logisticNum) {
-            $request->setBody(json_encode([
-                'billCode' => $logisticNum,
-            ]));
-            $response = json_decode($client->execute($request));
+        $lastRoute = $nativeRoutes[count($nativeRoutes) - 1];
 
-            if ($response->status) {
-                $result[] = [
-                    'routes' => $response->result,
-                    'logisticNum' => $logisticNum,
-                ];
-            } else {
-//                throw new WarningException("单号没有查询到快递路由信息','LogisticZopService->get->{$logisticNum}");
-            }
+        $result = [
+            'logistic_number' => $this->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,
+        ];
+        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']);
+        $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;
+    }
+
+    /**
+     * 正常的状态与签收时间
+     */
+    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)->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;
     }
+
 }

+ 32 - 3
app/Services/MaterialBoxService.php

@@ -5,6 +5,9 @@ namespace App\Services;
 
 
 use App\MaterialBox;
+use App\Station;
+use App\StationTaskMaterialBox;
+use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Cache;
 use App\Traits\ServiceAppAop;
@@ -20,15 +23,27 @@ class MaterialBoxService
     /**
      * 获取一个空料箱
      *
+     * @param array $blacklist
+     *
      * @return MaterialBox|null
      */
-    public function getAnEmptyBox()
+    public function getAnEmptyBox(array $blacklist = [])
     {
         $id = 0;
         while (true){
-            $boxes = MaterialBox::query()->select('id',"code")->where("id",">",$id)->where("code","like","IDE%")
-                ->where("status",4)->limit(10)->orderBy("id")->get();
+            $boxes = MaterialBox::query()->select('id',"code")
+                ->whereNotIn("id",$blacklist)
+                ->where("id",">",$id)->where("code","like","IDE%")
+                ->where("status",4)->limit(10)->orderBy("id")
+                ->whereNotIn("id",StationTaskMaterialBox::query()->select("material_box_id")
+                    ->where("status","!=","已完成")->groupBy("material_box_id"))
+                ->get();
             if ($boxes->count()==0)break;
+            $haiBoxes = DB::connection("mysql_haiRobotics")->table("ks_bin")
+                ->where("status",1)->whereIn("ks_bin_code",array_column($boxes->toArray(),"code"))->get();
+            if ($haiBoxes->count()==0)continue;
+            $haiBoxes->each(function ($haiBox)use(&$codes){$codes[$haiBox->ks_bin_code] = true;});
+            foreach ($boxes as $index=>$box)if (!isset($codes[$box->code]))$boxes->splice($index,1);
             $ides = [];
             $str = "(";
             for ($i=0;$i<count($boxes)-1;$i++){
@@ -50,4 +65,18 @@ sql;
         }
         return null;
     }
+
+    /**
+     * 获取料箱所在库区
+     *
+     * @param string $ide
+     *
+     * @return string|null
+     */
+    public function getBoxLocation(string $ide)
+    {
+        $bin = DB::connection("mysql_haiRobotics")->table("ks_bin")->select("ks_bin_space_code")
+            ->where("ks_bin_code",$ide)->where("status",1)->first();
+        return $bin->ks_bin_space_code ?? null;
+    }
 }

+ 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);
+        }
+    }
+}

+ 16 - 3
app/Services/OrderPackageReceivedSyncService.php

@@ -26,8 +26,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()
@@ -135,10 +135,23 @@ class OrderPackageReceivedSyncService
         foreach ($orderPackages as $data) {
             if (empty($data)) continue;
             $orderPackage = OrderPackage::query()->where('logistic_number', $data['logistic_number'])->first();
+            try {
+                if ($orderPackage->order && $orderPackage->order->issue) {
+                    unset($data['exception_type']);
+                    unset($data['exception']);
+                }
+            } catch (Exception $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'])) $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();
         }
@@ -288,7 +301,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'] < 2) ? $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) {

+ 50 - 32
app/Services/OrderService.php

@@ -6,7 +6,6 @@ use App\Commodity;
 use App\Feature;
 use App\Jobs\OrderCreateInstantBill;
 use App\Jobs\OrderFreeze;
-use App\Log;
 use App\Logistic;
 use App\OracleActAllocationDetails;
 use App\OracleDOCASNHeader;
@@ -17,7 +16,6 @@ use App\OrderIssue;
 use App\Owner;
 use App\OwnerFeeDetail;
 use App\OwnerFeeDetailLogistic;
-use App\OwnerPriceExpress;
 use App\OwnerReport;
 use App\Province;
 use App\RejectedBill;
@@ -30,7 +28,6 @@ use App\Warehouse;
 use Carbon\Carbon;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Support\Collection;
-use Illuminate\Support\Facades\App;
 use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Facades\DB;
 use App\Traits\ServiceAppAop;
@@ -179,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."%'";
@@ -233,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;
     }
 
@@ -250,10 +247,10 @@ 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
-        ,DOC_ORDER_HEADER.soreference5,DOC_ORDER_HEADER.EDISENDFLAG2,DOC_ORDER_HEADER.EDISendTime2,DOC_ORDER_HEADER.Notes,DOC_ORDER_HEADER.ERPCANCELFLAG,
+        ,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,
        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 as orderCodeName,
@@ -296,12 +293,12 @@ class OrderService
                       GROUP BY 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,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, DOC_ORDER_HEADER.soreference5,
+                      DOC_ORDER_HEADER.EDIREMARKS2,DOC_ORDER_HEADER.WaveNo,DOC_ORDER_HEADER.SOReference1, NVL(ACT_ALLOCATION_DETAILS.PICKTOTRACEID,DOC_ORDER_HEADER.soreference5),
                       DOC_ORDER_HEADER.EDISENDFLAG2,DOC_ORDER_HEADER.EDISendTime2,DOC_ORDER_HEADER.Notes,DOC_ORDER_HEADER.ERPCANCELFLAG,
                       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;
     }
 
@@ -326,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);
@@ -1198,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)
@@ -1299,7 +1317,7 @@ sql
         $order->loadMissing("packages","owner");//加载包裹
         if (!$order->packages || !$order->owner)return false;
         $order->owner->loadCount("ownerPriceExpresses");
-        if ($order->owner->owner_price_expresses_count < 1)return false; //不存在计费模型 跳出
+        //if ($order->owner->owner_price_expresses_count < 1)return false; //不存在计费模型 跳出
         foreach ($order->packages as $package)if (!$package->weight)return false; //包裹存在且全部存在数量
 
         $logistic_fee = 0;
@@ -1342,7 +1360,7 @@ sql
             $taxFee += $tax;
         }
         if ($isBunched && !$weightExceptionMark && $weight>0 && $provinceId)list($logistic_fee,$taxFee) = app("OwnerPriceExpressService")->matching($weight, $order->owner_id, $order->logistic_id, $provinceId);
-        if ($logistic_fee!==null && $logistic_fee>0) $feeBill->update(["logistic_fee"=>$logistic_fee,"volume"=>$volume,"weight"=>$weight,"logistic_tax_fee"=>$taxFee]);
+        $feeBill->update(["logistic_fee"=>$logistic_fee,"volume"=>$volume,"weight"=>$weight,"logistic_tax_fee"=>$taxFee]);
         return true;
     }
 

+ 2 - 2
app/Services/OwnerAreaReportService.php

@@ -62,8 +62,8 @@ class OwnerAreaReportService
                     ->where("counting_month",'like',$area->counting_month."%")->first();
                 if ($report){
                     if (!$area->ownerStoragePriceModel)return false;
-                    $storeFee = app("OwnerStoragePriceModelService")->calculationAmount($area->ownerStoragePriceModel, $values["accounting_area"], $area->owner_id, $area->counting_month);
-                    $up = ["storage_fee"=>$storeFee];
+                    list($storeFee,$taxFee) = app("OwnerStoragePriceModelService")->calculationAmount($area->ownerStoragePriceModel, $values["accounting_area"], $area->owner_id, $area->counting_month);
+                    $up = ["storage_fee"=>$storeFee,"storage_tax_fee"=>$taxFee];
                     if ($report->confirm_fee !== null || $report->confirmed == '是'){
                         $initial = $report->work_fee + $report->logistic_fee + $storeFee;
                         $up["difference"] = $initial - $report->confirm_fee;

+ 0 - 7
app/Services/OwnerPriceDirectLogisticService.php

@@ -106,14 +106,7 @@ class OwnerPriceDirectLogisticService
         if (!is_array($id))$id = [$id];
         OwnerPriceDirectLogisticCar::query()->whereIn("owner_price_direct_logistic_id",$id)->delete();
 
-        $query = "IN (";
-        for ($i=0;$i<count($id)-1;$i++)$query .= "{$id[$i]},";
-        $query .= "{$id[count($id)-1]})";
-
-        $sql = "SELECT * FROM owner_price_direct_logistic_owner WHERE owner_price_direct_logistic_id {$query}";
-        $owners = array_column(DB::select(DB::raw($sql)),"owner_id");
         DB::table("owner_price_direct_logistic_owner")->whereIn("owner_price_direct_logistic_id",$id)->delete();
-        app("OwnerService")->refreshRelevance($owners,4,true);
         return OwnerPriceDirectLogistic::destroy($id);
     }
 

+ 0 - 8
app/Services/OwnerPriceExpressService.php

@@ -193,15 +193,7 @@ class OwnerPriceExpressService
         if (!$id)return 0;
         if (!is_array($id))$id = [$id];
         OwnerPriceExpressProvince::query()->whereIn("owner_price_express_id",$id)->delete();
-
-        $query = "IN (";
-        for ($i=0;$i<count($id)-1;$i++)$query .= "{$id[$i]},";
-        $query .= "{$id[count($id)-1]})";
-
-        $sql = "SELECT * FROM owner_price_express_owner WHERE owner_price_express_id {$query}";
-        $owners = array_column(DB::select(DB::raw($sql)),"owner_id");
         DB::table("owner_price_express_owner")->whereIn("owner_price_express_id",$id)->delete();
-        app("OwnerService")->refreshRelevance($owners,2,true);
         DB::table("owner_price_express_logistic")->whereIn("owner_price_express_id",$id)->delete();
         return OwnerPriceExpress::destroy($id);
     }

+ 0 - 7
app/Services/OwnerPriceLogisticService.php

@@ -125,14 +125,7 @@ class OwnerPriceLogisticService
         if (!is_array($id))$id = [$id];
         OwnerPriceLogisticDetail::query()->whereIn("owner_price_logistic_id",$id)->delete();
 
-        $query = "IN (";
-        for ($i=0;$i<count($id)-1;$i++)$query .= "{$id[$i]},";
-        $query .= "{$id[count($id)-1]})";
-
-        $sql = "SELECT * FROM owner_price_logistic_owner WHERE owner_price_logistic_id {$query}";
-        $owners = array_column(DB::select(DB::raw($sql)),"owner_id");
         DB::table("owner_price_logistic_owner")->whereIn("owner_price_logistic_id",$id)->delete();
-        app("OwnerService")->refreshRelevance($owners,3,true);
         DB::table("owner_price_logistic_logistic")->whereIn("owner_price_logistic_id",$id)->delete();
 
         return OwnerPriceLogistic::destroy($id);

+ 26 - 18
app/Services/OwnerPriceOperationService.php

@@ -141,14 +141,7 @@ class OwnerPriceOperationService
         if (!is_array($id))$id = [$id];
         OwnerPriceOperationItem::query()->whereIn("owner_price_operation_id",$id)->delete();
 
-        $query = "IN (";
-        for ($i=0;$i<count($id)-1;$i++)$query .= "{$id[$i]},";
-        $query .= "{$id[count($id)-1]})";
-
-        $sql = "SELECT * FROM owner_price_operation_owner WHERE owner_price_operation_id {$query}";
-        $owners = array_column(DB::select(DB::raw($sql)),"owner_id");
         DB::table("owner_price_operation_owner")->whereIn("owner_price_operation_id",$id)->delete();
-        app("OwnerService")->refreshRelevance($owners,1,true);
 
         return OwnerPriceOperation::destroy($id);
     }
@@ -319,7 +312,7 @@ class OwnerPriceOperationService
      */
     public function matching($matchObject, $columnMapping, $ownerId, $type = '出库', $typeMark = null)
     {
-        $units = app("UnitService")->getUnitMapping(["件","箱"]); //获取单位映射集
+        $units = app("UnitService")->getUnitMapping(["件","箱","m³","T","kg"]); //获取单位映射集
         $rules = $this->getOwnerPriceOperation($ownerId,$type,$typeMark);//货主下的全部规则
         if (!$rules)return -2;  //规则不存在跳出
 
@@ -331,6 +324,9 @@ class OwnerPriceOperationService
         if ($type == '出库'){
             $total = app("OrderService")->getOrderQuantity($ownerId)+1;//获取该货主本月C端单量
             $matchObject->packages->each(function ($package)use(&$orderTotal){
+                if($package->commodities->count()==0)return;
+                $package->commodities[0]->bulk = $package->bulk/1000000;
+                $package->commodities[0]->weight = $package->weight;
                 $package->commodities->each(function ($commodity)use(&$orderTotal){
                     $orderTotal += (int)$commodity->amount;
                 });
@@ -468,17 +464,29 @@ class OwnerPriceOperationService
                 }
                 $package["price"] = $rule->unit_price;
             }
-            if ($units[$rule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
-                $amount = 0;
-                foreach ($matchObject as $commodity){
-                    $pack = $this->changeUnit($ownerId,$commodity[$columnMapping[9]]);
-                    if ($rule->odd_price){
-                        $amount += floor($amount/$pack);
-                        $surcharge += $rule->odd_price * ($amount%$pack); //零头附加费
-                    }else$amount += ceil($amount/$pack);
+            if ($units[$rule->unit_id] != '件'){ //非件时改变商品数量 此时数量可能为小数
+                foreach ($matchObject as &$commodity){
+                    switch ($units[$rule->unit_id]){
+                        case "箱"://为箱时同步商品寻找箱规并改变商品数量
+                            $pack = $this->changeUnit($ownerId,$commodity[$columnMapping[9]]);
+                            if ($rule->odd_price){
+                                $amount = floor($commodity[$columnMapping[8]]/$pack);
+                                $surcharge += $rule->odd_price * ($amount%$pack); //零头附加费
+                            }else$amount = ceil($commodity[$columnMapping[8]]/$pack);
+                            if ($amount<0)return $amount;
+                            $commodity[$columnMapping[8]] = $amount;
+                            break;
+                        case "m³":
+                            $commodity[$columnMapping[8]] = $commodity["bulk"] ?? 0;
+                            break;
+                        case "kg":
+                            $commodity[$columnMapping[8]] = $commodity["weight"] ?? 0;
+                            break;
+                        case "T":
+                            $commodity[$columnMapping[8]] = ($commodity["weight"]/1000) ?? 0;
+                            break;
+                    }
                 }
-                if ($amount<0)return $amount;
-                $package[$columnMapping[8]] = $amount;
             }
         }
         if ($matchObject){

+ 46 - 53
app/Services/OwnerService.php

@@ -185,14 +185,12 @@ class OwnerService
 
     public function get(array $params, array $withs = null, bool $authority = true, bool $notShowSoftDelete = false, $user = null)
     {
+        /** @var User $user */
+        if ($user==null)$user = Auth::user();
         return Cache::remember(
             'owner_'.md5(json_encode($params).json_encode($withs).$authority.$notShowSoftDelete.json_encode($user))
             ,config('cache.expirations.rarelyChange')
             ,function()use($params,$withs,$authority,$notShowSoftDelete,$user){
-            /** @var User $user */
-            if ($user==null) {
-                $user = Auth::user();
-            }
             $query = Owner::query();
             if ($withs)$query->with($withs);
             if ($authority&&$user){
@@ -380,58 +378,53 @@ sql
     /**
      * 计费模型变动时更新货主中关联属性
      *
-     * @param integer|array $owner
-     * @param integer $type
-     * @param bool $isDestroy
+     * @param integer $ownerId
      *
      */
-    public function refreshRelevance($owner, $type, $isDestroy = false)
+    public function refreshRelevance($ownerId)
     {
-        if (!$owner)return;
-        if (!is_array($owner))$owner = [$owner];
-        $owners = Owner::query()->select("id","relevance")->whereIn("id",$owner)->get();
-        $update = [["id","relevance"]];
-        foreach ($owners as $ow){
-            $relevance = $ow->relevance ?? [];
-            $index = array_search($type,$relevance);
-            $exist = $index===false ? false : true;
-            if ($exist && $isDestroy && !$this->isExistModel($ow->id,$type)){
-                array_splice($relevance,$index,1);
-                $update[] = [
-                    "id"=>$ow->id,
-                    "relevance"=>$relevance,
-                ];
-            }
-            if (!$exist && !$isDestroy){
-                array_push($relevance,$type);
-                $update[] = [
-                    "id"=>$ow->id,
-                    "relevance"=>$relevance,
-                ];
-            }
-        }
-        if (count($update)>1)app(BatchUpdateService::class)->batchUpdate("owners",$update);
-    }
-
-    private function isExistModel($owner, $type):bool
-    {
-        switch ($type){
-            case 0:
-                $table = "owner_storage_price_model_owner";
-                break;
-            case 1:
-                $table = "owner_price_operation_owner";
-                break;
-            case 2:
-                $table = "owner_price_logistic_owner";
-                break;
-            case 3:
-                $table = "owner_price_express_owner";
-                break;
-            default:
-                $table = "owner_price_direct_logistic_owner";
-        }
-        return DB::selectOne(DB::raw("SELECT 1 FROM {$table} WHERE owner_id = ? LIMIT 1"),[$owner]) ? true : false;
+        $relevance = [];
+        $sql = <<<sql
+SELECT 1 FROM owner_storage_price_models a 
+LEFT JOIN owner_storage_price_model_owner b ON a.id =  b.owner_storage_price_model_id 
+LEFT JOIN owners c ON b.owner_id = c.id 
+WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
+sql;
+        if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 0;
+        $sql = <<<sql
+SELECT 1 FROM owner_price_operations a 
+LEFT JOIN owner_price_operation_owner b ON a.id =  b.owner_price_operation_id 
+LEFT JOIN owners c ON b.owner_id = c.id 
+WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
+sql;
+        if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 1;
+        $sql = <<<sql
+SELECT 1 FROM owner_price_expresses a 
+LEFT JOIN owner_price_express_owner b ON a.id =  b.owner_price_express_id 
+LEFT JOIN owners c ON b.owner_id = c.id 
+WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
+sql;
+        if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 2;
+        $sql = <<<sql
+SELECT 1 FROM owner_price_logistics a 
+LEFT JOIN owner_price_logistic_owner b ON a.id =  b.owner_price_logistic_id 
+LEFT JOIN owners c ON b.owner_id = c.id 
+WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
+sql;
+        if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 3;
+        $sql = <<<sql
+SELECT 1 FROM owner_price_direct_logistics a 
+LEFT JOIN owner_price_direct_logistic_owner b ON a.id =  b.owner_price_direct_logistic_id 
+LEFT JOIN owners c ON b.owner_id = c.id 
+WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
+sql;
+        if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 4;
+        $sql = <<<sql
+SELECT 1 FROM owner_price_systems a LEFT JOIN owners b ON a.owner_id = b.id
+WHERE b.id = ? LIMIT 1
+sql;
+        if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 5;
+        Owner::query()->where("id",$ownerId)->update(["relevance"=>$relevance]);
     }
 
     /**

+ 0 - 4
app/Services/OwnerStoragePriceModelService.php

@@ -92,7 +92,6 @@ class OwnerStoragePriceModelService
     }
     public function destroy($id)
     {
-        $sql = "SELECT * FROM owner_storage_price_model_owner WHERE owner_storage_price_model_id ";
         if (is_array($id)){
             $query = "IN (";
             for ($i=0;$i<count($id)-1;$i++)$query .= "?,";
@@ -101,10 +100,7 @@ class OwnerStoragePriceModelService
             $query = "= ?";
             $id = [$id];
         }
-        $owners = array_column(DB::select(DB::raw($sql.$query),$id),"owner_id");
         DB::delete(DB::raw("DELETE FROM owner_storage_price_model_owner WHERE owner_storage_price_model_id ".$query),$id);
-        app("OwnerService")->refreshRelevance($owners,0,true);
-
         return OwnerStoragePriceModel::destroy($id);
     }
 

+ 13 - 0
app/Services/PrintPartService.php

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

+ 13 - 0
app/Services/PrintTemplateService.php

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

+ 4 - 2
app/Services/RejectedBillService.php

@@ -358,6 +358,8 @@ class RejectedBillService
             if ($bill) $bill->update([
                     "work_fee" => $money,
                     "owner_price_operation_id" => $id,
+                    "outer_id" => $rejectedBill->id,
+                    "outer_table_name" => "rejected_bills",
             ]); else app("OwnerFeeDetailService")->create([
                 "owner_id" => $store->owner_id,
                 "worked_at" => $store->created_at,
@@ -367,8 +369,8 @@ class RejectedBillService
                 "work_fee" => $money,
                 "owner_price_operation_id" => $id,
                 "created_at" => date('Y-m-d H:i:s'),
-                "outer_id" => $store->id,
-                "outer_table_name" => "stores",
+                "outer_id" => $rejectedBill->id,
+                "outer_table_name" => "rejected_bills",
                 "work_tax_fee" => $taxFee,
             ]);
         }

+ 2 - 1
app/Services/RejectedService.php

@@ -118,7 +118,8 @@ class RejectedService
         },config('cache.expirations.oftenChange'));
     }
     public function getSql(array $param){
-        $sql = $this->conditionQuery($param)->selectRaw('rejected_bills.*')->whereNull('rejected_bills.deleted_at')
+        $sql = $this->conditionQuery($param)->selectRaw("rejected_bills.*,CASE rejected_bills.is_loaded WHEN 0 THEN '否' WHEN 1 THEN '是' WHEN 2 THEN '待推单' WHEN 3 THEN '上传异常' WHEN 4 THEN '待确认' ELSE '无需入库' END loaded")
+            ->whereNull('rejected_bills.deleted_at')
             ->leftJoin('owners','rejected_bills.id_owner','=','owners.id')
             ->selectRaw('owners.name owner_name')
             ->leftJoin('logistics','rejected_bills.id_logistic_return','=','logistics.id')

+ 7 - 1
app/Services/StationService.php

@@ -60,16 +60,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']=='完成')
@@ -81,6 +85,8 @@ class StationService
                 "stationTaskBatches.batch",
                 "stationTaskMaterialBoxes.materialBox",
             ]);
+        LogService::log('海柔请求done1','broadcastBinMonitor',
+            $station_id.'|'.json_encode($stationTask));
         $this->broadcast($station_id, $stationTask);
     }
 

+ 1 - 1
app/Services/StationTaskBatchService.php

@@ -75,7 +75,7 @@ class StationTaskBatchService
             }
         }
         $this->batchService->updateWhereIn('id', data_get($batches_handled, '*.id'), ['status' => '处理中']);
-        $stationTaskBatches_toCreate=$stationTaskBatches_toCreate->reverse();
+        $stationTaskBatches_toCreate=$stationTaskBatches_toCreate->reverse();//这里的波次顺序是反的,不知为什么,所以反向一次就好了。其他解耦的地方都是正序,必须保持一致
         $this->insert($stationTaskBatches_toCreate->toArray());
 
         $stationTaskBatches_toCreate=$this->getAndAttachIds($stationTaskBatches_toCreate);

+ 61 - 0
app/Services/StorageService.php

@@ -0,0 +1,61 @@
+<?php 
+
+namespace App\Services;
+
+use App\StationTask;
+use App\StationTaskMaterialBox;
+use App\Traits\ServiceAppAop;
+use App\Storage;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Support\Collection;
+
+class StorageService
+{
+    use ServiceAppAop;
+    protected $modelClass=Storage::class;
+
+
+    /**
+     * 填充缓存架
+     *
+     * @param \Illuminate\Database\Eloquent\Collection $stations
+     */
+    public function paddingCacheShelf($stations)
+    {
+        $collection = new Collection();
+        $stationCollection = new Collection();
+        $blacklist = [];
+        foreach ($stations as $station){
+            $box = app("MaterialBoxService")->getAnEmptyBox($blacklist);
+            if (!$box)continue;
+            $task = StationTask::query()->create([
+                'status' => "待处理",
+                'station_id' => $station->id,
+            ]);
+            $collection->add(StationTaskMaterialBox::query()->create([
+                'station_id' => $station->id,
+                'material_box_id'=>$box->id,
+                'status'=>"待处理",
+                'type' => '取',
+                'station_task_id' => $task->id,
+            ]));
+            $stationCollection->add($station->code);
+            $blacklist[] = $box->id;
+        }
+        app("ForeignHaiRoboticsService")->fetchGroup_multiLocation($stationCollection,$collection,'','立架出至缓存架');
+    }
+    /**
+     * 标记指定库位为占用
+     *
+     * @param string $location
+     *
+     * @return int
+     */
+    public function markOccupy($location)
+    {
+        return Storage::query()->whereHas("station",function (Builder $query)use($location){
+            $query->where("code",$location);
+        })->update(["status"=>1]);
+    }
+
+}

+ 17 - 8
app/Services/WaybillService.php

@@ -28,8 +28,8 @@ class WaybillService
      */
     private function conditionQuery(array $param){
         $waybills = Waybill::filterAuthorities()->with(['owner','logistic','originationCity','destinationCity.parent',
-            'uploadFile','amountUnit','warehouseWeightUnit','carrierWeightUnit','district','order',
-            'warehouseWeightUnitOther','carrierWeightUnitOther','carType','uploadFile','waybillAuditLogs.user'])
+            'uploadFiles','amountUnit','warehouseWeightUnit','carrierWeightUnit','district','order',
+            'warehouseWeightUnitOther','carrierWeightUnitOther','carType','uploadFiles','waybillAuditLogs.user'])
             ->selectRaw('waybills.* ,waybill_on_tops.id top_id ,waybill_on_tops.remark,waybill_on_tops.updated_at top_update')
             ->leftJoin('waybill_on_tops','waybill_on_tops.waybill_id','=','waybills.id')
             ->whereNull('waybill_on_tops.deleted_at')
@@ -120,6 +120,17 @@ class WaybillService
 //            $this->searchWay($waybills,$param['wms_bill_number'],'waybills.wms_bill_number');
 //            unset($param['wms_bill_number']);
 //        }
+
+        if ($param["mileage"] ?? false){
+            $param["mileage"] = explode("-",$param["mileage"]);
+            $waybills->whereBetween("mileage",[(int)$param["mileage"][0] ?? 0,(int)$param["mileage"][1]] ?? 0);
+            unset($param["mileage"]);
+        }
+        if ($param["warehouse_weight_other"] ?? false){
+            $param["warehouse_weight_other"] = explode("-",$param["warehouse_weight_other"]);
+            $waybills->whereBetween("warehouse_weight_other",[(int)$param["warehouse_weight_other"][0] ?? 0,(int)$param["warehouse_weight_other"][1]] ?? 0);
+            unset($param["warehouse_weight_other"]);
+        }
         $columnQueryRules=[
             'waybill_number' => ['batch' => ''],
             'carrier_bill' => ['batch' => ''],
@@ -136,8 +147,6 @@ class WaybillService
             'uriType' => ['alias' => 'type'],
             'id' => ['multi' => ','],
             'logistic_id' => ['multi' => ','],
-            'mileage' => ['like' => ''],
-            'carrier_weight_other' => ['like' => ''],
         ];
         $waybills = app(QueryService::class)->query($param,$waybills,$columnQueryRules,"waybills");
         return $waybills;
@@ -154,18 +163,18 @@ class WaybillService
     }
     public function dailyBilling(array $param){
         $waybills = Waybill::query()->with(['owner','logistic','originationCity','destinationCity.parent',
-            'uploadFile','amountUnit','warehouseWeightUnit','carrierWeightUnit','district','order',
-            'warehouseWeightUnitOther','carrierWeightUnitOther','carType','uploadFile','waybillAuditLogs.user'])
+            'uploadFiles','amountUnit','warehouseWeightUnit','carrierWeightUnit','district','order',
+            'warehouseWeightUnitOther','carrierWeightUnitOther','carType','uploadFiles','waybillAuditLogs.user'])
             ->selectRaw('waybills.* ,waybill_on_tops.id top_id,waybill_on_tops.remark,waybill_on_tops.updated_at top_update')
             ->leftJoin('waybill_on_tops','waybill_on_tops.waybill_id','=','waybills.id')
             ->whereNull('waybill_on_tops.deleted_at')
             ->orderBy('waybill_on_tops.updated_at','desc')
             ->orderBy('waybills.id','desc')
-//            ->where('waybills.created_at','like',$param['screenDate'].'%')
             ->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);

+ 4 - 0
app/Station.php

@@ -35,6 +35,10 @@ class Station extends Model
             ->orderByDesc('id')
             ;
     }
+    public function stationTasks()
+    {   //站任务
+        return $this->hasMany(StationTask::class,"id","station_type_id");
+    }
     public function stationTypeBinMonitor(){
         return $this->hasOne(StationTypeBinMonitor::class);
     }

+ 14 - 3
app/Storage.php

@@ -11,17 +11,28 @@ class Storage extends Model
     use ModelLogChanging;
 
     protected $fillable = [
+        "station_id",
         "material_box_id",
         "commodity_id",
-        "amount"
+        "amount",
+        "status"
     ];
 
+    const STATUS=[
+        0 => "正常",
+        1 => "占用",
+    ];
+
+    public function station()
+    {   //货架
+        return $this->belongsTo(Station::class);
+    }
     public function materialBox()
     {   //料箱
-        $this->belongsTo(MaterialBox::class);
+        return $this->belongsTo(MaterialBox::class);
     }
     public function commodity()
     {   //商品
-        $this->belongsTo(Commodity::class);
+        return $this->belongsTo(Commodity::class);
     }
 }

+ 3 - 3
app/Waybill.php

@@ -105,10 +105,10 @@ class Waybill extends Model
         return $this->hasOne('App\CarType','id','carType_id');
     }
     public function waybillAuditLogs(){
-        return $this->hasMany('App\WaybillAuditLog','waybill_id','id');
+        return $this->hasMany('App\WaybillAuditLog','waybill_id','id')->orderByDesc("created_at");
     }
-    public function uploadFile(){
-        return $this->hasOne('App\UploadFile','table_id','id')->where('table_name','waybills');
+    public function uploadFiles(){
+        return $this->hasMany(UploadFile::class,'table_id','id')->where('table_name','waybills');
     }
     public function order()
     {   //订单

+ 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;
-    }
-
-
-}

+ 7 - 0
bootstrap/cache/packages.php

@@ -96,6 +96,13 @@
       0 => 'NunoMaduro\\Collision\\Adapters\\Laravel\\CollisionServiceProvider',
     ),
   ),
+  'oursdreams/export' => 
+  array (
+    'providers' => 
+    array (
+      0 => 'Oursdreams\\Export\\ExportServiceProvider',
+    ),
+  ),
   'overtrue/laravel-pinyin' => 
   array (
     'providers' => 

+ 20 - 18
bootstrap/cache/services.php

@@ -34,15 +34,16 @@
     30 => 'Maatwebsite\\Excel\\ExcelServiceProvider',
     31 => 'Carbon\\Laravel\\ServiceProvider',
     32 => 'NunoMaduro\\Collision\\Adapters\\Laravel\\CollisionServiceProvider',
-    33 => 'Overtrue\\LaravelPinyin\\ServiceProvider',
-    34 => 'Te7aHoudini\\LaravelTrix\\LaravelTrixServiceProvider',
-    35 => 'Yajra\\Oci8\\Oci8ServiceProvider',
-    36 => 'App\\Providers\\AppServiceProvider',
-    37 => 'App\\Providers\\AuthServiceProvider',
-    38 => 'App\\Providers\\BroadcastServiceProvider',
-    39 => 'App\\Providers\\EventServiceProvider',
-    40 => 'App\\Providers\\HorizonServiceProvider',
-    41 => 'App\\Providers\\RouteServiceProvider',
+    33 => 'Oursdreams\\Export\\ExportServiceProvider',
+    34 => 'Overtrue\\LaravelPinyin\\ServiceProvider',
+    35 => 'Te7aHoudini\\LaravelTrix\\LaravelTrixServiceProvider',
+    36 => 'Yajra\\Oci8\\Oci8ServiceProvider',
+    37 => 'App\\Providers\\AppServiceProvider',
+    38 => 'App\\Providers\\AuthServiceProvider',
+    39 => 'App\\Providers\\BroadcastServiceProvider',
+    40 => 'App\\Providers\\EventServiceProvider',
+    41 => 'App\\Providers\\HorizonServiceProvider',
+    42 => 'App\\Providers\\RouteServiceProvider',
   ),
   'eager' => 
   array (
@@ -66,15 +67,16 @@
     17 => 'Maatwebsite\\Excel\\ExcelServiceProvider',
     18 => 'Carbon\\Laravel\\ServiceProvider',
     19 => 'NunoMaduro\\Collision\\Adapters\\Laravel\\CollisionServiceProvider',
-    20 => 'Overtrue\\LaravelPinyin\\ServiceProvider',
-    21 => 'Te7aHoudini\\LaravelTrix\\LaravelTrixServiceProvider',
-    22 => 'Yajra\\Oci8\\Oci8ServiceProvider',
-    23 => 'App\\Providers\\AppServiceProvider',
-    24 => 'App\\Providers\\AuthServiceProvider',
-    25 => 'App\\Providers\\BroadcastServiceProvider',
-    26 => 'App\\Providers\\EventServiceProvider',
-    27 => 'App\\Providers\\HorizonServiceProvider',
-    28 => 'App\\Providers\\RouteServiceProvider',
+    20 => 'Oursdreams\\Export\\ExportServiceProvider',
+    21 => 'Overtrue\\LaravelPinyin\\ServiceProvider',
+    22 => 'Te7aHoudini\\LaravelTrix\\LaravelTrixServiceProvider',
+    23 => 'Yajra\\Oci8\\Oci8ServiceProvider',
+    24 => 'App\\Providers\\AppServiceProvider',
+    25 => 'App\\Providers\\AuthServiceProvider',
+    26 => 'App\\Providers\\BroadcastServiceProvider',
+    27 => 'App\\Providers\\EventServiceProvider',
+    28 => 'App\\Providers\\HorizonServiceProvider',
+    29 => 'App\\Providers\\RouteServiceProvider',
   ),
   'deferred' => 
   array (

+ 2 - 5
composer.json

@@ -26,6 +26,7 @@
         "laravel/tinker": "^2.0",
         "laravel/ui": "^2.0",
         "maatwebsite/excel": "^3.1",
+        "oursdreams/export": "^0.0.7",
         "overtrue/laravel-pinyin": "^4.0",
         "overtrue/pinyin": "~4.0",
         "predis/predis": "^1.1",
@@ -65,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": {

File diff suppressed because it is too large
+ 195 - 232
composer.lock


+ 15 - 0
config/database.php

@@ -63,6 +63,21 @@ return [
             ]) : [],
         ],
 
+        'mysql_haiRobotics' => [
+            'driver' => 'mysql',
+            'host' => '58.33.243.164',
+            'port' => '3306',
+            'database' => 'wms_core',
+            'username' => 'root',
+            'password' => 'root',
+            'unix_socket' => '',
+            'charset' => 'utf8mb4',
+            'collation' => 'utf8mb4_unicode_ci',
+            'prefix' => '',
+            'strict' => false,
+            'engine' => null,
+        ],
+
         'oracle' => [
             'driver' => env('ORACLE_DRIVER', 'oracle'),
             'host' => env('ORACLE_HOST', '47.103.12.61'),

+ 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),
+    ];
+});

+ 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,
+    ];
+});

+ 13 - 0
database/factories/PrintPartFactory.php

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

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