CommodityService.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. <?php
  2. namespace App\Services;
  3. use App\Commodity;
  4. use App\Http\Controllers\CommodityController;
  5. use App\CommodityBarcode;
  6. use App\OracleBasSKU;
  7. use App\Owner;
  8. use App\Services\common\BatchUpdateService;
  9. use App\Services\common\DataHandlerService;
  10. use App\ValueStore;
  11. use Carbon\Carbon;
  12. use Illuminate\Database\Eloquent\Builder;
  13. use Illuminate\Database\Eloquent\Collection;
  14. use Illuminate\Support\Facades\Cache;
  15. Class CommodityService
  16. {
  17. /**
  18. * @var CacheService $cacheService
  19. * @var OwnerService $ownerService
  20. */
  21. private $cacheService;
  22. private $ownerService;
  23. function __construct()
  24. {
  25. $this->cacheService = app('CacheService');
  26. $this->ownerService = app('OwnerService');
  27. }
  28. public function firstOrCreate($param, $column = null): Commodity
  29. {
  30. if ($column) return Commodity::query()->firstOrCreate($param, $column);
  31. return Commodity::query()->firstOrCreate($param);
  32. }
  33. public function updateOrCreate($param, $column = null)
  34. {
  35. if ($column) return Commodity::query()->updateOrCreate($param, $column);
  36. return Commodity::query()->updateOrCreate($param);
  37. }
  38. public function first(array $params, $with = null)
  39. {
  40. $commodity = Commodity::query();
  41. if ($with) $commodity->with($with);
  42. foreach ($params as $column => $value) {
  43. if (!is_array($value)) $commodity->where($column, $value);
  44. else $commodity->whereIn($column, $value);
  45. }
  46. return $commodity->first();
  47. }
  48. public function get(array $params)
  49. {
  50. $query = Commodity::query()->with('barcodes');
  51. if ($params["owner_id"] ?? false) {
  52. $query->where("owner_id", $params["owner_id"]);
  53. }
  54. if ($params["sku"] ?? false) {
  55. if (!is_array($params["sku"])) $params["sku"] = [$params["sku"]];
  56. $query->whereIn('sku', $params["sku"]);
  57. }
  58. return $query->get();
  59. }
  60. public function insert(array $params)
  61. {
  62. return Commodity::query()->insert($params);
  63. }
  64. public function getOwnerCommodities(array $params)
  65. {
  66. $query = Commodity::query();
  67. foreach ($params as $column => $value) {
  68. if (!is_array($value)) $query->where($column, $value);
  69. else $query->whereIn($column, $value);
  70. }
  71. return $query->get();
  72. }
  73. /* 批量更新 */
  74. public function batchUpdate(array $params)
  75. {
  76. return app(BatchUpdateService::class)->batchUpdate('commodities', $params);
  77. }
  78. /* 根据货主条形码查找商品 */
  79. private function ownerBarcodeSeekCommodityQuery(Builder $query, array $ownerParam, $barcode)
  80. {
  81. $query->whereHas('owner', function ($builder) use ($ownerParam) {
  82. foreach ($ownerParam as $column => $param) {
  83. $builder->where($column, $param);
  84. }
  85. });
  86. $query->whereHas('barcodes', function ($builder) use ($barcode) {
  87. if (is_array($barcode)) $builder->whereIn('code', $barcode);
  88. else $builder->where('code', $barcode);
  89. });
  90. // haozi 2020-12-14
  91. // $query->whereIn('id', function ($builder) use ($barcode) {
  92. // if (is_array($barcode)) $builder->from('commodity_barcodes')->select('commodity_id')->whereIn('code', $barcode);
  93. // else $builder->from('commodity_barcodes')->select('commodity_id')->where('code', $barcode);
  94. // });
  95. return $query;
  96. }
  97. public function ownerBarcodeSeekCommodityFirst(array $ownerParam, $barcode, $with = null)
  98. {
  99. $commodity = Commodity::query();
  100. if ($with) $commodity->with($with);
  101. $commodity = $this->ownerBarcodeSeekCommodityQuery($commodity, $ownerParam, $barcode);
  102. return $commodity->first();
  103. }
  104. public function ownerBarcodeSeekCommodityGet(array $ownerParam, $barcode, $isNullSku = false)
  105. {
  106. $commodities = Commodity::query()->with('barcodes');
  107. if ($isNullSku) $commodities->whereNull('sku');
  108. $commodities = $this->ownerBarcodeSeekCommodityQuery($commodities, $ownerParam, $barcode);
  109. return $commodities->get();
  110. }
  111. /* 通过货主代码与条形码寻找FLUX商品补充至WMS 单条*/
  112. public function ownerAndBarcodeFirstOrCreate(Owner $owner, $barcode)
  113. {
  114. $wmsCommodity = app('OracleBasSkuService')->first(['customerid' => $owner->code, 'barcode' => $barcode]);
  115. if (!$wmsCommodity) return null;
  116. $commodity = $this->firstOrCreate(['owner_id' => $owner->id, 'sku' => $wmsCommodity->sku], [
  117. "name" => $wmsCommodity->descr_c,
  118. "sku" => $wmsCommodity->sku,
  119. "owner_id" => $owner->id,
  120. "length" => $wmsCommodity->skulength,
  121. "width" => $wmsCommodity->skuwidth,
  122. "height" => $wmsCommodity->skuhigh,
  123. "volumn" => $wmsCommodity->cube,
  124. ]);
  125. if ($wmsCommodity->alternate_sku1) app('CommodityBarcodeService')->first([
  126. 'commodity_id' => $commodity->id,
  127. 'code' => $wmsCommodity->alternate_sku1,
  128. ]);
  129. if ($wmsCommodity->alternate_sku2) app('CommodityBarcodeService')->first([
  130. 'commodity_id' => $commodity->id,
  131. 'code' => $wmsCommodity->alternate_sku2,
  132. ]);
  133. return $commodity;
  134. }
  135. public function create(array $params)
  136. {
  137. return Commodity::query()->create($params);
  138. }
  139. public function getByWmsOrders($orderHeaders)
  140. {
  141. if (!$orderHeaders) return null;
  142. $customerId_sku_map = [];
  143. foreach ($orderHeaders as $orderHeader) {
  144. $oracleDOCOrderDetails = $orderHeader->oracleDOCOrderDetails;
  145. foreach ($oracleDOCOrderDetails as $oracleDOCOrderDetail) {
  146. $value = [
  147. 'owner_code' => $oracleDOCOrderDetail->customerid,
  148. 'sku' => $oracleDOCOrderDetail->sku
  149. ];
  150. if (!in_array($value, $customerId_sku_map)) {
  151. $customerId_sku_map[] = $value;
  152. }
  153. }
  154. }
  155. $owner_codes = array_diff(array_unique(data_get($customerId_sku_map, '*.owner_code')), ['', '*', null]);
  156. if (!$owner_codes) return null;
  157. $owners = Owner::query()->whereIn('code', $owner_codes)->get();
  158. $owners_code_map = [];
  159. $owners_id_map = [];
  160. foreach ($owners as $owner) {
  161. $owners_code_map[$owner->code] = $owner;
  162. $owners_id_map[$owner->id] = $owner;
  163. }
  164. $orderHeader_sku = array_diff(array_unique(data_get($customerId_sku_map, '*.sku')), ['', '*', null]);
  165. $commodities = Commodity::query()
  166. ->whereIn('owner_id', data_get($owners, '*.id'))
  167. ->whereIn('sku', $orderHeader_sku)
  168. ->groupBy('owner_id', 'sku') //*!!!!!!!!
  169. ->get();
  170. if ($commodities->count() < count($customerId_sku_map)) {
  171. $commoditiesInWAS索引_sku = [];
  172. foreach ($commodities as $commodityInWms) {
  173. $owner = $owners_id_map[$commodityInWms->owner_id] ?? '';
  174. if (!$owner) continue;
  175. $key = 'owner_cod=' . $owner['code'] . ' sku=' . $commodityInWms->sku;
  176. $commoditiesInWAS索引_sku[$key] = $commodityInWms;
  177. }
  178. $commodities需要新增 = [];
  179. foreach ($customerId_sku_map as $commodityInWms) {
  180. $key = 'owner_cod=' . $commodityInWms['owner_code'] . ' sku=' . $commodityInWms['sku'];
  181. if ($commoditiesInWAS索引_sku[$key] ?? false) continue;
  182. $commodities需要新增[$key] = $commodityInWms;
  183. }
  184. $commodity_set = $this->createCommodities($commodities需要新增, $owners_code_map);
  185. $commodities = $commodities->concat($commodity_set);
  186. }
  187. return $commodities;
  188. }
  189. public function createCommodities($params, $owners_code_map)
  190. {
  191. if (!$params) return [];
  192. $bas_sku_arr = OracleBasSKU::query()
  193. ->selectRaw('customerid,sku,descr_c,skulength,skuwidth,skuhigh,cube')
  194. ->whereIn('CustomerID', data_get($params, '*.owner_code'))
  195. ->whereIn('Sku', data_get($params, '*.sku'))
  196. ->get();
  197. $insert_params = [];
  198. $created_at = Carbon::now()->format('Y-m-d H:i:s');
  199. foreach ($bas_sku_arr as $bas_sku) {
  200. $owner = $owners_code_map[$bas_sku->customerid] ?? '';
  201. if (!$owner) continue;
  202. if ($bas_sku->sku == null) continue;
  203. if ($bas_sku->descr_c == '') continue;
  204. $insert_params[] = [
  205. 'owner_id' => $owner->id,
  206. 'sku' => $bas_sku->sku,
  207. 'name' => $bas_sku->descr_c,
  208. 'created_at' => $created_at,
  209. 'length' => $bas_sku->skulength,
  210. 'width' => $bas_sku->skuwidth,
  211. 'height' => $bas_sku->skuhigh,
  212. 'volumn' => $bas_sku->cube
  213. ];
  214. }
  215. if (count($insert_params) > 0) {
  216. try {
  217. $this->insert($insert_params);
  218. app('LogService')->log(__METHOD__, __FUNCTION__, '批量添加 commodity ' . count($insert_params) . json_encode($insert_params));
  219. } catch (\Exception $e) {
  220. app('LogService')->log(__METHOD__, __FUNCTION__, '批量添加 commodity error' . json_encode($insert_params) . "||" . $e->getMessage() . '||' . $e->getTraceAsString());
  221. }
  222. }
  223. return Commodity::query()
  224. ->whereIn('owner_id', data_get($owners_code_map, '*.id'))
  225. ->whereIn('sku', data_get($params, '*.sku'))
  226. ->get();
  227. }
  228. public function createTemporaryCommodity(array $params)
  229. {
  230. $params["type"] = "临时";
  231. return Commodity::query()->create($params);
  232. }
  233. public function syncBarcodes($barcodesStr, $ownerId, $sku): Commodity
  234. {
  235. $barcodes = (function () use ($barcodesStr) {
  236. $barcodes = rtrim($barcodesStr, ',');
  237. $barcodes = explode(',', $barcodes);
  238. foreach ($barcodes as $k => $barcode) {
  239. if (!trim($barcode)) unset($barcodes[$k]);
  240. }
  241. return $barcodes;
  242. })();
  243. //
  244. // $commodities=$this->get_([$ownerId],[$sku],[],true);
  245. // if ($commodities->first()){
  246. // $commodity=$commodities->first();
  247. // }else{
  248. $commodity = $this->firstOrCreate(['owner_id' => $ownerId, 'sku' => $sku]);
  249. // }
  250. $commodityBarcodes = $commodity['barcodes'] ?? new Collection();
  251. /** @var CommodityBarcodeService $commodityBarcodeService */
  252. $commodityBarcodeService = app('CommodityBarcodeService');
  253. $redundantCommodityBarcodes = new Collection();
  254. foreach ($commodityBarcodes as $commodityBarcode) {//清除数组中 已经在商品有的条码,清除商品条码中,不在数组中的条码
  255. $hasMatch = false;
  256. foreach ($barcodes as $key => $barcode) {
  257. if ($barcodes[$key] == $commodityBarcode['code']) {
  258. $hasMatch = true;
  259. unset($barcodes[$key]);
  260. break;
  261. }
  262. }
  263. if (!$hasMatch) {
  264. $redundantCommodityBarcodes->push($commodityBarcode);
  265. }
  266. }
  267. if (!empty($redundantCommodityBarcodes)) {
  268. $commodityBarcodeService->destroyCollections($redundantCommodityBarcodes);
  269. }
  270. if (!empty($barcodes)) {
  271. $commodityBarcodeService->insertMany_onCommodities([['commodity_id' => $commodity['id'], 'barcodes' => $barcodes]]);
  272. }
  273. return $commodity;
  274. }
  275. public function destroyWithOffspring(Commodity $commodity)
  276. {
  277. $barcodesIds = $commodity->barcodes->map(function ($barcode) {
  278. return $barcode['id'];
  279. });
  280. CommodityBarcode::destroy($barcodesIds);
  281. $commodity->delete();
  282. }
  283. public function syncWMSOrderCode($owner, $skus)
  284. {
  285. $basSku = OracleBasSKU::query()->whereIn('SKU', $skus)->where('CustomerID', $owner->code)->get();
  286. $inner_params = [];
  287. $created_at = new Carbon();
  288. $basSku->each(function ($bas_sku) use (&$inner_params, $owner, $created_at) {
  289. $inner_params = [
  290. 'owner_id' => $owner->id,
  291. 'sku' => $bas_sku->sku,
  292. 'name' => $bas_sku->descr_c,
  293. 'created_at' => $created_at,
  294. 'length' => $bas_sku->skulength,
  295. 'width' => $bas_sku->skuwidth,
  296. 'height' => $bas_sku->skuhigh,
  297. 'volumn' => $bas_sku->cube
  298. ];
  299. });
  300. if (count($inner_params) > 0) {
  301. try {
  302. $this->insert($inner_params);
  303. app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($inner_params));
  304. } catch (\Exception $e) {
  305. app('LogService')->log(__METHOD__, 'Error ' . __FUNCTION__, json_encode($inner_params) . ' || ' . $e->getMessage());
  306. }
  307. }
  308. }
  309. //获取箱规
  310. public function getPack($owner_id, $sku)
  311. {
  312. $that = $this;
  313. return app("CacheService")->getOrExecute("pack_{$owner_id}_{$sku}", function () use ($owner_id, $sku, $that) {
  314. $commodity = $that->first([
  315. "owner_id" => $owner_id,
  316. "sku" => $sku
  317. ]);
  318. if (!$commodity || $commodity->pack_spec === null) {
  319. $owner = app("OwnerService")->find($owner_id);
  320. $action = new CommodityController();
  321. $action->syncOwnerCommodities($owner->id, $owner->code, $sku);
  322. }
  323. return $that->first([
  324. "owner_id" => $owner_id,
  325. "sku" => $sku
  326. ])->pack_spec;
  327. });
  328. }
  329. //是否存在
  330. public function isExist(array $params)
  331. {
  332. $query = Commodity::query();
  333. if ($params["barcode"] ?? false) {
  334. $query->whereHas("barcodes", function ($query) use ($params) {
  335. /** @var Builder $query */
  336. $query->where("code", $params["barcode"]);
  337. });
  338. unset($params["barcode"]);
  339. }
  340. foreach ($params as $column => $param) {
  341. $query->where($column, $param);
  342. }
  343. if ($query->count() > 0) return true;
  344. return false;
  345. }
  346. public function getCommoditiesByMap($map)
  347. {
  348. $collect = collect();
  349. if (count($map) == 0) return $collect;
  350. foreach ($map as $item) {
  351. $commodity = $this->getCommodityByOwnerCodeAndSKU($item['owner_code'], $item['sku']);
  352. $collect->push($commodity);
  353. }
  354. return $collect;
  355. }
  356. public function getCommodityByOwnerCodeAndSKU($ownerCode, $sku)
  357. {
  358. $commodity_key = "owner_code_{$ownerCode}_sku_{$sku}";
  359. return Cache::remember($commodity_key, config('cache.expirations.forever'), function () use ($ownerCode, $sku) {
  360. $commodity = Commodity::query()->where('sku', $sku)->whereHas('owner', function ($query) use ($ownerCode) {
  361. $query->where('code', $ownerCode);
  362. })->first();
  363. if (isset($commodity)) return $commodity;
  364. $basSKu = app('OracleBasSkuService')->first(['sku' => $sku, 'customerid' => $ownerCode]);
  365. return Commodity::query()->create($this->getParamsByBasSku($basSKu));
  366. });
  367. }
  368. public function getParamsByBasSku($basSku, $owner = null)
  369. {
  370. if (empty($owner)) {
  371. $owner = app('OwnerService')->getOwnerByCode($basSku['customerid']);
  372. }
  373. return [
  374. 'owner_id' => $owner['id'] ?? '',
  375. 'sku' => $basSku['sku'],
  376. 'name' => $basSku['descr_c'],
  377. 'length' => $basSku['skulength'],
  378. 'width' => $basSku['skuwidth'],
  379. 'height' => $basSku['skuhigh'],
  380. 'volumn' => $basSku['cube']
  381. ];
  382. }
  383. public function syncCommodityCreated()
  384. {
  385. $created_at = config('sync.commodity_sync.created_at');
  386. $create_set = config('sync.commodity_sync.cache_prefix.create_set');
  387. $create_keys = config('sync.commodity_sync.cache_prefix.create_keys');
  388. $create_key = config('sync.commodity_sync.cache_prefix.create');
  389. /** @var OracleBasSkuService $oracleBasSkuService */
  390. $oracleBasSkuService = app(OracleBasSkuService::class);
  391. $last_time = $this->getAsnLastSyncAt($created_at, 'create');
  392. $basSkus = $oracleBasSkuService->getWmsCreatedCommodities($last_time);
  393. $last_time = $basSkus->first()['addtime'];
  394. $last_records = $basSkus->where('addtime', $last_time);
  395. if (!$basSkus) return;
  396. $this->syncCreateCommodity($basSkus);
  397. $this->deleteCacheKey($create_set, $create_keys);
  398. $this->setLastRecordsByRedis($create_key, $create_set, $create_keys, $last_records);
  399. $this->setAsnLastSyncAt($created_at, $last_time);
  400. }
  401. public function syncCommodityUpdated()
  402. {
  403. $updated_at = config('sync.commodity_sync.updated_at');
  404. $update_set = config('sync.commodity_sync.cache_prefix.update_set');
  405. $update_keys = config('sync.commodity_sync.cache_prefix.update_keys');
  406. $update_key = config('sync.commodity_sync.cache_prefix.update');
  407. /** @var OracleBasSkuService $oracleBasSkuService */
  408. $oracleBasSkuService = app(OracleBasSkuService::class);
  409. $last_time = $this->getAsnLastSyncAt($updated_at, 'update');
  410. $basSkus = $oracleBasSkuService->getWmsUpdatedCommodities($last_time);
  411. $last_time = $basSkus->first()['edittime'];
  412. $last_records = $basSkus->where('edittime', $last_time);
  413. if (!$basSkus) return;
  414. $this->syncUpdateCommodity($basSkus);
  415. $this->deleteCacheKey($update_set, $update_keys);
  416. $this->setLastRecordsByRedis($update_key, $update_set, $update_keys, $last_records);
  417. $this->setAsnLastSyncAt($updated_at, $last_time);
  418. }
  419. public function syncCreateCommodity($addBasSkus)
  420. {
  421. if (count($addBasSkus) < 1) return null;
  422. $insert_params = $this->getParamsByBasSkus($addBasSkus);
  423. if (!$insert_params) return;
  424. $this->insertCommodities($insert_params);
  425. /** @var CommodityBarcodeService $commodityBarcodeService */
  426. $commodityBarcodeService = app(CommodityBarcodeService::class);
  427. $commodityBarcodeService->createBarcodeByWms($addBasSkus);
  428. }
  429. public function insertCommodities($insert_params)
  430. {
  431. if (count($insert_params) < 1) return;
  432. $ownerIds = array_unique(data_get($insert_params, '*.owner_id'));
  433. sort($ownerIds);
  434. $skus = array_unique(data_get($insert_params, '*.sku'));
  435. sort($skus);
  436. try {
  437. $bool = Commodity::query()->insert($insert_params);
  438. if ($bool) {
  439. app('LogService')->log(__METHOD__, __FUNCTION__, "批量添加 Commodity Success " . count($insert_params) . ' || ' . json_encode($insert_params));
  440. $commodities = Commodity::query()->with('owner')->whereIn('owner_id', $ownerIds)->whereIn('sku', $skus)->get();
  441. $md5 = md5(json_encode([$skus, $ownerIds]));
  442. if (Cache::has('commodity_' . $md5)) Cache::forget('commodity_' . $md5);
  443. $this->pushToCache($commodities);
  444. } else app('LogService')->log(__METHOD__, __FUNCTION__, "批量添加 Commodity FAILED " . ' || ' . json_encode($insert_params));
  445. } catch (\Exception $e) {
  446. app('LogService')->log(__METHOD__, __FUNCTION__, "批量添加 Commodity ERROR " . ' || ' . json_encode($insert_params) . ' || ' . json_encode($e->getMessage()) . ' || ' . json_encode($e->getTraceAsString()));
  447. }
  448. }
  449. public function getParamsByBasSkus($addBasSkus)
  450. {
  451. $owner_sku_map = [];
  452. $sku = [];
  453. $owner_code = [];
  454. $owner_codes = [];
  455. $addBasSkus->each(function ($addBasSku) use (&$owner_sku_map, &$sku, &$owner_codes, &$owner_code) {
  456. if (!empty($addBasSku['customerid']) && !empty($addBasSku['sku'])) {
  457. $key = "owner_code_{$addBasSku['customerid']}_sku_{$addBasSku['sku']}";
  458. $owner_sku_map[$key] = ['owner_code' => $addBasSku['customerid'], 'sku' => $addBasSku['sku']];
  459. $sku[] = $addBasSku['sku'];
  460. $owner_code[] = $addBasSku['customerid'];
  461. $owner_codes[$addBasSku['customerid']] = $addBasSku['customerid'];
  462. }
  463. });
  464. /** @var OwnerService $ownerService */
  465. $ownerService = app(OwnerService::class);
  466. $owner_id = (function () use ($ownerService, $owner_codes) {
  467. $owners = $ownerService->getOwnerByCodes($owner_codes);
  468. $map = [];
  469. $owners->each(function ($owner) use (&$map) {
  470. $map[] = $owner['id'];
  471. });
  472. return $map;
  473. })();
  474. $owner_map = (function () use ($ownerService, $owner_codes) {
  475. $owners = $ownerService->getOwnerByCodes($owner_codes);
  476. $map = [];
  477. $owners->each(function ($owner) use (&$map) {
  478. $map[$owner['code']] = $owner['id'];
  479. });
  480. return $map;
  481. })();
  482. if (count($owner_sku_map) == 0) return null;
  483. $commodities = Commodity::query()
  484. ->whereIn('owner_id', array_unique($owner_id))
  485. ->whereIn('sku', array_unique($sku))
  486. ->groupBy('owner_id', 'sku')
  487. ->get();
  488. $unexists = [];
  489. foreach ($owner_sku_map as $item) {
  490. $commodity = Cache::get("owner_code_{$item['owner_code']}_sku_{$item['sku']}");
  491. if ($commodity) continue;
  492. $commodity = $commodities->where('sku', $item['sku'])->where('owner_id', $owner_map[$item['owner_code']])->first();
  493. if ($commodity) continue;
  494. $items = [
  495. 'owner_code' => $item['owner_code'],
  496. 'sku' => $item['sku']
  497. ];
  498. $unexists[json_encode($items)] = true;
  499. }
  500. if (count($unexists) == 0) return null;
  501. $BasSKUs = $addBasSkus->filter(function ($bas_sku) use ($unexists) {
  502. $arr = [
  503. 'owner_code' => $bas_sku['customerid'],
  504. 'sku' => $bas_sku['sku']
  505. ];
  506. return $unexists[json_encode($arr)] ?? false;
  507. });
  508. $inner_params = (function () use ($BasSKUs, $owner_map) {
  509. $map = [];
  510. $BasSKUs->each(function ($basSku) use (&$map, $owner_map) {
  511. $map[] = [
  512. 'owner_id' => $owner_map[$basSku['customerid']] ?? '',
  513. 'sku' => $basSku->sku,
  514. 'name' => $basSku->descr_c,
  515. 'length' => $basSku->skulength,
  516. 'width' => $basSku->skuwidth,
  517. 'height' => $basSku->skuhigh,
  518. 'volumn' => $basSku->cube,
  519. 'created_at' => $basSku->addtime,
  520. 'updated_at' => $basSku->edittime,
  521. 'pack_spec' => $basSku->packid == 'STANDARD' ? 0 : explode("/", $basSku->packid)[1],
  522. ];
  523. });
  524. return $map;
  525. })();
  526. if (count($inner_params) == 0) return null;
  527. return $inner_params;
  528. }
  529. public function syncUpdateCommodity($addBasSkus)
  530. {
  531. $sku = [];
  532. $owner_codes = [];
  533. $addBasSkus->each(function ($addBasSku) use (&$sku, &$owner_codes) {
  534. if (!empty($addBasSku['customerid']) && !empty($addBasSku['sku'])) {
  535. $sku[] = $addBasSku['sku'];
  536. $owner_codes[$addBasSku['customerid']] = $addBasSku['customerid'];
  537. }
  538. });
  539. /**
  540. * @var OwnerService $ownerService
  541. * @var DataHandlerService $dataHandlerService
  542. */
  543. $ownerService = app(OwnerService::class);
  544. $dataHandlerService = app(DataHandlerService::class);
  545. $owner_map = (function () use ($ownerService, $owner_codes) {
  546. $owners = $ownerService->getOwnerByCodes($owner_codes);
  547. $map = [];
  548. $owners->each(function ($owner) use (&$map) {
  549. $map[$owner['code']] = $owner['id'];
  550. });
  551. return $map;
  552. })();
  553. $owner_id = (function () use ($ownerService, $owner_codes) {
  554. $owners = $ownerService->getOwnerByCodes($owner_codes);
  555. $map = [];
  556. $owners->each(function ($owner) use (&$map) {
  557. $map[] = $owner['id'];
  558. });
  559. return $map;
  560. })();
  561. $commodities = Commodity::query()
  562. ->whereIn('owner_id', array_unique($owner_id))
  563. ->whereIn('sku', array_unique($sku))
  564. ->groupBy('owner_id', 'sku')
  565. ->get();
  566. $commodities_map = $dataHandlerService->dataHeader(['owner_id', 'sku'], $commodities);
  567. $updateParams = [[
  568. 'id', 'name', 'sku', 'owner_id', 'length', 'width', 'height', 'volumn', 'pack_spec', 'updated_at', 'created_at'
  569. ]];
  570. $insert_params = [];
  571. foreach ($addBasSkus as $basSku) {
  572. $commodity = Cache::get("owner_code_{$basSku['customerid']}_sku_{$basSku['sku']}");
  573. if (!$commodity) {
  574. $commodity = $dataHandlerService->getKeyValue(['owner_id' => $owner_map[$basSku['customerid']], 'sku' => $basSku['sku']], $commodities_map);
  575. if (!$commodity) {
  576. $insert_params[] = [
  577. 'owner_id' => $owner_map[$basSku['customerid']] ?? '',
  578. 'sku' => $basSku->sku,
  579. 'name' => $basSku->descr_c,
  580. 'length' => $basSku->skulength,
  581. 'width' => $basSku->skuwidth,
  582. 'height' => $basSku->skuhigh,
  583. 'volumn' => $basSku->cube,
  584. 'created_at' => $basSku->addtime,
  585. 'updated_at' => $basSku->edittime,
  586. 'pack_spec' => $basSku->packid == 'STANDARD' ? 0 : explode("/", $basSku->packid)[1],
  587. ];
  588. continue;
  589. };
  590. }
  591. if ($commodity->sku != $basSku->sku ||
  592. $commodity->name != $basSku->descr_c ||
  593. $commodity->length != $basSku->skulength ||
  594. $commodity->width != $basSku->skuwidth ||
  595. $commodity->height != $basSku->skuhigh ||
  596. $commodity->volumn != $basSku->cube ||
  597. $commodity->created_at != $basSku->addtime ||
  598. $commodity->updated_at != $basSku->edittime ||
  599. $commodity->pack_spec != $basSku->pickid) {
  600. $updateParams[] = [
  601. 'id' => $commodity->id,
  602. 'owner_id' => $owner_map[$basSku['customerid']] ?? '',
  603. 'sku' => $basSku->sku,
  604. 'name' => $basSku->descr_c,
  605. 'length' => $basSku->skulength,
  606. 'width' => $basSku->skuwidth,
  607. 'height' => $basSku->skuhigh,
  608. 'volumn' => $basSku->cube,
  609. 'created_at' => $basSku->addtime,
  610. 'updated_at' => $basSku->edittime,
  611. 'pack_spec' => $basSku->packid == 'STANDARD' ? 0 : explode("/", $basSku->packid)[1],
  612. ];
  613. }
  614. }
  615. if (count($insert_params) > 0) $this->insertCommodities($insert_params);
  616. if (count($updateParams) > 0) $this->updateCommodities($updateParams);
  617. /** @var CommodityBarcodeService $commodityBarcodeService */
  618. $commodityBarcodeService = app(CommodityBarcodeService::class);
  619. $commodityBarcodeService->updateBarcodeByWms($addBasSkus);
  620. }
  621. private function pushToCache($commodities)
  622. {
  623. if (count($commodities) < 1) return null;
  624. foreach ($commodities as $commodity) {
  625. $commodity_key = "owner_code_{$commodity['owner']['code']}_sku_{$commodity['sku']}";
  626. Cache::put($commodity_key, $commodity);
  627. }
  628. }
  629. public function getAsnLastSyncAt($key, $type)
  630. {
  631. $last_time = ValueStore::query()->where('name', $key)->value('value');
  632. if ($last_time) return $last_time;
  633. if ($type == 'create') {
  634. $store = Commodity::query()->orderByDesc('created_at')->first();
  635. if ($store) return $store->created_at;
  636. } else {
  637. $store = Commodity::query()->orderByDesc('updated_at')->first();
  638. if ($store) return $store->updated_at;
  639. }
  640. return Carbon::now()->subSeconds(65);
  641. }
  642. public function setAsnLastSyncAt($key, $last_time)
  643. {
  644. $asnLastSyncAt = ValueStore::query()->updateOrCreate([
  645. 'name' => $key,
  646. ], [
  647. 'name' => $key,
  648. 'value' => $last_time,
  649. ]);
  650. LogService::log(__METHOD__, __FUNCTION__, '修改或更新' . $key . json_encode($asnLastSyncAt));
  651. return $asnLastSyncAt;
  652. }
  653. public function deleteCacheKey($set, $keys)
  654. {
  655. if (Cache::get($set)) {
  656. $cacheKeys = Cache::get($keys);
  657. if (!$cacheKeys) return;
  658. foreach ($cacheKeys as $cacheKey) {
  659. Cache::forget($cacheKey);
  660. }
  661. Cache::forget($keys);
  662. }
  663. }
  664. public function setLastRecordsByRedis($prefixKey, $set, $keys, $last_records)
  665. {
  666. $cacheKeys = [];
  667. foreach ($last_records as $last_record) {
  668. Cache::put($prefixKey . $last_record->customerid . '_' . $last_record->sku, true);
  669. array_push($cacheKeys, $prefixKey . $last_record->customerid . '_' . $last_record->sku);
  670. }
  671. Cache::put($keys, $cacheKeys);
  672. Cache::put($set, true);
  673. }
  674. function updateCommodities($updateParams)
  675. {
  676. if (count($updateParams) < 1) return;
  677. $ownerIds = array_unique(data_get($updateParams, '*.owner_id'));
  678. sort($ownerIds);
  679. $skus = array_unique(data_get($updateParams, '*.sku'));
  680. sort($skus);
  681. $this->batchUpdate($updateParams);
  682. $md5 = md5(json_encode([$skus, $ownerIds]));
  683. if (Cache::has('commodity_' . $md5)) Cache::forget('commodity_' . $md5);
  684. $commodities = Commodity::query()->with('owner')->whereIn('owner_id', $ownerIds)->whereIn('sku', $skus)->get();
  685. $this->pushToCache($commodities);
  686. }
  687. // TODO
  688. /**
  689. * @param array $ownerIds
  690. * @param array $skus
  691. * @param array $barcodes
  692. * @param bool $isSyncWms 是否开启同步wms数据 开启则必须给定 $ownerIds 和 $skus
  693. * @param int $paginate 分页只对 货主$ownerIds 条件
  694. * @param int $page
  695. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|mixed|null
  696. */
  697. function get_(array $ownerIds = [], array $skus = [], array $barcodes = [], $isSyncWms = false, $paginate = 100, $page = 1)
  698. {
  699. if ($paginate < 100 || fmod($paginate, 100) != 0) return null; //$paginate小于100,或取余数100不为0,异常 //取余函数fmod()
  700. $time = config('cache.expirations.forever');
  701. $status = null;
  702. if ($ownerIds && !$skus && !$barcodes) $status = '只有货主条件';
  703. if ($skus) $status = '有SKU';
  704. if ($barcodes && !$skus) $status = '有条码没SKU';
  705. if (!$status) return null;
  706. switch ($status) {
  707. case $status == '有SKU':
  708. if ($isSyncWms) {
  709. if (!$ownerIds) return null;
  710. $owners = Owner::query()->whereIn('id', $ownerIds)->select('id', 'code')->get();
  711. if (!$owners) return null;
  712. foreach ($owners as $owner) {
  713. $ownerCodes[] = $owner->code;
  714. }
  715. $bas_skus = OracleBasSKU::query()
  716. ->select('customerid', 'sku', 'descr_c', 'alternate_sku1', 'alternate_sku2', 'alternate_sku3', 'skulength', 'skuwidth', 'skuhigh', 'cube', 'packid', 'addtime', 'edittime')
  717. ->whereIn('customerid', $ownerCodes)->whereIn('sku', $skus)
  718. ->get();
  719. if (!$bas_skus) return null;
  720. $this->syncUpdateCommodity($bas_skus);
  721. }
  722. sort($skus);
  723. //在取出的记录用 $ownerIds和$barcodes筛选
  724. $commodities = Commodity::query()
  725. ->with(['barcodes', 'owner'])
  726. ->whereIn('sku', $skus)->get();
  727. if ($ownerIds) {
  728. sort($ownerIds);
  729. // $md5 = md5(json_encode([$skus, $ownerIds]));
  730. // return Cache::remember('commodity_' . $md5, $time, function () use ($skus, $ownerIds, $commodities) {
  731. return $commodities->whereIn('owner_id', $ownerIds);
  732. // });
  733. }
  734. if ($barcodes && !$ownerIds) {
  735. sort($barcodes);
  736. $md5 = md5(json_encode([$skus, $barcodes]));
  737. return Cache::remember('commodity_' . $md5, $time, function () use ($skus, $barcodes) {
  738. return Commodity::query()
  739. ->with(['barcodes', 'owner'])
  740. ->whereIn('id', function ($query) use ($barcodes) {
  741. $query->from('commodity_barcodes')->select('commodity_id')->whereIn('code', $barcodes);
  742. })
  743. ->whereIn('sku', $skus)->get();
  744. });
  745. }
  746. return $commodities;
  747. case $status == '有条码没SKU':
  748. sort($barcodes);
  749. $commodities = Commodity::query()
  750. ->with(['barcodes', 'owner'])
  751. ->whereIn('id', function ($query) use ($barcodes) {
  752. $query->from('commodity_barcodes')->select('commodity_id')->whereIn('code', $barcodes);
  753. })->get();
  754. if ($ownerIds) {
  755. sort($ownerIds);
  756. $barcodes_ownerIds_md5 = md5(json_encode([$barcodes, $ownerIds]));
  757. return Cache::remember('commodity_' . $barcodes_ownerIds_md5, $time, function () use ($ownerIds) {
  758. return Commodity::query()->whereIn('owner_id', $ownerIds);
  759. });
  760. }
  761. return $commodities;
  762. case $status == '只有货主条件':
  763. sort($ownerIds);
  764. $md5 = md5(json_encode([$ownerIds, $paginate, $page]));
  765. $key = 'commodity_' . $md5;
  766. $commodities = Cache::get($key);
  767. if (is_null($commodities))//如果缓存已失效或者无缓存则重新缓存
  768. {
  769. $commodities = Commodity::query()
  770. ->with(['barcodes', 'owner'])
  771. ->whereIn('owner_id', $ownerIds)
  772. ->orderBy('owner_id', 'asc')
  773. ->paginate($paginate, '*', 'page', $page);
  774. Cache::add($key, $commodities->items());
  775. return $commodities;
  776. }
  777. return $commodities;
  778. }
  779. }
  780. }