CommodityService.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  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. //
  239. $commodities=$this->get_([$ownerId],[$sku],[],true);
  240. if ($commodities->first()){
  241. $commodity=$commodities->first();
  242. }else{
  243. $commodity = $this->firstOrCreate(['owner_id' => $ownerId, 'sku' => $sku]);
  244. }
  245. $commodityBarcodes = $commodity['barcodes'] ?? new Collection();
  246. /** @var CommodityBarcodeService $commodityBarcodeService */
  247. $commodityBarcodeService = app('CommodityBarcodeService');
  248. $redundantCommodityBarcodes = new Collection();
  249. foreach ($commodityBarcodes as $commodityBarcode) {//清除数组中 已经在商品有的条码,清除商品条码中,不在数组中的条码
  250. $hasMatch = false;
  251. foreach ($barcodes as $key => $barcode) {
  252. if ($barcodes[$key] == $commodityBarcode['code']) {
  253. $hasMatch = true;
  254. unset($barcodes[$key]);
  255. break;
  256. }
  257. }
  258. if (!$hasMatch) {
  259. $redundantCommodityBarcodes->push($commodityBarcode);
  260. }
  261. }
  262. if (!empty($redundantCommodityBarcodes)) {
  263. $commodityBarcodeService->destroyCollections($redundantCommodityBarcodes);
  264. }
  265. if (!empty($barcodes)) {
  266. $commodityBarcodeService->insertMany_onCommodities([['commodity_id' => $commodity['id'], 'barcodes' => $barcodes]]);
  267. }
  268. return $commodity;
  269. }
  270. public function destroyWithOffspring(Commodity $commodity)
  271. {
  272. $barcodesIds = $commodity->barcodes->map(function ($barcode) {
  273. return $barcode['id'];
  274. });
  275. CommodityBarcode::destroy($barcodesIds);
  276. $commodity->delete();
  277. }
  278. public function syncWMSOrderCode($owner, $skus)
  279. {
  280. $basSku = OracleBasSKU::query()->whereIn('SKU', $skus)->where('CustomerID', $owner->code)->get();
  281. $inner_params = [];
  282. $created_at = new Carbon();
  283. $basSku->each(function ($bas_sku) use (&$inner_params, $owner, $created_at) {
  284. $inner_params = [
  285. 'owner_id' => $owner->id,
  286. 'sku' => $bas_sku->sku,
  287. 'name' => $bas_sku->descr_c,
  288. 'created_at' => $created_at,
  289. 'length' => $bas_sku->skulength,
  290. 'width' => $bas_sku->skuwidth,
  291. 'height' => $bas_sku->skuhigh,
  292. 'volumn' => $bas_sku->cube
  293. ];
  294. });
  295. if (count($inner_params) > 0) {
  296. try {
  297. $this->insert($inner_params);
  298. app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($inner_params));
  299. } catch (\Exception $e) {
  300. app('LogService')->log(__METHOD__, 'Error ' . __FUNCTION__, json_encode($inner_params) . ' || ' . $e->getMessage());
  301. }
  302. }
  303. }
  304. //获取箱规
  305. public function getPack($owner_id, $sku)
  306. {
  307. $that = $this;
  308. return app("CacheService")->getOrExecute("pack_{$owner_id}_{$sku}", function () use ($owner_id, $sku, $that) {
  309. $commodity = $that->first([
  310. "owner_id" => $owner_id,
  311. "sku" => $sku
  312. ]);
  313. if (!$commodity || $commodity->pack_spec === null) {
  314. $owner = app("OwnerService")->find($owner_id);
  315. $action = new CommodityController();
  316. $action->syncOwnerCommodities($owner->id, $owner->code, $sku);
  317. }
  318. return $that->first([
  319. "owner_id" => $owner_id,
  320. "sku" => $sku
  321. ])->pack_spec;
  322. });
  323. }
  324. //是否存在
  325. public function isExist(array $params)
  326. {
  327. $query = Commodity::query();
  328. if ($params["barcode"] ?? false) {
  329. $query->whereHas("barcodes", function ($query) use ($params) {
  330. /** @var Builder $query */
  331. $query->where("code", $params["barcode"]);
  332. });
  333. unset($params["barcode"]);
  334. }
  335. foreach ($params as $column => $param) {
  336. $query->where($column, $param);
  337. }
  338. if ($query->count() > 0) return true;
  339. return false;
  340. }
  341. public function getCommoditiesByMap($map)
  342. {
  343. $collect = collect();
  344. if (count($map) == 0) return $collect;
  345. foreach ($map as $item) {
  346. $commodity = $this->getCommodityByOwnerCodeAndSKU($item['owner_code'], $item['sku']);
  347. $collect->push($commodity);
  348. }
  349. return $collect;
  350. }
  351. public function getCommodityByOwnerCodeAndSKU($ownerCode, $sku)
  352. {
  353. $commodity_key = "owner_code_{$ownerCode}_sku_{$sku}";
  354. return Cache::remember($commodity_key, config('cache.expirations.forever'), function () use ($ownerCode, $sku) {
  355. $commodity = Commodity::query()->where('sku', $sku)->whereHas('owner', function ($query) use ($ownerCode) {
  356. $query->where('code', $ownerCode);
  357. })->first();
  358. if (isset($commodity)) return $commodity;
  359. $basSKu = app('OracleBasSkuService')->first(['sku' => $sku, 'customerid' => $ownerCode]);
  360. return Commodity::query()->create($this->getParamsByBasSku($basSKu));
  361. });
  362. }
  363. public function getParamsByBasSku($basSku, $owner = null)
  364. {
  365. if (empty($owner)) {
  366. $owner = app('OwnerService')->getOwnerByCode($basSku['customerid']);
  367. }
  368. return [
  369. 'owner_id' => $owner['id'] ?? '',
  370. 'sku' => $basSku['sku'],
  371. 'name' => $basSku['descr_c'],
  372. 'length' => $basSku['skulength'],
  373. 'width' => $basSku['skuwidth'],
  374. 'height' => $basSku['skuhigh'],
  375. 'volumn' => $basSku['cube']
  376. ];
  377. }
  378. public function syncCommodityCreated()
  379. {
  380. $created_at = config('sync.commodity_sync.created_at');
  381. $create_set = config('sync.commodity_sync.cache_prefix.create_set');
  382. $create_keys = config('sync.commodity_sync.cache_prefix.create_keys');
  383. $create_key = config('sync.commodity_sync.cache_prefix.create');
  384. /** @var OracleBasSkuService $oracleBasSkuService */
  385. $oracleBasSkuService = app(OracleBasSkuService::class);
  386. $last_time = $this->getAsnLastSyncAt($created_at, 'create');
  387. $basSkus = $oracleBasSkuService->getWmsCreatedCommodities($last_time);
  388. $last_time = $basSkus->first()['addtime'];
  389. $last_records = $basSkus->where('addtime', $last_time);
  390. if (!$basSkus) return;
  391. $this->syncCreateCommodity($basSkus);
  392. $this->deleteCacheKey($create_set, $create_keys);
  393. $this->setLastRecordsByRedis($create_key, $create_set, $create_keys, $last_records);
  394. $this->setAsnLastSyncAt($created_at, $last_time);
  395. }
  396. public function syncCommodityUpdated()
  397. {
  398. $updated_at = config('sync.commodity_sync.updated_at');
  399. $update_set = config('sync.commodity_sync.cache_prefix.update_set');
  400. $update_keys = config('sync.commodity_sync.cache_prefix.update_keys');
  401. $update_key = config('sync.commodity_sync.cache_prefix.update');
  402. /** @var OracleBasSkuService $oracleBasSkuService */
  403. $oracleBasSkuService = app(OracleBasSkuService::class);
  404. $last_time = $this->getAsnLastSyncAt($updated_at, 'update');
  405. $basSkus = $oracleBasSkuService->getWmsUpdatedCommodities($last_time);
  406. $last_time = $basSkus->first()['edittime'];
  407. $last_records = $basSkus->where('edittime', $last_time);
  408. if (!$basSkus) return;
  409. $this->syncUpdateCommodity($basSkus);
  410. $this->deleteCacheKey($update_set, $update_keys);
  411. $this->setLastRecordsByRedis($update_key, $update_set, $update_keys, $last_records);
  412. $this->setAsnLastSyncAt($updated_at, $last_time);
  413. }
  414. public function syncCreateCommodity($addBasSkus)
  415. {
  416. if (count($addBasSkus) < 1) return null;
  417. $insert_params = $this->getParamsByBasSkus($addBasSkus);
  418. if (!$insert_params) return;
  419. $this->insertCommodities($insert_params);
  420. /** @var CommodityBarcodeService $commodityBarcodeService */
  421. $commodityBarcodeService = app(CommodityBarcodeService::class);
  422. $commodityBarcodeService->createBarcodeByWms($addBasSkus);
  423. }
  424. public function insertCommodities($insert_params)
  425. {
  426. if (count($insert_params) < 1) return;
  427. $ownerIds = array_unique(data_get($insert_params, '*.owner_id'));
  428. sort($ownerIds);
  429. $skus = array_unique(data_get($insert_params, '*.sku'));
  430. sort($skus);
  431. try {
  432. $bool = Commodity::query()->insert($insert_params);
  433. if ($bool) {
  434. app('LogService')->log(__METHOD__, __FUNCTION__, "批量添加 Commodity Success " . count($insert_params) . ' || ' . json_encode($insert_params));
  435. $commodities = Commodity::query()->with('owner')->whereIn('owner_id', $ownerIds)->whereIn('sku', $skus)->get();
  436. $md5 = md5(json_encode([$skus, $ownerIds]));
  437. if (Cache::has('commodity_' . $md5)) Cache::forget('commodity_' . $md5);
  438. $this->pushToCache($commodities);
  439. } else app('LogService')->log(__METHOD__, __FUNCTION__, "批量添加 Commodity FAILED " . ' || ' . json_encode($insert_params));
  440. } catch (\Exception $e) {
  441. app('LogService')->log(__METHOD__, __FUNCTION__, "批量添加 Commodity ERROR " . ' || ' . json_encode($insert_params) . ' || ' . json_encode($e->getMessage()) . ' || ' . json_encode($e->getTraceAsString()));
  442. }
  443. }
  444. public function getParamsByBasSkus($addBasSkus)
  445. {
  446. $owner_sku_map = [];
  447. $sku = [];
  448. $owner_code = [];
  449. $owner_codes = [];
  450. $addBasSkus->each(function ($addBasSku) use (&$owner_sku_map, &$sku, &$owner_codes, &$owner_code) {
  451. if (!empty($addBasSku['customerid']) && !empty($addBasSku['sku'])) {
  452. $key = "owner_code_{$addBasSku['customerid']}_sku_{$addBasSku['sku']}";
  453. $owner_sku_map[$key] = ['owner_code' => $addBasSku['customerid'], 'sku' => $addBasSku['sku']];
  454. $sku[] = $addBasSku['sku'];
  455. $owner_code[] = $addBasSku['customerid'];
  456. $owner_codes[$addBasSku['customerid']] = $addBasSku['customerid'];
  457. }
  458. });
  459. /** @var OwnerService $ownerService */
  460. $ownerService = app(OwnerService::class);
  461. $owner_id = (function () use ($ownerService, $owner_codes) {
  462. $owners = $ownerService->getOwnerByCodes($owner_codes);
  463. $map = [];
  464. $owners->each(function ($owner) use (&$map) {
  465. $map[] = $owner['id'];
  466. });
  467. return $map;
  468. })();
  469. $owner_map = (function () use ($ownerService, $owner_codes) {
  470. $owners = $ownerService->getOwnerByCodes($owner_codes);
  471. $map = [];
  472. $owners->each(function ($owner) use (&$map) {
  473. $map[$owner['code']] = $owner['id'];
  474. });
  475. return $map;
  476. })();
  477. if (count($owner_sku_map) == 0) return null;
  478. $commodities = Commodity::query()
  479. ->whereIn('owner_id', array_unique($owner_id))
  480. ->whereIn('sku', array_unique($sku))
  481. ->groupBy('owner_id', 'sku')
  482. ->get();
  483. $unexists = [];
  484. foreach ($owner_sku_map as $item) {
  485. $commodity = Cache::get("owner_code_{$item['owner_code']}_sku_{$item['sku']}");
  486. if ($commodity) continue;
  487. $commodity = $commodities->where('sku', $item['sku'])->where('owner_id', $owner_map[$item['owner_code']])->first();
  488. if ($commodity) continue;
  489. $items = [
  490. 'owner_code' => $item['owner_code'],
  491. 'sku' => $item['sku']
  492. ];
  493. $unexists[json_encode($items)] = true;
  494. }
  495. if (count($unexists) == 0) return null;
  496. $BasSKUs = $addBasSkus->filter(function ($bas_sku) use ($unexists) {
  497. $arr = [
  498. 'owner_code' => $bas_sku['customerid'],
  499. 'sku' => $bas_sku['sku']
  500. ];
  501. return $unexists[json_encode($arr)] ?? false;
  502. });
  503. $inner_params = (function () use ($BasSKUs, $owner_map) {
  504. $map = [];
  505. $BasSKUs->each(function ($basSku) use (&$map, $owner_map) {
  506. $map[] = [
  507. 'owner_id' => $owner_map[$basSku['customerid']] ?? '',
  508. 'sku' => $basSku->sku,
  509. 'name' => $basSku->descr_c,
  510. 'length' => $basSku->skulength,
  511. 'width' => $basSku->skuwidth,
  512. 'height' => $basSku->skuhigh,
  513. 'volumn' => $basSku->cube,
  514. 'created_at' => $basSku->addtime,
  515. 'updated_at' => $basSku->edittime,
  516. 'pack_spec' => $basSku->packid == 'STANDARD' ? 0 : explode("/", $basSku->packid)[1],
  517. ];
  518. });
  519. return $map;
  520. })();
  521. if (count($inner_params) == 0) return null;
  522. return $inner_params;
  523. }
  524. public function syncUpdateCommodity($addBasSkus)
  525. {
  526. $sku = [];
  527. $owner_codes = [];
  528. $addBasSkus->each(function ($addBasSku) use (&$sku, &$owner_codes) {
  529. if (!empty($addBasSku['customerid']) && !empty($addBasSku['sku'])) {
  530. $sku[] = $addBasSku['sku'];
  531. $owner_codes[$addBasSku['customerid']] = $addBasSku['customerid'];
  532. }
  533. });
  534. /**
  535. * @var OwnerService $ownerService
  536. * @var DataHandlerService $dataHandlerService
  537. */
  538. $ownerService = app(OwnerService::class);
  539. $dataHandlerService = app(DataHandlerService::class);
  540. $owner_map = (function () use ($ownerService, $owner_codes) {
  541. $owners = $ownerService->getOwnerByCodes($owner_codes);
  542. $map = [];
  543. $owners->each(function ($owner) use (&$map) {
  544. $map[$owner['code']] = $owner['id'];
  545. });
  546. return $map;
  547. })();
  548. $owner_id = (function () use ($ownerService, $owner_codes) {
  549. $owners = $ownerService->getOwnerByCodes($owner_codes);
  550. $map = [];
  551. $owners->each(function ($owner) use (&$map) {
  552. $map[] = $owner['id'];
  553. });
  554. return $map;
  555. })();
  556. $commodities = Commodity::query()
  557. ->whereIn('owner_id', array_unique($owner_id))
  558. ->whereIn('sku', array_unique($sku))
  559. ->groupBy('owner_id', 'sku')
  560. ->get();
  561. $commodities_map = $dataHandlerService->dataHeader(['owner_id', 'sku'], $commodities);
  562. $updateParams = [[
  563. 'id', 'name', 'sku', 'owner_id', 'length', 'width', 'height', 'volumn', 'pack_spec', 'updated_at', 'created_at'
  564. ]];
  565. $insert_params = [];
  566. foreach ($addBasSkus as $basSku) {
  567. $commodity = Cache::get("owner_code_{$basSku['customerid']}_sku_{$basSku['sku']}");
  568. if (!$commodity) {
  569. $commodity = $dataHandlerService->getKeyValue(['owner_id' => $owner_map[$basSku['customerid']], 'sku' => $basSku['sku']], $commodities_map);
  570. if (!$commodity) {
  571. $insert_params[] = [
  572. 'owner_id' => $owner_map[$basSku['customerid']] ?? '',
  573. 'sku' => $basSku->sku,
  574. 'name' => $basSku->descr_c,
  575. 'length' => $basSku->skulength,
  576. 'width' => $basSku->skuwidth,
  577. 'height' => $basSku->skuhigh,
  578. 'volumn' => $basSku->cube,
  579. 'created_at' => $basSku->addtime,
  580. 'updated_at' => $basSku->edittime,
  581. 'pack_spec' => $basSku->packid == 'STANDARD' ? 0 : explode("/", $basSku->packid)[1],
  582. ];
  583. continue;
  584. };
  585. }
  586. if ($commodity->sku != $basSku->sku ||
  587. $commodity->name != $basSku->descr_c ||
  588. $commodity->length != $basSku->skulength ||
  589. $commodity->width != $basSku->skuwidth ||
  590. $commodity->height != $basSku->skuhigh ||
  591. $commodity->volumn != $basSku->cube ||
  592. $commodity->created_at != $basSku->addtime ||
  593. $commodity->updated_at != $basSku->edittime ||
  594. $commodity->pack_spec != $basSku->pickid) {
  595. $updateParams[] = [
  596. 'id' => $commodity->id,
  597. 'owner_id' => $owner_map[$basSku['customerid']] ?? '',
  598. 'sku' => $basSku->sku,
  599. 'name' => $basSku->descr_c,
  600. 'length' => $basSku->skulength,
  601. 'width' => $basSku->skuwidth,
  602. 'height' => $basSku->skuhigh,
  603. 'volumn' => $basSku->cube,
  604. 'created_at' => $basSku->addtime,
  605. 'updated_at' => $basSku->edittime,
  606. 'pack_spec' => $basSku->packid == 'STANDARD' ? 0 : explode("/", $basSku->packid)[1],
  607. ];
  608. }
  609. }
  610. if (count($insert_params) > 0) $this->insertCommodities($insert_params);
  611. if (count($updateParams) > 0) $this->updateCommodities($updateParams);
  612. /** @var CommodityBarcodeService $commodityBarcodeService */
  613. $commodityBarcodeService = app(CommodityBarcodeService::class);
  614. $commodityBarcodeService->updateBarcodeByWms($addBasSkus);
  615. }
  616. private function pushToCache($commodities)
  617. {
  618. if (count($commodities) < 1) return null;
  619. foreach ($commodities as $commodity) {
  620. $commodity_key = "owner_code_{$commodity['owner']['code']}_sku_{$commodity['sku']}";
  621. Cache::put($commodity_key, $commodity);
  622. }
  623. }
  624. public function getAsnLastSyncAt($key, $type)
  625. {
  626. $last_time = ValueStore::query()->where('name', $key)->value('value');
  627. if ($last_time) return $last_time;
  628. if ($type == 'create') {
  629. $store = Commodity::query()->orderByDesc('created_at')->first();
  630. if ($store) return $store->created_at;
  631. } else {
  632. $store = Commodity::query()->orderByDesc('updated_at')->first();
  633. if ($store) return $store->updated_at;
  634. }
  635. return Carbon::now()->subSeconds(65);
  636. }
  637. public function setAsnLastSyncAt($key, $last_time)
  638. {
  639. $asnLastSyncAt = ValueStore::query()->updateOrCreate([
  640. 'name' => $key,
  641. ], [
  642. 'name' => $key,
  643. 'value' => $last_time,
  644. ]);
  645. LogService::log(__METHOD__, __FUNCTION__, '修改或更新' . $key . json_encode($asnLastSyncAt));
  646. return $asnLastSyncAt;
  647. }
  648. public function deleteCacheKey($set, $keys)
  649. {
  650. if (Cache::get($set)) {
  651. $cacheKeys = Cache::get($keys);
  652. if (!$cacheKeys) return;
  653. foreach ($cacheKeys as $cacheKey) {
  654. Cache::forget($cacheKey);
  655. }
  656. Cache::forget($keys);
  657. }
  658. }
  659. public function setLastRecordsByRedis($prefixKey, $set, $keys, $last_records)
  660. {
  661. $cacheKeys = [];
  662. foreach ($last_records as $last_record) {
  663. Cache::put($prefixKey . $last_record->customerid . '_' . $last_record->sku, true);
  664. array_push($cacheKeys, $prefixKey . $last_record->customerid . '_' . $last_record->sku);
  665. }
  666. Cache::put($keys, $cacheKeys);
  667. Cache::put($set, true);
  668. }
  669. function updateCommodities($updateParams)
  670. {
  671. if (count($updateParams) < 1) return;
  672. $ownerIds = array_unique(data_get($updateParams, '*.owner_id'));
  673. sort($ownerIds);
  674. $skus = array_unique(data_get($updateParams, '*.sku'));
  675. sort($skus);
  676. $this->batchUpdate($updateParams);
  677. $md5 = md5(json_encode([$skus, $ownerIds]));
  678. if (Cache::has('commodity_' . $md5)) Cache::forget('commodity_' . $md5);
  679. $commodities = Commodity::query()->with('owner')->whereIn('owner_id', $ownerIds)->whereIn('sku', $skus)->get();
  680. $this->pushToCache($commodities);
  681. }
  682. // TODO
  683. /**
  684. * @param array $ownerIds
  685. * @param array $skus
  686. * @param array $barcodes
  687. * @param bool $isSyncWms 是否开启同步wms数据 开启则必须给定 $ownerIds 和 $skus
  688. * @param int $paginate 分页只对 货主$ownerIds 条件
  689. * @param int $page
  690. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|mixed|null
  691. */
  692. function get_(array $ownerIds = [], array $skus = [], array $barcodes = [], $isSyncWms = false, $paginate = 100, $page = 1)
  693. {
  694. if ($paginate < 100 || fmod($paginate, 100) != 0) return null; //$paginate小于100,或取余数100不为0,异常 //取余函数fmod()
  695. $time = config('cache.expirations.forever');
  696. $status = null;
  697. if ($ownerIds && !$skus && !$barcodes) $status = '只有货主条件';
  698. if ($skus) $status = '有SKU';
  699. if ($barcodes && !$skus) $status = '有条码没SKU';
  700. if (!$status) return null;
  701. switch ($status) {
  702. case $status == '有SKU':
  703. if ($isSyncWms) {
  704. if (!$ownerIds) return null;
  705. $owners = Owner::query()->whereIn('id', $ownerIds)->select('id', 'code')->get();
  706. if (!$owners) return null;
  707. foreach ($owners as $owner) {
  708. $ownerCodes[] = $owner->code;
  709. }
  710. $bas_skus = OracleBasSKU::query()
  711. ->select('customerid', 'sku', 'descr_c', 'alternate_sku1', 'alternate_sku2', 'alternate_sku3', 'skulength', 'skuwidth', 'skuhigh', 'cube', 'packid', 'addtime', 'edittime')
  712. ->whereIn('customerid', $ownerCodes)->whereIn('sku', $skus)
  713. ->get();
  714. if (!$bas_skus) return null;
  715. $this->syncUpdateCommodity($bas_skus);
  716. }
  717. sort($skus);
  718. //在取出的记录用 $ownerIds和$barcodes筛选
  719. $commodities = Commodity::query()
  720. ->with(['barcodes', 'owner'])
  721. ->whereIn('sku', $skus)->get();
  722. if ($ownerIds) {
  723. sort($ownerIds);
  724. // $md5 = md5(json_encode([$skus, $ownerIds]));
  725. // return Cache::remember('commodity_' . $md5, $time, function () use ($skus, $ownerIds, $commodities) {
  726. return $commodities->whereIn('owner_id', $ownerIds);
  727. // });
  728. }
  729. if ($barcodes && !$ownerIds) {
  730. sort($barcodes);
  731. $md5 = md5(json_encode([$skus, $barcodes]));
  732. return Cache::remember('commodity_' . $md5, $time, function () use ($skus, $barcodes) {
  733. return Commodity::query()
  734. ->with(['barcodes', 'owner'])
  735. ->whereHas('barcodes', function ($query) use ($barcodes) {
  736. $query->whereIn('code', $barcodes);
  737. })
  738. ->whereIn('sku', $skus)->get();
  739. });
  740. }
  741. return $commodities;
  742. case $status == '有条码没SKU':
  743. sort($barcodes);
  744. $commodities = Commodity::query()
  745. ->with(['barcodes', 'owner'])
  746. ->whereHas('barcodes', function ($query) use ($barcodes) {
  747. $query->whereIn('code', $barcodes);
  748. })->get();
  749. if ($ownerIds) {
  750. sort($ownerIds);
  751. $barcodes_ownerIds_md5 = md5(json_encode([$barcodes, $ownerIds]));
  752. return Cache::remember('commodity_' . $barcodes_ownerIds_md5, $time, function () use ($ownerIds) {
  753. return Commodity::query()->whereIn('owner_id', $ownerIds);
  754. });
  755. }
  756. return $commodities;
  757. case $status == '只有货主条件':
  758. sort($ownerIds);
  759. $md5 = md5(json_encode([$ownerIds, $paginate, $page]));
  760. $key = 'commodity_' . $md5;
  761. $commodities = Cache::get($key);
  762. if (is_null($commodities))//如果缓存已失效或者无缓存则重新缓存
  763. {
  764. $commodities = Commodity::query()
  765. ->with(['barcodes', 'owner'])
  766. ->whereIn('owner_id', $ownerIds)
  767. ->orderBy('owner_id', 'asc')
  768. ->paginate($paginate, '*', 'page', $page);
  769. Cache::add($key, $commodities->items());
  770. return $commodities;
  771. }
  772. return $commodities;
  773. }
  774. }
  775. }