Просмотр исходного кода

Merge branch 'master' into yang

# Conflicts:
#	public/js/app.js
ANG YU 5 лет назад
Родитель
Сommit
b8caab9e64
100 измененных файлов с 1836 добавлено и 769 удалено
  1. 76 0
      .gitlab-ci.yml
  2. 1 3
      app/Commodity.php
  3. 57 11
      app/Console/Commands/SyncWMSOrderTask.php
  4. 1 0
      app/CustomField.php
  5. 12 5
      app/Http/Controllers/CommodityController.php
  6. 262 10
      app/Http/Controllers/CustomerController.php
  7. 361 250
      app/Http/Controllers/InventoryAccountController.php
  8. 14 1
      app/Http/Controllers/PackageController.php
  9. 5 4
      app/Http/Controllers/StoreCheckingReceiveController.php
  10. 14 6
      app/Http/Controllers/StoreController.php
  11. 50 11
      app/Http/Controllers/TestController.php
  12. 20 20
      app/Http/Controllers/UserDutyCheckController.php
  13. 0 1
      app/Http/Controllers/api/thirdPart/flux/SortingController.php
  14. 24 0
      app/Http/Controllers/api/thirdPart/haiq/PickStationController.php
  15. 4 10
      app/Imports/InventoryCompareImport.php
  16. 3 3
      app/Imports/StoreCheckingReceiveImport.php
  17. 0 1
      app/Imports/StoreCheckingReceiveSheets.php
  18. 12 29
      app/LaborReport.php
  19. 1 3
      app/LaborReportStatus.php
  20. 1 1
      app/Order.php
  21. 8 0
      app/OrderPackage.php
  22. 10 9
      app/Services/CacheService.php
  23. 24 5
      app/Services/CommodityService.php
  24. 2 2
      app/Services/CustomerService.php
  25. 125 22
      app/Services/FeatureService.php
  26. 47 0
      app/Services/InventoryAccountService.php
  27. 26 48
      app/Services/InventoryCompareService.php
  28. 1 1
      app/Services/LaborReportService.php
  29. 0 1
      app/Services/LogService.php
  30. 1 0
      app/Services/LogisticService.php
  31. 6 2
      app/Services/OracleBasCustomerService.php
  32. 3 0
      app/Services/OracleDOCOrderHeaderService.php
  33. 3 1
      app/Services/OrderIssueService.php
  34. 8 4
      app/Services/OrderPackageCommoditiesService.php
  35. 5 2
      app/Services/OrderPackageService.php
  36. 133 16
      app/Services/OrderService.php
  37. 1 1
      app/Services/OwnerPriceExpressService.php
  38. 3 4
      app/Services/OwnerPriceLogisticService.php
  39. 96 72
      app/Services/OwnerPriceOperationService.php
  40. 2 2
      app/Services/OwnerService.php
  41. 3 3
      app/Services/OwnerStoragePriceModelService.php
  42. 7 11
      app/Services/ShopService.php
  43. 2 2
      app/Services/StoreItemService.php
  44. 0 4
      app/Services/StoreService.php
  45. 1 1
      app/Services/UserService.php
  46. 2 3
      app/Services/WarehouseService.php
  47. 1 1
      app/Services/common/QueryService.php
  48. 1 1
      app/UserDutyCheck.php
  49. 1 1
      app/UserWorkgroup.php
  50. 14 0
      config/sync.php
  51. 16 0
      database/factories/CarTypeFactory.php
  52. 15 0
      database/factories/CityFactory.php
  53. 21 0
      database/factories/CommodityFactory.php
  54. 16 0
      database/factories/FeatureFactory.php
  55. 1 1
      database/factories/LogisticFactory.php
  56. 27 0
      database/factories/OrderFactory.php
  57. 41 0
      database/factories/OrderIssueFactory.php
  58. 12 0
      database/factories/OrderPackageFactory.php
  59. 21 0
      database/factories/OwnerAreaReportFactory.php
  60. 3 4
      database/factories/OwnerBillReportFactory.php
  61. 0 1
      database/factories/OwnerFactory.php
  62. 9 23
      database/factories/OwnerFeeDetailFactory.php
  63. 2 4
      database/factories/OwnerOutStorageRuleFactory.php
  64. 15 0
      database/factories/OwnerPriceDirectLogisticCarFactory.php
  65. 13 0
      database/factories/OwnerPriceDirectLogisticFactory.php
  66. 4 6
      database/factories/OwnerPriceExpressFactory.php
  67. 16 0
      database/factories/OwnerPriceExpressProvinceFactory.php
  68. 23 0
      database/factories/OwnerPriceLogisticDetailFactory.php
  69. 19 0
      database/factories/OwnerPriceLogisticFactory.php
  70. 6 4
      database/factories/OwnerReportFactory.php
  71. 3 4
      database/factories/OwnerStoragePriceModelFactory.php
  72. 15 0
      database/factories/OwnerTrakingOwnerFactory.php
  73. 2 4
      database/factories/ProcessMethodFactory.php
  74. 12 0
      database/factories/ProvinceFactory.php
  75. 2 4
      database/factories/ShopFactory.php
  76. 2 2
      database/migrations/2020_03_09_153510_create_stores_table.php
  77. 2 2
      database/migrations/2020_03_25_164101_create_processes_additional_bills_table.php
  78. 12 11
      database/migrations/2020_03_30_112202_drop_commodity_barcode_column_to_barcode_table.php
  79. 1 1
      database/migrations/2020_05_25_152252_change_user_workgroup.php
  80. 1 1
      database/migrations/2020_06_02_130804_change_user_duty_check.php
  81. 1 1
      database/migrations/2020_07_06_160500_create_operator_logs_table_and_add_authority_and_change_processes_column_status.php
  82. 1 1
      database/migrations/2020_07_20_162421_create_labor_report_statuses_table.php
  83. 1 1
      database/migrations/2020_08_26_093946_change_inventory_missions_to_inventory_account_missions.php
  84. 1 1
      database/migrations/2020_08_26_094015_change_inventories_to_inventory_accounts.php
  85. 1 1
      database/migrations/2020_08_31_102647_add_inventory_accounts_status.php
  86. 0 33
      database/migrations/2020_09_01_111054_change_inventory_account_mission_column_checked_to_three.php
  87. 1 1
      database/migrations/2020_09_10_143926_drop_shop_unique_name_index.php
  88. 1 1
      database/migrations/2020_09_11_115414_change_labor_reports_labor_company_to_labor_company_id.php
  89. 0 33
      database/migrations/2020_09_16_115715_change_inventory_account_mission_checked_column_checked_to_four.php
  90. 17 15
      database/migrations/2020_09_20_142656_change_order_issue.php
  91. 2 2
      database/migrations/2020_09_23_135848_add_authorities_and_change_inventory_accounts.php
  92. 2 2
      database/migrations/2020_09_24_152015_change_labor_report_status.php
  93. 2 2
      database/migrations/2020_10_12_092325_change_inventory_account_mission_checked_column_checked_to_five.php
  94. 1 1
      database/migrations/2020_10_12_105209_add_order_track_order_code.php
  95. 7 5
      database/migrations/2020_10_14_112825_add_order_issue_second_client_no.php
  96. 4 1
      database/migrations/2020_10_19_113042_create_logistic_timings_table.php
  97. 2 2
      database/migrations/2020_11_03_114135_change_store_status_column.php
  98. 2 2
      database/migrations/2020_11_03_114310_change_store_stored_method_column.php
  99. 2 2
      database/migrations/2020_11_03_180029_change_store_items_status_column.php
  100. 2 2
      database/migrations/2020_11_13_155436_change_inventory_accounts_status_column.php

+ 76 - 0
.gitlab-ci.yml

@@ -0,0 +1,76 @@
+stages:
+  - build
+  - test
+  - deploy
+
+cache:
+  paths:
+    - vendor/
+
+before_script:
+  - export PATH=$PATH:/etc/instantclient_19_9
+
+  - if ! command -v composer &> /dev/null
+  - then
+
+  - sudo apt-get update -yqq
+  #- if ! command -v vim &> /dev/null
+  - sudo apt-get install vim -yqq
+  #- fi
+
+  #- if ! command -v unzip &> /dev/null
+  - sudo apt-get install unzip -yqq
+  #- fi
+
+  #- if ! command -v php &> /dev/null
+  - sudo apt-get install php -yqq
+  - sudo apt-get install -yqq php-mbstring mcrypt php-pgsql php-curl php-json php-intl php-gd php-xml php-zip php-bz2 php7.4-opcache php-mysql php-xdebug composer php-bcmath php-pear php-dev
+  - sudo pecl channel-update pecl.php.net
+  #- fi
+
+  - sudo php -r "copy('https://install.phpcomposer.com/installer', 'composer-setup.php');"
+  - sudo php composer-setup.php
+  - sudo php -r "unlink('composer-setup.php');"
+  - sudo mv composer.phar /usr/bin/composer
+  # install Oracle Support
+  - phpIni=`php -i|grep "Loaded Configuration File"` && arr=(${phpIni//=>/}) && iniPath=${arr[3]}
+  - sudo sed -i 's/^;\(extension=oci8_12c\)/\1/' ${arr[3]}
+  - sudo wget https://download.oracle.com/otn_software/linux/instantclient/199000/instantclient-basic-linux.x64-19.9.0.0.0dbru.zip
+  - sudo wget https://download.oracle.com/otn_software/linux/instantclient/199000/instantclient-sdk-linux.x64-19.9.0.0.0dbru.zip
+  - sudo unzip instantclient-basic-linux.x64-19.9.0.0.0dbru.zip
+  - sudo unzip instantclient-sdk-linux.x64-19.9.0.0.0dbru.zip
+  - sudo mv instantclient_19_9 /etc -f
+  - sudo rm instantclient-basic-linux.x64-19.9.0.0.0dbru.zip instantclient-sdk-linux.x64-19.9.0.0.0dbru.zip -f
+  #- sudo echo /etc/instantclient_19_9/ > /etc/ld.so.conf.d/oracle-instantclient
+  #- sudo ldconfig
+  - sudo sed '$a\export ORACLE_HOME=/etc/instantclient_19_9\n' /etc/profile -i
+  - source /etc/profile
+  - printf "instantclient,/etc/instantclient_19_9\n" |sudo pecl install oci8
+
+  - fi
+  - composer update
+
+
+
+
+build:
+  stage: build
+  tags:
+    - was
+  script:
+    - echo "build ....."
+
+test:
+  stage: test
+  tags:
+    - was
+  script:
+    - echo "run test....."
+    - vendor/bin/phpunit --testsuite=Unit
+
+deploy:
+  stage: deploy
+  tags:
+    - was
+  script:
+    - echo "deploy ...."

+ 1 - 3
app/Commodity.php

@@ -9,7 +9,7 @@ use App\Traits\ModelTimeFormat;
 class Commodity extends Model
 {
     use ModelTimeFormat;
-    protected $fillable=['name','sku','owner_id','created_at','length','width','height','volumn',"type","pack"];
+    protected $fillable=['name','sku','owner_id','created_at','length','width','height','volumn',"type","pack_spec"];
     protected $appends=['barcode'];
 //    protected $appends=['barcode','owner_name','owner_code'];
 
@@ -36,8 +36,6 @@ class Commodity extends Model
         return $this->owner['code']??'';
     }
 
-
-
     public function newBarcode($barcode){
         $barcodeModel = $this->barcodes()->where('code', $barcode)->first();
         if(!$barcodeModel){

+ 57 - 11
app/Console/Commands/SyncWMSOrderTask.php

@@ -37,23 +37,69 @@ class SyncWMSOrderTask extends Command
      * Execute the console command.
      */
     public function handle()
+    {
+        $this->syncCreatedOrder();
+        $this->syncUpdatedOrder();
+    }
+
+    public function syncCreatedOrder()
     {
         /**
          * @var OracleDOCOrderHeaderService $oracleDOCOrderHeaderService
          * @var OrderService $orderService
          */
-        $oracleDOCOrderHeaderService = app('OracleDOCOrderHeaderService');
+        $newest         = config('sync.order_sync.cache_prefix.created_at');
+        $newest_list    = config('sync.order_sync.cache_prefix.newest_list');
+        $hasKey         = config('sync.order_sync.cache_prefix.newest_has');
+        $prefixKey      = config('sync.order_sync.cache_prefix.newest');
 
         $orderService = app('OrderService');
-        $start_date = Carbon::now()->subSeconds(60+5);
-
-        // 这段时间段内的新增
-        $orderHeaders_addTime = $oracleDOCOrderHeaderService->getWMSOrderOnStartDate($start_date);
-        // 这段时间段内的修改
-        $orderHeaders_editTime = $oracleDOCOrderHeaderService->getWMSOrderOnEditDate($start_date);
-        // 创建
-        $orderService->syncOrder($orderHeaders_addTime);
-        // 创建
-        $orderService->syncOrder($orderHeaders_editTime);
+        $oracleDOCOrderHeaderService = app('OracleDocOrderHeaderService');
+
+        $last_date = $orderService->getOrderSyncAt($newest,'newest');                              // 获取时间点
+        $orderHeaders = $oracleDOCOrderHeaderService->getWMSOrderOnStartDate($last_date);           // WMS订单
+        if(!$orderHeaders)return;
+        $last_order = $orderHeaders->first();                                                           // 时间点靠后的
+        $renewal_orders = $orderHeaders->where('addtime',$last_order->addtime);
+
+        $orderHeaders = $orderService->filterOrderByCache($orderHeaders,$newest_list);                  // 对比缓存
+
+        if(count($orderHeaders)>0 && count($orderHeaders) >0){
+            $orderService->syncOrder($orderHeaders);                                                //  同步订单
+            $orderService->cancelOrderCache($newest_list,$prefixKey);                                   //  清除缓存
+            $orderService->pushOrderCache($renewal_orders,$prefixKey,$hasKey,$newest_list);             //  添加缓存
+            $orderService->setOrderSyncAt($newest,$last_order->addtime,count($orderHeaders)>0);   //  更新时间
+        }
+    }
+
+    public function syncUpdatedOrder()
+    {
+        /**
+         * @var OracleDOCOrderHeaderService $oracleDOCOrderHeaderService
+         * @var OrderService $orderService
+         */
+        $renewal        = config('sync.order_sync.cache_prefix.updated_at');
+        $renewal_list   = config('sync.order_sync.cache_prefix.renewal_list');
+        $hasKey         = config('sync.order_sync.cache_prefix.renewal_has');
+        $prefixKey      = config('sync.order_sync.cache_prefix.renewal');
+
+        $orderService = app('OrderService');
+        $oracleDOCOrderHeaderService = app('OracleDocOrderHeaderService');
+
+        $last_date = $orderService->getOrderSyncAt($renewal,'renewal');                               // 获取时间点
+        $orderHeaders = $oracleDOCOrderHeaderService->getWMSOrderOnEditDate($last_date);                   // WMS订单
+
+        if(!$orderHeaders)return;
+        $renewal_order = $orderHeaders->first();                                                            // 时间点靠后的
+        $renewal_orders =  $orderHeaders->where('edittime',$renewal_order->edittime);
+
+        $orderHeaders = $orderService->filterOrderByCache($orderHeaders,$renewal_list);                     // 对比缓存
+
+        if(count($renewal_orders)>0 && count($orderHeaders)>0){
+            $orderService->syncOrder($orderHeaders);                                                    // 同步订单
+            $orderService->cancelOrderCache($renewal_list,$prefixKey);                                      // 清除缓存
+            $orderService->pushOrderCache($renewal_orders,$prefixKey,$hasKey,$renewal_list);                // 添加缓存
+            $orderService->setOrderSyncAt($renewal,$renewal_order->edittime,count($orderHeaders)>0);   // 更新时间
+        }
     }
 }

+ 1 - 0
app/CustomField.php

@@ -10,6 +10,7 @@ class CustomField extends Model
         'field',
         'present_name',
         'authority_name',
+        'authority_id',
         'condition_field',
         'condition_value'];
 }

+ 12 - 5
app/Http/Controllers/CommodityController.php

@@ -132,6 +132,13 @@ class CommodityController extends Controller
         return view('maintenance.commodity.import');
     }
 
+    public function isExist(Request $request)
+    {
+        if (app('CommodityService')->isExist($request->input()))
+            return ["success"=>true];
+        else return ["success"=>false];
+    }
+
     public function importExcel(Request $request)
     {
         $isOverride = $request->input('isOverride');
@@ -217,7 +224,7 @@ class CommodityController extends Controller
         $commodities = $commodityService->getOwnerCommodities(['owner_id' => $owner_id, 'sku'=>$skus]);
         $updateCommodities = [];
         $updateCommodities[] = [
-            'id', 'sku', 'name', 'length', 'width', 'height', 'volumn',"pack"
+            'id', 'sku', 'name', 'length', 'width', 'height', 'volumn',"pack_spec"
         ];
         $barcodeMap = [];
         $commoditiesId = [];
@@ -229,7 +236,7 @@ class CommodityController extends Controller
             if (($commodity->sku != $trimSku) || ($commodity->length != $wms->skulength)
                 || ($commodity->width != $wms->skuwidth) || ($commodity->name != $wms->descr_c)
                 || ($commodity->height != $wms->skuhigh) || ($commodity->volumn != $wms->cube)
-                || ($commodity->pack === null)){
+                || ($commodity->pack_spec === null)){
                 $updateCommodities[] = [
                     'id'=>$commodity->id,
                     'sku'=>$trimSku,
@@ -238,7 +245,7 @@ class CommodityController extends Controller
                     'width' => $wms->skuwidth,
                     'height' => $wms->skuhigh,
                     'volumn' => $wms->cube,
-                    "pack"  => $wms->packid == 'STANDARD' ? 0 : explode("/",$wms->packid)[1],
+                    "pack_spec"  => $wms->packid == 'STANDARD' ? 0 : explode("/",$wms->packid)[1],
                 ];
             }
             if ($wms->alternate_sku1){
@@ -300,7 +307,7 @@ class CommodityController extends Controller
                 'width' => $wms->skuwidth,
                 'height' => $wms->skuhigh,
                 'volumn' => $wms->cube,
-                "pack"  => $wms->packid == 'STANDARD' ? 0 : explode("/",$wms->packid)[1],
+                "pack_spec"  => $wms->packid == 'STANDARD' ? 0 : explode("/",$wms->packid)[1],
                 "created_at" => $today,
             ];
             $barcodeMap[$wms->sku] = [];
@@ -340,7 +347,7 @@ class CommodityController extends Controller
                             'width' => $goods['width'],
                             'height' => $goods['height'],
                             'volumn' => $goods['volumn'],
-                            "pack" => $goods["pack"],
+                            "pack_spec" => $goods["pack_spec"],
                         ];
                         unset($createCommodities[$barcodeIndex[$code->code]]);
                         break;

+ 262 - 10
app/Http/Controllers/CustomerController.php

@@ -11,7 +11,6 @@ use Exception;
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Http\Request;
 use Illuminate\Http\Response;
-use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Http;
@@ -142,31 +141,284 @@ class CustomerController extends Controller
             "Content-type"=>"application/octet-stream",
             "Content-Disposition"=>"attachment; filename=客户报表-".date('ymdHis').'.xlsx',
         ]);
-        $customers = $service->get(Auth::user(),['customer_id'=>true],['customer']);
-        return response()->view('customer.project.index');
     }
 
     public function projectCreate()
     {
         if(!Gate::allows('客户管理-项目-录入')){ return redirect('denied');  }
-        return response()->view('customer.project.create');
+        $customers = app('CustomerService')->getSelection();
+        $ownerGroups = app('UserOwnerGroupService')->getSelection();
+        $storagePriceModels = app('OwnerStoragePriceModelService')->getSelection(["id","counting_type","using_type","minimum_area","price","unit_id"],["unit"=>function($query){$query->select("id","name");}]);
+        $owner = null;
+        return response()->view('customer.project.create',compact("customers","ownerGroups","storagePriceModels","owner"));
     }
 
-    public function projectArea()
+    public function seekOwner(Request $request)
+    {
+        $params = $request->input();
+        $params["customer_id"] = true;
+        $owner = app('OwnerService')->first($params,["customer_id"=>"null"]);
+        if ($owner)return ["success"=>true,"data"=>$owner];
+        else return ["success"=>false];
+    }
+
+    public function projectStore(Request $request)
+    {
+        if(!Gate::allows('客户管理-项目-录入')){ return redirect('denied');  }
+        $this->validator($request->input())->validate();
+        $params = $request->input();
+        if ($params["id"]){
+            /** @var Owner $owner */
+            $owner = app('OwnerService')->find($params["id"]);
+            app('OwnerService')->update($owner,[
+                "customer_id"           => $params["customer_id"],
+                "tax_rate"              => $params["tax_rate"],
+                "contract_number"       => $params["contract_number"],
+                "salesman"              => $params["salesman"],
+                "linkman"               => $params["linkman"],
+                "phone_number"          => $params["phone_number"],
+                "user_owner_group_id"   => $params["owner_group_id"],
+                "waring_line_on"        => $params["waring_line_on"],
+                "description"           => $params["description"],
+            ],[
+                "ownerStoragePriceModels" => explode(',',$params["owner_storage_price_model_id"])
+            ]);
+            $msg = "成功更新“".$owner->name."”的信息!";
+        }else{
+            $owner = app('OwnerService')->create([
+                "name"                  => $params["name"],
+                "code"                  => $params["code"],
+                "customer_id"           => $params["customer_id"],
+                "tax_rate"              => $params["tax_rate"],
+                "contract_number"       => $params["contract_number"],
+                "salesman"              => $params["salesman"],
+                "linkman"               => $params["linkman"],
+                "phone_number"          => $params["phone_number"],
+                "user_owner_group_id"   => $params["owner_group_id"],
+                "waring_line_on"        => $params["waring_line_on"],
+                "description"           => $params["description"],
+            ],[
+                "ownerStoragePriceModels" => explode(',',$params["owner_storage_price_model_id"])
+            ]);
+            $msg = "成功创建“".$owner->name."”项目!";
+        }
+        return response()->redirectTo('customer/project/index')->with('successTip',$msg);
+    }
+
+    //获取货主下所有相关计费模型
+    public function getOwnerPriceModel(Request $request)
+    {
+        $owner = new Owner();
+        $owner->id = $request->id;
+        $owner->load(["ownerPriceOperations","ownerPriceExpresses","ownerPriceLogistics","ownerPriceDirectLogistics"]);
+        return ["success"=>true,"data"=>["ownerPriceOperations"=>$owner->ownerPriceOperations,
+            "ownerPriceExpresses"=>$owner->ownerPriceExpresses,
+            "ownerPriceLogistics"=>$owner->ownerPriceLogistics,
+            "ownerPriceDirectLogistics"=>$owner->ownerPriceDirectLogistics]];
+    }
+
+    public function projectEdit($id)
+    {
+        if(!Gate::allows('客户管理-项目-编辑')){ return redirect('denied');  }
+        /** @var Owner $owner */
+        $owner = app('OwnerService')->find($id);
+        $owner->owner_storage_price_model_id = $owner->getOwnerStoragePriceModelIds();
+        $customers = app('CustomerService')->getSelection();
+        $ownerGroups = app('UserOwnerGroupService')->getSelection();
+        $storagePriceModels = app('OwnerStoragePriceModelService')->getSelection(["id","counting_type","using_type","minimum_area","price","unit_id"],["unit"=>function($query){$query->select("id","name");}]);
+        return response()->view('customer.project.create',compact("customers","ownerGroups","storagePriceModels",'owner'));
+    }
+
+    public function projectArea(Request $request)
     {
         if(!Gate::allows('客户管理-项目-面积')){ return redirect('denied');  }
-        return response()->view('customer.project.area');
+        $areas = app('OwnerAreaReportService')->paginate($request->input(),["owner"=>function($query){$query->with(["customer","ownerStoragePriceModels"]);}]);
+        $ownerGroups = app('UserOwnerGroupService')->getSelection();
+        $customers = app('CustomerService')->getSelection();
+        $owners = app('OwnerService')->getSelection();
+        $params = $request->input();
+        return response()->view('customer.project.area',compact("areas","ownerGroups","customers","owners","params"));
     }
 
-    public function financeInstantBill()
+    public function updateArea(Request $request)
+    {
+        if(!Gate::allows('客户管理-项目-面积-编辑')){ return ["success"=>false,'data'=>"无权操作!"];  }
+        if (!($request->id ?? false) || !($request->area ?? false)) return ["success"=>false,'data'=>"传递错误!"];
+        $values = $request->area ?? null;
+        if (!$values)return ["success"=>true,"data"=>$values];
+        foreach ($values as $column=>$value){
+            if ($value && (!is_numeric($value) || $value<0))return ["success"=>false,'data'=>$column."非数字或小于0!"];
+        }
+        $accounting_area = ((int)$values["area_on_tray"]*205) + ((int)$values["area_on_half_tray"]*1.8) + ((int)$values["area_on_flat"]*1.3);
+        $values["accounting_area"] = $accounting_area;
+        if (app('OwnerAreaReportService')->update(["id"=>$request->id],$values))
+            return ["success"=>true,"data"=>$values];
+        return ["success"=>false,"data"=>"未知错误!"];
+    }
+
+    public function projectAreaExport(Request $request)
+    {
+        if(!Gate::allows('客户管理-项目-面积')){ return redirect('denied');  }
+        $params = $request->input();
+        if ($request->checkAllSign)unset($params['checkAllSign']);
+        else $params = ["id"=>$request->data];
+        /** @var OwnerAreaReportService $serves */
+        $serves = app('OwnerAreaReportService');
+        $areas = $serves->get($params,["owner"=>function($query){$query->with(["customer","ownerStoragePriceModels","userOwnerGroup"]);}]);
+
+        $column = ["状态","项目组","客户","子项目","结算月","录入时间","用仓类型","货物整托","货物半托","平面区面积","结算面积"];
+        $list = [];
+        foreach ($areas as $area){
+            $list[] = [
+                $area->status,
+                $area->owner ? ($area->owner->userOwnerGroup ? $area->owner->userOwnerGroup->name : '') : '',
+                $area->owner ? ($area->owner->customer ? $area->owner->customer->name : '') : '',
+                $area->owner ? $area->owner->name : '',
+                $area->counting_month,
+                $area->updated_at,
+                $area->owner ? implode(",",array_unique(array_column(($area->owner->ownerStoragePriceModels)->toArray(),"using_type"))) : '',
+                $area->area_on_tray,
+                $area->area_on_half_tray,
+                $area->area_on_flat,
+                $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',
+        ]);
+    }
+
+    public function financeInstantBill(Request $request)
     {
         if(!Gate::allows('客户管理-财务-即时账单')){ return redirect('denied');  }
-        return response()->view('customer.finance.instantBill');
+        $params = $request->input();
+        $shops = app('ShopService')->getSelection();
+        $customers = app('CustomerService')->getSelection();
+        $owners = app('OwnerService')->getSelection();
+        $details = app('OwnerFeeDetailService')->paginate($params,["owner"=>function($query){$query->with("customer");},"shop","processMethod","logistic"]);
+        return response()->view('customer.finance.instantBill',compact("details","params","shops","customers","owners"));
     }
 
