CommodityService.php 29 KB

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