CommodityService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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\ValueStore;
  10. use Carbon\Carbon;
  11. use Illuminate\Database\Eloquent\Builder;
  12. use Illuminate\Database\Eloquent\Collection;
  13. use Illuminate\Support\Facades\Cache;
  14. Class CommodityService
  15. {
  16. public function firstOrCreate($param, $column = null): Commodity
  17. {
  18. if ($column) return Commodity::query()->firstOrCreate($param, $column);
  19. return Commodity::query()->firstOrCreate($param);
  20. }
  21. public function updateOrCreate($param, $column = null)
  22. {
  23. if ($column) return Commodity::query()->updateOrCreate($param, $column);
  24. return Commodity::query()->updateOrCreate($param);
  25. }
  26. public function first(array $params, $with = null)
  27. {
  28. $commodity = Commodity::query();
  29. if ($with) $commodity->with($with);
  30. foreach ($params as $column => $value) {
  31. if (!is_array($value)) $commodity->where($column, $value);
  32. else $commodity->whereIn($column, $value);
  33. }
  34. return $commodity->first();
  35. }
  36. public function get(array $params)
  37. {
  38. $query = Commodity::query()->with('barcodes');
  39. if ($params["owner_id"] ?? false) {
  40. $query->where("owner_id", $params["owner_id"]);
  41. }
  42. if ($params["sku"] ?? false) {
  43. if (!is_array($params["sku"])) $params["sku"] = [$params["sku"]];
  44. $query->whereIn('sku', $params["sku"]);
  45. }
  46. return $query->get();
  47. }
  48. public function insert(array $params)
  49. {
  50. return Commodity::query()->insert($params);
  51. }
  52. public function getOwnerCommodities(array $params)
  53. {
  54. $query = Commodity::query();
  55. foreach ($params as $column => $value) {
  56. if (!is_array($value)) $query->where($column, $value);
  57. else $query->whereIn($column, $value);
  58. }
  59. return $query->get();
  60. }
  61. /* 批量更新 */
  62. public function batchUpdate(array $params)
  63. {
  64. return app(BatchUpdateService::class)->batchUpdate('commodities', $params);
  65. }
  66. /* 根据货主条形码查找商品 */
  67. private function ownerBarcodeSeekCommodityQuery(Builder $query, array $ownerParam, $barcode)
  68. {
  69. $query->whereHas('owner', function ($builder) use ($ownerParam) {
  70. foreach ($ownerParam as $column => $param) {
  71. $builder->where($column, $param);
  72. }
  73. });
  74. $query->whereHas('barcodes', function ($builder) use ($barcode) {
  75. if (is_array($barcode)) $builder->whereIn('code', $barcode);
  76. else $builder->where('code', $barcode);
  77. });
  78. return $query;
  79. }
  80. public function ownerBarcodeSeekCommodityFirst(array $ownerParam, $barcode, $with = null)
  81. {
  82. $commodity = Commodity::query();
  83. if ($with) $commodity->with($with);
  84. $commodity = $this->ownerBarcodeSeekCommodityQuery($commodity, $ownerParam, $barcode);
  85. return $commodity->first();
  86. }
  87. public function ownerBarcodeSeekCommodityGet(array $ownerParam, $barcode, $isNullSku = false)
  88. {
  89. $commodities = Commodity::query()->with('barcodes');
  90. if ($isNullSku) $commodities->whereNull('sku');
  91. $commodities = $this->ownerBarcodeSeekCommodityQuery($commodities, $ownerParam, $barcode);
  92. return $commodities->get();
  93. }
  94. /* 通过货主代码与条形码寻找FLUX商品补充至WMS 单条*/
  95. public function ownerAndBarcodeFirstOrCreate(Owner $owner, $barcode)
  96. {
  97. $wmsCommodity = app('OracleBasSkuService')->first(['customerid' => $owner->code, 'barcode' => $barcode]);
  98. if (!$wmsCommodity) return null;
  99. $commodity = $this->firstOrCreate(['owner_id' => $owner->id, 'sku' => $wmsCommodity->sku], [
  100. "name" => $wmsCommodity->descr_c,
  101. "sku" => $wmsCommodity->sku,
  102. "owner_id" => $owner->id,
  103. "length" => $wmsCommodity->skulength,
  104. "width" => $wmsCommodity->skuwidth,
  105. "height" => $wmsCommodity->skuhigh,
  106. "volumn" => $wmsCommodity->cube,
  107. ]);
  108. if ($wmsCommodity->alternate_sku1) app('CommodityBarcodeService')->first([
  109. 'commodity_id' => $commodity->id,
  110. 'code' => $wmsCommodity->alternate_sku1,
  111. ]);
  112. if ($wmsCommodity->alternate_sku2) app('CommodityBarcodeService')->first([
  113. 'commodity_id' => $commodity->id,
  114. 'code' => $wmsCommodity->alternate_sku2,
  115. ]);
  116. return $commodity;
  117. }
  118. public function create(array $params)
  119. {
  120. return Commodity::query()->create($params);
  121. }
  122. public function getByWmsOrders($orderHeaders)
  123. {
  124. if (!$orderHeaders) return null;
  125. $customerId_sku_map = [];
  126. foreach ($orderHeaders as $orderHeader) {
  127. $oracleDOCOrderDetails = $orderHeader->oracleDOCOrderDetails;
  128. foreach ($oracleDOCOrderDetails as $oracleDOCOrderDetail) {
  129. $value = [
  130. 'owner_code' => $oracleDOCOrderDetail->customerid,
  131. 'sku' => $oracleDOCOrderDetail->sku
  132. ];
  133. if (!in_array($value, $customerId_sku_map)) {
  134. $customerId_sku_map[] = $value;
  135. }
  136. }
  137. }
  138. $owner_codes = array_diff(array_unique(data_get($customerId_sku_map, '*.owner_code')), ['', '*', null]);
  139. if (!$owner_codes) return null;
  140. $owners = Owner::query()->whereIn('code', $owner_codes)->get();
  141. $owners_code_map = [];
  142. $owners_id_map = [];
  143. foreach ($owners as $owner) {
  144. $owners_code_map[$owner->code] = $owner;
  145. $owners_id_map[$owner->id] = $owner;
  146. }
  147. $orderHeader_sku = array_diff(array_unique(data_get($customerId_sku_map, '*.sku')), ['', '*', null]);
  148. $commodities = Commodity::query()
  149. ->whereIn('owner_id', data_get($owners, '*.id'))
  150. ->whereIn('sku', $orderHeader_sku)
  151. ->groupBy('owner_id', 'sku') //*!!!!!!!!
  152. ->get();
  153. if ($commodities->count() < count($customerId_sku_map)) {
  154. $commoditiesInWAS索引_sku = [];
  155. foreach ($commodities as $commodityInWms) {
  156. $owner = $owners_id_map[$commodityInWms->owner_id] ?? '';
  157. if (!$owner) continue;
  158. $key = 'owner_cod=' . $owner['code'] . ' sku=' . $commodityInWms->sku;
  159. $commoditiesInWAS索引_sku[$key] = $commodityInWms;
  160. }
  161. $commodities需要新增 = [];
  162. foreach ($customerId_sku_map as $commodityInWms) {
  163. $key = 'owner_cod=' . $commodityInWms['owner_code'] . ' sku=' . $commodityInWms['sku'];
  164. if ($commoditiesInWAS索引_sku[$key] ?? false) continue;
  165. $commodities需要新增[$key] = $commodityInWms;
  166. }
  167. $commodity_set = $this->createCommodities($commodities需要新增, $owners_code_map);
  168. $commodities = $commodities->concat($commodity_set);
  169. }
  170. return $commodities;
  171. }
  172. public function createCommodities($params, $owners_code_map)
  173. {
  174. if (!$params) return [];
  175. $bas_sku_arr = OracleBasSKU::query()
  176. ->selectRaw('customerid,sku,descr_c,skulength,skuwidth,skuhigh,cube')
  177. ->whereIn('CustomerID', data_get($params, '*.owner_code'))
  178. ->whereIn('Sku', data_get($params, '*.sku'))
  179. ->get();
  180. $insert_params = [];
  181. $created_at = Carbon::now()->format('Y-m-d H:i:s');
  182. foreach ($bas_sku_arr as $bas_sku) {
  183. $owner = $owners_code_map[$bas_sku->customerid] ?? '';
  184. if (!$owner) continue;
  185. if ($bas_sku->sku == null) continue;
  186. if ($bas_sku->descr_c == '') continue;
  187. $insert_params[] = [
  188. 'owner_id' => $owner->id,
  189. 'sku' => $bas_sku->sku,
  190. 'name' => $bas_sku->descr_c,
  191. 'created_at' => $created_at,
  192. 'length' => $bas_sku->skulength,
  193. 'width' => $bas_sku->skuwidth,
  194. 'height' => $bas_sku->skuhigh,
  195. 'volumn' => $bas_sku->cube
  196. ];
  197. }
  198. if (count($insert_params) > 0) {
  199. try {
  200. $this->insert($insert_params);
  201. app('LogService')->log(__METHOD__, __FUNCTION__, '批量添加 commodity ' . count($insert_params) . json_encode($insert_params));
  202. } catch (\Exception $e) {
  203. app('LogService')->log(__METHOD__, __FUNCTION__, '批量添加 commodity error' . json_encode($insert_params) . "||" . $e->getMessage() . '||' . $e->getTraceAsString());
  204. }
  205. }
  206. return Commodity::query()
  207. ->whereIn('owner_id', data_get($owners_code_map, '*.id'))
  208. ->whereIn('sku', data_get($params, '*.sku'))
  209. ->get();
  210. }
  211. public function createTemporaryCommodity(array $params)
  212. {
  213. $params["type"] = "临时";
  214. return Commodity::query()->create($params);
  215. }
  216. public function syncBarcodes($barcodesStr, $ownerId, $sku): Commodity
  217. {
  218. $barcodes = (function () use ($barcodesStr) {
  219. $barcodes = rtrim($barcodesStr, ',');
  220. $barcodes = explode(',', $barcodes);
  221. foreach ($barcodes as $k => $barcode) {
  222. if (!trim($barcode)) unset($barcodes[$k]);
  223. }
  224. return $barcodes;
  225. })();
  226. $commodity = $this->firstOrCreate(['owner_id' => $ownerId, 'sku' => $sku]);
  227. $commodityBarcodes = $commodity['barcodes'] ?? new Collection();
  228. /** @var CommodityBarcodeService $commodityBarcodeService */
  229. $commodityBarcodeService = app('CommodityBarcodeService');
  230. $redundantCommodityBarcodes = new Collection();
  231. foreach ($commodityBarcodes as $commodityBarcode) {//清除数组中 已经在商品有的条码,清除商品条码中,不在数组中的条码
  232. $hasMatch = false;
  233. foreach ($barcodes as $key => $barcode) {
  234. if ($barcodes[$key] == $commodityBarcode['code']) {
  235. $hasMatch = true;
  236. unset($barcodes[$key]);
  237. break;
  238. }
  239. }
  240. if (!$hasMatch) {
  241. $redundantCommodityBarcodes->push($commodityBarcode);
  242. }
  243. }
  244. if (!empty($redundantCommodityBarcodes)) {
  245. $commodityBarcodeService->destroyCollections($redundantCommodityBarcodes);
  246. }
  247. if (!empty($barcodes)) {
  248. $commodityBarcodeService->insertMany_onCommodities([['commodity_id' => $commodity['id'], 'barcodes' => $barcodes]]);
  249. }
  250. return $commodity;
  251. }
  252. public function destroyWithOffspring(Commodity $commodity)
  253. {
  254. $barcodesIds = $commodity->barcodes->map(function ($barcode) {
  255. return $barcode['id'];
  256. });
  257. CommodityBarcode::destroy($barcodesIds);
  258. $commodity->delete();
  259. }
  260. public function syncWMSOrderCode($owner, $skus)
  261. {
  262. $basSku = OracleBasSKU::query()->whereIn('SKU', $skus)->where('CustomerID', $owner->code)->get();
  263. $inner_params = [];
  264. $created_at = new Carbon();
  265. $basSku->each(function ($bas_sku) use (&$inner_params, $owner, $created_at) {
  266. $inner_params = [
  267. 'owner_id' => $owner->id,
  268. 'sku' => $bas_sku->sku,
  269. 'name' => $bas_sku->descr_c,
  270. 'created_at' => $created_at,
  271. 'length' => $bas_sku->skulength,
  272. 'width' => $bas_sku->skuwidth,
  273. 'height' => $bas_sku->skuhigh,
  274. 'volumn' => $bas_sku->cube
  275. ];
  276. });
  277. if (count($inner_params) > 0) {
  278. try {
  279. $this->insert($inner_params);
  280. app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($inner_params));
  281. } catch (\Exception $e) {
  282. app('LogService')->log(__METHOD__, 'Error ' . __FUNCTION__, json_encode($inner_params) . ' || ' . $e->getMessage());
  283. }
  284. }
  285. }
  286. //获取箱规
  287. public function getPack($owner_id, $sku)
  288. {
  289. $that = $this;
  290. return app("CacheService")->getOrExecute("pack_{$owner_id}_{$sku}", function () use ($owner_id, $sku, $that) {
  291. $commodity = $that->first([
  292. "owner_id" => $owner_id,
  293. "sku" => $sku
  294. ]);
  295. if (!$commodity || $commodity->pack_spec === null) {
  296. $owner = app("OwnerService")->find($owner_id);
  297. $action = new CommodityController();
  298. $action->syncOwnerCommodities($owner->id, $owner->code, $sku);
  299. }
  300. return $that->first([
  301. "owner_id" => $owner_id,
  302. "sku" => $sku
  303. ])->pack_spec;
  304. });
  305. }
  306. //是否存在
  307. public function isExist(array $params)
  308. {
  309. $query = Commodity::query();
  310. if ($params["barcode"] ?? false) {
  311. $query->whereHas("barcodes", function ($query) use ($params) {
  312. /** @var Builder $query */
  313. $query->where("code", $params["barcode"]);
  314. });
  315. unset($params["barcode"]);
  316. }
  317. foreach ($params as $column => $param) {
  318. $query->where($column, $param);
  319. }
  320. if ($query->count() > 0) return true;
  321. return false;
  322. }
  323. public function pushCommodityToCache()
  324. {
  325. $amount = 1000;
  326. $sum = Commodity::query()->count('id');
  327. $number = ceil($sum / $amount);
  328. for ($i = 0; $i < $number; $i++) {
  329. $commodities = $this->getPiece(($i * $amount), $amount);
  330. if (!$commodities) continue;
  331. $this->pushToCache($commodities);
  332. }
  333. }
  334. private function getPiece(int $start, int $amount)
  335. {
  336. $commodities = Commodity::query()->with(['owner', 'barcodes'])
  337. ->where('id', '>=', $start)
  338. ->where('id', '<', $amount)
  339. ->get();
  340. return $commodities;
  341. }
  342. private function pushToCache($commodities)
  343. {
  344. if (count($commodities) < 1) return null;
  345. foreach ($commodities as $commodity) {
  346. $commodity_key = "owner_code_{$commodity['owner']['code']}_sku_{$commodity['sku']}";
  347. Cache::remember($commodity_key, config('cache.expirations.forever'), function () use ($commodity) {
  348. return $commodity;
  349. });
  350. // if (count($commodity->barcodes) >= 1) {
  351. // foreach ($commodity->barcodes as $barcode) {
  352. // $barcode_key = "barcode_{$barcode['code']}";
  353. // Cache::remember($barcode_key, config('cache.expirations.forever'),function()use($commodity) {
  354. // return $commodity;
  355. // });
  356. // }
  357. // }
  358. }
  359. }
  360. public function syncCommodityCreated()
  361. {
  362. $created_at = config('sync.commodity_sync.created_at');
  363. $create_set = config('sync.commodity_sync.cache_prefix.create_set');
  364. $create_keys = config('sync.commodity_sync.cache_prefix.create_keys');
  365. $create_key = config('sync.commodity_sync.cache_prefix.create');
  366. /** @var OracleBasSkuService $oracleBasSkuService */
  367. $oracleBasSkuService = app(OracleBasSkuService::class);
  368. $last_time = $this->getAsnLastSyncAt($created_at, 'create');
  369. $basSkus = $oracleBasSkuService->getWmsCreatedCommodities($last_time);
  370. $last_time=$basSkus->first()['addtime'];
  371. $last_records = $basSkus->where('addtime', $last_time);
  372. if (!$basSkus) return;
  373. $addBasSkus = $this->getLastRecordsByRedis($create_set, $create_key, $basSkus);
  374. if (count($addBasSkus) > 0) $addBasSkus=$this->filterByCommodityCache($addBasSkus);
  375. if (count($addBasSkus) > 0) {
  376. $this->syncCreateCommodity($addBasSkus);
  377. $this->deleteCacheKey($create_set, $create_keys);
  378. $this->setLastRecordsByRedis($create_key,$create_set,$create_keys,$last_records);
  379. $this->setAsnLastSyncAt($created_at,$last_time);
  380. }
  381. }
  382. public function syncCommodityUpdated()
  383. {
  384. }
  385. // TODO
  386. public function syncCreateCommodity($addBasSkus)
  387. {
  388. $owner_codes = array_diff(array_unique(data_get($addBasSkus, '*.customerid')), ['', '*', null]);
  389. if (count($owner_codes)<1) return null;
  390. $owners = Owner::query()->whereIn('code', $owner_codes)->get();
  391. $owners_code_map = [];
  392. foreach ($owners as $owner) {
  393. $owners_code_map[$owner->code] = $owner;
  394. }
  395. }
  396. // TODO
  397. public function getParamsByBasSku($addBasSkus, $owners_code_map)
  398. {
  399. $params = [];
  400. $commodities = Commodity::query()->with(['owner' => function ($query) use ($addBasSkus) {
  401. return $query->whereIn('code', data_get($addBasSkus, '*.customerid'));
  402. }])
  403. ->whereIn('sku', data_get($addBasSkus, '*.sku'))
  404. ->get();
  405. $commodity_map = [];
  406. foreach ($commodities as $commodity) {
  407. $commodity_map[$commodity['owner']['code'].$commodity['sku']] = $commodity;
  408. }
  409. foreach ($addBasSkus as $addBasSku) {
  410. if ($store_asn_code_map[$addBasSku->customerid.$addBasSku->sku] ?? false) continue;
  411. $owner = $owners_code_map[$addBasSku->customerid] ?? null;
  412. $params[] = [
  413. ];
  414. }
  415. return $params;
  416. }
  417. public function getAsnLastSyncAt($key, $type)
  418. {
  419. $last_time = ValueStore::query()->where('name', $key)->value('value');
  420. if ($last_time) return $last_time;
  421. if ($type == 'create') {
  422. $store = Commodity::query()->orderByDesc('created_at')->first();
  423. if ($store) return $store->created_at;
  424. } else {
  425. $store = Commodity::query()->orderByDesc('updated_at')->first();
  426. if ($store) return $store->updated_at;
  427. }
  428. return Carbon::now()->subSeconds(65);
  429. }
  430. public function setAsnLastSyncAt($key, $last_time)
  431. {
  432. $asnLastSyncAt = ValueStore::query()->updateOrCreate([
  433. 'name' => $key,
  434. ], [
  435. 'name' => $key,
  436. 'value' => $last_time,
  437. ]);
  438. LogService::log(__METHOD__, __FUNCTION__, '修改或更新' . $key . json_encode($asnLastSyncAt));
  439. return $asnLastSyncAt;
  440. }
  441. public function getLastRecordsByRedis($set, $prefixKey, $basSkus)
  442. {
  443. if (Cache::get($set)) {
  444. $addBasSkus = collect();
  445. foreach ($basSkus as $basSku) {
  446. if (Cache::get($prefixKey . $basSkus->customerid . '_' . $basSkus->sku)) continue;
  447. $addBasSkus->add($basSku);
  448. }
  449. return $addBasSkus;
  450. }
  451. return $basSkus;
  452. }
  453. public function deleteCacheKey($set, $keys)
  454. {
  455. if (Cache::get($set)) {
  456. $cacheKeys = Cache::get($keys);
  457. if (!$cacheKeys) return;
  458. foreach ($cacheKeys as $cacheKey) {
  459. Cache::forget($cacheKey);
  460. }
  461. Cache::forget($keys);
  462. }
  463. }
  464. public function setLastRecordsByRedis($prefixKey, $set, $keys, $last_records)
  465. {
  466. if (Cache::get($set)) {
  467. $cacheKeys = [];
  468. foreach ($last_records as $last_record) {
  469. Cache::put($prefixKey . $last_record->customerid . '_' . $last_record->sku, true);
  470. array_push($cacheKeys, $prefixKey . $last_record->customerid . '_' . $last_record->sku);
  471. }
  472. Cache::put($keys, $cacheKeys);
  473. Cache::put($set, true);
  474. }
  475. }
  476. public function filterByCommodityCache($basSkus)
  477. {
  478. if (count($basSkus)<1)return null;
  479. $addBasSkus=collect();
  480. foreach ($basSkus as $basSku){
  481. if (Cache::get("owner_code_{$basSku['customerid']}_sku_{$basSku['sku']}")) continue;
  482. $addBasSkus->add($basSku);
  483. }
  484. return $addBasSkus;
  485. }
  486. }