CommodityService.php 35 KB

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