CommodityService.php 39 KB

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