CommodityService.php 34 KB

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