MGoodsBasic.Class.php 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515
  1. <?php
  2. /**
  3. * 商品基础数据模型
  4. * Created by PhpStorm.
  5. * User: XiaoMing
  6. * Date: 2019/10/30
  7. * Time: 14:26
  8. */
  9. namespace JinDouYun\Model\GoodsManage;
  10. use JinDouYun\Cache\PageCache;
  11. use JinDouYun\Controller\Common\Logger;
  12. use JinDouYun\Dao\GoodsManage\DSku;
  13. use JinDouYun\Dao\Shop\DShop;
  14. use JinDouYun\Model\Merchant\MMerchant;
  15. use JinDouYun\Model\Purchase\MSupplier;
  16. use Mall\Framework\Core\StatusCode;
  17. use Mall\Framework\Core\ErrorCode;
  18. use Mall\Framework\Core\ResultWrapper;
  19. use Jindouyun\Cache\RoleAclCache;
  20. use JinDouYun\Cache\SpecCache;
  21. use JinDouYun\Cache\GoodsBasicCache;
  22. use JinDouYun\Cache\GoodsBasicRelevant;
  23. use JinDouYun\Cache\OverviewCache;
  24. use JinDouYun\Dao\GoodsManage\DGoodsBrand;
  25. use JinDouYun\Dao\GoodsManage\DGoodsBasic;
  26. use JinDouYun\Dao\GoodsCategory\DGoodsCategory;
  27. use JinDouYun\Model\Goods\BasicAndSkuCache;
  28. use JinDouYun\Model\Stock\MInventory;
  29. use JinDouYun\Model\MBaseModel;
  30. use JinDouYun\Model\Shop\MShop;
  31. use JinDouYun\Model\GoodsCategory\MGoodsCategory;
  32. use Util\Common\ChineseCharacter;
  33. class MGoodsBasic extends MBaseModel
  34. {
  35. /**
  36. * BasicAndSkuCache
  37. */
  38. use BasicAndSkuCache;
  39. /**
  40. * @var DGoodsBasic
  41. */
  42. private $objDGoodsBasic;
  43. /**
  44. * @var MSku
  45. */
  46. private $objMSku;
  47. /**
  48. * @var int
  49. */
  50. private $onlineUserId;
  51. /**
  52. * @var
  53. */
  54. private $onlineEnterpriseId;
  55. /**
  56. * @var GoodsBasicCache
  57. */
  58. private $objGoodsBasicCache;
  59. /**
  60. * @var OverviewCache
  61. */
  62. private $objOverviewCache;
  63. /**
  64. * @var SpecCache
  65. */
  66. private $objSpecCache;
  67. /**
  68. * @var MInventory
  69. */
  70. private $objMInventory;
  71. /**
  72. * @var GoodsBasicRelevant
  73. */
  74. private $objGoodsBasicRelevant;
  75. /**
  76. * @var DGoodsCategory
  77. */
  78. private $objDGoodsCategory;
  79. /**
  80. * @var DGoodsBrand
  81. */
  82. private $objDGoodsBrand;
  83. /**
  84. * @var DShop
  85. */
  86. private $objDShop;
  87. /**
  88. * @var DSku
  89. */
  90. private $objDSku;
  91. /**
  92. * MGoodsBasic constructor.
  93. * @param $onlineUserId
  94. * @param $onlineEnterpriseId
  95. */
  96. public function __construct($onlineUserId, $onlineEnterpriseId)
  97. {
  98. $this->onlineUserId = $onlineUserId;
  99. $this->onlineEnterpriseId = $onlineEnterpriseId;
  100. parent::__construct($this->onlineEnterpriseId, $this->onlineUserId);
  101. $this->objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
  102. $this->objDGoodsBasic = new DGoodsBasic('default');
  103. $this->objOverviewCache = new OverviewCache();
  104. $this->objDGoodsBasic->setTable($this->objDGoodsBasic->get_Table() . '_' . $onlineEnterpriseId);
  105. $this->objDGoodsBasic->setSearchIndex('goods_basic_search')->setType('goodsBasic');
  106. $this->objGoodsBasicCache = new GoodsBasicCache($this->onlineEnterpriseId);
  107. $this->objGoodsBasicRelevant = new GoodsBasicRelevant($this->onlineEnterpriseId);
  108. $this->objSpecCache = new SpecCache($this->onlineEnterpriseId);
  109. $this->objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
  110. $this->objDGoodsCategory = new DGoodsCategory();
  111. $this->objDGoodsCategory->setTable('qianniao_goods_category_'.$this->onlineEnterpriseId);
  112. $this->objDGoodsBrand = new DGoodsBrand();
  113. $this->objDGoodsBrand->setTable('qianniao_goods_brand_'.$this->onlineEnterpriseId);
  114. $this->objDShop = new DShop();
  115. $this->objDShop->setTable('qianniao_shop_1');
  116. $this->objDSku = new DSku();
  117. $this->objDSku->setTable('qianniao_sku_'.$this->onlineEnterpriseId);
  118. }
  119. /**
  120. * @param $id
  121. * @return string
  122. */
  123. public function getGoodsBasicSubTableName()
  124. {
  125. return $this->objDGoodsBasic->get_Table();
  126. }
  127. /**
  128. * specType => 2
  129. * 添加多规格基础商品资料
  130. * @param $params
  131. * @return ResultWrapper
  132. */
  133. public function addMultipleSpecGoodsBasic($params)
  134. {
  135. $unitData = $params['unitData'];
  136. $specMultiple = $params['specMultiple'];
  137. unset($params['unitData']);
  138. unset($params['specMultiple']);
  139. $this->objDGoodsBasic->beginTransaction();
  140. $params['addUserId'] = $this->onlineUserId;//创建人id
  141. $objRoleAclCache = new RoleAclCache();
  142. $staffId = $objRoleAclCache->getStaffIdAndUserCenterId($this->onlineEnterpriseId, $this->onlineUserId);
  143. $params['salesManId'] = empty($staffId) ? 0 : $staffId;
  144. //商品名称转换搜索条件
  145. $objChineseCharacter = new ChineseCharacter();
  146. $params['condition'] = $objChineseCharacter->getInitials(trim($params['title']));
  147. $dbResult = $this->objDGoodsBasic->insert($params);
  148. $goodsBasicId = $dbResult;
  149. if ($dbResult === false) {
  150. $this->objDGoodsBasic->rollBack();
  151. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  152. }
  153. if (!empty($unitData)) {
  154. $insert = [];
  155. foreach ($unitData as $unit) {
  156. $specGroupIds = [];
  157. $hash = '';
  158. foreach ($specMultiple as $spec) {
  159. $specGroupIds = array_column($spec['specGroup'], 'specValueId');
  160. $hash = md5(implode('|', $specGroupIds));
  161. $insert[] = [
  162. 'goodsId' => $dbResult,
  163. 'specData' => json_encode($spec['specGroup']),
  164. 'specImage' => json_encode($spec['specImage']),
  165. 'specType' => $params['specType'],
  166. 'unitId' => $unit['unitId'],
  167. 'isMaster' => $unit['isMaster'],
  168. 'unitName' => $unit['unitName'],
  169. 'conversion' => isset($unit['conversion']) ? $unit['conversion'] : 0,
  170. 'specGroupHash' => $hash,
  171. 'barCode' => isset($spec['barCode'][$unit['unitId']]) ? $spec['barCode'][$unit['unitId']] : '',
  172. 'isDefault' => isset($spec['isDefault'][$unit['unitId']]) ? $spec['isDefault'][$unit['unitId']] : StatusCode::$delete,
  173. 'weight' => isset($spec['weight'][$unit['unitId']]) ? $spec['weight'][$unit['unitId']] : 0,
  174. 'isNew' => StatusCode::$standard,
  175. ];
  176. }
  177. }
  178. $result = $this->objMSku->addSku($insert, true);
  179. if (!$result->isSuccess()) {
  180. $this->objDGoodsBasic->rollBack();
  181. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  182. }
  183. unset($insert);
  184. }
  185. //缓存商品分类下基础商品数量
  186. $categoryIds = explode(',', $params['categoryPath']);
  187. foreach ($categoryIds as $v) {
  188. $this->objGoodsBasicCache->categoryKeyScoreIncr($v);
  189. }
  190. $this->objGoodsBasicCache->brandKeyScoreIncr($params['brandId']);
  191. //缓存商品数据
  192. $this->isUpdateBasicCache = true;
  193. $this->objectId = $goodsBasicId;
  194. $this->objDGoodsBasic->commit();
  195. //self::updateEsData($dbResult);
  196. return ResultWrapper::success($dbResult);
  197. }
  198. /**
  199. * specType => 1
  200. * 添加单规格商品基础数据
  201. * @param $params
  202. * @return ResultWrapper
  203. * @throws \Exception
  204. */
  205. public function addGoodsBasic($params)
  206. {
  207. $unitData = $params['unitData'];
  208. unset($params['unitData']);
  209. $beginStatus = $this->objDGoodsBasic->beginTransaction();
  210. $params['addUserId'] = $this->onlineUserId;//创建人id
  211. $objRoleAclCache = new RoleAclCache();
  212. $staffId = $objRoleAclCache->getStaffIdAndUserCenterId($this->onlineEnterpriseId, $this->onlineUserId);
  213. $params['salesManId'] = empty($staffId) ? 0 : $staffId;
  214. //商品名称转换搜索条件
  215. $objChineseCharacter = new ChineseCharacter();
  216. $params['condition'] = $objChineseCharacter->getInitials(trim($params['title']));
  217. $dbResult = $this->objDGoodsBasic->insert($params);
  218. $goodsBasicId = $dbResult;
  219. if ($dbResult === false) {
  220. $this->objDGoodsBasic->rollBack();
  221. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  222. }
  223. if (!empty($unitData)) {
  224. $insert = [];
  225. foreach ($unitData as $key => $unit) {
  226. $insert[] = [
  227. 'unitName' => $unit['unitName'],
  228. 'unitId' => $unit['unitId'],//单位ID
  229. 'goodsId' => $dbResult,
  230. 'isMaster' => $unit['isMaster'],
  231. 'conversion' => isset($unit['conversion']) ? $unit['conversion'] : 0,
  232. 'specType' => StatusCode::$specType['single'],//无属性
  233. 'barCode' => isset($unit['barCode']) ? $unit['barCode'] : '',
  234. 'isDefault' => isset($unit['isDefault']) ? $unit['isDefault'] : StatusCode::$delete,
  235. 'weight' => isset($unit['weight']) ? $unit['weight'] : '',
  236. 'isNew' => StatusCode::$standard,
  237. ];
  238. }
  239. $result = $this->objMSku->addSku($insert, true);
  240. if (!$result->isSuccess()) {
  241. $this->objDGoodsBasic->rollBack();
  242. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  243. }
  244. }
  245. //缓存商品分类下基础商品数量
  246. $categoryIds = explode(',', $params['categoryPath']);
  247. foreach ($categoryIds as $v) {
  248. $this->objGoodsBasicCache->categoryKeyScoreIncr($v);
  249. }
  250. $this->objGoodsBasicCache->brandKeyScoreIncr($params['brandId']);
  251. //缓存商品数据
  252. //缓存商品数据
  253. $this->isUpdateBasicCache = true;
  254. $this->objectId = $goodsBasicId;
  255. $beginStatus && $this->objDGoodsBasic->commit();
  256. //self::updateEsData($dbResult);
  257. return ResultWrapper::success($dbResult);
  258. }
  259. private function createEsDocumentId($goodsBasicId)
  260. {
  261. return 'EnterpriseId_' . $this->onlineEnterpriseId . '_GoodsBasicId_' . $goodsBasicId;
  262. }
  263. /**
  264. * 更新ES
  265. * @param $goodsBasicId
  266. */
  267. public function updateEsData($goodsBasicId)
  268. {
  269. //每次查询一遍,避免商品在数据库存在,在ES中不存在的情况
  270. $goodsBasic = $this->objDGoodsBasic->get_by('id', $goodsBasicId);
  271. if ($goodsBasic !== false && !empty($goodsBasic)) {
  272. $goodsBasic['goodsCode'] = createCode(StatusCode::$code['goodsBasic']['prefix'], $goodsBasicId, StatusCode::$code['goodsBasic']['length']);//商品编码
  273. $goodsBasic['enterpriseId'] = $this->onlineEnterpriseId;
  274. $goodsBasic['images'] = json_decode($goodsBasic['images'], true);
  275. //处理sku数据
  276. $skuInfo = $this->objMSku->getSkuInfo(['goodsId' => [$goodsBasicId]]);
  277. if ($skuInfo->isSuccess()) {
  278. $skuData = $skuInfo->getData();
  279. $goodsBasic['skuData'] = array_shift($skuData);
  280. }
  281. /*
  282. $_id = self::createEsDocumentId($goodsBasicId);
  283. $result = $this->objDGoodsBasic->addUpSearchIndexDocument($goodsBasic, $_id);
  284. if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
  285. //echo "es操作成功";die;
  286. } else {
  287. file_put_contents('/www/wwwroot/logs/api.junhailan.com/elasticsearch.log', date('Y-m-d H:i:s') . '操作商品资料es错误,错误原因' . var_export($result, true) . PHP_EOL, FILE_APPEND);
  288. }*/
  289. }
  290. }
  291. /**
  292. * Doc: (des="")
  293. * User: XMing
  294. * Date: 2020/8/22
  295. * Time: 4:29 下午
  296. * @param array $data
  297. * @param string $source
  298. * @return ResultWrapper
  299. */
  300. private function getExportDataBySelectParams($data,string $source)
  301. {
  302. if (empty($data)){
  303. return ResultWrapper::success([]);
  304. }
  305. switch ($source){
  306. case 'db':
  307. $result = self::getGoodsBasicBySelectParams($data);
  308. break;
  309. case 'es':
  310. $allIds = [];
  311. foreach ($data as $value){
  312. $allIds[] = $value['id'];
  313. }
  314. $result = self::getGoodsBasicBySelectParams(['id' => $allIds]);
  315. break;
  316. }
  317. if (!$result->isSuccess()){
  318. return ResultWrapper::fail($result->getData(),$result->getErrorCode());
  319. }
  320. return ResultWrapper::success($result->getData());
  321. }
  322. /**
  323. * Doc: (des="获取export查询方法返回的数据集合")
  324. * User: XMing
  325. * Date: 2020/8/22
  326. * Time: 11:42 上午
  327. * @param $object
  328. * @return array
  329. */
  330. private static function getGeneratorData($object)
  331. {
  332. $arrayList = [];
  333. foreach ($object as $value){
  334. $arrayList[] = $value;
  335. }
  336. return $arrayList;
  337. }
  338. /**
  339. * Doc: (des="基础商品资料导出")
  340. * User: XMing
  341. * Date: 2020/8/22
  342. * Time: 5:54 下午
  343. * @param array $data
  344. * @param string $source
  345. * @return ResultWrapper
  346. */
  347. private function exportGoodsBasic($data,string $source)
  348. {
  349. $listResult = self::getExportDataBySelectParams($data,$source);
  350. if (!$listResult->isSuccess()){
  351. return ResultWrapper::fail($listResult->getData(),$listResult->getErrorCode());
  352. }
  353. $list = $listResult->getData();
  354. if (empty($list)){
  355. return ResultWrapper::success([]);
  356. }
  357. $formatListsResult = self::formatExportList($list);
  358. if (!$formatListsResult->isSuccess()){
  359. return ResultWrapper::fail($formatListsResult->getData(),$formatListsResult->getErrorCode());
  360. }
  361. $formatLists = $formatListsResult->getData();
  362. self::exportCsv($formatLists);
  363. }
  364. /**
  365. * Doc: (des="")
  366. * User: XMing
  367. * Date: 2020/8/24
  368. * Time: 4:01 下午
  369. * @param array $result
  370. */
  371. private function exportCsv(array $result)
  372. {
  373. //导出到本地
  374. header("Content-type:application/vnd.ms-excel");
  375. header("Content-Disposition:filename=GoodsBasicCsv.csv");
  376. header('Cache-Control: max-age=0');
  377. $fp = fopen('php://output', 'a');
  378. $head = ['ID', '商品编码', '商品名称', '商品分类', '商品品牌','发布来源','状态', '保质期(天)', '创建时间',
  379. '商品卖点', '货架编码', '禁止销售店铺', '关键词', '计量单位', '规格', '主单位(主/辅)', '主辅换算比率', '商品条码'];//定义标题
  380. foreach ($head as $i => $v) {
  381. $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
  382. }
  383. fputcsv($fp, $head);
  384. $limit = 10000;
  385. $num = 0;//计数器
  386. $rows = [];
  387. foreach ($result as $v) {
  388. $num++;
  389. if($num == $limit){
  390. ob_flush(); //释放内存
  391. flush();
  392. }
  393. foreach ($v['specMultiple'] as $index => $item){
  394. self::buildExportFinalData($rows,$v,$item,$index);
  395. foreach ($rows as $kk => $vv) {
  396. $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
  397. }
  398. fputcsv($fp, $rs);
  399. $rows = [];
  400. }
  401. }
  402. exit;
  403. }
  404. /**
  405. * Doc: (des="映射导出的数据")
  406. * User: XMing
  407. * Date: 2020/8/24
  408. * Time: 4:20 下午
  409. * @param $rows
  410. * @param array $v
  411. * @param array $item
  412. * @param int $index
  413. */
  414. private function buildExportFinalData(&$rows,array $v,array $item,int $index)
  415. {
  416. $rows['id'] = '';
  417. $rows['goodsCode'] = '';
  418. $rows['goodsName'] = '';
  419. $rows['categoryName'] = '';
  420. $rows['brandName'] = '';
  421. $rows['sourceMsg'] ='';
  422. $rows['enableStatusMsg'] = '';
  423. $rows['expireTime'] = '';
  424. $rows['createTime'] = '';
  425. $rows['describe'] = '';
  426. $rows['storageCode'] = '';
  427. $rows['noSalesShopNames'] = '';
  428. $rows['tag'] = '';
  429. if ($index == 0){
  430. $rows['id'] = $v['id'];
  431. $rows['goodsCode'] = $v['goodsCode'];
  432. $rows['goodsName'] = $v['title'];
  433. $rows['categoryName'] = $v['categoryName'];
  434. $rows['brandName'] = $v['brandName'];
  435. $rows['sourceMsg'] =$v['sourceMsg'];
  436. $rows['enableStatusMsg'] = $v['enableStatusMsg'];
  437. $rows['expireTime'] = $v['expireTime'];
  438. $rows['createTime'] = $v['createTime'];
  439. $rows['describe'] = $v['describe'];
  440. $rows['storageCode'] = $v['storage'];
  441. $rows['noSalesShopNames'] = $v['noSalesShopNames'];
  442. $rows['tag'] = $v['tag'];
  443. }
  444. $rows['unitName'] = $item['unitName'];
  445. $rows['specGroup'] = $item['specGroup'];
  446. $rows['skuMsg'] = $item['skuMsg'];
  447. $rows['conversion'] = $item['conversion'];
  448. $rows['barCode'] = $item['barCode'];
  449. }
  450. /**
  451. * Doc: (des="格式化导出数据")
  452. * User: XMing
  453. * Date: 2020/8/22
  454. * Time: 6:12 下午
  455. * @param array $data
  456. * @return ResultWrapper
  457. */
  458. private function formatExportList(array $data)
  459. {
  460. if (empty($data)){
  461. return ResultWrapper::success([]);
  462. }
  463. $allCategoryIds = [];
  464. $allBrandIds = [];
  465. $allNoSalesShopIds = [];
  466. $allBasicIds = [];
  467. $merchantIds = [];
  468. $shopIds = [];
  469. $supplierIds = [];
  470. foreach ($data as $value){
  471. $allBasicIds[] = $value['id'];
  472. $allCategoryIds[] = $value['categoryId'];
  473. $merchantIds[] = $value['merchantId'];
  474. if (!empty($value['brandId'])){
  475. $allBrandIds[] = $value['brandId'];
  476. }
  477. if (!empty($value['noSalesShop'])){
  478. $array = explode(',',$value['noSalesShop']);
  479. $allNoSalesShopIds = array_merge($allNoSalesShopIds,$array);
  480. }
  481. if ($value['noSalesShop']) {
  482. $shopIds = array_merge($shopIds, explode(',', $value['noSalesShop']));
  483. }
  484. !empty($value['storeId']) && $shopIds[] = $value['storeId'];
  485. !empty($value['supplierId']) && $supplierIds[] = $value['supplierId'];
  486. }
  487. $allCategoryIds = array_values(array_unique($allCategoryIds));
  488. $allBrandIds = array_values(array_unique($allBrandIds));
  489. $allNoSalesShopIds = array_values(array_unique($allNoSalesShopIds));
  490. $merchantIds = array_values(array_unique($merchantIds));
  491. //查询分类
  492. $categoryMap = [];
  493. if (!empty($allCategoryIds)){
  494. $categoryLists = $this->objDGoodsCategory->exportSelect(['id' => $allCategoryIds],'id,title');
  495. if ($categoryLists === false){
  496. return ResultWrapper::fail($this->objDGoodsCategory->error(),ErrorCode::$dberror);
  497. }
  498. $categoryLists = self::getGeneratorData($categoryLists);
  499. foreach ($categoryLists as $value){
  500. $categoryMap[$value['id']] = $value['title'];
  501. }
  502. unset($value);
  503. unset($categoryLists);
  504. }
  505. //查询品牌
  506. $brandMap = [];
  507. if (!empty($allBrandIds)){
  508. $brandLists = $this->objDGoodsBrand->exportSelect(['id' => $allBrandIds],'id,title');
  509. if ($brandLists === false){
  510. return ResultWrapper::fail($this->objDGoodsBrand->error(),ErrorCode::$dberror);
  511. }
  512. $brandLists = self::getGeneratorData($brandLists);
  513. foreach ($brandLists as $value){
  514. $brandMap[$value['id']] = $value['title'];
  515. }
  516. unset($value);
  517. unset($brandLists);
  518. }
  519. //查询店铺
  520. $shopMap = [];
  521. if (!empty($allNoSalesShopIds)){
  522. $shopLists = $this->objDShop->exportSelect(['id'=>$allNoSalesShopIds],'id,name');
  523. if ($shopLists === false){
  524. return ResultWrapper::fail($this->objDShop->error(),ErrorCode::$dberror);
  525. }
  526. $shopLists = self::getGeneratorData($shopLists);
  527. foreach ($shopLists as $value){
  528. $shopMap[$value['id']] = $value['name'];
  529. }
  530. unset($value);
  531. unset($shopLists);
  532. }
  533. //查询sku
  534. $skuMap = [];
  535. if (!empty($allBasicIds)){
  536. $skuLists = $this->objDSku->exportSelect(['goodsId' => $allBasicIds,'deleteStatus' => StatusCode::$standard],'id,goodsId,conversion,unitName,isMaster,specData,barCode');
  537. if ($skuLists === false){
  538. return ResultWrapper::fail($this->objDSku->error(),ErrorCode::$dberror);
  539. }
  540. $skuLists = self::getGeneratorData($skuLists);
  541. foreach ($skuLists as &$value){
  542. $value['skuMsg'] = $value['isMaster'] == StatusCode::$standard ? '主' : '辅';
  543. $value['specGroup'] = empty($value['specData']) ? '无' : self::createSpecName(json_decode($value['specData'],true));
  544. $skuMap[$value['goodsId']][] = $value;
  545. }
  546. unset($value);
  547. unset($skuLists);
  548. }
  549. //查询发布来源(商户)
  550. if(!empty($merchantIds)){
  551. $objMMerchant = new MMerchant($this->onlineEnterpriseId, $this->onlineUserId);
  552. $modelResult = $objMMerchant->selectMerchantData(['id' => $merchantIds, 'deleteStatus' => StatusCode::$standard]);
  553. if(!$modelResult->isSuccess()){
  554. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  555. }
  556. $merchantResult = $modelResult->getData();
  557. unset($modelResult);
  558. $merchantData =[];
  559. foreach($merchantResult as $value){
  560. $merchantData[$value['id']] = $value;
  561. }
  562. }
  563. //商铺
  564. $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
  565. $shops = $objMShop->getShopName(array_values(array_unique($shopIds)));
  566. //供应商
  567. $objMSupplier = new MSupplier($this->onlineUserId,$this->onlineEnterpriseId);
  568. $supplierResult = $objMSupplier->getSupplierNameByIds($supplierIds);
  569. $supplierMap = [];
  570. if ($supplierResult->isSuccess()){
  571. $supplierMap = MSupplier::supplierMap($supplierResult->getData());
  572. }
  573. foreach ($data as $key => &$value){
  574. $value['categoryName'] = isset($categoryMap[$value['categoryId']]) ? $categoryMap[$value['categoryId']] : '无';
  575. $value['brandName'] = isset($brandMap[$value['brandId']]) ? $brandMap[$value['brandId']] : '无';
  576. if (empty($value['noSalesShop'])){
  577. $value['noSalesShopNames'] = '';
  578. }else{
  579. $noSalesShopStr = '';
  580. $noSalesShopArr = explode(',',$value['noSalesShop']);
  581. foreach ($noSalesShopArr as $shopId){
  582. !empty($noSalesShopStr) && $noSalesShopStr .= ',';
  583. $noSalesShopStr .= isset($shopMap[$shopId]) ? $shopMap[$shopId] : '无';
  584. }
  585. $value['noSalesShopNames'] = $noSalesShopStr;
  586. }
  587. $value['specMultiple'] = isset($skuMap[$value['id']]) ? $skuMap[$value['id']] : [];
  588. $value['goodsCode'] = createCode(StatusCode::$code['goodsBasic']['prefix'], $value['id'], StatusCode::$code['goodsBasic']['length']);;
  589. $data[$key]['sourceMsg'] = '平台';
  590. if (isset($value['storeId']) && !empty($value['storeId'])){
  591. $data[$key]['sourceMsg'] = getArrayItem($shops,$value['storeId'],'');
  592. }
  593. if (isset($value['supplierId']) && !empty($value['supplierId'])){
  594. $row = getArrayItem($supplierMap,$value['supplierId'],[]);
  595. if (!empty($row)){
  596. $data[$key]['sourceMsg'] = getArrayItem($row,'title','');
  597. }
  598. }
  599. $data[$key]['merchantName'] = '';
  600. if(isset($value['merchantId']) && !empty($value['merchantId']) && isset($merchantData[$value['merchantId']])){
  601. $data[$key]['sourceMsg'] = $merchantData[$value['merchantId']]['name'];
  602. $data[$key]['merchantName'] = $merchantData[$value['merchantId']]['name'];
  603. }
  604. $value['enableStatusMsg'] = $value['enableStatus'] == StatusCode::$standard ? '启用' : '禁用';
  605. $value['createTime'] = date('Y-m-d H:i:s',$value['createTime']);
  606. $value['storage'] = '无';
  607. if (!empty($value['extends'])){
  608. $value['storage'] = empty($value['extends']) ? '' : json_decode($value['extends'],true)['storage'];
  609. }
  610. }
  611. return ResultWrapper::success($data);
  612. }
  613. /**
  614. * Doc: (des="生成规格名字")
  615. * User: XMing
  616. * Date: 2020/8/22
  617. * Time: 2:47 下午
  618. * @param array $specGroup
  619. * @return string
  620. */
  621. private static function createSpecName(array $specGroup)
  622. {
  623. $str = '';
  624. foreach ($specGroup as $value){
  625. empty($str) && $str .= ' ';
  626. if (!empty($value['specName'])){
  627. $str .= $value['specName'].':';
  628. }
  629. if (!empty($value['specValueName'])){
  630. $str .= $value['specValueName'];
  631. }
  632. }
  633. return empty($str) ? '无' : $str;
  634. }
  635. /**
  636. * Doc: (des="导出查询数据")
  637. * User: XMing
  638. * Date: 2020/8/22
  639. * Time: 4:58 下午
  640. * @param array $selectParams
  641. * @return ResultWrapper
  642. */
  643. private function getGoodsBasicBySelectParams(array $selectParams)
  644. {
  645. $goodsBasicLists = $this->objDGoodsBasic->exportSelect($selectParams,'*','createTime DESC');
  646. if ($goodsBasicLists === false){
  647. return ResultWrapper::fail($this->objDGoodsBasic->error(),ErrorCode::$dberror);
  648. }
  649. $goodsBasicLists = self::getGeneratorData($goodsBasicLists);
  650. return ResultWrapper::success($goodsBasicLists);
  651. }
  652. /**
  653. * 获取全部商品基础数据列表
  654. * @param $selectParams
  655. * @param boolean $is_export
  656. * @return ResultWrapper
  657. * @throws \Exception
  658. */
  659. public function getAllGoodsBasic($selectParams,$is_export = false)
  660. {
  661. $limit = $selectParams['limit'];
  662. unset($selectParams['limit']);
  663. $offset = $selectParams['offset'];
  664. unset($selectParams['offset']);
  665. // $selectParams = parent::getSalesManQueryParams($selectParams, 'salesManId');
  666. $selectParams['deleteStatus'] = StatusCode::$standard;
  667. if ($is_export === true) self::exportGoodsBasic($selectParams,'db');
  668. $dbResult = $this->objDGoodsBasic->select($selectParams, '*', 'id desc', $limit, $offset);
  669. if ($dbResult === false) {
  670. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  671. }
  672. $total = $this->objDGoodsBasic->count($selectParams);
  673. $format = self::formatJson($dbResult);
  674. $format = self::formatCategory($format);
  675. foreach ($format as &$formatData) {
  676. $formatData['unitData'] = [];
  677. $formatData['specGroup'] = [];
  678. $formatData['specMultiple'] = [];
  679. $formatData = self::formatSingleSkuMapping($formatData);
  680. $formatData = self::formatMultipleSkuMapping($formatData);
  681. }
  682. $return = [
  683. 'data' => $format,
  684. 'total' => ($total) ? intval($total) : 0,
  685. ];
  686. return ResultWrapper::success($return);
  687. }
  688. public function fixEsData($selectParams)
  689. {
  690. $limit = $selectParams['limit'];
  691. unset($selectParams['limit']);
  692. $offset = $selectParams['offset'];
  693. unset($selectParams['offset']);
  694. //$selectParams['deleteStatus'] = StatusCode::$standard;
  695. $dbResult = $this->objDGoodsBasic->select($selectParams, 'id', null, $limit, $offset);
  696. foreach ($dbResult as $goods) {
  697. self::updateEsData($goods['id']);
  698. }
  699. print_r(count($dbResult) . '条数据');
  700. }
  701. /**
  702. * 获取商铺下允许销售的商品
  703. * @param $selectParams
  704. * @return ResultWrapper
  705. * @throws \Exception
  706. */
  707. public function getGoodsBasicOfShopId($selectParams)
  708. {
  709. $limit = $selectParams['limit'];
  710. $offset = $selectParams['offset'];
  711. /*
  712. $where = 'deleteStatus = ' . StatusCode::$standard;
  713. $where .= ' AND !FIND_IN_SET(' . $selectParams['shopId'] . ',noSalesShop)';
  714. if (isset($selectParams['title'])) {
  715. $where .= ' AND title LIKE "%' . $selectParams['title'] . '%"';
  716. }
  717. $dbResult = $this->objDGoodsBasic->select($where, '*', 'createTime desc', $limit, $offset);*/
  718. //查询已经发布的基础物料id
  719. $sql = 'SELECT `basicGoodsId` from qianniao_goods_' . $this->onlineEnterpriseId . ' WHERE `shopId` = ' . $selectParams['shopId'] . ' AND `deleteStatus` = '.StatusCode::$standard;
  720. $result = $this->objDGoodsBasic->query($sql);
  721. if ($result === false){
  722. return ResultWrapper::fail($this->objDGoodsBasic->error(),ErrorCode::$dberror);
  723. }
  724. unset($sql);
  725. $havingIds = [];
  726. foreach ($result as $item) {
  727. $havingIds[] = $item['basicGoodsId'];
  728. }
  729. $sql = 'SELECT `id` from qianniao_goods_basic_'.$this->onlineEnterpriseId.' WHERE FIND_IN_SET(' . $selectParams['shopId'] . ',`noSalesShop`)';
  730. $result = $this->objDGoodsBasic->query($sql);
  731. if ($result === false){
  732. return ResultWrapper::fail($this->objDGoodsBasic->error(),ErrorCode::$dberror);
  733. }
  734. unset($sql);
  735. $noSaleIds = [];
  736. foreach ($result as $item){
  737. $noSaleIds[] = $item['id'];
  738. }
  739. $notIds = array_merge($havingIds,$noSaleIds);
  740. $sql = 'SELECT * FROM qianniao_goods_basic_' . $this->onlineEnterpriseId . ' WHERE `enableStatus` = ' . StatusCode::$standard . ' AND `deleteStatus` = ' . StatusCode::$standard;
  741. if (!empty($notIds)){
  742. $notIds = trim(implode(',',$notIds),',');
  743. $sql .= ' AND id NOT IN ('. $notIds .')';
  744. }
  745. $sql .= ' AND level = '.StatusCode::$standard;
  746. if (isset($selectParams['title'])) {
  747. $sql .= ' AND title LIKE "%' . $selectParams['title'] . '%" ';
  748. }
  749. //筛选分类
  750. if (isset($selectParams['categoryId']) && !empty($selectParams['categoryId'])){
  751. $sql .= ' AND find_in_set('.$selectParams['categoryId'].',categoryPath) ';
  752. }
  753. $sql .= ' order by createTime desc limit ' . $offset . ',' . $limit;
  754. $dbResult = $this->objDGoodsBasic->query($sql);
  755. if ($dbResult === false) {
  756. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  757. }
  758. $sql = 'select count(id) as total from qianniao_goods_basic_' . $this->onlineEnterpriseId . ' where id not in(select basicGoodsId from qianniao_goods_' . $this->onlineEnterpriseId . ' where shopid = ' . $selectParams['shopId'] . ' AND deleteStatus = '.StatusCode::$standard.' ) and !FIND_IN_SET(' . $selectParams['shopId'] . ',noSalesShop) and enableStatus = ' . StatusCode::$standard . ' and deleteStatus =' . StatusCode::$standard;
  759. $sql .= ' AND level = '.StatusCode::$standard;
  760. if (isset($selectParams['title'])) {
  761. $sql .= ' AND title LIKE "%' . $selectParams['title'] . '%"';
  762. }
  763. //筛选分类
  764. if (isset($selectParams['categoryId']) && !empty($selectParams['categoryId'])){
  765. $sql .= ' AND find_in_set('.$selectParams['categoryId'].',categoryPath) ';
  766. }
  767. $total = $this->objDGoodsBasic->query($sql);
  768. if ($total === false) {
  769. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  770. }
  771. $total = $total[0]['total'];
  772. $format = self::formatJson($dbResult);
  773. $format = self::formatCategory($format);
  774. foreach ($format as &$detail) {
  775. $detail['unitData'] = [];
  776. $detail = self::formatSingleSkuMapping($detail);
  777. }
  778. $return = [
  779. 'data' => $format,
  780. 'total' => ($total) ? intval($total) : 0,
  781. ];
  782. return ResultWrapper::success($return);
  783. }
  784. /**
  785. * 获取指定基础商品详情
  786. * @param $id
  787. * @param $isAddGoods
  788. * @return ResultWrapper
  789. * @throws \Exception
  790. */
  791. public function getGoodsBasicInfoById($id, $isAddGoods)
  792. {
  793. $dbResult = $this->objDGoodsBasic->get_by('id', $id);
  794. if ($dbResult === false) {
  795. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  796. }
  797. $formatData = self::formatJson($dbResult);
  798. $formatData = self::formatCategory($formatData);
  799. $formatData = array_shift($formatData);
  800. $formatData = self::formatSingleSkuMapping($formatData);
  801. $formatData = self::formatMultipleSkuMapping($formatData, $isAddGoods);
  802. $formatData = self::formatMultipleSkuIndex($formatData);
  803. $formatData = self::getSkuInventorySpec($formatData);
  804. return ResultWrapper::success($formatData);
  805. }
  806. /**
  807. * @param $data
  808. * @return mixed
  809. */
  810. private function getSkuInventorySpec($data)
  811. {
  812. //print_r(array_column($data['specMultiple'],'id'));die;
  813. $InventoryResult = $this->objMInventory->getInventoryBySkuIds(array_column($data['specMultiple'], 'id'));
  814. $inventoryData = [];
  815. if (!$InventoryResult->isSuccess()) {
  816. file_put_contents('/www/wwwroot/logs/api.junhailan.com/MGoodsBasic_error.log', date('Y-m-d H:i:s') . '错误信息|sql错误 :' . $InventoryResult->getData() . PHP_EOL, FILE_APPEND);
  817. } else {
  818. $inventoryData = $InventoryResult->getData();
  819. }
  820. foreach ($data['specMultiple'] as &$row) {
  821. if (isset($inventoryData[$row['id']])) {
  822. $row['isEditSpec'] = StatusCode::$delete;//采购过,不能编辑
  823. } else {
  824. $row['isEditSpec'] = StatusCode::$standard;
  825. }
  826. $row['inventory'] = isset($inventoryData[$row['id']]) ? $inventoryData[$row['id']] : 0;
  827. }
  828. //查询物料库存
  829. $materielResult = $this->objMInventory->getInventoryByMaterielIds([$data['id']]);
  830. $materielMap = [];
  831. if (!$materielResult->isSuccess()) {
  832. file_put_contents('/www/wwwroot/logs/api.junhailan.com/MGoodsBasic_error.log', date('Y-m-d H:i:s') . '错误信息|sql错误 :' . var_export($materielResult->getData()) . PHP_EOL, FILE_APPEND);
  833. } else {
  834. $materielMap = $materielResult->getData();
  835. }
  836. if (!isset($materielMap[$data['id']])) {
  837. //从来没有采购过
  838. $data['isEditSpec'] = StatusCode::$standard;
  839. } else {
  840. //采购过
  841. $data['isEditSpec'] = StatusCode::$delete;
  842. }
  843. return $data;
  844. }
  845. /**
  846. *
  847. */
  848. public static function formatMultipleSkuIndex($details)
  849. {
  850. //生成规格唯一索引
  851. $specMultiple = $details['specMultiple'];
  852. if (empty($specMultiple)) {
  853. return $details;
  854. }
  855. foreach ($specMultiple as &$spec) {
  856. $index = $details['id'] . ':' . $spec['unitId'];//商品ID
  857. //$subName = '';
  858. if (!empty($spec['specGroup'])) {
  859. foreach ($spec['specGroup'] as $row) {
  860. $index .= empty($index) ? $row['specValueId'] : ':' . $row['specValueId'];
  861. //$subName .= empty($subName) ? $row['specIdName'] . ':' . $row['specValueIdName'] : '-' . $row['specIdName'] . ':' . $row['specValueIdName'];
  862. //$subName .= empty($subName) ? $row['specValueIdName'] : ':' . $row['specValueIdName'];
  863. }
  864. }
  865. $spec['index'] = $index;
  866. $spec['indexGroup'] = explode(':', $index);
  867. //$spec['subName'] = $subName;
  868. }
  869. $details['specMultiple'] = $specMultiple;
  870. return $details;
  871. }
  872. /**
  873. * 将相同的辅单位合并在一起(兼容之前数据所以使用md5判断)
  874. * @param $data
  875. * @return array
  876. */
  877. public function branchMerge($data)
  878. {
  879. if (empty($data)) {
  880. return $data;
  881. }
  882. $hash = [];
  883. $sku = [];
  884. foreach ($data as $key => $unit) {
  885. $thisHash = md5($unit['conversion'] . $unit['unitName'] . $unit['unitId']);
  886. $hash[$thisHash]['skuIds'][] = $unit['id'];
  887. $hash[$thisHash]['sku'] = $unit;
  888. }
  889. $mapping = [];
  890. foreach ($hash as &$value) {
  891. $value['sku']['skuIds'] = $value['skuIds'];
  892. $mapping[] = $value['sku'];
  893. }
  894. return $mapping;
  895. }
  896. /**
  897. * 单位
  898. * @param $data
  899. * @return mixed
  900. * @throws \Exception
  901. */
  902. public function formatSingleSkuMapping($data)
  903. {
  904. if(isset($data['basicGoodsId'])){
  905. $id = $data['basicGoodsId'];
  906. }else{
  907. $id = $data['id'];
  908. }
  909. //计量单位
  910. $selectParams = [
  911. 'goodsId' => $data['id'],
  912. ];
  913. if (isset($data['basicGoodsId'])){
  914. $id = $data['basicGoodsId'];
  915. }else{
  916. $id = $data['id'];
  917. }
  918. $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
  919. $sql = "SELECT id,barCode,unitId,unitName,conversion,isMaster,barCode,specType,isDefault,`weight`,isNew,specGroupHash FROM qianniao_sku_" . $this->onlineEnterpriseId . " WHERE goodsId=" . $id . " AND deleteStatus=" . StatusCode::$standard . " ORDER BY isMaster DESC";
  920. $skuResult = $objMSku->getQuery($sql);
  921. $skuData = [];
  922. if ($skuResult->isSuccess()) {
  923. $skuData = $skuResult->getData();
  924. $haveMaster = 0;
  925. $newSkuData = [];
  926. $noMasterUnidIds = [];
  927. foreach ($skuData as $key => &$value) {
  928. if ($data['specType'] == StatusCode::$specType['multiple']) {
  929. $value['barCode'] = '';
  930. }
  931. if ($value['isMaster'] == StatusCode::$standard && $haveMaster == 0) {
  932. $newSkuData[] = $value;
  933. $haveMaster = 1;
  934. }
  935. if ($value['isMaster'] == StatusCode::$delete && !in_array($value['unitId'], $noMasterUnidIds)) {
  936. $newSkuData[] = $value;
  937. $noMasterUnidIds[] = $value['unitId'];
  938. }
  939. }
  940. unset($skuData);
  941. $skuData = $newSkuData;
  942. }
  943. $data['unitData'] = $skuData;
  944. return $data;
  945. }
  946. /**
  947. * @param $data
  948. * @param $isAddGoods
  949. * @return mixed
  950. * @throws \Exception
  951. */
  952. public function formatMultipleSkuMapping($data, $isAddGoods = 4)
  953. {
  954. switch ($isAddGoods) {
  955. case StatusCode::$standard:
  956. $sql = "SELECT id,unitId,unitName,conversion,isDefault,isMaster,specGroupHash,specImage,specData,barCode,`weight`,isNew FROM qianniao_sku_" . $this->onlineEnterpriseId . " WHERE goodsId=" . $data['id'] . " AND deleteStatus=" . StatusCode::$standard;
  957. break;
  958. case StatusCode::$delete:
  959. $sql = "SELECT id,unitId,unitName,conversion,isDefault,isMaster,specGroupHash,specImage,specData,barCode,`weight`,isNew FROM qianniao_sku_" . $this->onlineEnterpriseId . " WHERE goodsId=" . $data['id'] . " AND deleteStatus=" . StatusCode::$standard . " AND isMaster=" . StatusCode::$standard . " GROUP BY specGroupHash";
  960. break;
  961. }
  962. //$sql = "SELECT id,unitId,unitName,conversion,isMaster,specGroupHash,specImage,specData FROM qianniao_sku_" . $this->onlineEnterpriseId . " WHERE goodsId=" . $data['id'] . " AND deleteStatus=" . StatusCode::$standard . " AND isMaster=" . StatusCode::$standard . " GROUP BY specGroupHash";
  963. $skuResult = $this->objMSku->getQuery($sql);
  964. $skuData = [];
  965. if ($skuResult->isSuccess()) {
  966. $skuData = $skuResult->getData();
  967. }
  968. $specMultiple = [];
  969. foreach ($skuData as $spec) {
  970. $specGroup = json_decode($spec['specData'], true);
  971. $specMultiple[] = [
  972. 'id' => $spec['id'],
  973. 'unitId' => $spec['unitId'],
  974. 'unitName' => $spec['unitName'],
  975. 'isMaster' => $spec['isMaster'],
  976. 'conversion' => $spec['conversion'],
  977. 'specGroup' => $specGroup,
  978. 'specGroupHash' => $spec['specGroupHash'],
  979. 'specImage' => json_decode($spec['specImage'], true),
  980. 'barCode' => $spec['barCode'],
  981. 'isDefault' => $spec['isDefault'],
  982. 'weight' => $spec['weight'],
  983. 'isNew' => $spec['isNew']
  984. ];
  985. }
  986. $data['specMultiple'] = $specMultiple;
  987. if ($isAddGoods == StatusCode::$delete) $data = self::formatBarCode($data);
  988. return $data;
  989. }
  990. /**
  991. *
  992. */
  993. public function formatBarCode(array $data)
  994. {
  995. if (empty($data)) {
  996. return $data;
  997. }
  998. if ($data['specType'] == StatusCode::$specType['single']) {
  999. return $data;
  1000. }
  1001. $skuResult = $this->objMSku->getSkuByParams(
  1002. [
  1003. 'specGroupHash' => array_column($data['specMultiple'], 'specGroupHash'),
  1004. 'goodsId' => $data['id'],
  1005. 'deleteStatus' => StatusCode::$standard
  1006. ]
  1007. );
  1008. if (!$skuResult->isSuccess()) {
  1009. file_put_contents('/www/wwwroot/logs/api.junhailan.com/MGoodsBasic_error.log', date('Y-m-d H:i:s') . '错误原因|sql:' . $skuResult->getData() . PHP_EOL, FILE_APPEND);
  1010. return $data;
  1011. }
  1012. $skuData = $skuResult->getData();
  1013. $map = [];
  1014. $isDefaultMap = [];
  1015. $weightMap = [];
  1016. foreach ($skuData as $item) {
  1017. $map[$item['specGroupHash']][$item['unitId']] = $item['barCode'];
  1018. $isDefaultMap[$item['specGroupHash']][$item['unitId']] = $item['isDefault'];
  1019. $weightMap[$item['specGroupHash']][$item['unitId']] = $item['weight'];
  1020. }
  1021. foreach ($data['specMultiple'] as &$spec) {
  1022. $spec['barCode'] = isset($map[$spec['specGroupHash']]) ? $map[$spec['specGroupHash']] : (object)[];
  1023. $spec['isDefault'] = isset($isDefaultMap[$spec['specGroupHash']]) ? $isDefaultMap[$spec['specGroupHash']] : (object)[];
  1024. $spec['weight'] = isset($weightMap[$spec['specGroupHash']]) ? $weightMap[$spec['specGroupHash']] : (object)[];
  1025. }
  1026. return $data;
  1027. }
  1028. /**
  1029. * specType => 1
  1030. * 编辑单规格基础商品数据
  1031. * @param $params
  1032. * @return ResultWrapper
  1033. * @throws \Exception
  1034. */
  1035. public function editGoodsBasic($params)
  1036. {
  1037. if (empty($params['id'])) {
  1038. return ResultWrapper::fail('没有指定要修改的商品数据id', ErrorCode::$paramError);
  1039. }
  1040. ;
  1041. $id = $params['id'];
  1042. unset($params['id']);
  1043. $unitData = $params['unitData'];
  1044. $delUnitIds = $params['delUnitIds'];
  1045. $delSpecSkuIds = $params['delSpecSkuIds'];
  1046. unset($params['delSpecSkuIds']);//属性删除
  1047. unset($params['delUnitIds']);
  1048. unset($params['unitData']);
  1049. unset($params['merchantId']);
  1050. $beginStatus = $this->objDGoodsBasic->beginTransaction();
  1051. $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
  1052. $dbResult = $objMSku->editSku($unitData, $id, $delUnitIds, $delSpecSkuIds);
  1053. if (!$dbResult->isSuccess()) {
  1054. $this->objDGoodsBasic->rollBack();
  1055. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1056. }
  1057. $dbResult = $this->objDGoodsBasic->update($params, ['id' => $id]);
  1058. if ($dbResult === false) {
  1059. $this->objDGoodsBasic->rollBack();
  1060. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1061. }
  1062. //缓存商品名称
  1063. $this->isUpdateBasicCache = true;
  1064. $this->objectId = $id;
  1065. $beginStatus && $this->objDGoodsBasic->commit();
  1066. //self::updateEsData($id);
  1067. $this->objMSku->delSkuCache($id);
  1068. // 每编辑一件商品需要清除一下小程序商品首页的缓存;
  1069. $objPageCache = new PageCache();
  1070. $objPageCache->delPage();
  1071. return ResultWrapper::success($dbResult);
  1072. }
  1073. /**
  1074. * specType => 2
  1075. * 编辑多规格基础商品资料
  1076. * @param $params
  1077. * @return ResultWrapper
  1078. * @throws \Exception
  1079. */
  1080. public function editMultipleGoodsBasic($params)
  1081. {
  1082. if (empty($params['id'])) {
  1083. return ResultWrapper::fail('没有指定要修改的商品数据id', ErrorCode::$paramError);
  1084. }
  1085. $id = $params['id'];//商品id
  1086. $delUnitIds = $params['delUnitIds'];//辅单位
  1087. $delSpecSkuIds = $params['delSpecSkuIds'];//属性
  1088. $specMultiple = $params['specMultiple'];
  1089. $unitData = $params['unitData'];
  1090. unset($params['unitData']);
  1091. unset($params['specMultiple']);
  1092. unset($params['delUnitIds']);
  1093. unset($params['delSpecSkuIds']);
  1094. unset($params['id']);
  1095. //编辑sku
  1096. $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
  1097. $dbResult = $objMSku->editMultipleSku($specMultiple, $id, $delUnitIds, $delSpecSkuIds, $unitData);
  1098. if (!$dbResult->isSuccess()) {
  1099. $this->objDGoodsBasic->rollBack();
  1100. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1101. }
  1102. //编辑基础资料
  1103. $dbResult = $this->objDGoodsBasic->update($params, ['id' => $id]);
  1104. if ($dbResult === false) {
  1105. $this->objDGoodsBasic->rollBack();
  1106. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1107. }
  1108. //缓存商品名称
  1109. $this->isUpdateBasicCache = true;
  1110. $this->objectId = $id;
  1111. $this->objDGoodsBasic->commit();
  1112. //self::updateEsData($id);
  1113. $this->objMSku->delSkuCache($id);
  1114. // 每编辑一件商品需要清除一下小程序商品首页的缓存;
  1115. $objPageCache = new PageCache();
  1116. $objPageCache->delPage();
  1117. return ResultWrapper::success($dbResult);
  1118. }
  1119. /**
  1120. * 更新基础商品的启用/禁用
  1121. * @param $params
  1122. * @return ResultWrapper
  1123. * @throws \Exception
  1124. */
  1125. public function updateEnableStatus($params)
  1126. {
  1127. if (!empty($params['deleteStatus'])){
  1128. $is_status['deleteStatus'] = $params['deleteStatus'];
  1129. }else{
  1130. $is_status['enableStatus'] = $params['enableStatus'];
  1131. }
  1132. $dbResult = $this->objDGoodsBasic->update($is_status, ['id' => $params['id']]);
  1133. if ($dbResult === false) {
  1134. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1135. }
  1136. /*if (is_array($params['id'])) {
  1137. foreach ($params['id'] as $id) {
  1138. self::updateEsData($id);
  1139. }
  1140. }*/
  1141. return ResultWrapper::success($dbResult);
  1142. }
  1143. /**
  1144. * 删除指定商品基础资料
  1145. * @param $id
  1146. * @return ResultWrapper
  1147. * @throws \Exception
  1148. */
  1149. public function delGoodsBasic($id)
  1150. {
  1151. $detail = $this->objDGoodsBasic->get($id, 'categoryPath,brandId');
  1152. if (empty($detail)) {
  1153. return ResultWrapper::fail('没有找到指定数据', ErrorCode::$dberror);
  1154. }
  1155. $dbResult = $this->objDGoodsBasic->update(['deleteStatus' => StatusCode::$delete], $id);
  1156. if ($dbResult === false) {
  1157. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1158. }
  1159. $categoryIds = explode(',', $detail['categoryPath']);
  1160. foreach ($categoryIds as $v) {
  1161. $this->objGoodsBasicCache->categoryKeyScoreDecr($v);
  1162. }
  1163. $this->objGoodsBasicCache->brandKeyScoreDecr($detail['brandId']);
  1164. /*
  1165. $_id = self::createEsDocumentId($id);
  1166. $this->objDGoodsBasic->esupdateTypeFieldVaule(['deleteStatus' => StatusCode::$delete], $_id); */
  1167. return ResultWrapper::success($dbResult);
  1168. }
  1169. /**
  1170. * Doc: (des="发布为平台商品")
  1171. * User: XMing
  1172. * Date: 2020/12/7
  1173. * Time: 12:02 下午
  1174. * @param int $id
  1175. * @return ResultWrapper
  1176. */
  1177. public function pushPlatform(int $id): ResultWrapper
  1178. {
  1179. $dbResult = $this->objDGoodsBasic->update(['level' => StatusCode::$standard,'updateTime' => time()], $id);
  1180. if ($dbResult === false) {
  1181. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1182. }
  1183. /*
  1184. $_id = self::createEsDocumentId($id);
  1185. $this->objDGoodsBasic->esupdateTypeFieldVaule(['level' => StatusCode::$standard,'updateTime' => time()], $_id);*/
  1186. return ResultWrapper::success(true);
  1187. }
  1188. /**
  1189. * 格式化Json数据
  1190. * @param $data
  1191. * @return mixed
  1192. * @throws \Exception
  1193. */
  1194. private function formatJson($data)
  1195. {
  1196. if (isset($data['id'])) {
  1197. $data['images'] = empty($data['images']) ? '' : json_decode($data['images'], true);
  1198. $data['code'] = createCode(StatusCode::$code['goodsBasic']['prefix'], $data['id'], StatusCode::$code['goodsBasic']['length']);
  1199. $data['description'] = empty($data['description']) ? '' : htmlspecialchars_decode($data['description'], ENT_QUOTES);
  1200. $data['specGroup'] = empty($data['specGroup']) ? [] : json_decode($data['specGroup'], true);
  1201. $extends = empty($data['extends']) ? [] : json_decode($data['extends'], true);
  1202. $data['storage'] = isset($extends['storage']) ? $extends['storage'] : '';
  1203. return $data;
  1204. }
  1205. foreach ($data as &$v) {
  1206. $v['code'] = createCode(StatusCode::$code['goodsBasic']['prefix'], $v['id'], StatusCode::$code['goodsBasic']['length']);
  1207. $v['images'] = empty($v['images']) ? '' : json_decode($v['images'], true);
  1208. $v['description'] = empty($v['description']) ? '' : htmlspecialchars_decode($v['description'], ENT_QUOTES);
  1209. $v['specGroup'] = empty($v['specGroup']) ? [] : json_decode($v['specGroup'], true);
  1210. $extends = empty($v['extends']) ? [] : json_decode($v['extends'], true);
  1211. $v['storage'] = isset($extends['storage']) ? $extends['storage'] : '';
  1212. }
  1213. return $data;
  1214. }
  1215. /**
  1216. * 获取品牌下的商品数量
  1217. * @param $where
  1218. * @param $enterpriseId
  1219. * @return ResultWrapper
  1220. * @throws \Exception
  1221. */
  1222. public function getGoodsBasicTotalByBrandId($where)
  1223. {
  1224. $tableName = self::getGoodsBasicSubTableName();
  1225. $sql = "SELECT brandId,count(id) num FROM " . $tableName . " where brandId IN (" . implode(',', $where['brandId']) . ') and deleteStatus=' . $where['deleteStatus'] . ' group by brandId';
  1226. $dbResult = $this->objDGoodsBasic->query($sql);
  1227. if ($dbResult === false) {
  1228. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1229. }
  1230. return ResultWrapper::success($dbResult);
  1231. }
  1232. /**
  1233. * 获取分类下的商品数量
  1234. * @param $where
  1235. * @param $enterpriseId
  1236. * @return ResultWrapper
  1237. * @throws \Exception
  1238. */
  1239. public function getGoodsBasicTotalByCategoryId($where)
  1240. {
  1241. $tableName = self::getGoodsBasicSubTableName();
  1242. $sql = "SELECT categoryId,count(id) num FROM " . $tableName . " where categoryId IN (" . implode(',', $where['categoryId']) . ') and deleteStatus=' . $where['deleteStatus'] . ' group by brandId';
  1243. $dbResult = $this->objDGoodsBasic->query($sql);
  1244. if ($dbResult === false) {
  1245. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1246. }
  1247. return ResultWrapper::success($dbResult);
  1248. }
  1249. /**
  1250. * Doc: (des="格式化物料列表")
  1251. * User: XMing
  1252. * Date: 2021/3/4
  1253. * Time: 11:39 上午
  1254. * @param array $data
  1255. * @return ResultWrapper
  1256. * @throws \Exception
  1257. */
  1258. public function formatMaterielLists(array $data): ResultWrapper
  1259. {
  1260. if (empty($data)){
  1261. return ResultWrapper::success($data);
  1262. }
  1263. $materielIds = [];
  1264. $categoryIds = [];
  1265. $brandIds = [];
  1266. $supplierIds = [];
  1267. $shopIds = [];
  1268. foreach ($data as $key => $value) {
  1269. if (!in_array($value['id'],$materielIds)){
  1270. $materielIds[] = $value['id'];
  1271. }
  1272. if (!in_array($value['categoryId'],$categoryIds) && !empty($value['categoryId'])){
  1273. $categoryIds[] = $value['categoryId'];
  1274. }
  1275. if (!in_array($value['assistCategoryId'],$categoryIds) && !empty($value['assistCategoryId'])){
  1276. $categoryIds[] = $value['assistCategoryId'];
  1277. }
  1278. if (!in_array($value['brandId'],$brandIds) && !empty($value['brandId'])){
  1279. $brandIds[] = $value['brandId'];
  1280. }
  1281. if (!empty($value['noSalesShop'])){
  1282. $noSalesShopArray = explode(',', $value['noSalesShop']);
  1283. $shopIds = array_merge($shopIds,$noSalesShopArray);
  1284. }
  1285. if (!empty($value['storeId']) && !in_array($value['storeId'],$shopIds)){
  1286. $shopIds[] = $value['storeId'];
  1287. }
  1288. if (!empty($value['supplierId']) && !in_array($value['supplierId'],$supplierIds)){
  1289. $supplierIds[] = $value['supplierId'];
  1290. }
  1291. }
  1292. $categoryMap = [];
  1293. $objMGoodsCategory = new MGoodsCategory($this->onlineUserId, $this->onlineEnterpriseId);
  1294. if (!empty($categoryIds)){
  1295. $categoryResult = $objMGoodsCategory->getCategoryTitleByIds($categoryIds);
  1296. if (!$categoryResult->isSuccess()){
  1297. return ResultWrapper::fail($categoryResult->getData(),$categoryResult->getErrorCode());
  1298. }
  1299. $categoryData = $categoryResult->getData();
  1300. $categoryMap = self::arrayToArrayMapping($categoryData);
  1301. if ($categoryMap === false){
  1302. return ResultWrapper::fail('ArrayToMap映射错误',ErrorCode::$paramError);
  1303. }
  1304. }
  1305. $brandMap = [];
  1306. if (!empty($brandIds)){
  1307. $objMGoodsBrand = new MGoodsBrand($this->onlineUserId, $this->onlineEnterpriseId);
  1308. $brandResult = $objMGoodsBrand->getBrandTitleByBrandId($brandIds);
  1309. if (!$brandResult->isSuccess()){
  1310. return ResultWrapper::fail($brandResult->getData(),$brandResult->getErrorCode());
  1311. }
  1312. $brandData = $brandResult->getData();
  1313. $brandMap = self::arrayToArrayMapping($brandData);
  1314. if ($brandMap === false){
  1315. return ResultWrapper::fail('ArrayToMap映射错误',ErrorCode::$paramError);
  1316. }
  1317. }
  1318. //商铺
  1319. $shopMap = [];
  1320. if (!empty($shopIds)){
  1321. $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
  1322. $shopResult = $objMShop->getShopByIds($shopIds);
  1323. if (!$shopResult->isSuccess()){
  1324. return ResultWrapper::fail($shopResult->getData(),$shopResult->getErrorCode());
  1325. }
  1326. $shopData = $shopResult->getData();
  1327. $shopMap = self::arrayToArrayMapping($shopData);
  1328. if ($shopMap === false){
  1329. return ResultWrapper::fail('ArrayToMap映射错误',ErrorCode::$paramError);
  1330. }
  1331. }
  1332. $supplierMap = [];
  1333. if (!empty($supplierIds)){
  1334. $objMSupplier = new MSupplier($this->onlineUserId,$this->onlineEnterpriseId);
  1335. $supplierResult = $objMSupplier->getSupplierNameByIds($supplierIds);
  1336. if (!$supplierResult->isSuccess()){
  1337. return ResultWrapper::fail($supplierResult->getData(),$supplierResult->getErrorCode());
  1338. }
  1339. $supplierData = $supplierResult->getData();
  1340. $supplierMap = self::arrayToArrayMapping($supplierData);
  1341. if ($supplierMap === false){
  1342. return ResultWrapper::fail('ArrayToMap映射错误',ErrorCode::$paramError);
  1343. }
  1344. }
  1345. $specTotalMapResult = self::getSpecTotal($data);
  1346. if (!$specTotalMapResult->isSuccess()){
  1347. return ResultWrapper::fail($specTotalMapResult->getData(),$specTotalMapResult->getErrorCode());
  1348. }
  1349. $specTotalMap = $specTotalMapResult->getData();
  1350. $masterUnitNameResult = $this->objMSku->getMasterUnitNameByMaterielIds($materielIds);
  1351. if (!$masterUnitNameResult->isSuccess()){
  1352. return ResultWrapper::fail($masterUnitNameResult->getData(),$masterUnitNameResult->getErrorCode());
  1353. }
  1354. $masterUnitNameMap = $masterUnitNameResult->getData();
  1355. foreach ($data as &$item){
  1356. $item['assistCategoryPath'] = json_decode($value['assistCategoryPath'], true);
  1357. $item['assistCategoryTitle'] = isset($categoryMap[$item['assistCategoryId']]) ? $categoryMap[$item['assistCategoryId']]['title'] : '';
  1358. $item['categoryTitle'] = isset($categoryMap[$item['categoryId']]) ? $categoryMap[$item['categoryId']]['title'] : '';
  1359. $item['brandTitle'] = isset($brandMap[$item['brandId']]['title']) ? $brandMap[$item['brandId']]['title'] : '';
  1360. $item['specTotal'] = isset($specTotalMap[$item['id']]) ? $specTotalMap[$item['id']] : 0;
  1361. $noSalesShopArray = explode(',', $item['noSalesShop']);
  1362. $noSalesShopNames = [];
  1363. foreach ($noSalesShopArray as $shopId) {
  1364. if ($shopId) {
  1365. $noSalesShopNames[] = isset($shopMap[$shopId]) ? $shopMap[$shopId]['name'] : '';
  1366. }
  1367. }
  1368. $item['noSalesShopNames'] = trim(implode(',', $noSalesShopNames),',');
  1369. $item['sourceMsg'] = '平台';
  1370. if (isset($item['storeId']) && !empty($item['storeId'])){
  1371. $item['sourceMsg'] = isset($shopMap[$item['storeId']]) ? $shopMap[$item['storeId']]['name'] : '';
  1372. }
  1373. if (isset($item['supplierId']) && !empty($item['supplierId'])){
  1374. $row = getArrayItem($supplierMap,$item['supplierId'],[]);
  1375. if (!empty($row)){
  1376. $item['sourceMsg'] = getArrayItem($row,'title','');
  1377. }
  1378. }
  1379. $item['code'] = createCode(StatusCode::$code['goodsBasic']['prefix'], $item['id'], StatusCode::$code['goodsBasic']['length']);//当前状态
  1380. $extends = empty($item['extends']) ? [] : json_decode($item['extends'],true);
  1381. $item['storage']= isset($extends['storage']) ? $extends['storage'] : '';
  1382. $item['unitNameMaster'] = getArrayItem($masterUnitNameMap,$item['id'],'');
  1383. }
  1384. unset($item);
  1385. return ResultWrapper::success($data);
  1386. }
  1387. /**
  1388. * 查询基础商品对应规格数量
  1389. * @param $data
  1390. * @return array
  1391. */
  1392. public function getSpecTotal(array $data): ResultWrapper
  1393. {
  1394. $goodsIds = array_values(array_unique(array_column($data, 'id')));
  1395. $goodsIds = trim(implode(',', $goodsIds), ',');
  1396. if (empty($goodsIds)){
  1397. return ResultWrapper::success([]);
  1398. }
  1399. $sql = 'SELECT COUNT(id) as total,goodsId FROM qianniao_sku_' . $this->onlineEnterpriseId . ' WHERE deleteStatus = ' . StatusCode::$standard . ' AND goodsId IN(' . $goodsIds . ') GROUP BY goodsId;';
  1400. $dbResult = $this->objMSku->getQuery($sql);
  1401. if (!$dbResult->isSuccess()) {
  1402. Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$dbResult->getData());
  1403. }
  1404. $allSpec = $dbResult->getData();
  1405. $mapping = [];
  1406. foreach ($allSpec as $spec) {
  1407. $mapping[$spec['goodsId']] = $spec['total'];
  1408. }
  1409. return ResultWrapper::success($mapping);
  1410. }
  1411. /**
  1412. * Doc: (des="")
  1413. * User: XMing
  1414. * Date: 2021/3/4
  1415. * Time: 12:03 下午
  1416. * @param array $array
  1417. * @param string $index
  1418. * @return array|false
  1419. */
  1420. public static function arrayToArrayMapping(array $array,string $index = 'id')
  1421. {
  1422. if (empty($array)){
  1423. return [];
  1424. }
  1425. $map = [];
  1426. foreach ($array as $key => $value){
  1427. if (!isset($value['id'])){
  1428. return false;
  1429. }
  1430. $map[$value[$index]] = $value;
  1431. }
  1432. return $map;
  1433. }
  1434. /**
  1435. * 格式化数据
  1436. * @param $data
  1437. * @param $enterpriseId
  1438. * @return mixed
  1439. * @throws \Exception
  1440. */
  1441. public function formatCategory($data)
  1442. {
  1443. if (empty($data)) {
  1444. return $data;
  1445. }
  1446. if (isset($data['categoryId'])) {
  1447. $dimension = $data;
  1448. unset($data);
  1449. $data[] = $dimension;
  1450. }
  1451. $allBrandIds = [];
  1452. $allCategoryIds = [];
  1453. //$noSalesShopIds = [];
  1454. $allGoodsBasicIds = [];
  1455. $shopIds = [];
  1456. $supplierIds = [];
  1457. $merchantIds = [];
  1458. foreach ($data as $key => $value) {
  1459. $allGoodsBasicIds[] = $value['id'];
  1460. $allCategoryIds[] = $value['categoryId'];
  1461. $allCategoryIds[] = $value['assistCategoryId'];
  1462. $allBrandIds[] = $value['brandId'];
  1463. !empty($value['merchantId']) && $merchantIds[] = $value['merchantId'];
  1464. if ($value['noSalesShop']) {
  1465. $shopIds = array_merge($shopIds, explode(',', $value['noSalesShop']));
  1466. }
  1467. !empty($value['storeId']) && $shopIds[] = $value['storeId'];
  1468. !empty($value['supplierId']) && $supplierIds[] = $value['supplierId'];
  1469. }
  1470. $allCategoryData = [];
  1471. $allBrandData = [];
  1472. //分类
  1473. $objMGoodsCategory = new MGoodsCategory($this->onlineUserId, $this->onlineEnterpriseId);
  1474. $categoryResult = $objMGoodsCategory->getCategoryTitleByIds(array_values(array_filter($allCategoryIds)));
  1475. if ($categoryResult->isSuccess()) {
  1476. $categoryData = $categoryResult->getData();
  1477. foreach ($categoryData as $key => $value) {
  1478. $allCategoryData[$value['id']] = $value;
  1479. }
  1480. }
  1481. //品牌
  1482. $objMGoodsBrand = new MGoodsBrand($this->onlineUserId, $this->onlineEnterpriseId);
  1483. $brandResult = $objMGoodsBrand->getBrandTitleByBrandId(array_values(array_filter($allBrandIds)));
  1484. if ($brandResult->isSuccess()) {
  1485. $brandData = $brandResult->getData();
  1486. //创建映射关系
  1487. foreach ($brandData as $key => $value) {
  1488. $allBrandData[$value['id']] = $value;
  1489. }
  1490. }
  1491. //商铺
  1492. $objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
  1493. $shops = $objMShop->getShopName(array_values(array_unique($shopIds)));
  1494. //供应商
  1495. $objMSupplier = new MSupplier($this->onlineUserId,$this->onlineEnterpriseId);
  1496. $supplierResult = $objMSupplier->getSupplierNameByIds($supplierIds);
  1497. $supplierMap = [];
  1498. if ($supplierResult->isSuccess()){
  1499. $supplierMap = MSupplier::supplierMap($supplierResult->getData());
  1500. }
  1501. //商户
  1502. if(!empty($merchantIds)){
  1503. $objMMerchant = new MMerchant($this->onlineEnterpriseId, $this->onlineUserId);
  1504. $modelResult = $objMMerchant->selectMerchantData(['id' => $merchantIds, 'deleteStatus' => StatusCode::$standard]);
  1505. if(!$modelResult->isSuccess()){
  1506. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  1507. }
  1508. $merchantResult = $modelResult->getData();
  1509. unset($modelResult);
  1510. $merchantData = [];
  1511. foreach($merchantResult as $value){
  1512. $merchantData[$value['id']] = $value;
  1513. }
  1514. }
  1515. foreach ($data as $key => &$value) {
  1516. $data[$key]['categoryTitle'] = isset($allCategoryData[$value['categoryId']]['title']) ? $allCategoryData[$value['categoryId']]['title'] : '';
  1517. $data[$key]['assistCategoryTitle'] = isset($allCategoryData[$value['assistCategoryId']]['title']) ? $allCategoryData[$value['assistCategoryId']]['title'] : '';
  1518. $data[$key]['assistCategoryPath'] = json_decode($value['assistCategoryPath'], true);
  1519. $data[$key]['brandTitle'] = isset($allBrandData[$value['brandId']]['title']) ? $allBrandData[$value['brandId']]['title'] : '';
  1520. $noSalesShop = explode(',', $value['noSalesShop']);
  1521. $noSalesShopNames = [];
  1522. foreach ($noSalesShop as $v) {
  1523. if ($v) {
  1524. $noSalesShopNames[] = isset($shops[$v]) ? $shops[$v]['name'] : '';
  1525. }
  1526. }
  1527. $data[$key]['noSalesShopNames'] = implode(',', $noSalesShopNames);
  1528. //$data[$key]['masterUnit'] = isset($skuData[$value['id']]['masterUnit']) ? $skuData[$value['id']]['masterUnit'] : '';
  1529. //$data[$key]['branchUnit'] = isset($skuData[$value['id']]['branchUnit']) ? $skuData[$value['id']]['branchUnit'] : '';
  1530. $data[$key]['sourceMsg'] = '平台';
  1531. if (isset($value['storeId']) && !empty($value['storeId'])){
  1532. $data[$key]['sourceMsg'] = getArrayItem($shops,$value['storeId'],'');
  1533. }
  1534. if (isset($value['supplierId']) && !empty($value['supplierId'])){
  1535. $row = getArrayItem($supplierMap,$value['supplierId'],[]);
  1536. if (!empty($row)){
  1537. $data[$key]['sourceMsg'] = getArrayItem($row,'title','');
  1538. }
  1539. }
  1540. $data[$key]['merchantName'] = '';
  1541. if(isset($value['merchantId']) && !empty($value['merchantId']) && isset($merchantData[$value['merchantId']])){
  1542. $data[$key]['sourceMsg'] = $merchantData[$value['merchantId']]['name'];
  1543. $data[$key]['merchantName'] = $merchantData[$value['merchantId']]['name'];
  1544. }
  1545. }
  1546. return $data;
  1547. }
  1548. /**
  1549. * 获取商品名称
  1550. * @param $goodsBasicIds
  1551. * @param string $fields
  1552. * @return array
  1553. */
  1554. public function getGoodsBasicNames($goodsBasicIds, $fields = "*"): ResultWrapper
  1555. {
  1556. if (!$goodsBasicIds) {
  1557. return ResultWrapper::success([]);
  1558. }
  1559. $dbResult = $this->objDGoodsBasic->select($goodsBasicIds, $fields);
  1560. if ($dbResult === false) {
  1561. return ResultWrapper::fail($this->objDGoodsBasic->error(),ErrorCode::$dberror);
  1562. }
  1563. foreach ($dbResult as $goodsBasic) {
  1564. $return[$goodsBasic['id']] = $goodsBasic;
  1565. }
  1566. return ResultWrapper::success($dbResult);
  1567. }
  1568. /**
  1569. * 统计分类下的商品数量
  1570. * @param $id
  1571. * @return ResultWrapper
  1572. */
  1573. public function getBasicTotalByIds($id)
  1574. {
  1575. $tableName = $this->objDGoodsBasic->get_Table();
  1576. $status = StatusCode::$standard;
  1577. $sql = "select categoryId,count(id) num from {$tableName} where deleteStatus={$status} AND FIND_IN_SET({$id},categoryPath)";
  1578. $dbResult = $this->objDGoodsBasic->query($sql);
  1579. if ($dbResult === false) {
  1580. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1581. }
  1582. $dbResult = empty($dbResult) ? '' : $dbResult[0];
  1583. return ResultWrapper::success($dbResult);
  1584. }
  1585. /**
  1586. * 搜索条件 ES
  1587. * @param $selectParams
  1588. * @param boolean $is_export
  1589. * @return array
  1590. */
  1591. public function setSearchWhere($selectParams = [],bool $is_export = false)
  1592. {
  1593. $defaultDSL = [];
  1594. if ($is_export === false) {
  1595. if (isset($selectParams['offset']) && $selectParams['offset']) {
  1596. $defaultDSL['from'] = $selectParams['offset'];
  1597. }
  1598. $defaultDSL['size'] = 2000;
  1599. if (isset($selectParams['limit']) && $selectParams['limit']) {
  1600. $defaultDSL['size'] = $selectParams['limit'];
  1601. }
  1602. }
  1603. $defaultDSL['sort'] = [
  1604. 'createTime' => [
  1605. 'order' => 'desc'
  1606. ],
  1607. ];
  1608. $dsl = [];
  1609. $dsl['query']['bool']['must'][] = [
  1610. 'bool' => [
  1611. 'must' => [
  1612. 'term' => ['enterpriseId' => $this->onlineEnterpriseId],
  1613. ],
  1614. ]
  1615. ];
  1616. //商品名称/编码/条码
  1617. if (isset($selectParams['keyword'])) {
  1618. if (!empty($selectParams['keyword'])) {
  1619. $dsl['query']['bool']['must'][] = [
  1620. 'bool'=>[
  1621. 'must' => [
  1622. 'multi_match' => [
  1623. 'fields' => ['title', 'code', 'barCode', 'goodsCode'],
  1624. 'query' => $selectParams['keyword'],
  1625. //'fuzziness' => 'AUTO',
  1626. "type" => "best_fields",
  1627. "tie_breaker" => 0.3,
  1628. "minimum_should_match" => "100%"
  1629. ]
  1630. ]
  1631. ],
  1632. ];
  1633. }
  1634. }
  1635. //销售状态 goods_basic表
  1636. if (isset($selectParams['enableStatus'])) {
  1637. if (!empty($selectParams['enableStatus'])) {
  1638. $dsl['query']['bool']['filter'][] =
  1639. ['term' => ['enableStatus' => $selectParams['enableStatus']]];
  1640. }
  1641. }
  1642. if (isset($selectParams['supplierId']) && !empty($selectParams['supplierId'])){
  1643. $dsl['query']['bool']['filter'][] =
  1644. ['term' => ['supplierId' => $selectParams['supplierId']]];
  1645. }
  1646. if (isset($selectParams['level']) && !empty($selectParams['level'])){
  1647. $dsl['query']['bool']['filter'][] =
  1648. ['term' => ['level' => $selectParams['level']]];
  1649. }
  1650. //删除状态
  1651. if (isset($selectParams['deleteStatus'])) {
  1652. $dsl['query']['bool']['filter'][] =
  1653. ['term' => ['deleteStatus' => $selectParams['deleteStatus']]];
  1654. }
  1655. //商品分类
  1656. if (isset($selectParams['categoryId'])) {
  1657. if (!empty($selectParams['categoryId'])) {
  1658. $dsl['query']['bool']['filter'][] =
  1659. ['term' => ['categoryId' => $selectParams['categoryId']]];
  1660. }
  1661. }
  1662. if (isset($selectParams['categoryPath'])) {
  1663. if (!empty($selectParams['categoryPath'])) {
  1664. $dsl['query']['bool']['must'][] = [
  1665. 'bool' => [
  1666. 'should' => [
  1667. [
  1668. 'wildcard' => ['categoryPath' => $selectParams['categoryPath'].',*'],
  1669. ],
  1670. [
  1671. 'wildcard' => ['categoryPath' => $selectParams['categoryPath']],
  1672. ],
  1673. ],
  1674. ]
  1675. ];
  1676. }
  1677. }
  1678. //商品品牌
  1679. if (isset($selectParams['brandId'])) {
  1680. if (!empty($selectParams['brandId'])) {
  1681. $dsl['query']['bool']['filter'][] =
  1682. ['term' => ['brandId' => $selectParams['brandId']]];
  1683. }
  1684. }
  1685. /*多选
  1686. * if (!empty($selectParams['brandIds'])) {
  1687. $dsl['query']['bool']['must'][] = [
  1688. 'terms' => [
  1689. 'brandId' => $selectParams['brandIds']
  1690. ]
  1691. ];
  1692. }*/
  1693. //销售员id
  1694. parent::getAccessSalesManIds();
  1695. if (!empty(parent::$salesManIds) && empty($selectParams['salesManId'])) {
  1696. $dsl['query']['bool']['filter'][] = [
  1697. 'terms' => ['salesManId' => parent::$salesManIds]
  1698. ];
  1699. }
  1700. //基本资料ids
  1701. if (isset($selectParams['ids'])) {
  1702. if (!empty($selectParams['ids'])) {
  1703. $dsl['query']['bool']['must'][] = [
  1704. 'terms' => [
  1705. 'id' => array_values($selectParams['ids'])
  1706. ]
  1707. ];
  1708. }
  1709. }
  1710. //导出
  1711. $dsl = array_merge($defaultDSL,$dsl);
  1712. return $dsl;
  1713. }
  1714. /**
  1715. * 搜索符合条件的GoodsBasic
  1716. * @param array $selectParams
  1717. * @return ResultWrapper
  1718. */
  1719. public function searchGoodsBasics($selectParams = [])
  1720. {
  1721. $dsl = $this->setSearchWhere($selectParams);
  1722. $result = $this->objDGoodsBasic->getSearchQueryDsl($dsl);
  1723. if (isset($result['status']) && $result['status'] == 400) {
  1724. file_put_contents('/www/wwwroot/logs/api.junhailan.com/elasticsearch.log', date('Y-m-d H:i:s') . '获取基本资料失败,错误原因' . var_export($result, true) . PHP_EOL, FILE_APPEND);
  1725. if ($result['error']['reason'] == 'all shards failed') {
  1726. return ResultWrapper::success([]);
  1727. }
  1728. return ResultWrapper::fail('基本资料id获取失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
  1729. }
  1730. if (!isset($result['hits']) || $result['hits']['total'] == 0) {
  1731. return ResultWrapper::success([]);
  1732. }
  1733. $total = $result['hits']['total'];
  1734. $dbResult = $result['hits']['hits'];
  1735. $goodsBasicIds = [];
  1736. foreach ($dbResult as $key => &$value) {
  1737. $goodsBasicIds[] = $value['_source'];
  1738. }
  1739. return ResultWrapper::success($goodsBasicIds);
  1740. }
  1741. public function buildSqlBySelectParams(array $selectParams): array
  1742. {
  1743. $countField = ' COUNT(id) as total ';
  1744. $fields = ' * ';
  1745. $tableName = $this->objDGoodsBasic->get_Table();
  1746. $where = '';
  1747. if (isset($selectParams['enableStatus']) && !empty($selectParams['enableStatus'])){
  1748. $where .= ' AND `enableStatus` = '.$selectParams['enableStatus'];
  1749. }
  1750. if (isset($selectParams['brandId']) && !empty($selectParams['brandId'])){
  1751. $where .= ' AND `brandId` = '.$selectParams['brandId'];
  1752. }
  1753. if (isset($selectParams['supplierId']) && !empty($selectParams['supplierId'])){
  1754. $where .= ' AND `supplierId` = '.$selectParams['supplierId'];
  1755. }
  1756. if (isset($selectParams['level']) && !empty($selectParams['level'])){
  1757. $where .= ' AND `level` = '.$selectParams['level'];
  1758. }
  1759. if (isset($selectParams['categoryId']) && !empty($selectParams['categoryId'])){
  1760. $where .= ' AND `categoryId` = '.$selectParams['categoryId'].' or find_in_set('.$selectParams['categoryId'].',assistCategoryId) ';
  1761. }
  1762. if (isset($selectParams['merchantId']) && !empty($selectParams['merchantId'])){
  1763. $where .= ' AND `merchantId` = '.$selectParams['merchantId'];
  1764. }
  1765. //商品关键字
  1766. if (isset($selectParams['keyword']) && !empty($selectParams['keyword'])){
  1767. $where .= ' and title like "%'.$selectParams['keyword'].'%"';
  1768. }
  1769. //分类路径
  1770. if (isset($selectParams['categoryPath']) && !empty($selectParams['categoryPath'])){
  1771. if (is_string($selectParams['categoryPath']) || is_int($selectParams['categoryPath'])){
  1772. $selectParams['categoryPath'] = explode(',',$selectParams['categoryPath']);
  1773. }
  1774. $endPathId = array_pop($selectParams['categoryPath']);
  1775. if (!empty($endPathId)){
  1776. $where .= ' and find_in_set('.$endPathId.',categoryPath) or find_in_set('.$endPathId.',assistCategoryId) ';
  1777. }
  1778. }
  1779. //排序
  1780. if (isset($selectParams['orderBy']) && !empty($selectParams['orderBy'])){
  1781. $where .= ' order by '.$selectParams['orderBy'];
  1782. }else{
  1783. $where .= ' order by createTime DESC ';
  1784. }
  1785. $countSql = 'SELECT '.$countField.' FROM '.$tableName.' WHERE `deleteStatus` ='.StatusCode::$standard.$where;
  1786. //分页
  1787. if (isset($selectParams['offset']) && isset($selectParams['limit']) && !empty($selectParams['limit'])){
  1788. $where .= ' limit '.$selectParams['offset'].','.$selectParams['limit'];
  1789. }
  1790. $sql = 'SELECT '.$fields.' FROM '.$tableName.' WHERE `deleteStatus` ='.StatusCode::$standard.$where;
  1791. return [
  1792. 'sql' => $sql,
  1793. 'countSql' => $countSql
  1794. ];
  1795. }
  1796. /**
  1797. * 搜索
  1798. * @param array $selectParams 过滤条件
  1799. * @param boolean $is_export
  1800. * @return ResultWrapper
  1801. * @throws \Exception
  1802. */
  1803. public function search($selectParams,bool $is_export = false)
  1804. {
  1805. $buildSql =self::buildSqlBySelectParams($selectParams);
  1806. $lists = $this->objDGoodsBasic->query($buildSql['sql']);
  1807. if ($lists === false){
  1808. return ResultWrapper::fail($this->objDGoodsBasic->error(),ErrorCode::$dberror);
  1809. }
  1810. $count = $this->objDGoodsBasic->query($buildSql['countSql']);
  1811. if ($count === false){
  1812. return ResultWrapper::fail($this->objDGoodsBasic->error(),ErrorCode::$dberror);
  1813. }
  1814. if (empty($lists)){
  1815. return ResultWrapper::success([
  1816. 'data' => [],
  1817. 'total' => 0
  1818. ]);
  1819. }
  1820. if ($is_export === true){
  1821. self::exportGoodsBasic($lists,'db');
  1822. die;
  1823. }
  1824. $format = self::formatJson($lists);
  1825. $format = self::formatCategory($format);
  1826. foreach ($format as &$formatData) {
  1827. $formatData['unitData'] = [];
  1828. $formatData['specGroup'] = [];
  1829. $formatData['specMultiple'] = [];
  1830. $formatData = self::formatSingleSkuMapping($formatData);
  1831. $formatData = self::formatMultipleSkuMapping($formatData);
  1832. }
  1833. $return = [
  1834. 'data' => $format,
  1835. 'total' => isset($count[0]['total']) ? $count[0]['total'] : 0,
  1836. ];
  1837. return ResultWrapper::success($return);
  1838. /*$dsl = $this->setSearchWhere($selectParams);
  1839. $result = $this->objDGoodsBasic->getSearchQueryDsl($dsl);
  1840. if (isset($result['status']) && $result['status'] == 400) {
  1841. return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
  1842. }
  1843. if (!isset($result['hits']) || $result['hits']['total'] == 0) {
  1844. return ResultWrapper::success([
  1845. 'data' => [],
  1846. 'total' => 0
  1847. ]);
  1848. }
  1849. $total = $result['hits']['total'];
  1850. $dbResult = $result['hits']['hits'];
  1851. $list = [];
  1852. foreach ($dbResult as $key => &$value) {
  1853. $data = [];
  1854. $data = $value['_source'];
  1855. //$data['id'] = $value['_id'];
  1856. $list[] = $data;
  1857. }
  1858. if ($is_export === true) self::exportGoodsBasic($list,'es');
  1859. foreach ($list as &$v) {
  1860. $v['masterUnit'] = isset($v['skuData']['masterUnit']) ? $v['skuData']['masterUnit'] : [];
  1861. $v['branchUnit'] = isset($v['skuData']['branchUnit']) ? $v['skuData']['branchUnit'] : [];
  1862. $v['code'] = createCode(StatusCode::$code['goodsBasic']['prefix'], $v['id'], StatusCode::$code['goodsBasic']['length']);
  1863. $v['description'] = empty($v['description']) ? '' : htmlspecialchars_decode($v['description'], ENT_QUOTES);
  1864. }
  1865. $return = [
  1866. 'data' => self::formatCategory($list),
  1867. 'total' => ($total) ? intval($total) : 0,
  1868. ];
  1869. return ResultWrapper::success($return);*/
  1870. }
  1871. /**
  1872. * 根据商品ids数组获取商品信息
  1873. * @param $whereIds
  1874. * @return array|ResultWrapper
  1875. */
  1876. public function getGoodsDataByGoodsIds($whereIds)
  1877. {
  1878. $GoodsBasic = $this->objDGoodsBasic->select($whereIds, 'title,id,images,expireTime,specType');
  1879. if ($GoodsBasic === false) {
  1880. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1881. }
  1882. if (empty($GoodsBasic)) {
  1883. return ResultWrapper::fail('商品基础资料为空', ErrorCode::$paramError);
  1884. }
  1885. $returnData = array_column($GoodsBasic, null, 'id');
  1886. return ResultWrapper::success($returnData);
  1887. }
  1888. /**
  1889. * 根据ids数组获取分类信息
  1890. * @param $ids
  1891. * @return ResultWrapper
  1892. * @throws \Exception
  1893. */
  1894. public function getCategoryByIds($ids)
  1895. {
  1896. if (empty($ids)) return ResultWrapper::success($ids);
  1897. $objDGoodsCategory = new DGoodsCategory('default');
  1898. $objDGoodsCategory->setTable($objDGoodsCategory->get_Table() . '_' . $this->onlineEnterpriseId);
  1899. $sql = "select b.id,c.id categoryId,c.title from " . $this->objDGoodsBasic->get_Table() . " b LEFT JOIN " . $objDGoodsCategory->get_Table() . " c on b.categoryId = c.id where b.id in(" . implode(',', $ids) . ")";
  1900. $dbResult = $this->objDGoodsBasic->query($sql);
  1901. if ($dbResult === false) {
  1902. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1903. }
  1904. $categoryNames = [];
  1905. foreach ($dbResult as $value) {
  1906. $categoryNames[$value['id']] = $value;
  1907. }
  1908. return ResultWrapper::success($categoryNames);
  1909. }
  1910. /**
  1911. * 根据ids数组获取品牌
  1912. * @param $ids
  1913. * @return ResultWrapper
  1914. * @throws \Exception
  1915. */
  1916. public function getBrandByIds($ids)
  1917. {
  1918. if (empty($ids)) return ResultWrapper::success($ids);
  1919. $objDGoodsBrand = new DGoodsBrand('default');
  1920. $objDGoodsBrand->setTable($objDGoodsBrand->get_Table() . '_' . $this->onlineEnterpriseId);
  1921. $sql = "select b.id,c.id brandId,c.title from " . $this->objDGoodsBasic->get_Table() . " b LEFT JOIN " . $objDGoodsBrand->get_Table() . " c on b.brandId = c.id where b.id in(" . implode(',', $ids) . ")";
  1922. $dbResult = $this->objDGoodsBasic->query($sql);
  1923. if ($dbResult === false) {
  1924. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1925. }
  1926. $brandNames = [];
  1927. foreach ($dbResult as $value) {
  1928. $brandNames[$value['id']] = $value;
  1929. }
  1930. return ResultWrapper::success($brandNames);
  1931. }
  1932. /**
  1933. * 更新基础商品分类
  1934. * @param $params
  1935. * @return ResultWrapper
  1936. */
  1937. public function updateCategory($params)
  1938. {
  1939. $dbResult = $this->objDGoodsBasic->select($params['id'], 'categoryPath');
  1940. if ($dbResult === false) {
  1941. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1942. }
  1943. //todo(减原来分类下的商品数量)
  1944. foreach ($dbResult as $value) {
  1945. $allCategoryIds = explode(',', $value['categoryPath']);
  1946. foreach ($allCategoryIds as $categoryId) {
  1947. $this->objGoodsBasicCache->categoryKeyScoreDecr($categoryId);
  1948. }
  1949. }
  1950. unset($allCategoryIds);
  1951. //更新商品分类
  1952. $dbResult = $this->objDGoodsBasic->update(['categoryId' => $params['categoryId'], 'categoryPath' => $params['categoryPath']], $params['id']);
  1953. if ($dbResult == false) {
  1954. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1955. }
  1956. //todo(增加现在分类下的商品数量)
  1957. $allCategoryIds = explode(',', $params['categoryPath']);
  1958. foreach ($allCategoryIds as $categoryId) {
  1959. $this->objGoodsBasicCache->categoryKeyScoreIncr($categoryId);
  1960. }
  1961. //修改ES中的数据
  1962. /*
  1963. foreach ($params['id'] as $id) {
  1964. $_id = self::createEsDocumentId($id);
  1965. $this->objDGoodsBasic->esupdateTypeFieldVaule(['categoryId' => $params['categoryId'], 'categoryPath' => $params['categoryPath']], $_id);
  1966. }
  1967. usleep(500000);//500ms */
  1968. return ResultWrapper::success($dbResult);
  1969. }
  1970. /**
  1971. * 批量设置不可销售店铺
  1972. * @param $params
  1973. * @return ResultWrapper
  1974. */
  1975. public function setNoSalesShop($params)
  1976. {
  1977. $dbResult = $this->objDGoodsBasic->update(['noSalesShop' => $params['noSalesShop']], $params['id']);
  1978. if ($dbResult === false) {
  1979. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1980. }
  1981. //修改ES中的数据
  1982. foreach ($params['id'] as $id) {
  1983. $_id = self::createEsDocumentId($id);
  1984. $this->objDGoodsBasic->esupdateTypeFieldVaule(['noSalesShop' => $params['noSalesShop']], $_id);
  1985. }
  1986. return ResultWrapper::success($dbResult);
  1987. }
  1988. /**
  1989. * 批量设置品牌
  1990. * @param $params
  1991. * @return ResultWrapper
  1992. */
  1993. public function setBrand($params)
  1994. {
  1995. $dbResult = $this->objDGoodsBasic->update(['brandId' => $params['brandId']], $params['id']);
  1996. if ($dbResult === false) {
  1997. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  1998. }
  1999. //修改ES中的数据
  2000. foreach ($params['id'] as $id) {
  2001. $_id = self::createEsDocumentId($id);
  2002. $this->objDGoodsBasic->esupdateTypeFieldVaule(['brandId' => $params['brandId']], $_id);
  2003. }
  2004. return ResultWrapper::success($dbResult);
  2005. }
  2006. public function todayGoodsRanking($ranking = 1, $shopId = null)
  2007. {
  2008. if ($ranking == 1) {
  2009. $result = $this->objOverviewCache->getRanking($this->onlineEnterpriseId, 'goodsRanking', $shopId);
  2010. } else {
  2011. $result = $this->objOverviewCache->getSalesMoneyRanking($this->onlineEnterpriseId, 'goodsRanking', $shopId);
  2012. }
  2013. if (empty($result)) {
  2014. return [];
  2015. }
  2016. $total = array_sum($result);
  2017. //拼接goodsBasicId
  2018. $goodsBasicIds = [];
  2019. $i = 1;
  2020. foreach ($result as $goodsBasicId => $v) {
  2021. $goodsBasicIds[] = $goodsBasicId;
  2022. $i++;
  2023. if ($i >= 8) {
  2024. break;
  2025. }
  2026. }
  2027. $goodsBasicResult = self::getGoodsBasicNames($goodsBasicIds);
  2028. if (!$goodsBasicResult->isSuccess()){
  2029. return [];
  2030. }
  2031. $goodsBasicResult = $goodsBasicResult->getData();
  2032. $goodsBasicNameData = [];
  2033. foreach ($goodsBasicResult as $goodsBasicData) {
  2034. $goodsBasicNameData[$goodsBasicData['id']] = $goodsBasicData['title'];
  2035. }
  2036. //拼接返回数据
  2037. $return = [];
  2038. foreach ($result as $goodsBasicId => $v) {
  2039. $i = 1;
  2040. $rank = [];
  2041. $rank['id'] = $i;
  2042. $rank['goodsName'] = isset($goodsBasicNameData[$goodsBasicId]) ? $goodsBasicNameData[$goodsBasicId] : '';
  2043. $rank['numberOrMoney'] = $v;
  2044. $rank['percent'] = $v ? (float)bcmul(bcdiv($v, $total), 100, 2) : 0;
  2045. $return[] = $rank;
  2046. $i++;
  2047. if ($i >= 8) {
  2048. break;
  2049. }
  2050. }
  2051. return $return;
  2052. }
  2053. public function getBasicInfoByIds($params, $field = "*")
  2054. {
  2055. $dbResult = $this->objDGoodsBasic->select($params, $field);
  2056. if ($dbResult === false) {
  2057. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  2058. }
  2059. return ResultWrapper::success($dbResult);
  2060. }
  2061. /**
  2062. * 查
  2063. * @param $id
  2064. * @return array|bool
  2065. */
  2066. public function getBasicById($id)
  2067. {
  2068. $dbResult = $this->objDGoodsBasic->get(['id' => $id]);
  2069. if($dbResult === false){
  2070. return [];
  2071. }
  2072. if(isset($dbResult['images']) && !empty($dbResult['images'])){
  2073. $dbResult['images'] = json_decode($dbResult['images'], true);
  2074. }else{
  2075. $dbResult['images'] = [];
  2076. }
  2077. return $dbResult;
  2078. }
  2079. /**
  2080. * 基础商品资料按照sku列表显示
  2081. * @param array $selectParams
  2082. * @return ResultWrapper
  2083. */
  2084. public function getAllGoodsBasicBySku(array $selectParams)
  2085. {
  2086. $fields ='b.isEq,s.id as skuId,s.unitName,s.unitId,s.specType,s.conversion,s.specData as specGroup,s.isMaster as isMaster,b.title,b.images as images,b.id,c.title as categoryName,c.id as categoryId';
  2087. $sql = 'SELECT '.$fields.' FROM qianniao_sku_'.$this->onlineEnterpriseId.' as s
  2088. LEFT JOIN qianniao_goods_basic_'.$this->onlineEnterpriseId.' as b
  2089. ON b.id = s.goodsId
  2090. LEFT JOIN qianniao_goods_category_'.$this->onlineEnterpriseId.' as c
  2091. ON c.id = b.categoryId
  2092. WHERE s.deleteStatus = '.StatusCode::$standard.'
  2093. AND b.deleteStatus= '.StatusCode::$standard.'';
  2094. //是否显示全部单位主/辅
  2095. if (isset($selectParams['isRevealSku']) && $selectParams['isRevealSku'] == StatusCode::$standard){
  2096. $sql .= ' AND s.isMaster = '.$selectParams['isRevealSku'];
  2097. }
  2098. if (isset($selectParams['materielId']) && !empty($selectParams['materielId'])){
  2099. $sql .= ' AND s.goodsId = '.$selectParams['materielId'];
  2100. }
  2101. //筛选分类
  2102. if (isset($selectParams['categoryId']) && !empty($selectParams['categoryId'])){
  2103. $sql .= ' and find_in_set('.$selectParams['categoryId'].',b.categoryPath) ';
  2104. }
  2105. if (isset($selectParams['keyword']) && !empty($selectParams['keyword'])){
  2106. $keyword = '%'.$selectParams['keyword'].'%';
  2107. $sql .= ' AND (b.title LIKE "'.$keyword.'" OR b.condition LIKE "'.$keyword.'")';
  2108. }
  2109. if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])){
  2110. // $sql .= ' AND b.storeId = '.$selectParams['shopId'];
  2111. $sql .= ' AND b.storeId in ('.$selectParams['shopId'].',0)';
  2112. }
  2113. if( isset($selectParams['merchantId']) ){
  2114. $sql .= ' AND b.merchantId = '.$selectParams['merchantId'];
  2115. } else {
  2116. if (isset($selectParams['ifMerchant']) ){
  2117. if($selectParams['ifMerchant'] == StatusCode::$delete){
  2118. $sql .= ' AND b.merchantId = 0';
  2119. } else {
  2120. $sql .= ' AND b.merchantId <> 0';
  2121. }
  2122. }
  2123. }
  2124. $total = count((array)$this->objDGoodsBasic->query($sql));
  2125. $sql .= ' ORDER BY b.createTime DESC LIMIT '.$selectParams['offset'].','.$selectParams['limit'].'';
  2126. $dbResult = $this->objDGoodsBasic->query($sql);
  2127. if ($dbResult === false){
  2128. return ResultWrapper::fail($this->objDGoodsBasic->error(),ErrorCode::$dberror);
  2129. }
  2130. $return = [
  2131. 'data' => self::format($dbResult),
  2132. 'total' => $total,
  2133. ];
  2134. return ResultWrapper::success($return);
  2135. }
  2136. /**
  2137. * @param $data
  2138. * @return mixed
  2139. */
  2140. public static function format($data)
  2141. {
  2142. if (empty($data)){
  2143. return $data;
  2144. }
  2145. foreach ($data as &$value){
  2146. $value['specGroup'] = empty($value['specGroup']) ? [] : json_decode($value['specGroup'],true);
  2147. $value['images'] = empty($value['images']) ? [] : json_decode($value['images'],true);
  2148. $value['conversion'] = empty($value['conversion']) ? 0 : $value['conversion'];
  2149. $value['code'] = createCode(StatusCode::$code['goodsBasic']['prefix'], $value['id'], StatusCode::$code['goodsBasic']['length']);
  2150. }
  2151. return $data;
  2152. }
  2153. /**
  2154. * @After
  2155. */
  2156. public function __destruct()
  2157. {
  2158. // TODO: Implement __destruct() method.
  2159. self::cacheBasic();
  2160. }
  2161. /**
  2162. * Doc: (des="根据基础商品资料id获取商品数据,及分类名称,品牌名称")
  2163. * User: XMing
  2164. * Date: 2020/7/9
  2165. * Time: 7:01 下午
  2166. * @param array $ids
  2167. * @return ResultWrapper
  2168. */
  2169. public function getBasicGoodsFieldByIds(array $ids)
  2170. {
  2171. $mapping = [];
  2172. $notFoundCacheIds = [];
  2173. foreach ($ids as $id){
  2174. $result = $this->objGoodsBasicRelevant->getNameByBasicId($id,true);
  2175. if ($result===false || empty($result)){
  2176. //缓存中没有
  2177. $notFoundCacheIds[] = $id;
  2178. continue;
  2179. }
  2180. $mapping[$id] = $result;
  2181. }
  2182. if (!empty($notFoundCacheIds)){
  2183. //查询数据库
  2184. $fields = "c.title as categoryName,b.*,d.title as brandName";
  2185. $idStr = implode(',',$notFoundCacheIds);
  2186. $sql = 'select '.$fields.' from qianniao_goods_basic_'.$this->onlineEnterpriseId.' as b
  2187. left join qianniao_goods_category_'.$this->onlineEnterpriseId.' as c
  2188. on b.categoryId = c.id
  2189. left join qianniao_goods_brand_'.$this->onlineEnterpriseId.' as d
  2190. on d.id = b.brandId
  2191. where b.id in('.$idStr.')';
  2192. $basicResult = $this->objDGoodsBasic->query($sql);
  2193. if ($basicResult === false){
  2194. Logger::logs(E_USER_ERROR,'查询出错',__CLASS__,__LINE__,$this->objDGoodsBasic->error());
  2195. return ResultWrapper::fail($this->objDGoodsBasic->error(),ErrorCode::$dberror);
  2196. }
  2197. foreach ($basicResult as $item){
  2198. $this->objGoodsBasicRelevant->cacheBasicIdRelationName($item,$item['id']);
  2199. $item['images'] = json_decode($item['images'], true);
  2200. $mapping[$item['id']] = $item;
  2201. }
  2202. }
  2203. return ResultWrapper::success($mapping);
  2204. }
  2205. /**
  2206. * Doc: (des="根据供应商获取商品数量")
  2207. * User: XMing
  2208. * Date: 2020/12/26
  2209. * Time: 4:54 下午
  2210. * @param $supplierId
  2211. * @return ResultWrapper
  2212. */
  2213. public function getTotalBySupplierId($supplierId): ResultWrapper
  2214. {
  2215. $selectParams = [
  2216. 'supplierId' => $supplierId,
  2217. 'deleteStatus' => StatusCode::$standard,
  2218. ];
  2219. $total = $this->objDGoodsBasic->count($selectParams);
  2220. if ($total === false){
  2221. return ResultWrapper::fail($this->objDGoodsBasic->error(),ErrorCode::$dberror);
  2222. }
  2223. return ResultWrapper::success($total);
  2224. }
  2225. /**
  2226. * Doc: (des="")
  2227. * User: XMing
  2228. * Date: 2020/12/19
  2229. * Time: 9:41 上午
  2230. * @param $ids
  2231. * @return ResultWrapper
  2232. */
  2233. public function getMapsByIds($ids): ResultWrapper
  2234. {
  2235. if (empty($ids)){
  2236. return ResultWrapper::success([]);
  2237. }
  2238. $lists = $this->objDGoodsBasic->select(['id' => $ids],'id,images,title');
  2239. if ($lists === false){
  2240. return ResultWrapper::fail($this->objDGoodsBasic->error(),ErrorCode::$dberror);
  2241. }
  2242. $map = [];
  2243. foreach ($lists as $list){
  2244. $list['code'] = createCode(StatusCode::$code['goodsBasic']['prefix'], $list['id'], StatusCode::$code['goodsBasic']['length']);
  2245. $list['images'] = !empty($list['images']) ? json_decode($list['images'],true) : [];
  2246. $map[$list['id']] = $list;
  2247. }
  2248. return ResultWrapper::success($map);
  2249. }
  2250. /**
  2251. * 根据商品名称关键字查询商品ids
  2252. */
  2253. public function getBasicGoodsIdsByGoodsTitleKeyword($keyword)
  2254. {
  2255. $sql = 'select id from qianniao_goods_basic_'.$this->onlineEnterpriseId.' where title like "%'.$keyword.'%" and deleteStatus = '.StatusCode::$standard;
  2256. $dbResult = $this->objDGoodsBasic->query($sql);
  2257. if($dbResult === false){
  2258. return ResultWrapper::fail($this->objDGoodsBasic->error(), ErrorCode::$dberror);
  2259. }
  2260. return ResultWrapper::success(array_pop($dbResult));
  2261. }
  2262. }