-    public function financeBillConfirmation()
+    public function financeInstantBillExport(Request $request)
+    {
+        if(!Gate::allows('客户管理-财务-即时账单')){ return redirect('denied');  }
+        $params = $request->input();
+        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',
+        ]);
+    }
+
+    public function financeBillConfirmation(Request $request)
+    {
+        if(!Gate::allows('客户管理-财务-账单确认')){ return redirect('denied');  }
+        $params = $request->input();
+        $ownerGroups = app('UserOwnerGroupService')->getSelection();
+        $customers = app('CustomerService')->getSelection();
+        $owners = app('OwnerService')->getSelection();
+        $bills = app('OwnerBillReportService')->paginate($params,["owner"=>function($query){
+            /** @var Builder $query */
+            $query->with(["customer","userOwnerGroup"]);
+        }]);
+        return response()->view('customer.finance.billConfirmation',compact("params","owners","ownerGroups","customers","bills"));
+    }
+
+    public function financeBillConfirmationExport(Request $request)
     {
         if(!Gate::allows('客户管理-财务-账单确认')){ return redirect('denied');  }
-        return response()->view('customer.finance.billConfirmation');
+        $params = $request->input();
+        if ($request->checkAllSign)unset($params['checkAllSign']);
+        else $params = ["id"=>$request->data];
+        /** @var OwnerBillReportService $serves */
+        $serves = app('OwnerBillReportService');
+        $bills = $serves->get($params,["owner"=>function($query){
+            /** @var Builder $query */
+            $query->with(["customer","userOwnerGroup"]);
+        }]);
+
+        $column = ["项目小组","客户","子项目","结算月","录入日期","原始账单金额","确认账单金额","差额","状态"];
+        $list = [];
+        foreach ($bills as $bill){
+            $list[] = [
+                $bill->owner ? ($bill->owner->userOwnerGroup ? $bill->owner->userOwnerGroup->name : '') : '',
+                $bill->owner ? ($bill->owner->customer ? $bill->owner->customer->name : '') : '',
+                $bill->owner ? $bill->owner->name : '',
+                $bill->counting_month,
+                $bill->updated_at,
+                $bill->initial_fee,
+                $bill->confirm_fee,
+                $bill->difference,
+                $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',
+        ]);
+    }
+
+    public function updateBillReport(Request $request)
+    {
+        if(!Gate::allows('客户管理-财务-账单确认-编辑')){ return ["success"=>false,'data'=>"无权操作!"];  }
+        if (!$request->confirm_fee || !is_numeric($request->confirm_fee) || $request->confirm_fee<0)return ["success"=>false,"data"=>"非法金额参数"];
+        $date = date('Y-m-d H:i:s');
+        app('OwnerBillReportService')->update(["id"=>$request->id],["confirm_fee"=>$request->confirm_fee,"difference"=>DB::raw($request->confirm_fee.'- initial_fee'),"updated_at"=>$date]);
+        return ["success"=>true,"data"=>$date];
+    }
+
+    public function billConfirm(Request $request)
+    {
+        if(!Gate::allows('客户管理-财务-账单确认-完结')){ return ["success"=>false,'data'=>"无权操作!"];  }
+        if (!($request->id ?? false))return["success"=>false,"data"=>"非法参数"];
+        app('OwnerBillReportService')->update(["id"=>$request->id],["confirmed"=>"是"]);
+        return ["success"=>true];
+    }
+
+    private function validator(array $params){
+        $id = $params['id'] ?? null;
+        $validator=Validator::make($params,[
+            'id' => ['required_without_all:code,name'],
+            'code'=>['required','max:50',$id ? "unique:owners,code,$id":'unique:owners,code'],
+            'name'=>['required','max:50'],
+            'customer_id'=>['required'],
+            'owner_group_id'=>['required'],
+            'tax_rate' => ['required','numeric'],
+        ],[
+            'required'=>':attribute 为必填项',
+            'unique'=>':attribute 已存在',
+        ],[
+            'code'=>'项目代码',
+            'name'=>'项目名称',
+            'customer_id'=>'客户',
+            'owner_group_id'=>'工作组',
+            'tax_rate' => '税率'
+        ]);
+        return $validator;
     }
 }

+ 361 - 250
app/Http/Controllers/InventoryAccountController.php

