CommodityService.php 36 KB

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