@@ -19,322 +19,433 @@ class InventoryAccountController extends Controller
 {
     public function __construct()
     {
-        app()->singleton('inventoryAccountService',InventoryAccountService::class);
+        app()->singleton('inventoryAccountService', InventoryAccountService::class);
     }
 
     //创建盘点任务
-    public function createStockInventoryMission(Request $request){
-        if(!Gate::allows("库存管理-盘点")){ return redirect(url('/'));  }
+    public function createStockInventoryMission(Request $request)
+    {
+        if (!Gate::allows("库存管理-盘点")) {
+            return redirect(url('/'));
+        }
 //        $date_start=$request->input('formData.date_start');
 //        $date_end=$request->input('formData.date_end');
 //        $ownerId=$request->input('formData.owner_id')[0];
-        $date_start=$request->input('date_start');
-        $date_end=$request->input('date_end');
-        $ownerId=$request->input('owner_id');
-        $location=$request->input('location');
-        $barcode=$request->input('barcode');
-        $inventoryAccount=app('inventoryAccountService')->createMission($date_start,$date_end,$ownerId,$location,$barcode);
-        $inventoryAccount=InventoryAccount::with('owner')->find($inventoryAccount->id);
-        if (is_null($inventoryAccount)) return ['success'=>false,'data'=>'参数错误!'];
-        return ['success'=>true,'data'=>$inventoryAccount];
+        $date_start = $request->input('date_start');
+        $date_end = $request->input('date_end');
+        $ownerId = $request->input('owner_id');
+        $location = $request->input('location');
+        $barcode = $request->input('barcode');
+        $inventoryAccount = app('inventoryAccountService')->createMission($date_start, $date_end, $ownerId, $location, $barcode);
+        $inventoryAccount = InventoryAccount::with('owner')->find($inventoryAccount->id);
+        if (is_null($inventoryAccount)) return ['success' => false, 'data' => '参数错误!'];
+        return ['success' => true, 'data' => $inventoryAccount];
     }
+
     //删除盘点任务
-    public function deleteStockInventoryMission($id){
-        if(!Gate::allows('库存管理-盘点')){return['success'=>0,'status'=>'没有权限'];}
-        if(is_null($id)){return ['success'=>false,'data'=>'传入id为空'];}
-        $inventoryAccount=InventoryAccount::where('id',$id)->delete();
-        return ['success'=>true,'data'=>$inventoryAccount];
+    public function deleteStockInventoryMission($id)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return ['success' => 0, 'status' => '没有权限'];
+        }
+        if (is_null($id)) {
+            return ['success' => false, 'data' => '传入id为空'];
+        }
+        $inventoryAccount = InventoryAccount::where('id', $id)->delete();
+        return ['success' => true, 'data' => $inventoryAccount];
     }
-    public function inventoryChecked(Request $request){
-        if(!Gate::allows('库存管理-盘点-项目审核')){return['success'=>false,'msg'=>'没有权限'];}
-        $id=$request->id;
-        if(is_null($id)){return ['success'=>false,'msg'=>'传入id为空'];}
-        $inventoryAccount=InventoryAccount::query()->where('id',$id)->update([
-            'auditor'=>Auth::user()['id'],
-            'status'=>'已审核',
+
+    public function inventoryChecked(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点-项目审核')) {
+            return ['success' => false, 'msg' => '没有权限'];
+        }
+        $id = $request->id;
+        if (is_null($id)) {
+            return ['success' => false, 'msg' => '传入id为空'];
+        }
+        $inventoryAccount = InventoryAccount::query()->where('id', $id)->update([
+            'auditor' => Auth::user()['id'],
+            'status' => '已审核',
         ]);
-        if ($inventoryAccount==1) {
-            $inventoryAccount=InventoryAccount::query()->with('userAuditor')->find($id);
-            return ['success'=>true,'data'=>$inventoryAccount];
-        }else{
-            return ['success'=>false,'msg'=>'审核失败!'];
+        if ($inventoryAccount == 1) {
+            $inventoryAccount = InventoryAccount::query()->with('userAuditor')->find($id);
+            return ['success' => true, 'data' => $inventoryAccount];
+        } else {
+            return ['success' => false, 'msg' => '审核失败!'];
         }
     }
 
     //盘点-任务页面
-    public function mission(Request $request,OwnerService $ownerService){
-        if(!Gate::allows("库存管理-盘点")){ return redirect(url('/'));  }
+    public function mission(Request $request, OwnerService $ownerService)
+    {
+        if (!Gate::allows("库存管理-盘点")) {
+            return redirect(url('/'));
+        }
         $paginateParams = $request->input();
-        $queryParam=$request->all();
-        $inventoryAccounts=app('inventoryAccountService')->paginate($queryParam);
-        $owners=$ownerService->getSelection();
-        return view('inventory.stockInventory.mission',compact('owners','inventoryAccounts','paginateParams'));
+        $queryParam = $request->all();
+        $inventoryAccounts = app('inventoryAccountService')->paginate($queryParam);
+        $owners = $ownerService->getSelection();
+        return view('inventory.stockInventory.mission', compact('owners', 'inventoryAccounts', 'paginateParams'));
     }
+
     //进入盘点中或复盘页面
-    public function enterStockInventory($id,Request $request){
-        if (!Gate::allows('库存管理-盘点')){return redirect(url('/')); }
-        if (!$id) return ['success'=>false,'data'=>'参数错误!'];
-        $inventoryAccount=InventoryAccount::with('owner')->find($id);
-        $inventoryAccountMissions=InventoryAccountMission::with(['commodity.barcodes','stockInventoryPersons'])->where('inventory_account_id',$id)->orderBy('difference_amount','desc')->get();
-        return view('inventory.stockInventory.inventoryMission',compact('inventoryAccount','inventoryAccountMissions'));
+    public function enterStockInventory($id, Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return redirect(url('/'));
+        }
+        if (!$id) return ['success' => false, 'data' => '参数错误!'];
+        $inventoryAccount = InventoryAccount::with('owner')->find($id);
+        $inventoryAccountMissions = InventoryAccountMission::with(['commodity.barcodes', 'stockInventoryPersons'])->where('inventory_account_id', $id)->orderBy('difference_amount', 'desc')->get();
+        return view('inventory.stockInventory.inventoryMission', compact('inventoryAccount', 'inventoryAccountMissions'));
     }
-    public function enterBlindReceive($id){
-        if (!Gate::allows('库存管理-盘点')){return redirect(url('/')); }
-        if (!$id) return ['success'=>false,'data'=>'参数错误!'];
-        $inventoryAccount=InventoryAccount::with('owner')->find($id);
-        return view('inventory.stockInventory.blindReceive',compact('inventoryAccount'));
+
+    public function enterBlindReceive($id)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return redirect(url('/'));
+        }
+        if (!$id) return ['success' => false, 'data' => '参数错误!'];
+        $inventoryAccount = InventoryAccount::with('owner')->find($id);
+        return view('inventory.stockInventory.blindReceive', compact('inventoryAccount'));
     }
+
     //依据盘点任务id进行 --盘点
-    public function stockInventory(Request $request){
-        if (!Gate::allows('库存管理-盘点')){return redirect(url('/')); }
-        $location=$request->input('location');
-        $barcode=$request->input('barcode');
-        $inventoryId=$request->input('inventoryId');
-        $count=$request->input('count');
-        $id=$request->input('id');
-        if (is_null($count)) return ['success'=>false,'data'=>'盘点数不能为空!'];
-        /** @var InventoryAccountService $inventoryAccountMission */
-        $inventoryAccountService=app('inventoryAccountService');
-        $inventoryAccountMission=$inventoryAccountService->stockInventory($id,$location,$barcode,$count,$inventoryId);
-        if (!$inventoryAccountMission)return ['success'=>false,'data'=>'参数错误!'];
+    public function stockInventory(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return redirect(url('/'));
+        }
+        $location = $request->input('location');
+        $barcode = $request->input('barcode');
+        $inventoryId = $request->input('inventoryId');
+        $count = $request->input('count');
+        $id = $request->input('id');
+        if (is_null($count)) return ['success' => false, 'data' => '盘点数不能为空!'];
+        /** @var InventoryAccountService $inventoryAccountService */
+        $inventoryAccountService = app('inventoryAccountService');
+        $inventoryAccountMission = $inventoryAccountService->stockInventory($id, $location, $barcode, $count, $inventoryId);
+        if (!$inventoryAccountMission) return ['success' => false, 'data' => '参数错误!'];
         /** @var InventoryAccountService $inventoryService */
-        $inventoryService=app('inventoryAccountService');
-        $inventoryAccount=$inventoryService->updateInventory($inventoryId);
-        $stockInventoryPersons=$inventoryAccountMission->stockInventoryPersons;
-        return ['success'=>true,'inventoryMission'=>$inventoryAccountMission,'inventory'=>$inventoryAccount,'stockInventoryPersons'=>$stockInventoryPersons];
+        $inventoryService = app('inventoryAccountService');
+        $inventoryAccount = $inventoryService->updateInventory($inventoryId);
+        $stockInventoryPersons = $inventoryAccountMission->stockInventoryPersons;
+        return ['success' => true, 'inventoryMission' => $inventoryAccountMission, 'inventory' => $inventoryAccount, 'stockInventoryPersons' => $stockInventoryPersons];
     }
-    public function baseOnBlindReceive(Request $request){
-        if (!Gate::allows('库存管理-盘点')){return redirect(url('/')); }
-        $location=$request->input('location');
-        $inventoryId=$request->input('inventoryId');
-        $owner_code=$request->input('owner_code');
-        $goodses=$request->input('goodses');
-        if (!$location) return ['success'=>false,'fail_info'=>'盘点库位不存在!'];
-        if (count($goodses)<1) return ['success'=>false,'fail_info'=>'盘点商品不存在!'];
+
+    public function baseOnBlindReceive(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return redirect(url('/'));
+        }
+        $location = $request->input('location');
+        $inventoryId = $request->input('inventoryId');
+        $owner_code = $request->input('owner_code');
+        $goodses = $request->input('goodses');
+        if (!$location) return ['success' => false, 'fail_info' => '盘点库位不存在!'];
+        if (count($goodses) < 1) return ['success' => false, 'fail_info' => '盘点商品不存在!'];
         //dd($location,$owner_code,$goodses,$inventoryId,$owner_id);
         /** @var InventoryAccountService $inventoryAccountMission */
-        $inventoryAccountService=app('inventoryAccountService');
-        $inventoryAccountMissions=$inventoryAccountService->baseOnBlindReceive($location,$owner_code,$goodses,$inventoryId);
-        if (count($inventoryAccountMissions)<0)return ['success'=>false,'fail_info'=>'盲收盘点失败!'];
+        $inventoryAccountService = app('inventoryAccountService');
+        $inventoryAccountMissions = $inventoryAccountService->baseOnBlindReceive($location, $owner_code, $goodses, $inventoryId);
+        if (count($inventoryAccountMissions) < 0) return ['success' => false, 'fail_info' => '盲收盘点失败!'];
         /** @var InventoryAccountService $inventoryService */
-        $inventoryService=app('inventoryAccountService');
-        $inventoryAccount=$inventoryService->updateInventory($inventoryId);
-        if ($inventoryAccountMissions&&$inventoryAccount)
-        $stockInventoryPersons=$inventoryAccountMissions[0]->stockInventoryPersons;
-        return ['success'=>true,'inventoryMissions'=>$inventoryAccountMissions,'inventory'=>$inventoryAccount,'stockInventoryPersons'=>$stockInventoryPersons];
+        $inventoryService = app('inventoryAccountService');
+        $inventoryAccount = $inventoryService->updateInventory($inventoryId);
+        if ($inventoryAccountMissions && $inventoryAccount)
+            $stockInventoryPersons = $inventoryAccountMissions[0]->stockInventoryPersons;
+        return ['success' => true, 'inventoryMissions' => $inventoryAccountMissions, 'inventory' => $inventoryAccount, 'stockInventoryPersons' => $stockInventoryPersons];
     }
+
     //根据该库存和产品条码查询该条盘点记录??
-    public function searchStockInventoryRecord(Request $request){
-        if (!Gate::allows('库存管理-盘点')){return redirect(url('/')); }
-        $location=$request->input('location');
-        $barcode=$request->input('barcode');
-        $inventoryId=$request->input('inventoryId');
+    public function searchStockInventoryRecord(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return redirect(url('/'));
+        }
+        $location = $request->input('location');
+        $barcode = $request->input('barcode');
+        $inventoryId = $request->input('inventoryId');
         /** @var InventoryAccountService $application */
         $application = app('inventoryAccountService');
-        $inventoryAccountMissions= $application->searchStockInventoryRecord($location,$barcode,$inventoryId);
-        if ($inventoryAccountMissions->isEmpty())return ['success'=>false,'data'=>'没有找到相应记录!'];
+        $inventoryAccountMissions = $application->searchStockInventoryRecord($location, $barcode, $inventoryId);
+        if ($inventoryAccountMissions->isEmpty()) return ['success' => false, 'data' => '没有找到相应记录!'];
 //        $stockInventoryPersons=$inventoryAccountMissions->stockInventoryPersons;
 //        return ['success'=>true,'data'=>$inventoryAccountMissions,'stockInventoryPersons'=>$stockInventoryPersons];
-        return ['success'=>true,'data'=>$inventoryAccountMissions];
+        return ['success' => true, 'data' => $inventoryAccountMissions];
     }
 
     //盘点任务导出
-    public function stockInventoryExport(Request $request){
-        if (!Gate::allows('库存管理-盘点')){return redirect(url('/')); }
-        ini_set('max_execution_time',3500);
-        ini_set('memory_limit','3526M');
-        if ($request->checkAllSign){
+    public function stockInventoryExport(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return redirect(url('/'));
+        }
+        ini_set('max_execution_time', 3500);
+        ini_set('memory_limit', '3526M');
+        if ($request->checkAllSign) {
             $request->offsetUnset('checkAllSign');
-            $queryParam=$request->all();
-            $inventoryAccounts=app('inventoryAccountService')->get($queryParam);
-        }else{
-            $queryParam=$request->all();
-            $inventoryAccounts=app('inventoryAccountService')->some($queryParam);
-        }
-        $row=[[
-            'id'=>'盘点编号',
-            'status'=>'盘点状态',
-            'created_at'=>'创建时间',
-            'owner_id'=>'货主',
-            'type'=>'任务类型',
-            'start_at'=>'起始时间',
-            'end_at'=>'结束时间',
-            'total'=>'记录数',
-            'processed'=>'已盘数',
-            'surplus'=>'剩余数',
-            'difference'=>'复盘差异',
-            'returned'=>'复盘归位',
+            $queryParam = $request->all();
+            $inventoryAccounts = app('inventoryAccountService')->get($queryParam);
+        } else {
+            $queryParam = $request->all();
+            $inventoryAccounts = app('inventoryAccountService')->some($queryParam);
+        }
+        $row = [[
+            'id' => '盘点编号',
+            'status' => '盘点状态',
+            'created_at' => '创建时间',
+            'owner_id' => '货主',
+            'type' => '任务类型',
+            'start_at' => '起始时间',
+            'end_at' => '结束时间',
+            'total' => '记录数',
+            'processed' => '已盘数',
+            'surplus' => '剩余数',
+            'difference' => '复盘差异',
+            'returned' => '复盘归位',
         ]];
-        $list=[];
-        for ($i=0; $i<count($inventoryAccounts);$i++){
-            $inventoryAccount=$inventoryAccounts[$i];
-            $w=[
-                'id'=>isset($inventoryAccount->id)?$inventoryAccount->id:'',
-                'status'=>isset($inventoryAccount->status)?$inventoryAccount->status:'',
-                'created_at'=>isset($inventoryAccount->created_at)?$inventoryAccount->created_at:'',
-                'owner_id'=>isset($inventoryAccount->owner->name)?$inventoryAccount->owner->name:'',
-                'type'=>isset($inventoryAccount->type)?$inventoryAccount->type:'',
-                'start_at'=>isset($inventoryAccount->start_at)?$inventoryAccount->start_at:'',
-                'end_at'=>isset($inventoryAccount->end_at)?$inventoryAccount->end_at:'',
-                'total'=>isset($inventoryAccount->total)?$inventoryAccount->total:'',
-                'processed'=>isset($inventoryAccount->processed)?$inventoryAccount->processed:'',
-                'surplus'=>isset($inventoryAccount->surplus)?$inventoryAccount->surplus:'',
-                'difference'=>isset($inventoryAccount->difference)?$inventoryAccount->difference:'',
-                'returned'=>isset($inventoryAccount->returned)?$inventoryAccount->returned:'',
+        $list = [];
+        for ($i = 0; $i < count($inventoryAccounts); $i++) {
+            $inventoryAccount = $inventoryAccounts[$i];
+            $w = [
+                'id' => isset($inventoryAccount->id) ? $inventoryAccount->id : '',
+                'status' => isset($inventoryAccount->status) ? $inventoryAccount->status : '',
+                'created_at' => isset($inventoryAccount->created_at) ? $inventoryAccount->created_at : '',
+                'owner_id' => isset($inventoryAccount->owner->name) ? $inventoryAccount->owner->name : '',
+                'type' => isset($inventoryAccount->type) ? $inventoryAccount->type : '',
+                'start_at' => isset($inventoryAccount->start_at) ? $inventoryAccount->start_at : '',
+                'end_at' => isset($inventoryAccount->end_at) ? $inventoryAccount->end_at : '',
+                'total' => isset($inventoryAccount->total) ? $inventoryAccount->total : '',
+                'processed' => isset($inventoryAccount->processed) ? $inventoryAccount->processed : '',
+                'surplus' => isset($inventoryAccount->surplus) ? $inventoryAccount->surplus : '',
+                'difference' => isset($inventoryAccount->difference) ? $inventoryAccount->difference : '',
+                'returned' => isset($inventoryAccount->returned) ? $inventoryAccount->returned : '',
             ];
-            $list[$i]=$w;
+            $list[$i] = $w;
         }
-        return Excel::download(new Export($row,$list),date('YmdHis', time()).'-盘点任务记录单.xlsx');
+        return Excel::download(new Export($row, $list), date('YmdHis', time()) . '-盘点任务记录单.xlsx');
     }
-    public function stockInventoryEnd(Request $request){
-        if (!Gate::allows('库存管理-盘点-结束初盘')){return ['success'=>false,'data'=>'没有权限']; }
-        $id=$request->input('id');
-        if (!$id) return ['success'=>false,'data'=>'参数错误!'];
-        $inventoryAccount=InventoryAccount::query()->where('id',$id)->update(['status'=>'复盘中']);
-        app('LogService')->log(__METHOD__,'结束初盘任务'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
-        if ($inventoryAccount>0) return ['success'=>true,'data'=>'复盘中'];
-        return ['success'=>false,'data'=>'参数错误!'];
+
+    public function stockInventoryEnd(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点-结束初盘')) {
+            return ['success' => false, 'data' => '没有权限'];
+        }
+        $id = $request->input('id');
+        if (!$id) return ['success' => false, 'data' => '参数错误!'];
+        $inventoryAccount = InventoryAccount::query()->where('id', $id)->update(['status' => '复盘中']);
+        app('LogService')->log(__METHOD__, '结束初盘任务' . __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
+        if ($inventoryAccount > 0) return ['success' => true, 'data' => '复盘中'];
+        return ['success' => false, 'data' => '参数错误!'];
     }
-    public function syncOwners(OwnerService $ownerService){
-        if (!Gate::allows('库存管理-盘点')){return redirect(url('/')); }
-        $owners=$ownerService->syncOwnersData();
-        if (!$owners)return ['success'=>false,'data'=>'同步货主失败!'];
-        return ['success'=>true,'data'=>$owners];
+
+    public function syncOwners(OwnerService $ownerService)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return redirect(url('/'));
+        }
+        $owners = $ownerService->syncOwnersData();
+        if (!$owners) return ['success' => false, 'data' => '同步货主失败!'];
+        return ['success' => true, 'data' => $owners];
     }
-    public function 修改质量状态(Request $request){
-        if (!Gate::allows('库存管理-盘点')){return redirect(url('/')); }
-        $id=$request->input('id');
-        $location=$request->location;
-        $sku=$request->sku;
-        $quality=$request->quality;
-        $ownerCode=$request->ownerCode;
-        $inventoryAccountMission=app('inventoryAccountService')->修改质量状态($id,$location,$sku,$quality,$ownerCode);
-        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
-        if ($inventoryAccountMission==null) return ['success'=>false,'data'=>'WMS中不存在该条记录!'];
-        return ['success'=>true,'data'=>'质量状态修改成功'];
+
+    public function 修改质量状态(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return redirect(url('/'));
+        }
+        $id = $request->input('id');
+        $location = $request->location;
+        $sku = $request->sku;
+        $quality = $request->quality;
+        $ownerCode = $request->ownerCode;
+        $inventoryAccountMission = app('inventoryAccountService')->修改质量状态($id, $location, $sku, $quality, $ownerCode);
+        app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
+        if ($inventoryAccountMission == null) return ['success' => false, 'data' => 'WMS中不存在该条记录!'];
+        return ['success' => true, 'data' => '质量状态修改成功'];
 
     }
-    public function 完结盘点任务($id){
-        if(!Gate::allows('库存管理-盘点-完结')){return['success'=>false,'status'=>'没有权限'];}
-        if (!$id)return['success'=>false,'status'=>'参数错误!'];
-        $inventoryAccount=app('inventoryAccountService')->完结盘点任务($id);
-        if (!$inventoryAccount)return['success'=>false,'status'=>'修改完结状态失败!'];
-        return['success'=>true,'data'=>$inventoryAccount];
+
+    public function 完结盘点任务($id)
+    {
+        if (!Gate::allows('库存管理-盘点-完结')) {
+            return ['success' => false, 'status' => '没有权限'];
+        }
+        if (!$id) return ['success' => false, 'status' => '参数错误!'];
+        $inventoryAccount = app('inventoryAccountService')->完结盘点任务($id);
+        if (!$inventoryAccount) return ['success' => false, 'status' => '修改完结状态失败!'];
+        return ['success' => true, 'data' => $inventoryAccount];
 
     }
-    public function 增加系统之外的盘点记录(Request $request){
-        if(!Gate::allows('库存管理-盘点')){return['success'=>false,'data'=>'没有权限'];}
-        $location=$request->input('location');
-        $barcode=$request->input('barcode');
-        $inventoryId=$request->input('inventoryId');
-        $count=$request->input('count');
-        $owner_code=$request->input('owner_code');
-        $param=$request->input('param');
-        if (is_null($count)) return ['success'=>false,'data'=>'盘点数不能为空!'];
-        $inventoryAccountMission=app('inventoryAccountService')->增加系统之外的盘点记录($location,$barcode,$inventoryId,$count,$owner_code,$param);
-        if (!$inventoryAccountMission)return ['success'=>false,'data'=>'添加系统之外的库位记录失败!'];
-        $inventoryAccountMission=InventoryAccountMission::with(['commodity.barcodes','stockInventoryPersons'])->where('id',$inventoryAccountMission->id)->first();
-        $stockInventoryPersons=$inventoryAccountMission->stockInventoryPersons;
-        return ['success'=>true,'inventoryAccountMission'=>$inventoryAccountMission,'stockInventoryPersons'=>$stockInventoryPersons];
+
+    public function 增加系统之外的盘点记录(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return ['success' => false, 'data' => '没有权限'];
+        }
+        $location = $request->input('location');
+        $barcode = $request->input('barcode');
+        $inventoryId = $request->input('inventoryId');
+        $count = $request->input('count');
+        $owner_code = $request->input('owner_code');
+        $param = $request->input('param');
+        if (is_null($count)) return ['success' => false, 'data' => '盘点数不能为空!'];
+        $inventoryAccountMission = app('inventoryAccountService')->增加系统之外的盘点记录($location, $barcode, $inventoryId, $count, $owner_code, $param);
+        if (!$inventoryAccountMission) return ['success' => false, 'data' => '添加系统之外的库位记录失败!'];
+        $inventoryAccountMission = InventoryAccountMission::with(['commodity.barcodes', 'stockInventoryPersons'])->where('id', $inventoryAccountMission->id)->first();
+        $stockInventoryPersons = $inventoryAccountMission->stockInventoryPersons;
+        return ['success' => true, 'inventoryAccountMission' => $inventoryAccountMission, 'stockInventoryPersons' => $stockInventoryPersons];
     }
-    public function 盘点选中任务(Request $request){
-        if(!Gate::allows('库存管理-盘点')){return['success'=>false,'data'=>'没有权限'];}
-        $id=$request->input('id');
-        $count=$request->count;
-        $inventoryId=$request->input('inventoryId');
-        $produced_at=$request->input('produced_at');
-        $valid_at=$request->input('valid_at');
-        $batch_number=$request->input('batch_number');
-        if (is_null($count)) return ['success'=>false,'data'=>'盘点数不能为空!'];
-        if ($produced_at||$valid_at||$batch_number){
+
+    public function 盘点选中任务(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return ['success' => false, 'data' => '没有权限'];
+        }
+        $id = $request->input('id');
+        $count = $request->count;
+        $inventoryId = $request->input('inventoryId');
+        $produced_at = $request->input('produced_at');
+        $valid_at = $request->input('valid_at');
+        $batch_number = $request->input('batch_number');
+        if (is_null($count)) return ['success' => false, 'data' => '盘点数不能为空!'];
+        if ($produced_at || $valid_at || $batch_number) {
             /** @var InventoryAccountService $inventoryAccountMission */
-            $inventoryAccountService=app('inventoryAccountService');
-            $inventoryAccountMission=$inventoryAccountService ->盘点生产日期_失效日期_批号有改动任务($id,$count,$inventoryId,$produced_at,$valid_at,$batch_number);
-            if (!$inventoryAccountMission)return ['success'=>false,'data'=>'盘点生产日期_失效日期_批号有改动任务失败!'];
+            $inventoryAccountService = app('inventoryAccountService');
+            $inventoryAccountMission = $inventoryAccountService->盘点生产日期_失效日期_批号有改动任务($id, $count, $inventoryId, $produced_at, $valid_at, $batch_number);
+            if (!$inventoryAccountMission) return ['success' => false, 'data' => '盘点生产日期_失效日期_批号有改动任务失败!'];
             /** @var InventoryAccountService $inventoryService */
-            $inventoryService=app('inventoryAccountService');
-            $inventoryAccount=$inventoryService->updateInventory($inventoryId);
-            $stockInventoryPersons=$inventoryAccountMission[0]->stockInventoryPersons;
-            return ['success'=>true,'inventoryMission'=>$inventoryAccountMission,'inventory'=>$inventoryAccount,'stockInventoryPersons'=>$stockInventoryPersons];
-        }else{
+            $inventoryService = app('inventoryAccountService');
+            $inventoryAccount = $inventoryService->updateInventory($inventoryId);
+            $stockInventoryPersons = $inventoryAccountMission[0]->stockInventoryPersons;
+            return ['success' => true, 'inventoryMission' => $inventoryAccountMission, 'inventory' => $inventoryAccount, 'stockInventoryPersons' => $stockInventoryPersons];
+        } else {
             /** @var InventoryAccountService $inventoryAccountMission */
-            $inventoryAccountService=app('inventoryAccountService');
-            $inventoryAccountMission=$inventoryAccountService ->盘点选中任务($id,$count,$inventoryId);
-            if (!$inventoryAccountMission)return ['success'=>false,'data'=>'盘点选中任务失败!'];
+            $inventoryAccountService = app('inventoryAccountService');
+            $inventoryAccountMission = $inventoryAccountService->盘点选中任务($id, $count, $inventoryId);
+            if (!$inventoryAccountMission) return ['success' => false, 'data' => '盘点选中任务失败!'];
             /** @var InventoryAccountService $inventoryService */
-            $inventoryService=app('inventoryAccountService');
-            $inventoryAccount=$inventoryService->updateInventory($inventoryId);
-            $stockInventoryPersons=$inventoryAccountMission->stockInventoryPersons;
-            return ['success'=>true,'inventoryMission'=>$inventoryAccountMission,'inventory'=>$inventoryAccount,'stockInventoryPersons'=>$stockInventoryPersons];
+            $inventoryService = app('inventoryAccountService');
+            $inventoryAccount = $inventoryService->updateInventory($inventoryId);
+            $stockInventoryPersons = $inventoryAccountMission->stockInventoryPersons;
+            return ['success' => true, 'inventoryMission' => $inventoryAccountMission, 'inventory' => $inventoryAccount, 'stockInventoryPersons' => $stockInventoryPersons];
         }
     }
 
-    public function 删除盘点记录(Request $request){
-        if(!Gate::allows('库存管理-盘点-删除')){return['success'=>false,'data'=>'没有权限'];}
-        $inventoryAccountMissionId=$request->input('inventoryAccountMissionId');
-        $inventoryAccountId=$request->input('inventoryAccountId');
-        if(is_null($inventoryAccountMissionId)){return ['success'=>false,'data'=>'传入id为空'];}
+    public function 删除盘点记录(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点-删除')) {
+            return ['success' => false, 'data' => '没有权限'];
+        }
+        $inventoryAccountMissionId = $request->input('inventoryAccountMissionId');
+        $inventoryAccountId = $request->input('inventoryAccountId');
+        if (is_null($inventoryAccountMissionId)) {
+            return ['success' => false, 'data' => '传入id为空'];
+        }
         /** @var InventoryAccountService $inventoryService */
-        $inventoryService=app('inventoryAccountService');
-        $inventoryAccountMission=$inventoryService->删除盘点记录($inventoryAccountMissionId,$inventoryAccountId);
-        return ['success'=>true,'data'=>$inventoryAccountMission];
+        $inventoryService = app('inventoryAccountService');
+        $inventoryAccountMission = $inventoryService->删除盘点记录($inventoryAccountMissionId, $inventoryAccountId);
+        return ['success' => true, 'data' => $inventoryAccountMission];
     }
-    public function 跳过盘点记录(Request $request){
-        if(!Gate::allows('库存管理-盘点')){return['success'=>false,'data'=>'没有权限'];}
-        $inventoryAccountMissionId=$request->inventoryAccountMissionId;
-        $inventoryAccountId=$request->input('inventoryAccountId');
-        if(is_null($inventoryAccountMissionId)){return ['success'=>false,'data'=>'传入id为空'];}
+
+    public function 跳过盘点记录(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return ['success' => false, 'data' => '没有权限'];
+        }
+        $inventoryAccountMissionId = $request->inventoryAccountMissionId;
+        $inventoryAccountId = $request->input('inventoryAccountId');
+        if (is_null($inventoryAccountMissionId)) {
+            return ['success' => false, 'data' => '传入id为空'];
+        }
         /** @var InventoryAccountService $inventoryService */
-        $inventoryService=app('inventoryAccountService');
-        $inventoryAccountMission=$inventoryService->跳过盘点记录($inventoryAccountMissionId,$inventoryAccountId);
-        return ['success'=>true,'inventoryAccountMission'=>$inventoryAccountMission];
+        $inventoryService = app('inventoryAccountService');
+        $inventoryAccountMission = $inventoryService->跳过盘点记录($inventoryAccountMissionId, $inventoryAccountId);
+        return ['success' => true, 'inventoryAccountMission' => $inventoryAccountMission];
     }
-    public function 确认盘点差异(Request $request){
-        if(!Gate::allows('库存管理-盘点')){return['success'=>false,'data'=>'没有权限'];}
-        $inventoryAccountMissionId=$request->inventoryAccountMissionId;
-        $inventoryAccountId=$request->input('inventoryAccountId');
-        if(is_null($inventoryAccountMissionId)){return ['success'=>false,'data'=>'传入id为空'];}
+
+    public function 确认盘点差异(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return ['success' => false, 'data' => '没有权限'];
+        }
+        $inventoryAccountMissionId = $request->inventoryAccountMissionId;
+        $inventoryAccountId = $request->input('inventoryAccountId');
+        if (is_null($inventoryAccountMissionId)) {
+            return ['success' => false, 'data' => '传入id为空'];
+        }
         /** @var InventoryAccountService $inventoryService */
-        $inventoryService=app('inventoryAccountService');
-        $inventoryAccountMission=$inventoryService->确认盘点差异($inventoryAccountMissionId,$inventoryAccountId);
-        return ['success'=>true,'inventoryAccountMission'=>$inventoryAccountMission];
+        $inventoryService = app('inventoryAccountService');
+        $inventoryAccountMission = $inventoryService->确认盘点差异($inventoryAccountMissionId, $inventoryAccountId);
+        return ['success' => true, 'inventoryAccountMission' => $inventoryAccountMission];
     }
-    public function 批量跳过或确认差异(Request $request){
-        if(!Gate::allows('库存管理-盘点')){return['success'=>false,'data'=>'没有权限'];}
-        $checkData=$request->checkData;
-        if(is_null($checkData)){return ['success'=>false,'data'=>'传入勾选盘点记录为空'];}
-        $marks=[];
-        foreach ($checkData as $inventoryMission){
-            array_push($marks,$inventoryMission['mark']);
-        }
-        if (in_array('确认差异',$marks)||in_array('跳过',$marks)||in_array('无差异',$marks)||in_array('已复盘无差异',$marks))return ['success'=>false,'data'=>'传入勾选盘点记录存在不可操作项!'];
+
+    public function 批量跳过或确认差异(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return ['success' => false, 'data' => '没有权限'];
+        }
+        $checkData = $request->checkData;
+        if (is_null($checkData)) {
+            return ['success' => false, 'data' => '传入勾选盘点记录为空'];
+        }
+        $marks = [];
+        foreach ($checkData as $inventoryMission) {
+            array_push($marks, $inventoryMission['mark']);
+        }
+        if (in_array('确认差异', $marks) || in_array('跳过', $marks) || in_array('无差异', $marks) || in_array('已复盘无差异', $marks)) return ['success' => false, 'data' => '传入勾选盘点记录存在不可操作项!'];
         /** @var InventoryAccountService $inventoryService */
-        $inventoryService=app('inventoryAccountService');
-        $inventoryAccountMissions=$inventoryService->批量跳过或确认差异($checkData);
-        return ['success'=>true,'inventoryAccountMissions'=>$inventoryAccountMissions];
+        $inventoryService = app('inventoryAccountService');
+        $inventoryAccountMissions = $inventoryService->批量跳过或确认差异($checkData);
+        return ['success' => true, 'inventoryAccountMissions' => $inventoryAccountMissions];
     }
-    public function exportInventoryAccountMission(Request $request){
-        if(!Gate::allows("库存管理-盘点")){ return redirect(url('/'));  }
-        $post = Http::post(config('go.export.url'),['type'=>'inventoryAccountMission','data'=>$request->data]);
-        if ($post->status() == 500){
+
+    public function exportInventoryAccountMission(Request $request)
+    {
+        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"));
         }
-        return response($post,200, [
-            "Content-type"=>"application/octet-stream",
-            "Content-Disposition"=>"attachment; filename=库存盘点记录-".date('ymdHis').'.xlsx',
+        return response($post, 200, [
+            "Content-type" => "application/octet-stream",
+            "Content-Disposition" => "attachment; filename=库存盘点记录-" . date('ymdHis') . '.xlsx',
         ]);
     }
-    public function searchCommodityByBarcode(Request $request){
-        if(!Gate::allows('库存管理-盘点')){return['success'=>false,'data'=>'没有权限'];}
-        $barcode=$request->input('barcode');
-        $owner_code=$request->input('owner_code');
+
+    public function searchCommodityByBarcode(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) {
+            return ['success' => false, 'data' => '没有权限'];
+        }
+        $barcode = $request->input('barcode');
+        $owner_code = $request->input('owner_code');
         /** @var InventoryAccountService $inventoryService */
-        $inventoryService=app('inventoryAccountService');
-        $commodity=$inventoryService->searchCommodityByBarcode($barcode,$owner_code);
-        if ($commodity){
-            return ['success'=>true,'data'=>$commodity];
-        }else{
-            return ['success'=>false,'data'=>'输入的条码没有对应商品!'];
+        $inventoryService = app('inventoryAccountService');
+        $commodity = $inventoryService->searchCommodityByBarcode($barcode, $owner_code);
+        if ($commodity) {
+            return ['success' => true, 'data' => $commodity];
+        } else {
+            return ['success' => false, 'data' => '输入的条码没有对应商品!'];
         }
     }
+    //根据库位批量盘点该库位下盘点记录
+    public function batchStockByLocation(Request $request)
+    {
+        if (!Gate::allows('库存管理-盘点')) return ['success' => false, 'msg' => '没有权限'];
+        $missions=$request->mission;
+        $inventoryId=$request->inventoryId;
+        if (!$inventoryId||count($missions)<1) return ['success' => false, 'msg' => '参数错误'];
+        /** @var InventoryAccountService $inventoryService */
+        $inventoryService = app('inventoryAccountService');
+        $inventoryMissions=$inventoryService->batchStockByLocation($missions,$inventoryId);
+        $inventoryService = app('inventoryAccountService');
+        $inventoryAccount = $inventoryService->updateInventory($inventoryId);
+        $stockInventoryPersons = $inventoryMissions[0]->stockInventoryPersons;
+        return ['success' => true, 'inventoryMission' => $inventoryMissions, 'inventory' => $inventoryAccount, 'stockInventoryPersons' => $stockInventoryPersons];
+    }
 }

+ 14 - 1
app/Http/Controllers/PackageController.php

@@ -56,7 +56,6 @@ class PackageController extends Controller
         $package=null;
         $successTip = '操作成功';
 
-
         /** @var OrderPackage $package */
         if ($order_code){
             $package=OrderPackage::query()->with(['order'=>function($query)use($order_code){
@@ -71,11 +70,18 @@ class PackageController extends Controller
             }
         }
         $accomplishToWMS=new Api\thirdPart\flux\PackageController();
+
+
         if($batch_number){
             app('LogService')->log(__METHOD__,'活动波次开始同步_'.__FUNCTION__,json_encode($package),Auth::user()['name']);
 //            $this->syncBatch($package->batch_number,$weight,null,null,null,Carbon::now(),null);
             $result=$accomplishToWMS->markWMSOnBatch($batch_number,$weight);
+
+
+
             OrderPackage::createPackagesFromBatchCode($batch_number,$weight);
+
+
             if($package&&$package->isActivityBatch())
                 $package->unifyThisMeasureUnderSameBatch();
 
@@ -85,6 +91,7 @@ class PackageController extends Controller
                 return redirect('package/create')->with('successTip', $successTip);
             }
             Controller::logS(__METHOD__,'error_'.__FUNCTION__,'批量更改波次上传异常:'.$result['message'].$batch_number);
+
             return redirect('package/create')->with('successError','录入失败!'.$result['message']);
         }
         if (!$package && !$logistic_number)return redirect('package/create')->with('successError','录入失败!系统内没有对应波次的包裹!');
@@ -103,7 +110,9 @@ class PackageController extends Controller
             $package->save();
             app('LogService')->log(__METHOD__,'create_'.__FUNCTION__,json_encode($package),Auth::user()['name']);
 //            event(new WeighedEvent($package));
+
         }else{
+
             /** @var OrderPackageService */
             $package = app('OrderPackageService')->firstOrCreate($logistic_number,[
                 'weight'=>$weight,
@@ -124,7 +133,11 @@ class PackageController extends Controller
             }
             $package->save();
             $successTip = $str;
+
+
         }
+
+
         return redirect('package/create')->with('successTip', $successTip);
     }
 

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

@@ -267,6 +267,7 @@ class StoreCheckingReceiveController extends Controller
             'counted_amount'=>0,
             'imported_diff_amount'=>null,
             'asn_diff_amount'=>null,
+            'bin_number'=>null,
         ]);
         app('LogService')->log(__METHOD__,"重置盘收任务所有数量","store_checking_receive_id:".$id);
         return ['success'=>true];
@@ -296,7 +297,7 @@ class StoreCheckingReceiveController extends Controller
         ]);
         if (count($docAsnDetails) < 1) return ['success'=>false, 'data'=>'该货主下此ASN号不存在'];
 
-        $diffAmount = 0;
+        $diffAmount = null;
         $skus = [];
         foreach ($docAsnDetails as $detail){
             if ($skus[$detail->sku] ?? false) $skus[$detail->sku] += $detail->expectedqty;
@@ -322,7 +323,7 @@ class StoreCheckingReceiveController extends Controller
                 $item->asn_diff_amount = $asn_diff_amount;
                 unset($skus[$item->commodity->sku]);
             }
-            $diffAmount += $item->asn_diff_amount;
+            if ($item->asn_diff_amount)$diffAmount += $item->asn_diff_amount;
         }
         if (count($updateItems) > 0){
             app('StoreCheckingReceiveItemService')->batchUpdate($updateItems);
@@ -357,7 +358,7 @@ class StoreCheckingReceiveController extends Controller
             if (count($createItems) > 0)app('StoreCheckingReceiveItemService')->insert($createItems);
         }
         $data = app('StoreCheckingReceiveService')->updateFind($storeCheckingReceive,[
-            'asn'=>$asn,'is_asn_diff'=>$diffAmount==0 ? "否" : "是",'status'=>'已ASN入库'
+            'asn'=>$asn,'is_asn_diff'=>$diffAmount===0 ? "否" : "是",'status'=>'已ASN入库'
         ]);
         app('LogService')->log(__METHOD__,"修改盘收任务",json_encode($data,JSON_UNESCAPED_UNICODE));
         return ['success'=>true, 'data'=>$data];
@@ -375,7 +376,7 @@ class StoreCheckingReceiveController extends Controller
         if ($storeCheckingReceive->status == '已收货')return ['success'=>false, 'data'=>'盘收任务已结束'];
 
         $storeController = new StoreController();
-        $result = $storeController->quickStorage($storeCheckingReceive->asn,"正品",null);
+        $result = $storeController->quickStorage($storeCheckingReceive->asn,"正品",null,false);
         if ($result['success']) $data = $storeCheckingReceiveService->updateFind($storeCheckingReceive,['status'=>"已收货"]);
         else{
             $data = $storeCheckingReceiveService->updateFind($storeCheckingReceive,['status'=>"收货失败"]);

+ 14 - 6
app/Http/Controllers/StoreController.php

@@ -22,8 +22,10 @@ use Illuminate\Routing\Redirector;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Gate;
 use Illuminate\Support\Facades\Validator;
+use Illuminate\Support\Str;
 use Illuminate\View\View;
 use App\Http\Controllers\Api\thirdPart\flux\StoreController as FStoreController;
+use Ramsey\Uuid\Uuid;
 
 class StoreController extends Controller
 {
@@ -174,15 +176,20 @@ class StoreController extends Controller
         return ['success'=>false, 'data'=>"失败!请检查错误日志"];
     }
 
-    public function quickStorage($asnno,$quality,$depository_code)
+    public function quickStorage($asnno,$quality,$depository_code,$isVerification = true)
     {
+        $task = Store::query()->where("asn_code",$asnno)->where("stored_method","快速入库")
+            ->where("status","已入库")->first();
+        if ($task)return ['success'=>false, 'data'=>"已被快速入库"];
         $db = DB::connection('oracle');
         $query = DB::raw("SELECT * FROM DOC_ASN_HEADER WHERE ASNNO = ?");
         $asn = $db->selectOne($query,[$asnno]);
         if (!$asn) return ['success'=>false, 'data'=>"单据号不存在"];
         if ($asn->asnstatus != '00')return ['success'=>false, 'data'=>'单据号状态非创建订单'];
-        if (array_search($asn->customerid,array_values(config('stores.owners'))) === false)return ['success'=>false, 'data'=>"不允许该货主快速入库"];
-        if (array_search($asn->asntype,array_values(config('stores.types'))) === false)return ['success'=>false, 'data'=>"该单据类型不允许被入库"];
+        if ($isVerification){
+            if (array_search($asn->customerid,array_values(config('stores.owners'))) === false)return ['success'=>false, 'data'=>"不允许该货主快速入库"];
+            if (array_search($asn->asntype,array_values(config('stores.types'))) === false)return ['success'=>false, 'data'=>"该单据类型不允许被入库"];
+        }
         $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 = ?");
@@ -202,8 +209,9 @@ class StoreController extends Controller
         $items = [];
         $toDay = Carbon::now()->toDateTimeString();
         $depositories = [];
+        $traceId = rand(100,999);
         foreach ($details as $detail) {
-            $result = $this->executeSP($detail,$asnno,$depository_code,$db,$quality,$conn,$sql_sp);
+            $result = $this->executeSP($detail,$asnno,$depository_code,$db,$quality,$conn,$sql_sp,$traceId);
             if (substr($result, 0, 3) != '000') {
                 oci_close($conn);
                 app('LogService')->log(__METHOD__,"快速入库-FLUX收货失败","ASNNO:".$asnno.";ERROR:".$result);
@@ -245,13 +253,13 @@ class StoreController extends Controller
         return ['success'=>true,"data"=>"已成功将“".$asnno."”入库"];
     }
 
-    private function executeSP($detail, $asnno, $depository_code, $db, $quality, $conn, $sql_sp){
+    private function executeSP($detail, $asnno, $depository_code, $db, $quality, $conn, $sql_sp,$traceId){
         $IN_Warehouse = $detail->warehouseid ?? '';
         $In_Process_Action = '3';
         $In_ASNNo_C = $detail->asnno ?? '';
         $In_ASNLineNo_C = $detail->asnlineno ?? '';
         $In_FMTraceID_C = '';
-        $In_New_TraceID_C = '';
+        $In_New_TraceID_C = $traceId;
         $In_ProductStatus = '00';
         $In_ProductStatus_Descr = '正常';
         $In_HoldRejectCode_C = 'OK';

+ 50 - 11
app/Http/Controllers/TestController.php

@@ -6,10 +6,12 @@ namespace App\Http\Controllers;
 use App\Authority;
 use App\Commodity;
 use App\CommodityBarcode;
+use App\Console\Commands\SyncWMSOrderTask;
 use App\Events\CancelOrder;
 use App\Imports\OrderTrackingImport;
 use App\InventoryAccount;
 use App\LaborReport;
+use App\Feature;
 use App\Log;
 use App\Logistic;
 use App\OracleActAllocationDetails;
@@ -22,6 +24,7 @@ use App\OrderCommodity;
 use App\OrderIssue;
 use App\OrderPackage;
 use App\Owner;
+use App\OwnerAreaReport;
 use App\Package;
 use App\Process;
 use App\ProcessDaily;
@@ -31,6 +34,7 @@ use App\RejectedBillItem;
 use App\Services\CacheService;
 use App\Services\common\BatchUpdateService;
 use App\Services\common\DataHandlerService;
+use App\Services\FeatureService;
 use App\Services\InventoryCompareService;
 use App\Services\OracleDocAsnHerderService;
 use App\Services\OracleDOCOrderHeaderService;
@@ -50,6 +54,7 @@ use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\Cache;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Redis;
 use Illuminate\Support\Str;
 use Maatwebsite\Excel\Facades\Excel;
 use Ramsey\Collection\Collection;
@@ -90,12 +95,12 @@ class TestController extends Controller
         }
     }
     public function test4(){
-        DB::beginTransaction();
-        Unit::query()->lockForUpdate()->where("id",14)->first();
-        for($i=0;$i<=100;$i++){
-            sleep(1);
-            var_dump($i);
+        $units = Unit::get();
+        //dd($units);
+        foreach ($units as $index => $unit){
+            if ($index!=1)unset($units[$index]);
         }
+        dd($units);
     }
 
     public function updateLaborRemark(){
@@ -957,10 +962,14 @@ where (commodities.owner_id,commodity_barcodes.code) in (select commodities.owne
         app(StoreService::class)->syncWmsAsnData($startDate);
     }
 
-    public function chageOrder()
+    public function changeOrder()
     {
+        /**
+         * @var OrderService $orderService
+         */
         $carbon =Carbon::now()->subMinutes(30);
-        $orderHeader = OracleDOCOrderHeader::query()->selectRaw(implode(',',OracleDOCOrderHeaderService::$columns))
+        var_dump('$orderHeader',new Carbon());
+        $orderHeader_start = OracleDOCOrderHeader::query()->selectRaw(implode(',',OracleDOCOrderHeaderService::$columns))
             ->with(['oracleBASCustomer'=>function($query){
                 $query->selectRaw('BAS_CUSTOMER.CustomerID,BAS_CUSTOMER.Customer_Type,BAS_CUSTOMER.Descr_C,BAS_CUSTOMER.Active_Flag');
             },'oracleDOCOrderDetails'=>function($query){
@@ -971,14 +980,15 @@ where (commodities.owner_id,commodity_barcodes.code) in (select commodities.owne
                 $query->selectRaw('BAS_Codes.CodeID,BAS_Codes.CodeName_C,BAS_Codes.Code');
             }])
             ->where('DOC_Order_Header.addTime','>=',$carbon)
-//            ->where('orderno','SO201112029795')
+//            ->where('DOC_Order_Header.editTime','>=',$carbon)
             ->get();
-        var_dump($orderHeader->count());
         var_dump((string)Carbon::now());
-        /** @var OrderService $orderService */
+
         $orderService = app('OrderService');
-        $orderService->syncOrder($orderHeader);
+        $orderService->syncOrder($orderHeader_start);
+//      $orderService->syncOrder($orderHeader_edit);
         var_dump((string)Carbon::now());
+//      orderService  getCreateOrderModelsByWMSOrderHeaders
     }
 
     public function testOrderPackages(){
@@ -1122,4 +1132,33 @@ where (commodities.owner_id,commodity_barcodes.code) in (select commodities.owne
 //        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode(['$orderIds'=>$orderIds,'$orderPackages'=>$orderPackages,'$orderPackageIds'=>$orderPackageIds,'$orderTrackingIds'=>$orderTrackingIds,]));
 //
 //    }
+
+    public function testSyncOrder()
+     {
+        $carbon =Carbon::now()->subHours(1);
+        $date = '2020-05-18 18:13:50';
+        $orderHeader = OracleDOCOrderHeader::query()->selectRaw(implode(',',OracleDOCOrderHeaderService::$columns))
+            ->with(['oracleBASCustomer'=>function($query){
+                $query->selectRaw('BAS_CUSTOMER.CustomerID,BAS_CUSTOMER.Customer_Type,BAS_CUSTOMER.Descr_C,BAS_CUSTOMER.Active_Flag');
+            },'oracleDOCOrderDetails'=>function($query){
+                $query->selectRaw('doc_order_details.orderNo,doc_order_details.customerid,doc_order_details.sku,doc_order_details.QtyOrdered');
+            }, 'actAllocationDetails'=>function($query){
+                $query->selectRaw('ACT_Allocation_Details.AllocationDetailsID,ACT_Allocation_Details.OrderNo,ACT_Allocation_Details.Qty_Each,ACT_Allocation_Details.PickToTraceID,ACT_Allocation_Details.CustomerID,ACT_Allocation_Details.Sku');
+            },'oracleBASCode'=>function($query){
+                $query->selectRaw('BAS_Codes.CodeID,BAS_Codes.CodeName_C,BAS_Codes.Code');
+            }])
+//            ->where('DOC_Order_Header.addTime','>=',$startDate)
+//            ->where('orderno','SO201112029795')
+            ->where('DOC_Order_Header.addTime','>=',$carbon)
+            ->get();
+        /** @var OrderService $service */
+        $service = app('OrderService');
+        $service->syncOrder($orderHeader);
+    }
+
+    public function OrderSync(){
+        $tack = new SyncWMSOrderTask();
+        $tack->handle();
+        dump(11);
+    }
 }

+ 20 - 20
app/Http/Controllers/UserDutyCheckController.php

@@ -135,26 +135,26 @@ class UserDutyCheckController extends Controller
             $userDutyCheck->save();
             app('LogService')->log(__METHOD__, "创建打卡记录" . __FUNCTION__, json_encode($userDutyCheck));
             return $userDutyCheck;
-        }
-
-        if ($importAndExportQRCodeType && $importAndExportQRCodeType == 'import') {
-            if ($userDutyCheckOld->type == '登入'&&$userDutyCheckOld->laborReport) {
-                $userDutyCheck->import = true;//已入场的不能再入场
-                return $userDutyCheck;
+        }else{
+            if ($importAndExportQRCodeType && $importAndExportQRCodeType == 'import') {
+                if ($userDutyCheckOld->type == '登入'&&$userDutyCheckOld->laborReport) {
+                    $userDutyCheck->import = true;//已入场的不能再入场
+                    return $userDutyCheck;
+                }
+                $userDutyCheck->type = '登入';
             }
-            $userDutyCheck->type = '登入';
-        }
-        if ($importAndExportQRCodeType && $importAndExportQRCodeType == 'export') {
-            if ($userDutyCheckOld->type == '登出') {
-                $userDutyCheck->export = true;//已出场的不能再出场
-                return $userDutyCheck;
+            if ($importAndExportQRCodeType && $importAndExportQRCodeType == 'export') {
+                if ($userDutyCheckOld->type == '登出') {
+                    $userDutyCheck->export = true;//已出场的不能再出场
+                    return $userDutyCheck;
+                }
+                $userDutyCheck->verify_user_id = $userDutyCheckOld->verify_user_id;
+                $userDutyCheck->type = '登出';
             }
-            $userDutyCheck->verify_user_id = $userDutyCheckOld->verify_user_id;
-            $userDutyCheck->type = '登出';
+            $userDutyCheck->save();
+            app('LogService')->log(__METHOD__, "创建打卡记录" . __FUNCTION__, json_encode($userDutyCheck));
+            return $userDutyCheck;
         }
-        $userDutyCheck->save();
-        app('LogService')->log(__METHOD__, "创建打卡记录" . __FUNCTION__, json_encode($userDutyCheck));
-        return $userDutyCheck;
     }
     //去往登记资料页面
     public function createUserDetail($mobile_phone)
@@ -196,7 +196,7 @@ class UserDutyCheckController extends Controller
         if ($errorMessage) return $errorMessage;
         $laravelEchoPrefix = config('database.redis.options.prefix');
         return response()->view('personnel/checking-in/importAndExportSuccess',['full_name'=>$userDetail->full_name,'checked_at'=>$userDutyCheck->checked_at,'type'=>$userDutyCheck->type,'laravelEchoPrefix'=>$laravelEchoPrefix])
-            ->cookie('userLaborToken', $userLaborToken, config('users.cookie_expire_minutes'), '/');
+            ->cookie('userLaborToken', $userLaborToken, config('users.token_check_in_expire_minutes'), '/');
     }
 
     public function updateValidator(Request $request)
@@ -256,7 +256,7 @@ class UserDutyCheckController extends Controller
         Controller::logS(__METHOD__,"录入临时工,用户,对应工作组,打卡记录".__FUNCTION__,json_encode($userDetail));
         $laravelEchoPrefix = config('database.redis.options.prefix');
         return response()->view('personnel/checking-in/importAndExportSuccess',['full_name'=>$userDetail->full_name,'checked_at'=>$userDutyCheck->checked_at,'type'=>$userDutyCheck->type,'laravelEchoPrefix'=>$laravelEchoPrefix])
-            ->cookie('userLaborToken',$userLaborToken,config('users.cookie_expire_minutes'),'/');
+            ->cookie('userLaborToken',$userLaborToken,config('users.token_check_in_expire_minutes'),'/');
 
     }
 
@@ -334,7 +334,7 @@ class UserDutyCheckController extends Controller
         }
         if ($userLaborToken){
             return response()->view('personnel/checking-in/success', ['group_name' => $group_name ?? '', 'full_name' => $userDetail->full_name, 'check_in_at' => $newLaborReport->check_in_at, 'laravelEchoPrefix' => $laravelEchoPrefix])
-                ->cookie('userLaborToken',$userLaborToken,config('users.cookie_expire_minutes'),'/');
+                ->cookie('userLaborToken',$userLaborToken,config('users.token_check_in_expire_minutes'),'/');
         }else{
             return response()->view('personnel/checking-in/success', ['group_name' => $group_name ?? '', 'full_name' => $userDetail->full_name, 'check_in_at' => $newLaborReport->check_in_at, 'laravelEchoPrefix' => $laravelEchoPrefix]);
         }

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

@@ -187,7 +187,6 @@ class SortingController extends Controller
         return true;
     }
 
-
     public function informBatchFinished(Batch $batch){
         $sendingData=['request'=>[]];
         $batch->orders()->each(function (Order $order)use($batch,&$sendingData){

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

@@ -0,0 +1,24 @@
+<?php
+
+
+namespace App\Http\Controllers\api\thirdPart\haiq;
+
+
+
+
+use Illuminate\Http\Request;
+
+class PickStationController
+{
+    protected $request;
+
+    public function __construct()
+    {
+    }
+
+    public function processed(Request $request){
+        $success = $request->input('success');
+        $code= $success?200:0;
+        return ['code'=>$code,'errMsg'=>'','data'=>$request->all()];
+    }
+}

+ 4 - 10
app/Imports/InventoryCompareImport.php

@@ -24,7 +24,6 @@ class InventoryCompareImport implements ToCollection, WithHeadingRow, WithMultip
     protected $ownerArr=[];
     public function __construct()
     {
-//            $this->owner_id=$owner_id;
             app()->singleton('InventoryCompareService',InventoryCompareService::class);
     }
 
@@ -45,9 +44,9 @@ class InventoryCompareImport implements ToCollection, WithHeadingRow, WithMultip
             if($array[0]['仓库']??false) return '仓库';
             if($array[0]['属性仓']??false) return '属性仓';
         })();
-        $sku=$array[0][$skuName];
-        $amount=$array[0][$amountName];
-        $customLocation=$array[0][$customLocationName];
+        $sku=$array[0][$skuName] ?? null;
+        $amount=$array[0][$amountName] ?? null;
+        $customLocation=$array[0][$customLocationName] ?? null;
 
         $endIS = false;
         if (!isset($sku) || !isset($amount) || !isset($customLocation)) {
@@ -57,7 +56,7 @@ class InventoryCompareImport implements ToCollection, WithHeadingRow, WithMultip
         }
         foreach ($collection as $row) {
             $customLocationArr=[
-                'custom_location'=>$row[$customLocationName],
+                'custom_location'=>$row[$customLocationName] ?? null,
             ];
             array_push($this->customLocationArrs,$customLocationArr);
         }
@@ -76,7 +75,6 @@ class InventoryCompareImport implements ToCollection, WithHeadingRow, WithMultip
                 'custom_location'=>$customLocation,
             ];
             $this->ownerArr = array_merge($this->ownerArr,[$owners['custom_location']=>$owners]);
-
         }
         $skuAndWarehouseArr=[];
         $inventoryCompares=[];
@@ -97,7 +95,6 @@ class InventoryCompareImport implements ToCollection, WithHeadingRow, WithMultip
                     $sum++;
                     continue;
                 }
-
                 if ($this->ownerArr["$row[$customLocationName]"]['owner_id']){
                     $this->owner_id=$this->ownerArr["$row[$customLocationName]"]['owner_id'];
                     $this->ownerCode=$this->ownerArr["$row[$customLocationName]"]['owner_code'];
@@ -158,13 +155,10 @@ class InventoryCompareImport implements ToCollection, WithHeadingRow, WithMultip
                 array_push($inventoryCompares,$inventoryCompare);
                 $sum++;
             }
-//            if(empty($exception)){
                 /** @var InventoryCompareService $service */
                 $service = app('InventoryCompareService');
                 $inventoryCompare= $service->createInventoryCompares($inventoryCompares);
                 if (!$inventoryCompare) array_push($exception, ['创建库存对比失败!']);
-//            }
-
         }
         Cache::put('exception', $exception, 86400);
     }

+ 3 - 3
app/Imports/StoreCheckingReceiveImport.php

@@ -160,7 +160,7 @@ class StoreCheckingReceiveImport implements ToCollection,WithHeadingRow
                 $date = Carbon::now();
                 foreach ($commoditiesTem as $item){
                     //对比本地与导入的存在商品中条码差异 补充数据库
-                    foreach (array_unique(array_diff($skuMap[$item->sku], $item->barcodes)) as $code){
+                    foreach (array_unique(array_diff($skuMap[$item->sku], $item->barcodes->toArray())) as $code){
                         $barcodes[] = [
                             'commodity_id' => $item->id,
                             'code' => $code,
@@ -254,8 +254,8 @@ class StoreCheckingReceiveImport implements ToCollection,WithHeadingRow
         app('LogService')->log(__METHOD__,"导入盘收任务-录入盘收任务",json_encode($storeCheckingReceive,JSON_UNESCAPED_UNICODE));
         $storeCheckingReceive->owner_name = $owner_name;
 
-        foreach ($items as &$item){
-            $item["store_checking_receive_id"] = $storeCheckingReceive->id;
+        foreach ($items as &$it){
+            $it["store_checking_receive_id"] = $storeCheckingReceive->id;
         }
 
         app('StoreCheckingReceiveItemService')->insert($items);

+ 0 - 1
app/Imports/StoreCheckingReceiveSheets.php

@@ -8,7 +8,6 @@ class StoreCheckingReceiveSheets implements WithMultipleSheets
 {
     public function sheets(): array
     {
-        // TODO: Implement sheets() method.
         return [
           0 => new StoreCheckingReceiveImport(),
         ];

+ 12 - 29
app/LaborReport.php

@@ -20,7 +20,7 @@ class LaborReport extends Model
         'user_duty_check_id','relax_time','remark'
     ];
     protected $appends = [
-        'is_exportGroup','is_export', 'exit_at','enter_at','sequence', 'amountOfJoined',/*'remark',*/'thisRecordOnlineTime','thisRecordWorkingTime','thisRoundRecordWorkingTime',
+        'is_exportGroup','is_export', 'exit_at','enter_at','sequence', 'amountOfJoined','thisRecordOnlineTime','thisRecordWorkingTime','thisRoundRecordWorkingTime',
         'totalOnlineTime','verifyPerson','userDutyCheckVerifyUserId','isAdult','round_check_in_at','round_check_out_at','has_group_verify_right',
     ];
     protected $tempFields = [
@@ -47,18 +47,8 @@ class LaborReport extends Model
     public function laborReportStatus(){
         return $this->hasMany('App\LaborReportStatus','labor_report_id','id');
     }
-    public function 未审核(){
-        return $this->hasOne('App\LaborReportStatus','labor_report_id','id')
-            ->where('status','未审核');
-    }
-    public function 已退场(){
-        return $this->hasOne('App\LaborReportStatus','labor_report_id','id')
-            ->where('status','已退场');
-    }
-    public function remarks(){
-        return $this->hasOne('App\Sign','signable_id','id')
-            ->where('field','remark')->where('signable_type','labor_reports');
-    }
+
+
     public function getRoundCheckInAtAttribute(){
         if (!$this['check_in_at'])return null;
         $round_check_in_at=Carbon::parse($this['check_in_at'])->format('i');
@@ -73,11 +63,7 @@ class LaborReport extends Model
         if ($round_check_out_at>=25&&$round_check_out_at<=55) return Carbon::parse($this['check_out_at'])->clone()->setMinutes(30)->setSeconds(00)->format('Y-m-d H:i:s');
         if ($round_check_out_at>55&&$round_check_out_at<=59) return Carbon::parse($this['check_out_at'])->clone()->addHour()->setMinutes(00)->setSeconds(00)->format('Y-m-d H:i:s');
     }
-//    public function getRemarkAttribute(){
-////        $this->hasOne('App\Sign','signable_id','id')
-////            ->where('field','remark')->where('signable_type','labor_reports')->value('mark');
-//        return $this['remarks']?$this['remarks']['mark']:null;
-//    }
+    //has_group_verify_right'
     public function getHasGroupVerifyRightAttribute(){
         if (!Gate::allows('人事管理-临时工报表')){return null; }
         if (Gate::allows('人事管理-临时工报表-管理全部组')){return true;}
@@ -217,10 +203,9 @@ class LaborReport extends Model
     //进场时间
     public function getEnterAtAttribute()
     {
-//        $laborReportStatus=LaborReportStatus::where('labor_report_id',$this['id'])->where('status','未审核')->orderBy('id','desc')->first();
-//        if (empty($laborReportStatus))return null;
-//        return Carbon::parse($laborReportStatus['created_at'])->format('Y-m-d H:i:s');
-        return $this['未审核']?Carbon::parse($this['未审核']['created_at'])->format('Y-m-d H:i:s'):null;
+        $laborReportStatus=LaborReportStatus::where('labor_report_id',$this['id'])->where('status','未审核')->orderBy('id','desc')->first();
+        if (empty($laborReportStatus))return null;
+        return Carbon::parse($laborReportStatus['created_at'])->format('Y-m-d H:i:s');
     }
 
     public function getEnteringRecordAttribute()
@@ -235,10 +220,9 @@ class LaborReport extends Model
 
     public function getExitAtAttribute()
     {
-        //$laborReportStatus=LaborReportStatus::where('labor_report_id',$this['id'])->where('status','已退场')->orderBy('id','desc')->first();
-        //if (empty($laborReportStatus))return null;
-        //return Carbon::parse($laborReportStatus['created_at'])->format('Y-m-d H:i:s');
-        return $this['已退场']?Carbon::parse($this['已退场']['created_at'])->format('Y-m-d H:i:s'):null;
+        $laborReportStatus=LaborReportStatus::where('labor_report_id',$this['id'])->where('status','已退场')->orderBy('id','desc')->first();
+        if (empty($laborReportStatus))return null;
+        return Carbon::parse($laborReportStatus['created_at'])->format('Y-m-d H:i:s');
     }
 
     //创建或获取进场编号
@@ -252,9 +236,8 @@ class LaborReport extends Model
     }
 
     public function getIsExportAttribute(){
-//        $laborReportStatus=LaborReportStatus::where('labor_report_id',$this['id'])->orderBy('id','desc')->first();
-//        return $laborReportStatus['status']=='已退场'?true:false;
-        return $this['已退场']?true:false;
+        $laborReportStatus=$this->laborReportStatus()->where('labor_report_id',$this['id'])->orderBy('id','desc')->first();
+        return $laborReportStatus['status']=='已退场'?true:false;
     }
     //出场更新临时工报表信息
     static function exitAndChangeLaborReport($laborReport,$userDutyCheck){

+ 1 - 3
app/LaborReportStatus.php

@@ -11,7 +11,5 @@ class LaborReportStatus extends Model
     protected $fillable=[
         'id','status','labor_report_id','created_at',
     ];
-//    public function laborReport(){
-//        return $this->hasOne('App\LaborReport','id','labor_report_id');
-//    }
+
 }

+ 1 - 1
app/Order.php

@@ -14,7 +14,7 @@ class Order extends Model
         'id', 'batch_id',  'owner_id', 'status',
         'created_at', 'code', 'shop_id',  'client_code',
         'logistic_id', 'consignee_name', 'consignee_phone', 'province',
-        'city', 'district', 'address', 'wms_status','status','warehouse_id','wms_edittime'];
+        'city', 'district', 'address', 'wms_status','warehouse_id','wms_edittime'];
 
     /*
      * wms订单号             code=>DOC_ORDER_HEADER[orderno]

+ 8 - 0
app/OrderPackage.php

@@ -96,6 +96,9 @@ class OrderPackage extends Model
         $this['batch_number'] = $this->oracleInfo['waveno']??null;
     }
     static public function createPackagesFromBatchCode($batchCode,$weight){
+
+
+
         $queryBuilder=OracleDOCOrderHeader::query()->select(self::$oracleOrderHeaderFields);
         $queryBuilder->where('doc_order_header.waveno',$batchCode);
         $queryBuilder->leftJoin('act_allocation_details','act_allocation_details.orderno','doc_order_header.orderno');
@@ -104,6 +107,7 @@ class OrderPackage extends Model
         $resultOracleObjs_grouped=$resultOracleObjs->groupBy('soreference5');
         $packages = [];
         $now = Carbon::now();
+
         foreach($resultOracleObjs_grouped as $resultOracleObj_grouped){
             $resultOracleObj = $resultOracleObj_grouped[0];
             /** @var OrderService $orderService*/
@@ -123,6 +127,8 @@ class OrderPackage extends Model
                 "created_at"=>$now,
             ]);
         }
+
+
         $packagesLogisticNumbers = array_map(function ($orderPackage) {
             return $orderPackage['logistic_number'];
         } ,$packages);
@@ -143,6 +149,8 @@ class OrderPackage extends Model
         DB::transaction(function ()use($newPackages){
             OrderPackage::query()->insert($newPackages);
         });
+
+
         app('LogService')->log(__METHOD__,"批量录入包裹成功",json_encode($packages),Auth::user()['id']);
     }
     public function unifyThisMeasureUnderSameBatch(){

+ 10 - 9
app/Services/CacheService.php

@@ -9,14 +9,15 @@ use Illuminate\Support\Facades\Cache;
 class CacheService
 {
     function getOrExecute(String $key, $func, $expiration=null){
-        $results = Cache::get($key);
-        if(!$results){
-            if(!$func||gettype($func)!='object') throw new \Exception('执行函数类型错误');
-            $results = $func();
-            if(!$results)return null;
-            if(!$expiration) $expiration=config('cache.expirations.default');
-            Cache::put($key, $results, $expiration);
-        }
-        return $results;
+        return Cache::remember($key, $expiration, $func);
+//        $results = Cache::get($key);
+//        if(!$results){
+//            if(!$func||gettype($func)!='object') throw new \Exception('执行函数类型错误');
+//            $results = $func();
+//            if(!$results)return null;
+//            if(!$expiration) $expiration=config('cache.expirations.default');
+//            Cache::put($key, $results, $expiration);
+//        }
+//        return $results;
     }
 }

+ 24 - 5
app/Services/CommodityService.php

@@ -177,15 +177,17 @@ Class CommodityService
     {
         if(!$params) return [];
         $bas_sku_arr = OracleBasSKU::query()
+            ->selectRaw('customerid,sku,descr_c,skulength,skuwidth,skuhigh,cube')
             ->whereIn('CustomerID',data_get($params,'*.owner_code'))
             ->whereIn('Sku',data_get($params,'*.sku'))
             ->get();
         $insert_params = [];
-
+        $created_at = Carbon::now()->format('Y-m-d H:i:s');
         foreach ($bas_sku_arr as $bas_sku) {
             $owner = $owners_code_map[$bas_sku->customerid] ?? '';
             if(!$owner)continue;
-            $created_at = Carbon::now()->format('Y-m-d H:i:s');
+            if($bas_sku->sku==null)continue;
+            if($bas_sku->descr_c=='')continue;
             $insert_params[] = [
                 'owner_id' => $owner->id,
                 'sku' => $bas_sku->sku,
@@ -197,7 +199,6 @@ Class CommodityService
                 'volumn' => $bas_sku->cube
             ];
         }
-
         if(count($insert_params) > 0){
             try {
                 $this->insert($insert_params);
@@ -302,7 +303,7 @@ Class CommodityService
                 "owner_id" => $owner_id,
                 "sku" => $sku
             ]);
-            if (!$commodity || $commodity->pack === null){
+            if (!$commodity || $commodity->pack_spec === null){
                 $owner = app("OwnerService")->find($owner_id);
                 $action = new CommodityController();
                 $action->syncOwnerCommodities($owner->id,$owner->code,$sku);
@@ -310,7 +311,25 @@ Class CommodityService
             return $that->first([
                 "owner_id" => $owner_id,
                 "sku" => $sku
-            ])->pack;
+            ])->pack_spec;
         });
     }
+
+    //是否存在
+    public function isExist(array $params)
+    {
+        $query = Commodity::query();
+        if ($params["barcode"] ?? false) {
+            $query->whereHas("barcodes",function ($query)use($params){
+                /** @var Builder $query */
+                $query->where("code",$params["barcode"]);
+            });
+            unset($params["barcode"]);
+        }
+        foreach ($params as $column => $param){
+            $query->where($column,$param);
+        }
+        if ($query->count() > 0)return true;
+        return false;
+    }
 }

+ 2 - 2
app/Services/CustomerService.php

@@ -11,9 +11,9 @@ Class CustomerService
         return Customer::query()->select($column)->get();
     }
 
-    public function paginate()
+    public function paginate($paginate = 50)
     {
-        return Customer::query()->orderByDesc('id')->paginate(50);
+        return Customer::query()->orderByDesc('id')->paginate($paginate);
     }
 
     public function create(array $params)

+ 125 - 22
app/Services/FeatureService.php

@@ -16,6 +16,22 @@ Class FeatureService
         return $map;
     }
 
+    /**
+     *  将特征翻译为数组显示
+     *      $str : "1&2|(3&4)"
+     *      array:[
+     *          "strategyGroupStartSign" => false,  //是否为策略组起点,这将在解析时解析为 (
+                "calculation" => "",                //运算规则,目前仅有 &,| 翻译后填入
+                "type"=>"",                         //特征类型
+                "id"=>"",                           //特征ID
+                "logic"=>"",                        //特征逻辑
+                "describe"=>"",                     //特征信息
+                "strategyGroupEndSign" => false,    //是否为策略组终点,这将在解析时解析为 )
+     *      ]
+     *
+     * @param string $str
+     * @return array
+     */
     public function translationFeature($str)
     {
         if (!$str)return null;
@@ -24,14 +40,14 @@ Class FeatureService
         $sign = 0;  //为第二次切割做起点标记
         $model = [];//第二次切割数组
         $ids = [];//记录出现的特征ID,统一查询
-        foreach ($result[0] as $index => &$str){
-            if (is_numeric($str)){
+        foreach ($result[0] as $index => &$item){
+            if (is_numeric($item)){
                 $model[] = array_slice($result[0],$sign,($index-$sign)+1);
                 $sign = $index+1;
-                $ids[] = $str;
+                $ids[] = $item;
                 continue;
             }
-            if ($index == count($result[0])-1 && $str == ')'){
+            if ($index == count($result[0])-1 && $item == ')'){
                 $model[] = [")"];
             }
         }//以数字为标准切割策略组
@@ -50,17 +66,17 @@ Class FeatureService
                 "describe"=>"",  //特征信息
                 "strategyGroupEndSign" => false,//是否为策略组终点,这将在解析时解析为 )
             ];//最终对象组模型,策略组将几组特征组合引用
-            foreach ($m as $str){
-                if (is_numeric($str)){//填入特征信息
-                    if (isset($featureMap[$str])){
-                        $arr["type"] = $features[$featureMap[$str]]->type;
-                        $arr["id"] = $features[$featureMap[$str]]->id;
-                        $arr["logic"] = $features[$featureMap[$str]]->logic;
-                        $arr["describe"] = $features[$featureMap[$str]]->describe;
+            foreach ($m as $string){
+                if (is_numeric($string)){//填入特征信息
+                    if (isset($featureMap[$string])){
+                        $arr["type"] = $features[$featureMap[$string]]->type;
+                        $arr["id"] = $features[$featureMap[$string]]->id;
+                        $arr["logic"] = $features[$featureMap[$string]]->logic;
+                        $arr["describe"] = $features[$featureMap[$string]]->describe;
                     }
                     continue;
                 }
-                switch ($str){//特殊字符的翻译
+                switch ($string){//特殊字符的翻译
                     case "(":
                         $arr["strategyGroupStartSign"] = true;
                         break;
@@ -84,6 +100,24 @@ Class FeatureService
         return $model;
     }
 
+    /**
+     *  与translationFeature相反,将一组与translationFeature参数解析为简述
+     *      $features:[
+     *          "strategyGroupStartSign" => false,  //是否为策略组起点,这将在解析时解析为 (
+                "calculation" => "",                //运算规则,目前仅有 &,| 翻译后填入
+                "type"=>"",                         //特征类型
+                "id"=>"",                           //特征ID
+                "logic"=>"",                        //特征逻辑
+                "describe"=>"",                     //特征信息
+                "strategyGroupEndSign" => false,    //是否为策略组终点,这将在解析时解析为 )
+     *      ]
+     *      array:[
+     *          "feature"   //简述结果
+     *          "map"       //简述中出现的Map特征对象重组为key-val数组
+     *      ]
+     * @param array $features
+     * @return array
+     */
     public function analysisFeature($features)
     {
         $str = "";
@@ -98,7 +132,7 @@ Class FeatureService
             $feature["id"] = $f->id;
             $map[$feature["id"]] = $f;
             if ($feature["calculation"] == '并且')$str .= '&';
-            else $str .= '|';
+            if ($feature["calculation"] == '或') $str .= '|';
             if ($feature["strategyGroupStartSign"])$str .= "(";
             $str .= $feature["id"];
             if ($feature["strategyGroupEndSign"])$str .= ")";
@@ -106,6 +140,18 @@ Class FeatureService
         return ['feature'=>$str,"map"=>$map];
     }
 
+    /**
+     * 格式化简述特征为可阅读显示
+     *      $features : 特征对象集 重组为key-val数组数据,key为ID
+     *      $value : 简述特征 例: "1&2|(3&4)"
+     *      $columnMapping : 特征type属性字段映射 例:["商品名称"=>"commodity_name"],指定该参数会使特征格式化为SQL段
+     *      string : 例:"商品名称 包含 衣服 并且(订单类型 等于 创建订单 或者 承运商 不包含 顺丰)"
+     *
+     * @param array $features
+     * @param string $value
+     * @param array $columnMapping
+     * @return string
+     */
     public function formatFeature(array $features, $value, $columnMapping = null)
     {
         if (!$features)return $value;
@@ -130,7 +176,7 @@ Class FeatureService
                             $logic = " = ";
                             break;
                     }
-                    $str = $column.$logic.$describe;
+                    $str = $column.$logic."'".$describe."'";
                 }else $str = $features[$str]["type"].' '.$features[$str]["logic"].' '.$features[$str]["describe"];
             }
             if ($str == "&"){
@@ -145,21 +191,48 @@ Class FeatureService
         return implode("",$result[0]);
     }
 
-    public function matchFeature($value, $columnMapping, $matchObject) :bool
+    /**
+     *  匹配特征
+     *      $vale : 特征简述 例: "1&2|(3|4)"
+     *      $columnMapping : 列映射 例:["商品名称"=>"commodity_name"]
+     *      $matchObject : 被匹配对象,必须存在列映射所指定字段 例:["commodity_name"=>"衣服"]
+     *      $isMultiMatching 是否开启多重匹配 开启将匹配对象视为二维数组深层寻找商品(入库需要)
+     *      bool true匹配成功 false匹配失败
+     *
+     * @param string $value
+     * @param array $columnMapping
+     * @param array $matchObject
+     * @param bool $isMultiMatching
+     * @return bool
+     */
+    public function matchFeature($value, $columnMapping, $matchObject, $isMultiMatching = false) :bool
     {
-        preg_match_all('/\d+/',$value,$ids);
-        if ($ids[0])$fs = Feature::query()->whereIn("id",$ids[0])->get();
-        else return false;
-        $features = [];
-        foreach ($fs as $f){
-            $features[$f->id] = $f;
-        }
         preg_match_all('/\d+|[\&\|\(\)]/',$value,$result);
+        if (implode("",$result[0]) != $value)return false;
+
+        $features = app(CacheService::class)->getOrExecute($value,function ()use($value){
+            preg_match_all('/\d+/',$value,$ids);
+            if ($ids[0])$fs = Feature::query()->whereIn("id",$ids[0])->get();
+            else return false;
+            $features = [];
+            foreach ($fs as $f){
+                $features[$f->id] = $f;
+            }
+            return $features;
+        });
+
+
         foreach ($result[0] as &$str) {
             if (is_numeric($str) && isset($features[$str])) {
                 $column = $features[$str]["type"];
                 $logic = $features[$str]["logic"];
                 $describe = $features[$str]["describe"];
+                if ($column == '商品名称' && $isMultiMatching){
+                    $packageColumn = $columnMapping["packages"] ?? "packages";
+                    $packages = $matchObject[$packageColumn] ?? [];
+                    $str = $this->multiMatching($packages,$logic,$describe,$columnMapping[$column] ?? '');
+                    continue;
+                }
                 $value = isset($columnMapping[$column]) ? $matchObject[$columnMapping[$column]] : '';
                 switch ($logic) {
                     case "包含":
@@ -186,4 +259,34 @@ Class FeatureService
         return eval("return $is;");
     }
 
+    /**
+     * 多重子项匹配
+     *
+     * @param array $packages
+     * @param string $logic
+     * @param string $describe
+     * @param string $column
+     * @return string           //"true" || "false"
+     */
+    private function multiMatching($packages, $logic, $describe, $column):string
+    {
+        if(!$column)return 'false';
+
+        foreach ($packages as $package){
+            $value = $package[$column] ?? '';
+            switch ($logic) {
+                case "包含":
+                    if (mb_strpos($value,$describe)!==false)return 'true';
+                    break;
+                case "不包含":
+                    if (mb_strpos($value,$describe) === false)return 'true';
+                    break;
+                case "等于":
+                    if ($value == $describe)return 'true';
+                    break;
+            }
+        }
+        return "false";
+    }
+
 }

+ 47 - 0
app/Services/InventoryAccountService.php

@@ -14,6 +14,7 @@ use App\OracleInvLotAtt;
 use App\OracleBasCustomer;
 use App\OracleInvLotLocId;
 use App\Owner;
+use App\Services\common\BatchUpdateService;
 use App\Services\common\QueryService;
 use Carbon\Carbon;
 use Illuminate\Support\Facades\Auth;
@@ -635,4 +636,50 @@ class InventoryAccountService
         return $inventoryAccountMissions;
     }
 
+    public function batchStockByLocation($missions,$inventoryId)
+    {
+        $inventory=InventoryAccount::query()->find($inventoryId);
+        if($inventory->status=='复盘中'){
+            $updateParams = [[
+                'id','returned','difference_amount','re_checked_amount','checked','updated_at'
+            ]];
+            foreach ($missions as $mission){
+                if (($mission['amount']-$mission['stored_amount'])==0){
+                    $return='是';
+                }else{
+                    $return='否';
+                }
+                $updateParams[] = [
+                    'id'=>$mission['id'],
+                    're_checked_amount'=>$mission['amount'],
+                    'difference_amount'=>$mission['amount']-$mission['stored_amount'],
+                    'returned'=>$return,
+                    'checked'=>'已复核',
+                    'updated_at' =>Carbon::now()->format('Y-m-d H:i:s'),
+                ];
+            }
+        }else{//初盘
+            $updateParams = [[
+                'id','difference_amount','checked','verified_amount','updated_at'
+            ]];
+            foreach ($missions as $mission){
+                $updateParams[] = [
+                    'id'=>$mission['id'],
+                    'verified_amount'=>$mission['amount'],
+                    'difference_amount'=>$mission['amount']-$mission['stored_amount'],
+                    'checked'=>'是',
+                    'updated_at' =>Carbon::now()->format('Y-m-d H:i:s'),
+                ];
+            }
+        }
+        if(count($updateParams) > 1) app(BatchUpdateService::class)->batchUpdate('inventory_account_missions',$updateParams);
+        LogService::log(__METHOD__,__FUNCTION__,'根据库位批量盘点'.count($updateParams).json_encode($updateParams));
+        $ids = array_unique(data_get($missions,'*.id'));
+        $inventoryMissions=InventoryAccountMission::query()->whereIn('id',$ids)->get();
+        foreach ($inventoryMissions as $inventoryMission){
+            $inventoryMission->createSignStockInventoryPersons();
+        }
+        return InventoryAccountMission::query()->with(['commodity.barcodes','stockInventoryPersons'])->whereIn('id',$ids)->get();
+    }
+
 }

+ 26 - 48
app/Services/InventoryCompareService.php

@@ -19,28 +19,6 @@ use Ramsey\Uuid\Uuid;
 class InventoryCompareService
 {
     static private $missionCode;
-//    private function conditionQuery($SKU,$LotAtt05,$descr_c){
-//        $sql='select * from (select result.*,rownum rn from (';
-//        $sql.=' select customer.Descr_C as 货主,storeStatus.CUSTOMERID 客户,storeStatus.LocationID 库位, sku.SKU 产品编码, sku.ALTERNATE_SKU1 产品条码, ';
-//        $sql.=' sku.Descr_C 商品名称, lot.LotAtt05 属性仓, lot.LotAtt08 质量状态, lot.LotAtt02 失效日期, storeStatus.ADDTIME 创建时间, ';
-//        $sql.=' lot.LotAtt04 批号 ';
-//        $sql.=' , storeStatus.QTY 在库数量, storeStatus.QtyAllocated 占用数量,count(1) over () as sum from ';
-//        $sql.=' INV_LOT_LOC_ID storeStatus';
-//        $sql.=' left join BAS_Customer customer on customer.CustomerID=storeStatus.CUSTOMERID ';
-//        $sql.=' left join BAS_SKU sku on sku.SKU=storeStatus.SKU and sku.CUSTOMERID=storeStatus.CUSTOMERID ';
-//        $sql.=' left join INV_LOT_ATT lot on lot.LOTNUM = storeStatus.LOTNUM AND lot.CUSTOMERID = storeStatus.CUSTOMERID ';
-//        $sql.=' group by storeStatus.LocationID,customer.Descr_C,sku.SKU,sku.ALTERNATE_SKU1 ';
-//        $sql.=' ,sku.Descr_C,lot.LotAtt05,lot.LotAtt08,lot.LotAtt02,lot.LotAtt04 ';
-//        $sql.=' , storeStatus.QTY, storeStatus.QtyAllocated,storeStatus.CUSTOMERID,storeStatus.ADDTIME  ';
-//        $sql.=' )result where 1=1 ';
-//        if ($SKU)$sql.=" and 产品编码 like '".$SKU."' ";
-//        if ($LotAtt05)$sql .=" and 属性仓 like '".$LotAtt05."' ";
-//        if ($descr_c)$sql.=" and 货主 = '".$descr_c."' ";
-//        $sql.=' )  ';
-//        return DB::connection('oracle')->select($sql);
-//    }
-
-
     public function getCreatingMissionCode($ownerName=''){
         if(self::$missionCode)return self::$missionCode;
         $sequence=Cache::get('InventoryCompareMissionSequence');
@@ -106,41 +84,41 @@ class InventoryCompareService
             $wmsInventoryCompareZp=$query->where('属性仓',$custom_location)->where('产品编码',$sku)->where('质量状态','ZP')->first();
             $wmsInventoryCompareCc=$query->where('属性仓',$custom_location)->where('产品编码',$sku)->where('质量状态','CC')->first();
             $wmsInventoryCompareDj=$query->where('属性仓',$custom_location)->where('产品编码',$sku)->where('质量状态','DJ')->first();
-            $unknownQualityStatus=$query->where('属性仓',$custom_location)->where('产品编码',$sku)->whereNotIn('质量状态',['DJ','CC','ZP']);
+            $wmsInventoryCompareYjz=$query->where('属性仓',$custom_location)->where('产品编码',$sku)->where('质量状态','YJZ')->first();
+            $unknownQualityStatus=$query->where('属性仓',$custom_location)->where('产品编码',$sku)->whereNotIn('质量状态',['DJ','CC','ZP','YJZ']);
             if (!$wmsInventoryCompareZp&&!$wmsInventoryCompareCc&&!$wmsInventoryCompareDj&&$unknownQualityStatus->isEmpty()){
                 $this->createInventoryCompare_underImport($sku, $custom_location, $amount, $owner_id,$owner_name);
+                continue;
             }
             $creatingMissionCode = $this->getCreatingMissionCode($owner_name);
             $commodityId=Commodity::where('sku',$sku)->where('owner_id',$owner_id)->value('id');
+            $params = [
+                'owner_id' => $owner_id,
+                'commodity_id' => $commodityId,
+                'mission_code' => $creatingMissionCode,
+                'custom_location' => $custom_location,
+                'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
+                'amount_in_compare'=>$amount,
+            ];
             if ($wmsInventoryCompareZp||$wmsInventoryCompareDj) {
-                $wasInventoryCompareZP = [
-                    'owner_id' => $owner_id,
-                    'commodity_id' => $commodityId,
-                    'mission_code' => $creatingMissionCode,
-                    'custom_location' => $custom_location,
-                    'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
-                    'quality' => '正品',
-                    'amount_in_sys' => ($wmsInventoryCompareZp['在库数量'] ?? 0)+($wmsInventoryCompareDj['在库数量'] ?? 0),
-                    'amount_in_compare' => $amount,
-                    'differ' => $amount-(($wmsInventoryCompareZp['在库数量'] ?? 0) + ($wmsInventoryCompareDj['在库数量'] ?? 0)),
-                ];
-                array_push($wasInventoryCompares,$wasInventoryCompareZP);
+                $params['quality'] = '正品';
+                $params['amount_in_sys'] = ($wmsInventoryCompareZp['在库数量'] ?? 0)+($wmsInventoryCompareDj['在库数量'] ?? 0);
+                $params['differ'] = $amount-(($wmsInventoryCompareZp['在库数量'] ?? 0) + ($wmsInventoryCompareDj['在库数量'] ?? 0));
+                array_push($wasInventoryCompares,$params);
             }
             if ($wmsInventoryCompareCc){
-                $wasInventoryCompareCC=[
-                    'owner_id'=>$owner_id,
-                    'commodity_id'=>$commodityId,
-                    'mission_code'=>$creatingMissionCode,
-                    'custom_location'=>$custom_location,
-                    'created_at'=>Carbon::now()->format('Y-m-d H:i:s'),
-                    'quality'=>'次品',
-                    'amount_in_sys'=>$wmsInventoryCompareCc['在库数量'],
-                    'amount_in_compare' =>$amount,
-                    'differ' =>$amount-($wmsInventoryCompareCc['在库数量']??0),
-                ];
-                array_push($wasInventoryCompares,$wasInventoryCompareCC);
+                $params['quality'] = '次品';
+                $params['amount_in_sys'] = $wmsInventoryCompareCc['在库数量'];
+                $params['differ'] = $amount-($wmsInventoryCompareCc['在库数量']??0);
+                array_push($wasInventoryCompares,$params);
+            }
+            if ($wmsInventoryCompareYjz){
+                $params['quality'] = '有价值';
+                $params['amount_in_sys'] = $wmsInventoryCompareYjz['在库数量'];
+                $params['differ'] = $amount-($wmsInventoryCompareYjz['在库数量']??0);
+                array_push($wasInventoryCompares,$params);
             }
-            if($unknownQualityStatus->isNotEmpty())return null;
+            if($unknownQualityStatus->isNotEmpty())continue;
         }
         $inventoryCompares=DB::table('inventory_compares')->insert($wasInventoryCompares);
         if (!$inventoryCompares)return null;

+ 1 - 1
app/Services/LaborReportService.php

@@ -28,7 +28,7 @@ class LaborReportService
     private function conditionQuery(array $params){
         $user=Auth::user();
         $laborReports=LaborReport::query()
-            ->with(['user','userDutyCheck','userWorkgroup','laborCompany','laborReportStatus','已退场','未审核'])->orderBy('labor_reports.id','DESC');
+            ->with(['user','userDutyCheck','userWorkgroup.signs','laborCompany','laborReportStatus'])->orderBy('labor_reports.id','DESC');
         if (!($params["is_export"] ?? false)&&!($params['id']??null)){
             $laborReports = $laborReports->whereNotIn('labor_reports.enter_number',function ($builder)use($params){
                 $builder->select('enter_number')->from('labor_reports')

+ 0 - 1
app/Services/LogService.php

@@ -7,7 +7,6 @@ namespace App\Services;
 use App\Log;
 use Exception;
 use Illuminate\Support\Facades\Redis;
-use Illuminate\Support\Facades\Request;
 
 class LogService
 {

+ 1 - 0
app/Services/LogisticService.php

@@ -46,6 +46,7 @@ Class LogisticService
     public function createLogisticByCarrierIds($codes){
         if(!$codes){return [];}
         $baseCustomers = OracleBasCustomer::query()
+            ->selectRaw('Customer_Type,CustomerID,Descr_C')
             ->where('Customer_Type','CA')
             ->whereIn('CustomerID',$codes)
             ->get();

+ 6 - 2
app/Services/OracleBasCustomerService.php

@@ -14,9 +14,13 @@ Class OracleBasCustomerService
     public function getWareHouse($customerIDs = null)
     {
         if(!$customerIDs){
-            return OracleBasCustomer::query()->where('Customer_Type','WH')->get();
+            return OracleBasCustomer::query()->selectRaw('Customer_Type,CustomerId,Descr_C')->where('Customer_Type','WH')->get();
         }
-        return  OracleBasCustomer::query()->where('Customer_Type','WH')->get();
+        return  OracleBasCustomer::query()
+            ->selectRaw('Customer_Type,CustomerId,Descr_C')
+            ->where('Customer_Type','WH')
+            ->whereIn('CustomerId',$customerIDs)
+            ->get();
     }
     public function getCustomers($codes)
     {

+ 3 - 0
app/Services/OracleDOCOrderHeaderService.php

@@ -78,6 +78,7 @@ Class OracleDOCOrderHeaderService
                 $query->selectRaw('BAS_Codes.CodeID,BAS_Codes.CodeName_C,BAS_Codes.Code');
             }])
             ->where('DOC_Order_Header.addTime','>=',$startDate)
+            ->orderByDesc('DOC_Order_Header.addTime')
             ->get();
     }
 
@@ -93,6 +94,8 @@ Class OracleDOCOrderHeaderService
                 $query->selectRaw('BAS_Codes.CodeID,BAS_Codes.CodeName_C,BAS_Codes.Code');
             }])
             ->where('DOC_Order_Header.editTime','>=',$startDate)
+            ->whereColumn('DOC_Order_Header.editTime','!=','DOC_Order_Header.addTime')
+            ->orderByDesc('DOC_Order_Header.editTime')
             ->get();
     }
 }

+ 3 - 1
app/Services/OrderIssueService.php

@@ -320,6 +320,7 @@ class OrderIssueService
         $orders = Order::query()->whereIn('code',data_get($orderHeaders,'*.orderno'))->whereHas('packages')->get();
         if($orders->count()==0)return false;
         $innerParams = [];
+        $data = Carbon::now()->format('Y-m-d H:i:s');
         foreach ($orderHeaders as $orderHeader) {
             $order = $orders->where('code',$orderHeader->orderno)->first();
             if($order==null){
@@ -331,7 +332,8 @@ class OrderIssueService
                 'result_explain' => $result_explain,
                 'imported_status' => $imported_status,
                 'custom_code' => $custom_code,
-                'hidden_tag' => $hiddenTag
+                'hidden_tag' => $hiddenTag,
+                'updated_at' => $data
             ];
         }
         try {

+ 8 - 4
app/Services/OrderPackageCommoditiesService.php

@@ -696,10 +696,10 @@ class OrderPackageCommoditiesService
             if(isset($orderAllocationDetails[$key])){
                 if(count($orderCommodity) == 1  && $orderAllocationDetails[$key]['amount'] != $orderCommodity[0]['amount']){
                     $update_params[$key] = $orderCommodity[0];
-                    $update_params['amount'] = $orderAllocationDetails[$key]['amount'];
+                    $update_params[$key]['amount'] = $orderAllocationDetails[$key]['amount'];
                 }elseif(count($orderCommodity)>1){
                     $update_params[$key] = array_shift($orderCommodity);
-                    $update_params[$key]['amount'] = $orderAllocationDetails[$key]['amount'];
+                    $update_params[$key][0]['amount'] = $orderAllocationDetails[$key]['amount'];
                     collect($orderCommodity)->each(function($item)use(&$del_orderCommodities){
                         $del_orderCommodities[] = $item;
                     });
@@ -775,6 +775,7 @@ class OrderPackageCommoditiesService
         foreach ($inner_params as $inner_param) {
             if($inner_param['logistic_number'] === '*' || $inner_param['logistic_number'] === ' ')continue;
             $package = $dataHandlerService->getKeyValue(['logistic_number'=>$inner_param['logistic_number']],$package_map);
+            if(!$package)continue;
             $commodity = $commodity_map[' owner='.$inner_param['owner_code'].' sku='.$inner_param['sku']] ?? null;
             $create_params[] = [
                 'order_package_id'=>$package->id,
@@ -786,8 +787,11 @@ class OrderPackageCommoditiesService
         }
         if(count($create_params)>0){
             try {
-                $bool = $this->insert($create_params);
-                LogService::log(__METHOD__,__FUNCTION__,'批量添加 orderCommodity --'. $bool ." || ".count($create_params).' || '.json_encode($create_params));
+                $inner_array = array_chunk($create_params,1000);
+                foreach ($inner_array as $item) {
+                    $bool = $this->insert($item);
+                    LogService::log(__METHOD__,__FUNCTION__,'批量添加 orderCommodity --'. $bool ." || ".count($create_params).' || '.json_encode($create_params));
+                }
             } catch (\Exception $e) {
                 LogService::log(__METHOD__,__FUNCTION__.'error','批量添加 orderCommodity error'." || ".count($create_params).' || '.json_encode($create_params));
             }

+ 5 - 2
app/Services/OrderPackageService.php

@@ -439,8 +439,11 @@ class OrderPackageService
         }
         if(count($inner_params)>0){
             try {
-                $bool = $this->insert($inner_params);
-                $bool ? LogService::log(__METHOD__, __FUNCTION__, '批量添加 OrderPackage ' . count($inner_params) . ' || ' . json_encode($inner_params)) : null;
+                $inner_array = array_chunk($inner_params,1000);
+                foreach ($inner_array as $params) {
+                    $bool = $this->insert($params);
+                    $bool ? LogService::log(__METHOD__, __FUNCTION__, '批量添加 OrderPackage ' . count($inner_params) . ' || ' . json_encode($inner_params)) : null;
+                }
             } catch (\Exception $e) {
                 LogService::log(__METHOD__, __FUNCTION__, '批量添加 OrderPackage error ' . count($inner_params) . ' || ' .json_encode($e->getMessage()). json_encode($inner_params).json_encode($e->getTraceAsString()));
             }

+ 133 - 16
app/Services/OrderService.php

@@ -13,11 +13,14 @@ use App\RejectedBill;
 use App\Services\common\BatchUpdateService;
 use App\Services\common\DataHandlerService;
 use App\Shop;
+use App\ValueStore;
 use App\Warehouse;
 use Carbon\Carbon;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\App;
+use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Redis;
 
 class OrderService
 {
@@ -30,10 +33,11 @@ class OrderService
         if(count($params)==0) return true;
         try {
             $bool= Order::query()->insert($params);
-            app('LogService')->log(__METHOD__, __FUNCTION__, '批量创建 Order' . json_encode($params));
+            if($bool)app('LogService')->log(__METHOD__, __FUNCTION__, '批量创建 Order' . json_encode($params));
+            else app('LogService')->log(__METHOD__,'ERROR'. __FUNCTION__, '批量创建 Order ERROR' . json_encode($params));
             return $bool;
         } catch (\Exception $e) {
-            app('LogService')->log(__METHOD__, __FUNCTION__, '批量创建 Order error' . json_encode($params).json_encode($e->getMessage()).json_encode($e->getTraceAsString()));
+            app('LogService')->log(__METHOD__, 'ERROR'.__FUNCTION__, '批量创建 Order ERROR' . json_encode($params).json_encode($e->getMessage()).json_encode($e->getTraceAsString()));
             return false;
         }
     }
@@ -543,7 +547,7 @@ class OrderService
         $insert_params = $this->getParamsByOrderHeader($orderHeaders,$owners_code_map,$logistics_code_map,$shop_name_map,$warehouses_code_map);
         $update_params = $this->getUpdateParams($orderHeaders,$owners_code_map,$logistics_code_map,$shop_name_map,$warehouses_code_map);
         if(count($insert_params)> 0){
-            $this->create($insert_params);
+            $this->insert($insert_params);
         }
         if(count($update_params)>1){
             $this->batchUpdate($update_params);
@@ -562,6 +566,7 @@ class OrderService
         foreach ($orders as $order) {
             $order_code_map[$order->code]= $order;
         }
+        $date = Carbon::now()->format('Y-m-d H:i:s');
         foreach ($orderHeaders_map as $orderHeader) {
             if($order_code_map[$orderHeader->orderno] ?? false)continue;
             $owner = $owners_code_map[$orderHeader->customerid] ?? null;
@@ -574,6 +579,7 @@ class OrderService
                 'owner_id' => $owner->id ?? null,
                 'wms_status' => $orderHeader->oracleBASCode ? $orderHeader->oracleBASCode->codename_c : null,
                 'created_at' => $orderHeader->addtime,
+                'updated_at' =>$date,
                 'logistic_id' => $logistic->id ?? null,
                 'shop_id' => $shop->id ?? null,
                 'consignee_name' => $orderHeader->c_contact,
@@ -796,6 +802,7 @@ class OrderService
         $warehouses = $warehouseService->getByWmsOrders($orderHeaders);
         $orders = $this->getByWmsOrders($orderHeaders);
         $created_params = $this->getCreateOrderModelsByWMSOrderHeaders($orderHeaders,$orders,$warehouses,$owners,$logistics,$shops); //3s
+
         $update_order = $this->getUpdateOrderModelByWMSOrderHeaders($orderHeaders,$orders,$warehouses,$owners,$logistics,$shops);
         // 转换插入 3s
         if(count($created_params) > 0){
@@ -803,13 +810,6 @@ class OrderService
                 $this->insert($inner_params->toArray());
             });
         }
-//        $this->insert($created_params);
-//        $this->insert($created_order->map(function($item){
-//            $array = $item->toArray();
-//            unset($array['logisticNumbers'],$array['packages'],$array['commodityPackages'],$array['amount']);
-//            return $array;
-//        })->toArray());
-
         $update_params = [
             ['id','code','warehouse_id','owner_id','shop_id','logistic_id','consignee_name','consignee_phone','province','city','district','address','client_code','wms_status','created_at','updated_at','wms_edittime']
         ];
@@ -977,19 +977,136 @@ class OrderService
          */
         $orderPackageService = app('OrderPackageService');
         $orderPackageCommoditiesService = app('OrderPackageCommoditiesService');
-        $order = Order::query()->with('packages.commodities')->where('code',$orderHeader->orderno)->first();
-        if($order) return $order;
-        $create_param = $this->getParamByOrderHeader($orderHeader);
+        $orderHeaders = collect();
+        $orderHeaders->push($orderHeader);
         try {
-            $orderHeaders = [$orderHeader];
-            $order = Order::query()->create($create_param);
+            $this->syncOrderByWMSOrderHeaders($orderHeaders);
             $orderPackageService->syncOrderPackage($orderHeaders);
             $orderPackageCommoditiesService->syncOrderPackageCommodities($orderHeaders);
             return  Order::query()->with('packages.commodities')->where('code',$orderHeader->orderno)->first();
         } catch (\Exception $e) {
-            app('LogService')->log(__METHOD__, 'Error'.__FUNCTION__, '创建 Order Error' .' || '. json_encode($order).' || '.json_encode($e->getMessage()).' || '.json_encode($e->getTraceAsString()));
+            app('LogService')->log(__METHOD__, 'Error'.__FUNCTION__, '创建 Order Error' .' || '. json_encode($orderHeader).' || '.json_encode($e->getMessage()).' || '.json_encode($e->getTraceAsString()));
             return null;
         }
     }
 
+
+    // TODO
+    public function setOrderSyncAt($key,$date,$bool=true){
+        if($bool){
+            ValueStore::query()->where('name',$key)->update(['value'=>Carbon::parse($date)->subSeconds(1)]);
+        } else {
+            ValueStore::query()->where('name',$key)->update(['value'=>$date]);
+        }
+    }
+    // TODO
+    public function getOrderSyncAt($key,$type='newest'){
+        $keyValue = ValueStore::query()->where('name',$key)->first();
+        if($keyValue->value)return $keyValue->value;
+        if($type == 'newest') $order = Order::query()->orderByDesc('Created_At')->first();
+        else $order = Order::query()->orderByDesc('Wms_EditTime')->first();
+        if($order)return $order->created_at;
+        return Carbon::now()->subSeconds(65);
+    }
+    // TODO
+    public function pushOrderCache($orderHeaders,$prefixKey,$hasKey,$list_key){
+        $list = [];
+        try {
+            Redis::LLEN($list_key);
+            collect($orderHeaders)->each(function($item)use(&$list,$prefixKey){
+                $list[] =$item->orderno;
+                Cache::put($prefixKey.$item->orderno,true);
+            });
+            if(count($orderHeaders) > 0){
+                Cache::put($list_key,$list);
+                Cache::put($hasKey,true);
+            }
+        } catch (\Exception $e) {
+
+        }
+    }
+    // TODO
+    public function filterOrderByCache($orderHeaders,$key)
+    {
+        /**
+         * @var OracleDOCOrderHeader $item
+         */
+        if(!$orderHeaders)return $orderHeaders;
+        if(!$key)return $orderHeaders;
+        try {
+            Redis::LLEN($key);
+            return array_filter($orderHeaders,function($item)use($key){
+                $bool = Cache::get($key.$item->orderno);
+                return !$bool;
+            });
+        } catch (\Exception $e) {
+            return $orderHeaders;
+        }
+    }
+    // TODO
+    public function cancelOrderCache($key,string $prefix)
+    {
+        try {
+            $list = Cache::get($key);
+            collect($list)->each(function ($item)use($prefix) {
+                Cache::forget($prefix.$item);
+            });
+            Cache::put($key,[]);
+        } catch (\Exception $e) {
+        }
+    }
+    // TODO
+    public function syncCreatedOrder(){
+        /**
+         * @var OracleDOCOrderHeaderService $oracleDOCOrderHeaderService
+         * @var OrderService $orderService
+         */
+        $newest         = config('sync.order_sync.cache_prefix.created_at');
+        $newest_list    = config('sync.order_sync.cache_prefix.newest_list');
+        $hasKey         = config('sync.order_sync.cache_prefix.newest_has');
+        $prefixKey      = config('sync.order_sync.cache_prefix.newest');
+
+        $last_date = $orderService->getOrderSyncAt($newest,'newest');                              // 获取时间点
+
+        $orderHeaders = $oracleDOCOrderHeaderService->getWmsOrderOnStartDateEdit($last_date);           // WMS订单
+
+        $last_order = $orderHeaders->first();                                                           // 时间点靠后的
+        $renewal_orders = $orderHeaders->where('addTime',$last_order->addtime);
+
+        $orderHeaders = $orderService->filterOrderByCache($orderHeaders,$newest_list);                  // 对比缓存
+
+        if(count($orderHeaders)>0 && count($orderHeaders) >0){
+            $orderService->syncOrder($orderHeaders);                                                //  同步订单
+            $orderService->cancelOrderCache($newest_list);                                              //  清除缓存
+            $orderService->pushOrderCache($renewal_orders,$prefixKey,$hasKey,$newest_list);             //  添加缓存
+            $orderService->setOrderSyncAt($newest,$last_order->addTime,count($orderHeaders)>0);   //  更新时间
+        }
+    }
+    // TODO
+    public function syncUpdatedOrder(){
+        /**
+         * @var OracleDOCOrderHeaderService $oracleDOCOrderHeaderService
+         * @var OrderService $orderService
+         */
+        $renewal        = config('sync.order_sync.cache_prefix.updated_at');
+        $renewal_list   = config('sync.order_sync.cache_prefix.renewal_list');
+        $hasKey         = config('sync.order_sync.cache_prefix.renewal_has');
+        $prefixKey      = config('sync.order_sync.cache_prefix.renewal');
+
+        $last_date = $orderService->getOrderSyncAt($renewal,'renewal');                               // 获取时间点
+
+        $orderHeaders = $oracleDOCOrderHeaderService->getWMSOrderOnStartDate($last_date);                   // WMS订单
+
+        $renewal_order = $orderHeaders->first();                                                            // 时间点靠后的
+        $renewal_orders =  $orderHeaders->where('addTime',$renewal_order->addtime);
+
+        $orderHeaders = $orderService->filterOrderByCache($orderHeaders,$renewal_list);                     // 对比缓存
+
+        if(count($renewal_orders)>0 && count($orderHeaders)>0){
+            $orderService->syncOrder($orderHeaders);                                                    // 同步订单
+            $orderService->cancelOrderCache($renewal_list);                                                 // 清除缓存
+            $orderService->pushOrderCache($renewal_orders,$prefixKey,$hasKey,$renewal_list);                // 添加缓存
+            $orderService->setOrderSyncAt($renewal,$renewal_order->addTime,count($orderHeaders)>0);   // 更新时间
+        }
+    }
 }

+ 1 - 1
app/Services/OwnerPriceExpressService.php

@@ -125,6 +125,6 @@ Class OwnerPriceExpressService
         if ($weight < $model->initial_weight)$weight = $model->initial_weight;
         $initialMoney = $model->initial_weight*$model->details[0]->initial_weight_price;
         $weight -= $model->initial_weight;
-        return ($weight*$model->details[0]->additional_weight_price)+$initialMoney;
+        return (ceil($weight/$model->additional_weight)*$model->details[0]->additional_weight_price)+$initialMoney;
     }
 }

+ 3 - 4
app/Services/OwnerPriceLogisticService.php

@@ -131,9 +131,8 @@ Class OwnerPriceLogisticService
     private function calculation($amount, $detail, $fee)
     {
         if ($amount < $detail->initial_amount)$amount = $detail->initial_amount; //小于起始数以起始数为准
-        $initialMoney = $detail->initial_amount*$detail->unit_price; //起始数计费
-        $amount -= $detail->initial_amount; //减起始数为续数
-        if ($initialMoney < $detail->initial_fee)$initialMoney = $detail->initial_fee; //小于起始计费以起始计费为准
-        return ($amount*$detail->unit_price)+$initialMoney+$detail->delivery_fee+$fee;
+        $money = $amount * $detail->unit_price;
+        if ($money < $detail->initial_fee)$money = $detail->initial_fee; //小于起始计费以起始计费为准
+        return $money+$detail->delivery_fee+$fee;
     }
 }

+ 96 - 72
app/Services/OwnerPriceOperationService.php

@@ -97,29 +97,29 @@ Class OwnerPriceOperationService
     /** 参数顺序: 数量 匹配对象 列映射 货主ID 单位ID 类型 SKU .
      *  匹配顺序: 类型 货主 策略 单位 特征                    ..多对多匹配规则废弃,1对1,设单位必定为件,对应规则必然只有一项存在
      *  单位匹配: 件,箱,单 由小到大,依次换算匹配           .
-     * @param int $amount
+     *
+     *  2:没有总数量存在,都为子项内数量
+     *
      * @param array|object $matchObject  key-val
      * @param array $columnMapping       key-val
      * @param string $owner_id
      * @param string $type
      * @param string $sku
      * @return double
-     * 错误代码: -1:非法数量 -2:无计费模型 -3:未知单位 -4:sku为空 -5:货主未找到 -6:无箱规 -7:未匹配到计费模型
+     * 错误代码: -1:无匹配对象 -2:无计费模型 -3:未知单位 -4:sku为空 -5:货主未找到 -6:无箱规 -7:未匹配到计费模型
      */
-    public function matchRule($amount, $matchObject, $columnMapping, $owner_id, $sku = null, $type = '出库')
+    public function matchRule($matchObject, $columnMapping, $owner_id, $sku = null, $type = '出库')
     {
-        if ($amount <= 0 )return -1;
-
         $unitModels = Unit::query()->whereIn("name",["件","箱","单"])->get();
         $units = [];
         foreach ($unitModels as $unitModel)$units[$unitModel->id] = $unitModel->name;
 
         $withs = $type=='出库' ? ['ownerOutStorageRules'=>function($query){
             /** @var Builder $query */
-            $query->orderByRaw("CASE strategy  WHEN '默认' THEN 1 WHEN '特征' THEN 2 WHEN '起步' THEN 3 END DESC,priority DESC");
+            $query->orderByRaw("CASE strategy  WHEN '起步' THEN 1 WHEN '默认' THEN 2 WHEN '特征' THEN 3 END DESC,priority DESC");
         }] : ['ownerInStorageRule'] ;
         $rules = OwnerPriceOperation::query()->with($withs)
-            ->where("operation_type","出库")
+            ->where("operation_type",$type)
             ->whereHas("ownerPriceOperationOwners",function ($query)use($owner_id){
                 /** @var Builder $query */
                 $query->where("id",$owner_id);
@@ -128,27 +128,36 @@ Class OwnerPriceOperationService
         if (!$rules)return -2;
 
         if ($type == '入库'){
+            $amountColumn = $columnMapping["amount"] ?? "amount";
+            $packageColumn = $columnMapping["packages"] ?? "packages";
+            $packages = $matchObject[$packageColumn] ?? false;
+            if (!$packages)return -1;
+
+            $amount = 0;
+            foreach ($packages as $package)$amount += $package[$amountColumn] ?? 0;
+            if (!$amount)return -1;
             foreach ($rules as $rule){
+                $sum = $amount;
                 if (!$rule->ownerInStorageRule)continue;
                 if ($rule->strategy == '特征'){
                     $bool = app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject);
                     if ($bool === true){
                         if (!isset($units[$rule->ownerInStorageRule->unit_id])) return -3;
                         if ($units[$rule->ownerInStorageRule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
-                            $amount = $this->changeUnit($amount,$owner_id,$sku);
-                            if ($amount<0) return $amount;
+                            $sum = $this->changeUnit($sum,$owner_id,$sku);
+                            if ($sum<0)return $sum;
                         }
-                        if ($units[$rule->ownerInStorageRule->unit_id] == '单')$amount = 1; //为单时数量设为1;
-                        return ceil($amount/$rule->ownerInStorageRule->amount)*$rule->ownerInStorageRule->unit_price;
+                        if ($units[$rule->ownerInStorageRule->unit_id] == '单')$sum = 1; //为单时数量设为1;
+                        return ceil($sum/$rule->ownerInStorageRule->amount)*$rule->ownerInStorageRule->unit_price;
                     };
                 }else{
                     if (!isset($units[$rule->ownerInStorageRule->unit_id])) return -3;
                     if ($units[$rule->ownerInStorageRule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
-                        $amount = $this->changeUnit($amount,$owner_id,$sku);
-                        if ($amount<0) return $amount;
+                        $sum = $this->changeUnit($sum,$owner_id,$sku);
+                        if ($sum<0)return $sum;
                     }
-                    if ($units[$rule->ownerInStorageRule->unit_id] == '单')$amount = 1; //为单时数量设为1;
-                    return ceil($amount/$rule->ownerInStorageRule->amount)*$rule->ownerInStorageRule->unit_price;
+                    if ($units[$rule->ownerInStorageRule->unit_id] == '单')$sum = 1; //为单时数量设为1;
+                    return ceil($sum/$rule->ownerInStorageRule->amount)*$rule->ownerInStorageRule->unit_price;
                 };
             }
             return -7;
@@ -159,11 +168,11 @@ Class OwnerPriceOperationService
             if ($rule->strategy == '特征'){
                 $bool = app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject);//匹配特征
                 if ($bool === true){
-                    $money = $this->matchOutStorage($amount,$rule->ownerOutStorageRules,$columnMapping,$matchObject,$units,$owner_id,$sku);
+                    $money = $this->matchOutStorage($rule->ownerOutStorageRules,$columnMapping,$matchObject,$units,$owner_id,$sku);
                     if ($money>0)return $money;
                 };
             }else{
-                $money = $this->matchOutStorage($amount,$rule->ownerOutStorageRules,$columnMapping,$matchObject,$units,$owner_id,$sku);
+                $money = $this->matchOutStorage($rule->ownerOutStorageRules,$columnMapping,$matchObject,$units,$owner_id,$sku);
                 if ($money>0)return $money;
             };
         }
@@ -176,78 +185,93 @@ Class OwnerPriceOperationService
         if (!$pack)return -6;
         return ceil($amount/$pack);
     }
-    private function matchOutStorage($amount, $rules, $columnMapping, $matchObject, $units, $owner_id, $sku)
+
+    private function matchOutStorage($rules, $columnMapping, $matchObject, $units, $owner_id, $sku)
     {
-        $money = 0;
+        $amountColumn = $columnMapping["amount"] ?? "amount";
+        $packageColumn = $columnMapping["packages"] ?? "packages";
+        $packages = $matchObject[$packageColumn] ?? false;
+        $commodityColumn = $columnMapping["商品名称"] ?? 'commodity';
+        if (!$packages)return -1;
+
+        $unitName = "";
         foreach ($rules as $rule){
             switch ($rule->strategy){
-                case "起步":
-                    $money = $rule->amount * $rule->unit_price;
-                    if ($units[$rule->unit_id] == '箱') { //为箱时同步商品寻找箱规
-                        if (!$sku)return -4;
-                        $pack = app("CommodityService")->getPack($owner_id,$sku);
-                        if (!$pack)return -6;
-                        $rule->amount *= $pack;
-                    }
-
-                    if ($amount < $rule->amount)$amount = $rule->amount;
-                    else $amount -= $rule->amount;
-                    break;
                 case "特征":
-                    if (app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject)){
-                        if (!isset($units[$rule->unit_id]) || $units[$rule->unit_id] == '单') return -3;
+                    foreach ($packages as &$package){
+                        if ($package["price"] ?? false)continue;
+                        if (!app("FeatureService")->matchFeature($rule->feature,["商品名称"=>"commodity"],["commodity"=>$package[$commodityColumn] ?? ''])) continue;
+
+                        if (!$unitName)$unitName = $units[$rule->unit_id];
+                        else {
+                            if ($unitName != $units[$rule->unit_id])
+                                return -3;
+                        }
+                        $package["price"] = $rule->unit_price;
+                        if (!isset($units[$rule->unit_id]) || $units[$rule->unit_id] == '单')return -3;
                         if ($units[$rule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
-                            $amount = $this->changeUnit($amount,$owner_id,$sku);
+                            $amount = $this->changeUnit($package[$amountColumn],$owner_id,$sku);
+                            if ($amount<0)return $amount;
+                            $package[$amountColumn] = $amount;
                         }
-                        return (ceil($amount/$rule->amount)*$rule->unit_price)+$money;
-                    };
+                    }
                     break;
                 case "默认":
-                    if (!isset($units[$rule->unit_id]) || $units[$rule->unit_id] == '单') return -3;
-                    if ($units[$rule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
-                        $amount = $this->changeUnit($amount,$owner_id,$sku);
+                    foreach ($packages as &$package){
+                        if ($package["price"] ?? false)continue; //校验是否已匹配到
+                        if (!$unitName)$unitName = $units[$rule->unit_id]; //校验单位是否一致
+                        else {
+                            if ($unitName != $units[$rule->unit_id])
+                                return -3;
+                        }
+
+                        $package["price"] = $rule->unit_price;
+                        if (!isset($units[$rule->unit_id]) || $units[$rule->unit_id] == '单')return -3;
+                        if ($units[$rule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
+                            $amount = $this->changeUnit($package[$amountColumn],$owner_id,$sku);
+                            if ($amount<0)return $amount;
+                            $package[$amountColumn] = $amount;
+                        }
                     }
-                    return (ceil($amount/$rule->amount)*$rule->unit_price)+$money;
                     break;
+                default:
+                    if ($unitName && $unitName != $units[$rule->unit_id])return -3; //校验单位是否一致
+
+                    $money = $rule->amount * $rule->unit_price;
+                    $startNumber = $rule->amount;
+                    $packages = $this->settingCount($packages,$amountColumn,$startNumber);
+                    if ($packages){
+                        foreach ($packages as $package){
+                            $money += $package[$amountColumn] * $package["price"];
+                        }
+                    }
+                    return $money;
             }
         }
         return -7;
     }
-
-    private function matchInStorage($amount, $matchObject, $columnMapping, $owner_id, $unit_id, $rules, $sku, $units = null, $isMatch = false)
+    //设置数量
+    private function settingCount($packages,$amountColumn,$startNumber)
     {
-        /*foreach ($rules as $rule){
-            if ($unit_id != $rule->ownerInStorageRule->unit_id)continue;
-            else{
-                if ($rule->strategy == '特征'){
-                    $bool = app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject);
-                    if ($bool === true){
-                        return ceil($amount/$rule->ownerInStorageRule->amount)*$rule->ownerInStorageRule->unit_price;
-                    };
-                }else{
-                    return ceil($amount/$rule->ownerInStorageRule->amount)*$rule->ownerInStorageRule->unit_price;
-                };
+        if (!$packages) return null;
+        $maxPrice = 0;
+        $index = null;
+        foreach ($packages as $i => $package){
+            if ($package[$amountColumn] <= 0){
+                unset($packages[$i]);continue;
+            }
+            if ($package["price"] > $maxPrice){
+                $maxPrice = $package["price"];
+                $index = $i;
             }
         }
-        //单位换算
-        if (!$units){
-            $unitModels = Unit::query()->whereIn("name",["件","箱","单"])->get();
-            if (!$unitModels) return null;
-            foreach ($unitModels as $unitModel)$units[$unitModel->name] = $unitModel->id;
+        if ($packages[$index][$amountColumn] >= $startNumber){
+            $packages[$index][$amountColumn] -= $startNumber;
+            return $packages;
+        }else{
+            unset($packages[$index]);
+            $startNumber -= $packages[$index][$amountColumn];
+            $this->settingCount($packages,$amountColumn,$startNumber);
         }
-        $name = array_search($unit_id,$units);
-        //递归匹配
-        switch ($name){
-            case "件"://布尔值校验是否匹配过件来确保箱只匹配一次件
-                return $this->matchInStorage($amount, $matchObject, $columnMapping, $owner_id, $units["箱"], $rules, $sku, $units, true);
-            case "箱"://箱存在向下向上转换
-                if ($isMatch){
-                    return $this->matchInStorage($amount, $matchObject, $columnMapping, $owner_id, $units["单"], $rules, $sku, $units);
-                }else{
-                    return $this->matchInStorage($amount, $matchObject, $columnMapping, $owner_id, $units["件"], $rules, $sku, $units);
-                }
-            case "单"://三次匹配皆无,返回null
-                return null;
-        }*/
     }
 }

+ 2 - 2
app/Services/OwnerService.php

@@ -118,9 +118,9 @@ Class OwnerService
     public function getByWmsOrders($orderHeaders){
         $customerIds = array_unique(data_get($orderHeaders,'*.customerid'));
         $customerIds = array_diff($customerIds,[null,'','*']);
-        $owners = Owner::query()->whereIn('code',data_get($orderHeaders,'*.customerid'))->get();
+        $owners = Owner::query()->whereIn('code',$customerIds)->get();
 
-        if($owners->count() < count($customerIds)){
+         if($owners->count() < count($customerIds)){
             $customerIds = array_diff($customerIds,data_get($owners,'*.code'));
             $owner_list = $this->createByWmsCustomerIds($customerIds);
             $owners=$owners->concat($owner_list);

+ 3 - 3
app/Services/OwnerStoragePriceModelService.php

@@ -43,10 +43,10 @@ Class OwnerStoragePriceModelService
     }
 
     //暂时不考虑单位换算问题:后期可能存在多单位换算,此处仅视为单位为 m²
-    public function calculationAmount(OwnerStoragePriceModel $model, $area, $owner_id = null, $month = null) :int
+    public function calculationAmount(OwnerStoragePriceModel $model, $area, $owner_id = null, $month = null)
     {
         if (!$model || !$area) return 0;
-        if ((int)$area < $model->minimum_area) $area = (int)$model->minimum_area;
+        if ($area < $model->minimum_area) $area = $model->minimum_area;
         $money = $area*$model->price;
         switch ($model->discount_type){
             case "按单减免":
@@ -58,7 +58,7 @@ Class OwnerStoragePriceModelService
                 }
                 break;
             case "固定减免":
-                $money -= (int)$model->discount_value;
+                $money -= $model->discount_value;
                 break;
         }
         return $money;

+ 7 - 11
app/Services/ShopService.php

@@ -31,8 +31,8 @@ class ShopService
     }
 
     public function getByWmsOrders($orderHeaders)
-    {    //issuepartyname
-        $maps = [];
+    {
+        $maps = []; //issuepartyname
         foreach ($orderHeaders as $orderHeader) {
             $value = ['owner_code'=>$orderHeader->customerid,'issuepartyname'=>$orderHeader->issuepartyname];
             if(!in_array($value,$maps))
@@ -46,10 +46,10 @@ class ShopService
             })->whereIn('name',$issuepartynames)->get();
         if($shops->count() < count($issuepartynames)){
             $shops_code = data_get($shops,'*.name');
-            $issuepartynames = array_diff($issuepartynames,$shops_code);
+            $names = array_diff($issuepartynames,$shops_code);
             $params = [];
             foreach ($maps as $item){
-               if(in_array($item['issuepartyname'],$issuepartynames))
+               if(in_array($item['issuepartyname'],$names))
                    $params[] = $item;
             }
             $shops_list = $this->createByNameAndOwnerCode($params);
@@ -59,9 +59,7 @@ class ShopService
     }
 
     public function createByNameAndOwnerCode(array $params){
-        $owners = Owner::query()
-            ->whereIn('code',data_get($params,'*.owner_code'))
-            ->get();
+        $owners = Owner::query()->whereIn('code',data_get($params,'*.owner_code'))->get();
         $owners_map = [];
         foreach ($owners as $owner) {
             $owners_map[$owner->code] = $owner;
@@ -82,11 +80,9 @@ class ShopService
                 app('LogService')->log(__METHOD__, __FUNCTION__, '批量创建 shop ' . count($insert_params) . json_encode($insert_params));
             }
         } catch (\Exception $e) {
-            app('LogService')->log(__METHOD__, __FUNCTION__, '批量创建 shop ' . json_encode($insert_params) .'||'.$e->getMessage().'||'.$e->getTraceAsString());
+            app('LogService')->log(__METHOD__, 'Error '.__FUNCTION__, '批量创建 shop Error' . json_encode($insert_params) .'||'.$e->getMessage().'||'.$e->getTraceAsString());
         } finally {
-            return Shop::query()
-                ->whereIn('name',data_get($params,'*.issuepartyname'))
-                ->get();
+            return Shop::query()->whereIn('name',data_get($params,'*.issuepartyname'))->get();
         }
     }
 

+ 2 - 2
app/Services/StoreItemService.php

@@ -104,7 +104,7 @@ Class StoreItemService
         $storeItems = $this->getByWms($asnDetails);
         $asnDetails_map = $dataHandlerService->dataHeader(['asnno', 'asnlineno', 'sku'], $asnDetails);
         $updateParams = [[
-            'id', 'store_id', 'asn_line_code', 'name', 'sku', 'barcode', 'amount', 'quality', 'status', 'created_at', 'updated_at'
+           /* 'id',*/ 'store_id', 'asn_line_code', 'name', 'sku', 'barcode', 'amount', 'quality', 'status', 'created_at', 'updated_at'
         ]];
         $delete_storeItems = [];
         foreach ($storeItems as $storeItem) {
@@ -124,7 +124,7 @@ Class StoreItemService
                 $storeItem->created_at != $asnDetail['addtime'] ||
                 $storeItem->updated_at != $asnDetail['edittime']) {
                 $updateParams[] = [
-                    'id' => $storeItem->id,
+                   /* 'id' => $storeItem->id,*/
                     'store_id' => $storeItem->store->id,
                     'asn_line_code' => $asnDetail['asnlineno'],
                     'name' => $asnDetail['skudescrc'],

+ 0 - 4
app/Services/StoreService.php

@@ -45,12 +45,8 @@ Class StoreService
     {
         /** @var OracleDocAsnHerderService $oracleDocAsnHerderService */
         $oracleDocAsnHerderService = app(OracleDocAsnHerderService::class);
-        var_dump('getWmsAsnOnStartDateCreate_start',Carbon::now());
         $asnHerders = $oracleDocAsnHerderService->getWmsAsnOnStartDateCreate($startDate);
-        var_dump('getWmsAsnOnStartDateCreate_end',Carbon::now());
-        var_dump('createStore_start',Carbon::now());
         $this->createStore($asnHerders);
-        var_dump('createStore_end',Carbon::now());
     }
 
     public function storeUpdateByWms($startDate)

+ 1 - 1
app/Services/UserService.php

@@ -28,6 +28,6 @@ class UserService
         if(!$user)return [];
         return $this->cacheService->getOrExecute("user{$user['id']}->getPermittingOwnerIds",function()use($user){
             return $user->getPermittingOwnerIdsAttribute() ?? [];
-        });
+        })??[];
     }
 }

+ 2 - 3
app/Services/WarehouseService.php

@@ -40,9 +40,9 @@ Class WarehouseService
         if(!$warehouse_ids)return null;
         /** @var Collection $oracleBasCustomers */
         $oracleBasCustomers=app(OracleBasCustomerService::class)->getWareHouse($warehouse_ids);
-        $warehouses=Warehouse::query()->where('code',data_get($oracleBasCustomers,'*.CustomerID'))->get();
+        $warehouses=Warehouse::query()->whereIn('code',data_get($oracleBasCustomers,'*.customerid'))->get();
         $oracleBasCustomers=$oracleBasCustomers->filter(function($oracleBasCustomer)use($warehouses){
-            return $warehouses->where('code',$oracleBasCustomer->warehouseid)->count()>0;
+            return $warehouses->where('code',$oracleBasCustomer->warehouseid)->count()==0;
         });
         foreach ($oracleBasCustomers as $oracleBasCustomer){
             $wereHouse=Warehouse::query()->create([
@@ -78,7 +78,6 @@ Class WarehouseService
                 'created_at' => $created_at,
             ];
         }
-
         try {
             if (count($insert_params) > 0) {
                 $this->insert($insert_params);

+ 1 - 1
app/Services/common/QueryService.php

@@ -42,7 +42,7 @@ Class QueryService
                     $queryTemp=$queryTemp->where($tableName.$column,'like','%'.$params[$param].'%')
                         ->where($tableName.'created_at','>',$today);
                     if($queryTemp->count()==0 || $queryTemp->first()[$column]==$params[$param]){
-                        $query=$query->where($tableName.$column,$params[$param]);
+                        $query=$query->where($tableName.$column,"like",$params[$param]."%");
                     }else{
                         $query=$query->where($tableName.$column,'like','%'.$params[$param].'%')
                             ->where($tableName.'created_at','>',$today);

+ 1 - 1
app/UserDutyCheck.php

@@ -28,7 +28,7 @@ class UserDutyCheck extends Model
         return $this->belongsTo('App\UserWorkgroup','workgroup_id','id');
     }
     public function laborReport(){
-        return $this->hasOne('App\LaborReport');
+        return $this->belongsTo('App\LaborReport','id','user_duty_check_id');
     }
 
     public function laborEnterCheck(){

+ 1 - 1
app/UserWorkgroup.php

@@ -20,7 +20,7 @@ class UserWorkgroup extends Model
         return $this->belongsTo('App\Warehouse','warehouse_id','id');
     }
     public  function signs(){
-        return $this->hasOne('App\Sign','signable_id','id');
+        return $this->belongsTo('App\Sign','signable_id','id');
     }
     public  function getTokenAttribute(){
         return md5($this['name'].Carbon::now()->format('Y-m-d'));

+ 14 - 0
config/sync.php

@@ -8,4 +8,18 @@ return [
         'interval' => 1,   // 时间以分为单位
         'start_at'=> '',    // 开始同步WMS的时间  时间格式: yyyy-MM-dd HH:mm:ss 如 2020-09-05 13:15:16
     ],
+    'order_sync' => [
+        'interval' => 1,   // 时间以分为单位
+        'start_at'=> '',    // 开始同步WMS的时间  时间格式: yyyy-MM-dd HH:mm:ss 如 2020-09-05 13:15:16
+        'cache_prefix' => [
+            'newest' =>'order_newest_',
+            'renewal' =>'order_renewal_',
+            'newest_has' => 'order_newest_has_set',             // 创建标记
+            'renewal_has' => 'order_renewal_has_set',           // 跟新标记
+            'created_at' => 'order_last_created_sync_at',       // 最后创建时间
+            'updated_at' => 'order_last_updated_sync_at',       // 最后更新时间
+            'newest_list' => 'order_newest_cache_keys',               // 新增保存记录
+            'renewal_list' => 'order_renewal_cache_keys'              // 创建保存记录
+        ]
+    ]
 ];

+ 16 - 0
database/factories/CarTypeFactory.php

@@ -0,0 +1,16 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\CarType;
+use Faker\Generator as Faker;
+
+$factory->define(CarType::class, function (Faker $faker) {
+    return [
+        'name' => $faker->name,
+        'model' => $faker->name,
+        'length' => mt_rand(6,250) / 4,
+        'load' => mt_rand(6,250) / 4,
+        'remark' => $faker->text(20),
+    ];
+});

+ 15 - 0
database/factories/CityFactory.php

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

+ 21 - 0
database/factories/CommodityFactory.php

@@ -0,0 +1,21 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\Commodity;
+use Faker\Generator as Faker;
+
+$factory->define(Commodity::class, function (Faker $faker) {
+    $type = ["无","临时"];
+    return [
+        'name' => $faker->name,
+        'sku' => md5(date('Ymd').\Illuminate\Support\Str::random(3)),
+        'owner_id' => factory(\App\Owner::class),
+        'length' => mt_rand(1,90) / 3,
+        'width' => mt_rand(1,90) / 3,
+        'height' => mt_rand(1,90) / 3,
+        'volumn' => mt_rand(10,900) / 3,
+        "type" => $type[array_rand($type)],
+        "pack_spec" => mt_rand(1,100)
+    ];
+});

+ 16 - 0
database/factories/FeatureFactory.php

@@ -0,0 +1,16 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\Feature;
+use Faker\Generator as Faker;
+
+$factory->define(Feature::class, function (Faker $faker) {
+    $type = ['商品名称','订单类型','承运商','店铺类型'];
+    $logic = ['包含','不包含','等于'];
+    return [
+        "type" => $type[array_rand($type)],     //类型
+        "logic" => $logic[array_rand($logic)],    //逻辑
+        "describe" => \Illuminate\Support\Str::random(5), //特征
+    ];
+});

+ 1 - 1
database/factories/LogisticFactory.php

@@ -8,6 +8,6 @@ use Faker\Generator as Faker;
 $factory->define(Logistic::class, function (Faker $faker) {
     return [
         'name' => $faker->name,
-        'code' => \Illuminate\Support\Str::random(8),
+        'code' => \Illuminate\Support\Str::random(3).md5(\Illuminate\Support\Str::random(5)),
     ];
 });

+ 27 - 0
database/factories/OrderFactory.php

@@ -0,0 +1,27 @@
+<?php
+
+/**
+ * @var \Illuminate\Database\Eloquent\Factory $factory
+ */
+use App\Order;
+use Faker\Generator as Faker;
+
+
+$factory->define(Order::class, function (Faker $faker) {
+    $status = ['处理中','未处理','已处理','取消','异常'];
+    $wms_status = ['分配完成','部分分配','订单完成'];
+    return [
+        'status' => $status[rand(0,4)],
+        'created_at'=>$faker->dateTime->format('y-m-d'),
+        'code' => $faker->uuid,
+        'client_code' =>$faker->uuid,
+        'consignee_name'=>$faker->uuid,
+        'consignee_phone' => $faker->phoneNumber,
+        'province' => $faker->state,
+        'city' =>$faker->city,
+        'district'=>$faker->secondaryAddress,
+        'address' => $faker->address,
+        'wms_status' => $wms_status[rand(0,2)],
+        'wms_edittime' => $faker->dateTimeBetween( '-30 hour', 'now',  null)
+    ];
+});

+ 41 - 0
database/factories/OrderIssueFactory.php

@@ -0,0 +1,41 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OrderIssue;
+use Faker\Generator as Faker;
+
+$factory->define(OrderIssue::class, function (Faker $faker) {
+    $rejecting_status = ['无','未退回','全部退回','部分退回','差异退回','超量退回','全部退回'];
+    $is_new_rejecting = ['无','有','已处理'];
+    $finance_confirm = ['是','否'];
+    $final_status = ['已解决','待退回','退回中'];
+    $logistic_express_remission = ['原单减免','部分减免','全部减免'];
+    $baoshi_express_remission = ['原单减免','部分减免','全部减免'];
+    $imported_status = ['正常','导入未处理','导入已梳理'];
+    return [
+        'order_id' =>function(){
+            return factory(\App\Order::class)->create()->id;
+        },
+        'created_at' => $faker->date('y-m-d'),
+        'rejected_bill_id' => 0,
+        'rejecting_status' => $rejecting_status[rand(0,count($rejecting_status)-1)],
+        'result_explain' => $faker->text(20),
+        'logistic_number_return'=>$faker->name,
+        'order_issue_type_id' => 0,
+        'second_order_id' => 0,
+        'is_new_rejecting' => $is_new_rejecting[rand(0,count($is_new_rejecting) -1)],
+        'second_client_no' => $faker->name,
+        'second_logistic_number' => $faker->name,
+        'final_status' => $final_status[rand(0,count($final_status)-1)],
+        'logistic_indemnity_money' => rand(0,10),
+        'logistic_express_remission' =>$logistic_express_remission[rand(0,1)] ,
+        'baoshi_indemnity_money' =>rand(0,1),
+        'baoshi_express_remission' => $baoshi_express_remission[rand(0,1)],
+        'user_workgroup_id' => 0,
+        'custom_code' => $faker->name,
+        'imported_status' => $imported_status[rand(0,count($imported_status)-1)],
+        'finance_confirm' =>$finance_confirm[rand(0,1)],
+        'hidden_tag' => $faker->name
+    ];
+});

+ 12 - 0
database/factories/OrderPackageFactory.php

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

+ 21 - 0
database/factories/OwnerAreaReportFactory.php

@@ -0,0 +1,21 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OwnerAreaReport;
+use Faker\Generator as Faker;
+
+$factory->define(OwnerAreaReport::class, function (Faker $faker) {
+    $status = ['编辑中','已完成',"编辑中","编辑中"];
+    return [
+        "owner_id" => factory(\App\Owner::class),             //货主ID
+        "counting_month" => $faker->date(),       //结算月
+        "owner_storage_price_model_id" => factory(\App\OwnerStoragePriceModel::class), //仓储计费ID
+        "user_owner_group_id" => factory(\App\UserOwnerGroup::class),  //项目组ID
+        "area_on_tray" => mt_rand(5,1000) / 6,         //货物整托
+        "area_on_half_tray" => mt_rand(5,1000) / 6,    //货物半托
+        "area_on_flat" => mt_rand(5,1000) / 6,         //平面区面积
+        "accounting_area" => mt_rand(50,10000) / 6,      //结算面积
+        "status" => $status[array_rand($status)]            //状态
+    ];
+});

+ 3 - 4
database/factories/OwnerBillReportFactory.php

@@ -4,13 +4,12 @@
 
 use App\OwnerBillReport;
 use Faker\Generator as Faker;
-$owner = \App\Owner::query()->whereNotNull("user_owner_group_id")->first();
-$factory->define(OwnerBillReport::class, function (Faker $faker)use(&$owner) {
-    if (!$owner)$owner = \App\Owner::query()->whereNotNull("user_owner_group_id")->first();
+
+$factory->define(OwnerBillReport::class, function (Faker $faker) {
     $initial_fee = mt_rand(0,50000) / 10;
     $confirm_fee = mt_rand(0,50000) / 10;
     return [
-        "owner_id" => $owner ? $owner->id : factory(\App\Owner::class),       //项目ID
+        "owner_id" => factory(\App\Owner::class),       //项目ID
         "counting_month" => $faker->date(), //结算月
         "initial_fee" => $initial_fee,    //原始账单金额
         "confirm_fee" => $confirm_fee,    //确认账单金额

+ 0 - 1
database/factories/OwnerFactory.php

@@ -10,7 +10,6 @@ $factory->define(Owner::class, function (Faker $faker) {
         'name' => $faker->name,                 //名称
         'code' => \Illuminate\Support\Str::random(5).date('yymmdd'),                 //代码
         'checking_count' => mt_rand(0,5),       //审核数量
-        "customer_id" => factory(App\Customer::class),          //客户ID
         "tax_rate" => mt_rand(0,100) / 10,             //税率
         "contract_number" => \Illuminate\Support\Str::random(5).date('yymmdd'),      //合同号
         "salesman" => $faker->name,             //销售名称

+ 9 - 23
database/factories/OwnerFeeDetailFactory.php

@@ -5,34 +5,20 @@
 use App\OwnerFeeDetail;
 use Faker\Generator as Faker;
 
-$owner = \App\Owner::query()->whereNotNull('customer_id')->first();
-if ($owner)$shop = \App\Shop::query()->where("owner_id",$owner->id)->first();
-else $shop = null;
-$logistic = \App\Logistic::query()->first();
-$method = \App\ProcessMethod::query()->first();
-$factory->define(OwnerFeeDetail::class, function (Faker $faker)use(&$owner,&$shop,&$logistic,&$method) {
-    if (!$owner)$owner = \App\Owner::query()->whereNotNull('customer_id')->first();
-    if (!$shop){
-        if ($owner)$shop = \App\Shop::query()->where("owner_id",$owner->id)->first();
-        else $shop = null;
-    }
-    if (!$logistic) $logistic = \App\Logistic::query()->first();
-    if (!$method)$method = \App\ProcessMethod::query()->first();
+$factory->define(OwnerFeeDetail::class, function (Faker $faker) {
     $type = ["发货","收货","增值服务"];
     return [
-        "owner_id"          => $owner ? $owner->id : factory(\App\Owner::class),         //货主ID
+        "owner_id"          => factory(\App\Owner::class),         //货主ID
         "worked_at"         => $faker->date(),//作业时间
-        "type"              =>$type[array_rand($type)],//类型
-        "shop_id"           =>$shop ? $shop->id : factory(\App\Shop::class),//店铺ID
+        "type"              => $type[array_rand($type)],//类型
+        "shop_id"           => factory(\App\Shop::class),//店铺ID
         "operation_bill"    => \Illuminate\Support\Str::random(10),//发/收/退/提货单号
         "consignee_name"    => $faker->name,   //收件人
-        "consignee_phone"   =>$faker->phoneNumber,  //收件人电话
-        "commodity_amount"  =>mt_rand(0,100), //商品数量
-        "logistic_bill"     =>\Illuminate\Support\Str::random(12),    //快递单号
-        "volume"            =>mt_rand(10,2600) / 88,//体积
-        "weight"            =>mt_rand(10,2600) / 88,           //重量
-        "logistic_id"       =>$logistic ? $logistic->id : factory(\App\Logistic::class),      //物流ID
-        "process_method_id" =>$method ? $method->id : factory(\App\ProcessMethod::class),//加工类型ID
+        "consignee_phone"   => $faker->phoneNumber,  //收件人电话
+        "commodity_amount"  => mt_rand(0,100), //商品数量
+        "logistic_bill"     => \Illuminate\Support\Str::random(12),    //快递单号
+        "volume"            => mt_rand(10,2600) / 88,//体积
+        "weight"            => mt_rand(10,2600) / 88,           //重量
         "work_fee"          =>mt_rand(100,10000) / 10,         //作业费
         "logistic_fee"      =>mt_rand(100,10000) / 10,     //物流费
     ];

+ 2 - 4
database/factories/OwnerOutStorageRuleFactory.php

@@ -5,15 +5,13 @@
 use App\OwnerOutStorageRule;
 use Faker\Generator as Faker;
 
-$unit = \App\Unit::query()->first();
-$factory->define(OwnerOutStorageRule::class, function (Faker $faker)use(&$unit) {
-    if (!$unit)$unit = \App\Unit::query()->first();
+$factory->define(OwnerOutStorageRule::class, function (Faker $faker) {
     $strategy = ['默认','特征'];
     return [
         "owner_price_operation_id"          => factory(\App\OwnerPriceOperation::class),         //作业计费ID
         "strategy"                          =>$strategy[array_rand($strategy)],         //策略
         "amount"                            =>mt_rand(0,100),                           //起步数
-        "unit_id"                           => $unit ? $unit->id : factory(\App\Unit::class),//单位ID
+        "unit_id"                           => factory(\App\Unit::class),//单位ID
         "unit_price"                        =>mt_rand(10,100) / 12,                       //单价
         "feature"                           =>\Illuminate\Support\Str::random(6),                          //特征
     ];

+ 15 - 0
database/factories/OwnerPriceDirectLogisticCarFactory.php

@@ -0,0 +1,15 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OwnerPriceDirectLogisticCar;
+use Faker\Generator as Faker;
+
+$factory->define(OwnerPriceDirectLogisticCar::class, function (Faker $faker) {
+    return [
+        "owner_price_direct_logistic_id" => factory(\App\OwnerPriceDirectLogistic::class),   //直发车计费ID
+        "car_type_id" => factory(\App\CarType::class),                      //车型ID
+        "base_fee" => mt_rand(6,250) / 4,                         //起步费
+        "additional_fee" => mt_rand(6,250) / 4,                   //续费(元/KM)
+    ];
+});

+ 13 - 0
database/factories/OwnerPriceDirectLogisticFactory.php

@@ -0,0 +1,13 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OwnerPriceDirectLogistic;
+use Faker\Generator as Faker;
+
+$factory->define(OwnerPriceDirectLogistic::class, function (Faker $faker) {
+    return [
+        "name" => $faker->name.md5(\Illuminate\Support\Str::random(3)),     //名称
+        "base_km" => mt_rand(1,100),  //起步公里数
+    ];
+});

+ 4 - 6
database/factories/OwnerPriceExpressFactory.php

@@ -5,12 +5,10 @@
 use App\OwnerPriceExpress;
 use Faker\Generator as Faker;
 
-$unit = \App\Unit::query()->first();
-$factory->define(OwnerPriceExpress::class, function (Faker $faker)use(&$unit) {
-    if (!$unit)$unit = \App\Unit::query()->first();
+$factory->define(OwnerPriceExpress::class, function (Faker $faker) {
     return [
-        "name" => $faker->name,                     //名称
-        "initial_weight_unit_id" => $unit ? $unit->id : factory(\App\Unit::class),   //首重单位
-        "additional_weight_unit_id" => $unit ? $unit->id : factory(\App\Unit::class),//续重单位
+        "name" => $faker->name,
+        "initial_weight" => mt_rand(6,260) / 5,
+        "additional_weight" => mt_rand(6,260) / 5,
     ];
 });

+ 16 - 0
database/factories/OwnerPriceExpressProvinceFactory.php

@@ -0,0 +1,16 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OwnerPriceExpressProvince;
+use Faker\Generator as Faker;
+
+$factory->define(OwnerPriceExpressProvince::class, function (Faker $faker) {
+    $province = \App\Province::query()->first();
+    return [
+        "owner_price_express_id" => factory(\App\OwnerPriceExpress::class),   //快递价格ID
+        "province_id" => $province->id,              //省份ID
+        "initial_weight_price" => mt_rand(6,260) / 5,     //初始单价
+        "additional_weight_price"=>mt_rand(6,260) / 5,  //续重单价
+    ];
+});

+ 23 - 0
database/factories/OwnerPriceLogisticDetailFactory.php

@@ -0,0 +1,23 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OwnerPriceLogisticDetail;
+use Faker\Generator as Faker;
+
+$factory->define(OwnerPriceLogisticDetail::class, function (Faker $faker) {
+    $province = \App\Province::query()->first();
+    $city = \App\City::query()->where("province_id",$province->id)->first();
+    return [
+        "owner_price_logistic_id" => factory(\App\OwnerPriceLogistic::class),  //物流计费
+        "unit_id" => factory(\App\Unit::class),                  //单位ID
+        "range" => "0-5",                    //区间
+        "province_id" => $province->id,              //省份ID
+        "city_id" => $city->id,                  //城市ID
+        "unit_price" => mt_rand(1,36) / 3,               //单价
+        "delivery_fee" => mt_rand(1,136) / 3,             //送货费
+        "initial_fee" => mt_rand(1,136) / 3,              //起始计费
+        "initial_amount" => mt_rand(1,136) / 3,           //起始计数
+        "rate" =>  mt_rand(1,136) / 3,                       //费率
+    ];
+});

+ 19 - 0
database/factories/OwnerPriceLogisticFactory.php

@@ -0,0 +1,19 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OwnerPriceLogistic;
+use Faker\Generator as Faker;
+
+$factory->define(OwnerPriceLogistic::class, function (Faker $faker) {
+    return [
+        "name" => $faker->name,             //名称
+        "unit_range" => "0-5,5-10,10-15,15-20",       //单价一区间
+        "unit_id" => factory(\App\Unit::class),          //单位一ID
+        "other_unit_range" => "0-5,5-10,10-15,15-20,30-", //单位二区间
+        "other_unit_id" => factory(\App\Unit::class),    //单位二ID
+        "pick_up_price" => mt_rand(2,230) / 3,    //提货费
+        "fuel_price" => mt_rand(2,230) / 3,       //燃油附加费
+        "service_price" => mt_rand(2,230) / 3,    //信息服务费
+    ];
+});

+ 6 - 4
database/factories/OwnerReportFactory.php

@@ -4,14 +4,16 @@
 
 use App\OwnerReport;
 use Faker\Generator as Faker;
-
-$factory->define(OwnerReport::class, function (Faker $faker) {
+$owner = \App\Owner::query()->first();
+$factory->define(OwnerReport::class, function (Faker $faker)use($owner) {
+    if (!$owner)$owner = \App\Owner::query()->first();
     return [
-        "owner_id" => factory(App\Owner::class),                     //货主ID
+        "owner_id" => $owner ? $owner->id : factory(App\Owner::class),                     //货主ID
         "counting_month" => $faker->date(),               //结算月
         "daily_average_order_amount" => mt_rand(0,10000),  //日均单量
         "current_month_counting_area" => mt_rand(100,100000) / 50,  //结算月盘点面积
         "last_month_counting_area"   => mt_rand(100,100000) / 50,  //结算月上月盘点面积
-        "owner_bill_report_id"  =>factory(App\OwnerBillReport::class)        //账单ID
+        "owner_bill_report_id"  =>factory(App\OwnerBillReport::class),        //账单ID
+        "total" => mt_rand(1,2000),
     ];
 });

+ 3 - 4
database/factories/OwnerStoragePriceModelFactory.php

@@ -4,9 +4,8 @@
 
 use App\OwnerStoragePriceModel;
 use Faker\Generator as Faker;
-$unit = \App\Unit::query()->first();
-$factory->define(OwnerStoragePriceModel::class, function (Faker $faker) use(&$unit){
-    if (!$unit) $unit = \App\Unit::query()->first();
+
+$factory->define(OwnerStoragePriceModel::class, function (Faker $faker){
     $counting_type = ['包仓','灵活用仓','统单价'];
     $using_type = ['常温','恒温'];
     $discount_type = ['无减免','按单减免','固定减免'];
@@ -17,6 +16,6 @@ $factory->define(OwnerStoragePriceModel::class, function (Faker $faker) use(&$un
         "price" => mt_rand(1,20) / 10,            //单价
         "discount_type" => $discount_type[array_rand($discount_type)],    //减免类型
         "discount_value" => mt_rand(0,10) / 12,   //减免值
-        "unit_id" => $unit ? $unit->id : factory(\App\Unit::class),          //单位ID
+        "unit_id" => factory(\App\Unit::class) ,          //单位ID
     ];
 });

+ 15 - 0
database/factories/OwnerTrakingOwnerFactory.php

@@ -0,0 +1,15 @@
+<?php
+
+/** @var \Illuminate\Database\Eloquent\Factory $factory */
+
+use App\OrderTrackingOwner;
+use Faker\Generator as Faker;
+
+$factory->define(OrderTrackingOwner::class, function (Faker $faker) {
+    return [
+        'owner_id'=>function(){
+            return factory(\App\Owner::class)->create()->id;
+        },
+        'status' => '启用'
+    ];
+});

+ 2 - 4
database/factories/ProcessMethodFactory.php

@@ -5,12 +5,10 @@
 use App\ProcessMethod;
 use Faker\Generator as Faker;
 
-$unit = \App\Unit::query()->first();
-$factory->define(ProcessMethod::class, function (Faker $faker)use(&$unit) {
-    if (!$unit)$unit = \App\Unit::query()->first();
+$factory->define(ProcessMethod::class, function (Faker $faker) {
     return [
         'name' => $faker->name,
-        "unit_id" => $unit ? $unit->id : factory(\App\Unit::class),
+        "unit_id" => factory(\App\Unit::class),
         "unit_price" => mt_rand(10,50) / 9,
     ];
 });

+ 12 - 0
database/factories/ProvinceFactory.php

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

+ 2 - 4
database/factories/ShopFactory.php

@@ -5,11 +5,9 @@
 use App\Shop;
 use Faker\Generator as Faker;
 
-$owner = \App\Owner::query()->whereNotNull('customer_id')->first();
-$factory->define(Shop::class, function (Faker $faker)use(&$owner) {
-    if (!$owner) $owner = \App\Owner::query()->whereNotNull('customer_id')->first();
+$factory->define(Shop::class, function (Faker $faker) {
     return [
         'name' => $faker->name,
-        'owner_id' => $owner ? $owner->id : factory(\App\Owner::class),
+        'owner_id' => factory(\App\Owner::class),
     ];
 });

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

@@ -18,8 +18,8 @@ class CreateStoresTable extends Migration
             $table->string('asn_code')->nullable()->unique()->comment('WMS的ASNNO单号');
             $table->integer('warehouse_id')->nullable()->comment('仓库ID');
             $table->integer('owner_id')->index()->nullable()->comment('货主ID');
-            $table->enum('stored_method',['正常','快速入库'])->default('正常');
-            $table->enum('status',['无需入库','已入库','未入库','待推单'])->nullable();
+            $table->enum('stored_method',['正常','快速入库','采购入库','笕尚退货入库单','笕尚进仓入库单','笕尚移仓入库单','B2B入库','笕尚调整入库单','换货入库','初始化库存','虚拟入库','其他入库','退货入库','调拨入库'])->default('正常');
+            $table->enum('status',['待盘点','盘点中','复盘中','已完成','已审核'])->default(null)->nullable();
             $table->string('remark')->nullable();
             $table->timestamp('deleted_at')->nullable()->index();
             $table->timestamp('updated_at')->nullable();

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

@@ -15,7 +15,7 @@ class CreateProcessesAdditionalBillsTable extends Migration
      */
     public function up()
     {
-        Schema::create('processes_contents', function (Blueprint $table) {
+        Schema::create('processes_additional_bills', function (Blueprint $table) {
             $table->bigIncrements('id');
             $table->bigInteger('process_id')->index()->comment('外键二次加工单');
             $table->string('wms_code')->index()->comment('单据号');
@@ -32,6 +32,6 @@ class CreateProcessesAdditionalBillsTable extends Migration
      */
     public function down()
     {
-        Schema::dropIfExists('processes_contents');
+        Schema::dropIfExists('processes_additional_bills');
     }
 }

+ 12 - 11
database/migrations/2020_03_30_112202_drop_commodity_barcode_column_to_barcode_table.php

@@ -15,21 +15,22 @@ class DropCommodityBarcodeColumnToBarcodeTable extends Migration
      */
     public function up()
     {
-        DB::insert('INSERT commodity_barcodes (code,commodity_id) SELECT barcode, id FROM commodities');
-        $this->delRepeated();
+//        \App\Commodity::query()->count();
+//        DB::insert('INSERT commodity_barcodes (code,commodity_id) SELECT barcode, id FROM commodities');
+//        $this->delRepeated();
         Schema::table('commodities', function (Blueprint $table) {
             $table->dropColumn('barcode');
         });
     }
 
-    private function delRepeated(){
-        $codes=CommodityBarcode::groupBy('code','commodity_id')->havingRaw('count(*) > ?', [1])->get();
-        $codes->each(function(CommodityBarcode $code){
-            $delCodes=CommodityBarcode::where('code',$code['code'])->where('commodity_id',$code['commodity_id'])->where('id','!=',$code['id'])->get();
-            $delCodes->each(function(CommodityBarcode $delcode){
-                $delcode->delete();
-            });
-        });
-    }
+//    private function delRepeated(){
+//        $codes=CommodityBarcode::groupBy('code','commodity_id')->havingRaw('count(*) > ?', [1])->get();
+//        $codes->each(function(CommodityBarcode $code){
+//            $delCodes=CommodityBarcode::where('code',$code['code'])->where('commodity_id',$code['commodity_id'])->where('id','!=',$code['id'])->get();
+//            $delCodes->each(function(CommodityBarcode $delcode){
+//                $delcode->delete();
+//            });
+//        });
+//    }
 
 }

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

@@ -14,7 +14,7 @@ class ChangeUserWorkgroup extends Migration
     public function up()
     {
         Schema::table('user_workgroups', function (Blueprint $table) {
-            $table->bigInteger('warehouse_id')->comment('外键到工作组');
+            $table->bigInteger('warehouse_id')->nullable()->comment('外键到工作组');
         });
     }
 

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

@@ -14,7 +14,7 @@ class ChangeUserDutyCheck extends Migration
     public function up()
     {
         Schema::table('user_duty_checks', function (Blueprint $table) {
-            $table->bigInteger('workgroup_id')->comment('外键到工作组');
+            $table->bigInteger('workgroup_id')->nullable()->comment('外键到工作组');
         });
     }
 

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

@@ -43,7 +43,7 @@ class CreateOperatorLogsTableAndAddAuthorityAndChangeProcessesColumnStatus exten
             $table->dropColumn('status');
         });
         Schema::table('processes',function (Blueprint $table){
-            $table->enum('status',['待审核','已驳回','待接单','待加工','加工中','待验收','待交接','交接完成'])->comment('状态');
+            $table->enum('status',['待审核','已驳回','待接单','待加工','加工中','待验收','待交接','交接完成'])->default('待审核')->comment('状态');
         });
     }
 

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

@@ -16,7 +16,7 @@ class CreateLaborReportStatusesTable extends Migration
         Schema::create('labor_report_statuses', function (Blueprint $table) {
             $table->bigIncrements('id');
             $table->bigInteger('labor_report_id')->index()->comment('外键临时工报表')->nullable();
-            $table->enum('status',['未审核','已入场','已退场','已换组','已退组'])->default('未审核')->nullable();
+            $table->enum('status',['未审核','已入场','已退场','已换组','已退组','已删除'])->default('未审核')->nullable();
             $table->timestamps();
         });
     }

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

@@ -31,7 +31,7 @@ class ChangeInventoryMissionsToInventoryAccountMissions extends Migration
             $table->integer('re_checked_amount')->nullable()->comment('复盘数量');
             $table->integer('difference_amount')->nullable()->comment('盘点差异');
             $table->integer('occupied_amount')->nullable()->comment('分配数量');
-            $table->enum('checked',['是','否'])->default('否')->comment('已盘点');
+            $table->enum('checked',['是','否','已复核','跳过','确认差异'])->default('否')->comment('否');
             $table->enum('returned',['是','否','无'])->default('无')->comment('已归位');
             $table->timestamps();
         });

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

@@ -17,7 +17,7 @@ class ChangeInventoriesToInventoryAccounts extends Migration
         Schema::create('inventory_accounts', function (Blueprint $table) {
             $table->bigIncrements('id');
             $table->integer('owner_id')->index();
-            $table->enum('type',['全盘','动盘'])->comment('盘点类型');
+            $table->enum('type',['全盘','动盘','局部盘点'])->comment('盘点类型');
             $table->timestamp('start_at')->nullable();
             $table->timestamp('end_at')->nullable();
             $table->integer('total')->nullable()->comment('记录数');

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

@@ -14,7 +14,7 @@ class AddInventoryAccountsStatus extends Migration
     public function up()
     {
         Schema::table('inventory_accounts', function (Blueprint $table) {
-            $table->enum('status',['待盘点','盘点中','复盘中','已完成'])->default('待盘点')->comment('盘点状态');
+            $table->enum('status',['待盘点','盘点中','复盘中','已完成','已审核'])->nullable()->default(null)->comment('盘点状态');
         });
     }
 

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

@@ -1,33 +0,0 @@
-<?php
-
-use Illuminate\Database\Migrations\Migration;
-use Illuminate\Database\Schema\Blueprint;
-use Illuminate\Support\Facades\DB;
-use Illuminate\Support\Facades\Schema;
-
-class ChangeInventoryAccountMissionColumnCheckedToThree extends Migration
-{
-    /**
-     * Run the migrations.
-     *
-     * @return void
-     */
-    public function up()
-    {
-        DB::statement("ALTER TABLE inventory_account_missions MODIFY COLUMN checked enum ('是','否','已复核') default '否'");
-        Schema::table('inventory_account_missions', function (Blueprint $table) {
-        });
-    }
-
-    /**
-     * Reverse the migrations.
-     *
-     * @return void
-     */
-    public function down()
-    {
-        DB::statement("ALTER TABLE inventory_account_missions MODIFY COLUMN checked enum ('是','否') default '否'");
-        Schema::table('inventory_account_missions', function (Blueprint $table) {
-        });
-    }
-}

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

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

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

@@ -14,7 +14,7 @@ class ChangeLaborReportsLaborCompanyToLaborCompanyId extends Migration
     public function up()
     {
         Schema::table('labor_reports', function (Blueprint $table) {
-            $table->bigInteger('labor_company_id')->index()->comment('劳务所');
+            $table->bigInteger('labor_company_id')->nullable()->index()->comment('劳务所');
         });
         $laborReports=\App\LaborReport::query()->get();
         foreach ($laborReports as $laborReport){

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

@@ -1,33 +0,0 @@
-<?php
-
-use Illuminate\Database\Migrations\Migration;
-use Illuminate\Database\Schema\Blueprint;
-use Illuminate\Support\Facades\DB;
-use Illuminate\Support\Facades\Schema;
-
-class ChangeInventoryAccountMissionCheckedColumnCheckedToFour extends Migration
-{
-    /**
-     * Run the migrations.
-     *
-     * @return void
-     */
-    public function up()
-    {
-        DB::statement("ALTER TABLE inventory_account_missions MODIFY COLUMN checked enum ('是','否','已复核','跳过') default '否'");
-        Schema::table('inventory_account_missions', function (Blueprint $table) {
-        });
-    }
-
-    /**
-     * Reverse the migrations.
-     *
-     * @return void
-     */
-    public function down()
-    {
-        DB::statement("ALTER TABLE inventory_account_missions MODIFY COLUMN checked enum ('是','否','已复核') default '否'");
-        Schema::table('inventory_account_missions', function (Blueprint $table) {
-        });
-    }
-}

+ 17 - 15
database/migrations/2020_09_20_142656_change_order_issue.php

@@ -18,12 +18,13 @@ class ChangeOrderIssue extends Migration
             $table->string('logistic_number_return')->nullable()->index()->after('order_id');
         });
 
-        $orderIssues = \App\OrderIssue::query()->get();
-
-        foreach ($orderIssues as $orderIssue) {
-            $rejectedBill = $orderIssue->hasOne(RejectedBill::class, 'id', 'rejected_bill_id')->first();
-            if($rejectedBill ?? false){
-                $orderIssue->update(['logistic_number_return'=>$rejectedBill->logistic_number_return ?? null]);
+        $orderIssues = \App\OrderIssue::query()->withTrashed()->get();
+        if($orderIssues->count()>0){
+            foreach ($orderIssues as $orderIssue) {
+                $rejectedBill = $orderIssue->hasOne(RejectedBill::class, 'id', 'rejected_bill_id')->first();
+                if($rejectedBill ?? false){
+                    $orderIssue->update(['logistic_number_return'=>$rejectedBill->logistic_number_return ?? null]);
+                }
             }
         }
 
@@ -45,17 +46,18 @@ class ChangeOrderIssue extends Migration
 //            $table->integer('rejected_bill_id')->index()->nullable()->comment('退回单')->after('order_id');
 //        });
 
-        $orderIssues = \App\OrderIssue::query()->get();
-
-        foreach ($orderIssues as $orderIssue) {
-            $rejectedBill =  $orderIssue->hasOne(RejectedBill::class, 'logistic_number_return', 'logistic_number_return')->first();
-            if($rejectedBill ?? false){
-                $orderIssue->update(['rejected_bill_id'=>$rejectedBill->id ?? null]);
+        $orderIssues = \App\OrderIssue::query()->withTrashed()->get();
+        if($orderIssues->count()>0){
+            foreach ($orderIssues as $orderIssue) {
+                $rejectedBill =  $orderIssue->hasOne(RejectedBill::class, 'logistic_number_return', 'logistic_number_return')->first();
+                if($rejectedBill ?? false){
+                    $orderIssue->update(['rejected_bill_id'=>$rejectedBill->id ?? null]);
+                }
             }
         }
 
-        Schema::table('order_issues',function (Blueprint $table) {
-            $table->dropColumn('logistic_number_return');
-        });
+//        Schema::table('order_issues',function (Blueprint $table) {
+//            $table->dropColumn('logistic_number_return');
+//        });
     }
 }

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

@@ -16,7 +16,7 @@ class AddAuthoritiesAndChangeInventoryAccounts extends Migration
     public function up()
     {
         (new Authority(['name'=>'人事管理-临时工报表-编辑备注','alias_name'=>'人事管理-临时工报表-编辑备注']))->save();
-        DB::statement("ALTER TABLE inventory_accounts MODIFY COLUMN type enum ('全盘','动盘','局部盘点')");
+//        DB::statement("ALTER TABLE inventory_accounts MODIFY COLUMN type enum ('全盘','动盘','局部盘点')");
         Schema::table('inventory_accounts', function (Blueprint $table) {
             $table->string('remark')->nullable()->comment('备注');
         });
@@ -31,7 +31,7 @@ class AddAuthoritiesAndChangeInventoryAccounts extends Migration
     public function down()
     {
         Authority::where('name','人事管理-临时工报表-编辑备注')->delete();
-        DB::statement("ALTER TABLE inventory_accounts MODIFY COLUMN type enum ('全盘','动盘')");
+//        DB::statement("ALTER TABLE inventory_accounts MODIFY COLUMN type enum ('全盘','动盘')");
         Schema::table('inventory_accounts', function (Blueprint $table) {
             $table->dropColumn('remark');
         });

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

@@ -14,7 +14,7 @@ class ChangeLaborReportStatus extends Migration
      */
     public function up()
     {
-        DB::statement("ALTER TABLE labor_report_statuses MODIFY COLUMN status enum ('未审核','已入场','已退场','已换组','已退组','已删除') default '未审核'");
+//        DB::statement("ALTER TABLE labor_report_statuses MODIFY COLUMN status enum ('未审核','已入场','已退场','已换组','已退组','已删除') default '未审核'");
     }
 
     /**
@@ -24,6 +24,6 @@ class ChangeLaborReportStatus extends Migration
      */
     public function down()
     {
-        DB::statement("ALTER TABLE labor_report_statuses MODIFY COLUMN status enum ('未审核','已入场','已退场','已换组','已退组') default '未审核'");
+//        DB::statement("ALTER TABLE labor_report_statuses MODIFY COLUMN status enum ('未审核','已入场','已退场','已换组','已退组') default '未审核'");
     }
 }

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

@@ -14,7 +14,7 @@ class ChangeInventoryAccountMissionCheckedColumnCheckedToFive extends Migration
      */
     public function up()
     {
-        DB::statement("ALTER TABLE inventory_account_missions MODIFY COLUMN checked enum ('是','否','已复核','跳过','确认差异') default '否'");
+//        DB::statement("ALTER TABLE inventory_account_missions MODIFY COLUMN checked enum ('是','否','已复核','跳过','确认差异') default '否'");
         Schema::table('inventory_account_missions', function (Blueprint $table) {
         });
     }
@@ -26,7 +26,7 @@ class ChangeInventoryAccountMissionCheckedColumnCheckedToFive extends Migration
      */
     public function down()
     {
-        DB::statement("ALTER TABLE inventory_account_missions MODIFY COLUMN checked enum ('是','否','已复核','跳过') default '否'");
+//        DB::statement("ALTER TABLE inventory_account_missions MODIFY COLUMN checked enum ('是','否','已复核','跳过') default '否'");
         Schema::table('inventory_account_missions', function (Blueprint $table) {
         });
     }

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

@@ -15,7 +15,7 @@ class AddOrderTrackOrderCode extends Migration
     {
         //
         Schema::table('order_trackings', function (Blueprint $table) {
-            $table->string('order_client_code')->index()->comment('订单号')->after('web_order_number');
+            $table->string('order_client_code')->nullable()->index()->comment('订单号')->after('web_order_number');
         });
     }
 

+ 7 - 5
database/migrations/2020_10_14_112825_add_order_issue_second_client_no.php

@@ -18,11 +18,13 @@ class AddOrderIssueSecondClientNo extends Migration
         Schema::table('order_issues', function (Blueprint $table) {
             $table->string('second_client_no')->index()->nullable()->comment('二次客户订单号')->after('second_order_id');
         });
-        $orderIssues = \App\OrderIssue::query()->whereNotNull('second_order_id')->get();
-        foreach ($orderIssues as $orderIssue) {
-            $order = $orderIssue->hasOne('App\Order', 'id', 'second_order_id')->first();
-            if($order ?? false){
-                $orderIssue->update(['second_client_no'=>$order->client_code ?? null]);
+        $orderIssues = \App\OrderIssue::query()->withTrashed()->whereNotNull('second_order_id')->get();
+        if($orderIssues->count() > 0){
+            foreach ($orderIssues as $orderIssue) {
+                $order = $orderIssue->hasOne('App\Order', 'id', 'second_order_id')->first();
+                if($order ?? false){
+                    $orderIssue->update(['second_client_no'=>$order->client_code ?? null]);
+                }
             }
         }
     }

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

@@ -68,7 +68,10 @@ class CreateLogisticTimingsTable extends Migration
                 'updated_at' => $time
             ];
         }
-        LogisticTiming::query()->insert($create_array);
+        $inner_param = array_chunk($create_array,100);
+        foreach ($inner_param as $item) {
+            LogisticTiming::query()->insert($item);
+        }
     }
 
     public function getMap()

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

@@ -14,7 +14,7 @@ class ChangeStoreStatusColumn extends Migration
      */
     public function up()
     {
-        DB::statement("ALTER TABLE stores MODIFY COLUMN status enum ('无需入库','已入库','未入库','待推单','完全收货','部分收货','已码盘','订单创建','ASN关闭','等待释放','收货取消') default null");
+//        DB::statement("ALTER TABLE stores MODIFY COLUMN status enum ('无需入库','已入库','未入库','待推单','完全收货','部分收货','已码盘','订单创建','ASN关闭','等待释放','收货取消') default null");
         Schema::table('stores', function (Blueprint $table) {
         });
     }
@@ -26,7 +26,7 @@ class ChangeStoreStatusColumn extends Migration
      */
     public function down()
     {
-        DB::statement("ALTER TABLE stores MODIFY COLUMN status enum ('无需入库','已入库','未入库','待推单') default null");
+//        DB::statement("ALTER TABLE stores MODIFY COLUMN status enum ('无需入库','已入库','未入库','待推单') default null");
         Schema::table('stores', function (Blueprint $table) {
         });
     }

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

@@ -14,7 +14,7 @@ class ChangeStoreStoredMethodColumn extends Migration
      */
     public function up()
     {
-        DB::statement("ALTER TABLE stores MODIFY COLUMN stored_method enum ('正常','快速入库','采购入库','笕尚退货入库单','笕尚进仓入库单','笕尚移仓入库单','B2B入库','笕尚调整入库单','换货入库','初始化库存','虚拟入库','其他入库','退货入库','调拨入库') default '正常'");
+//        DB::statement("ALTER TABLE stores MODIFY COLUMN stored_method enum ('正常','快速入库','采购入库','笕尚退货入库单','笕尚进仓入库单','笕尚移仓入库单','B2B入库','笕尚调整入库单','换货入库','初始化库存','虚拟入库','其他入库','退货入库','调拨入库') default '正常'");
         Schema::table('stores', function (Blueprint $table) {
         });
     }
@@ -26,7 +26,7 @@ class ChangeStoreStoredMethodColumn extends Migration
      */
     public function down()
     {
-        DB::statement("ALTER TABLE stores MODIFY COLUMN stored_method enum ('正常','快速入库') default '正常'");
+//        DB::statement("ALTER TABLE stores MODIFY COLUMN stored_method enum ('正常','快速入库') default '正常'");
         Schema::table('stores', function (Blueprint $table) {
         });
     }

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

@@ -14,7 +14,7 @@ class ChangeStoreItemsStatusColumn extends Migration
      */
     public function up()
     {
-        DB::statement("ALTER TABLE store_items MODIFY COLUMN status enum ('无需入库','已入库','未入库','待推单','完全收货','部分收货','已码盘','订单创建','ASN关闭','等待释放','收货取消') default null");
+//        DB::statement("ALTER TABLE store_items MODIFY COLUMN status enum ('无需入库','已入库','未入库','待推单','完全收货','部分收货','已码盘','订单创建','ASN关闭','等待释放','收货取消') default null");
         Schema::table('store_items', function (Blueprint $table) {
         });
     }
@@ -26,7 +26,7 @@ class ChangeStoreItemsStatusColumn extends Migration
      */
     public function down()
     {
-        DB::statement("ALTER TABLE store_items MODIFY COLUMN status enum ('无需入库','已入库','未入库','待推单') default null");
+//        DB::statement("ALTER TABLE store_items MODIFY COLUMN status enum ('无需入库','已入库','未入库','待推单') default null");
         Schema::table('store_items', function (Blueprint $table) {
         });
     }

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

@@ -14,7 +14,7 @@ class ChangeInventoryAccountsStatusColumn extends Migration
      */
     public function up()
     {
-        DB::statement("ALTER TABLE inventory_accounts MODIFY COLUMN status enum ('待盘点','盘点中','复盘中','已完成','已审核') default null");
+//        DB::statement("ALTER TABLE inventory_accounts MODIFY COLUMN status enum ('待盘点','盘点中','复盘中','已完成','已审核') default null");
         Schema::table('inventory_accounts', function (Blueprint $table) {
         });
 
@@ -27,7 +27,7 @@ class ChangeInventoryAccountsStatusColumn extends Migration
      */
     public function down()
     {
-        DB::statement("ALTER TABLE inventory_accounts MODIFY COLUMN status enum ('待盘点','盘点中','复盘中','已完成') default null");
+//        DB::statement("ALTER TABLE inventory_accounts MODIFY COLUMN status enum ('待盘点','盘点中','复盘中','已完成') default null");
         Schema::table('inventory_accounts', function (Blueprint $table) {
         });
     }

Некоторые файлы не были показаны из-за большого количества измененных файлов