MPrice.Class.php 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: phperstar
  5. * Date: 2019/5/9
  6. * Time: 3:10 PM
  7. */
  8. namespace JinDouYun\Model\Price;
  9. use JinDouYun\Cache\PriceCache;
  10. use JinDouYun\Controller\Common\Logger;
  11. use JinDouYun\Dao\Customer\DCustomer;
  12. use JinDouYun\Dao\Goods\DGoods;
  13. use JinDouYun\Dao\GoodsManage\DSku;
  14. use JinDouYun\Dao\Price\DCustomerPriceEffective;
  15. use JinDouYun\Dao\Price\DCustomerTypePriceEffective;
  16. use JinDouYun\Dao\Price\DPriceRangeSheet;
  17. use JinDouYun\Model\Customer\MCustomer;
  18. use JinDouYun\Model\Market\MActivity;
  19. use Mall\Framework\Core\ResultWrapper;
  20. use Mall\Framework\Core\ErrorCode;
  21. use Mall\Framework\Core\StatusCode;
  22. use JinDouYun\Model\GoodsManage\MGoodsBasic;
  23. use JinDouYun\Model\MBaseModel;
  24. use JinDouYun\Model\Goods\MGoods;
  25. use JinDouYun\Dao\Price\DPriceAdjustment;
  26. use JinDouYun\Dao\Price\DNationalUnifiedPrice;
  27. use JinDouYun\Dao\Price\DLastEffectiveSalePriceAreaType;
  28. use JinDouYun\Dao\Price\DAreaPrice;
  29. class MPrice extends MBaseModel
  30. {
  31. /**
  32. * @var int
  33. */
  34. private $onlineUserId;
  35. /**
  36. * @var int
  37. */
  38. private $onlineEnterpriseId;
  39. /**
  40. * @var DPriceAdjustment
  41. */
  42. private $objDPriceAdjustment;
  43. /**
  44. * @var DPriceRangeSheet
  45. */
  46. private $objDPriceRangeSheet;
  47. /**
  48. * @var $readCache boolean 是否读取缓存
  49. */
  50. private static $readCache = false;
  51. /**
  52. * MPrice constructor.
  53. * @param $onlineUserId
  54. * @param $onlineEnterpriseId
  55. * @throws \Exception
  56. */
  57. public function __construct($onlineUserId, $onlineEnterpriseId)
  58. {
  59. $this->onlineUserId = $onlineUserId;
  60. $this->onlineEnterpriseId = $onlineEnterpriseId;
  61. parent::__construct($this->onlineEnterpriseId, $this->onlineUserId);
  62. $this->objDPriceAdjustment = new DPriceAdjustment();
  63. $this->objDPriceRangeSheet = new DPriceRangeSheet();
  64. $this->objDPriceAdjustment->setSearchIndex('goods_search')->setType('goods');
  65. }
  66. /**
  67. * 批量调价
  68. * 批量调价基于基本的运算公式进行调价,举例一个商品的销售价格是100元。通过批量调价,订货价=销售价-1,那么结果就是 98(订货价)=99(销售价 salePrice)-1(调价数字)
  69. * @param $params
  70. * @return ResultWrapper
  71. * @throws \Exception
  72. */
  73. public function batchPrice($params)
  74. {
  75. $objDNationalUnifiedPrice = new DNationalUnifiedPrice();
  76. $objDNationalUnifiedPrice->setTable($objDNationalUnifiedPrice->get_Table() . '_' . $this->onlineEnterpriseId);
  77. //批量获取这些商品的原提交单
  78. $rows = $params['rows'];
  79. $oldResult = $objDNationalUnifiedPrice->select(['goodsId' => array_column($rows, 'goodsId'), 'shopId' => array_column($rows, 'shopId')]);
  80. if ($oldResult === false) {
  81. return ResultWrapper::fail($objDNationalUnifiedPrice->error(), ErrorCode::$dberror);
  82. }
  83. if (empty($oldResult)) {
  84. return ResultWrapper::fail('未获取到调价数据', ErrorCode::$dberror);
  85. }
  86. //在原数据上进行修改
  87. foreach ($oldResult as $key => $value) {
  88. $salePrice = json_decode($value['salePrice'], true);
  89. foreach ($salePrice as $k => &$v) {
  90. $v['salePrice'] = self::calc($v['salePrice'], $params['sales']['float'], $params['sales']['adj']);
  91. if ($v['enabledLadder']) {
  92. foreach ($v['ladderPrice'] as &$ladder) {
  93. //对阶梯价进行操作
  94. $ladder['price'] = self::calc($ladder['price'], $params['ladder']['float'], $params['ladder']['adj']);
  95. }
  96. }
  97. }
  98. $oldResult[$key]['salePrice'] = json_encode($salePrice);
  99. }
  100. $log = [
  101. 'origin' => $oldResult,
  102. 'action' => $params,
  103. ];
  104. //保存修改
  105. $dbResult = $objDNationalUnifiedPrice->replace($oldResult, true);
  106. if ($dbResult === false) {
  107. return ResultWrapper::fail($objDNationalUnifiedPrice->error(), ErrorCode::$dberror);
  108. }
  109. self::saveLog([
  110. 'userCenterId' => $this->onlineUserId,
  111. 'enterpriseId' => $this->onlineEnterpriseId,
  112. 'createTime' => time(),
  113. 'no' => '',
  114. 'actionType' => '批量调价',
  115. 'operationData' => $log,
  116. ]);
  117. return ResultWrapper::success($dbResult);
  118. }
  119. /**
  120. * 批量调价日志
  121. * Overrides
  122. * @param $data
  123. */
  124. public static function saveLog($data)
  125. {
  126. $i = 1;
  127. do {
  128. $postData = [
  129. 'topicName' => 'MyJob',
  130. 'topicClass' => 'Jobs\Model\MTopic\Log\MPriceLog',
  131. 'topicMethon' => 'push',
  132. 'topicMethonParams' => [
  133. 'userCenterId' => $data['userCenterId'],
  134. 'enterpriseId' => $data['enterpriseId'],
  135. 'createTime' => $data['createTime'],//操作时间
  136. 'no' => $data['no'], // 如:单据编号D563875634856 订单编号N42332435435
  137. 'actionType' => $data['actionType'], //批量调价
  138. 'operationData' => $data['operationData'], //本次操作请求的数据(可空) json格式
  139. ],
  140. ];
  141. $url = QIANNIAO_QUEUE . '/CAddJob/add';
  142. $result = request($url, $postData);
  143. $i++;
  144. } while ($result['httpcode'] != 200 && $i <= 3);
  145. }
  146. /**
  147. * @param $origin
  148. * @param $float
  149. * @param $adj
  150. * @param int $scale
  151. * @return string
  152. */
  153. private static function calc($origin, $float, $adj, $scale = 4)
  154. {
  155. $res = 0;
  156. switch ($adj) {
  157. case '+'://加法
  158. $res = bcadd($origin, $float, $scale);
  159. break;
  160. case '-'://减法
  161. $res = bcsub($origin, $float, $scale);
  162. break;
  163. case '*'://乘法
  164. $res = bcmul($origin, $float, $scale);
  165. break;
  166. case '/'://除法
  167. $res = bcdiv($origin, $float, $scale);
  168. break;
  169. default:
  170. $res = 0;
  171. break;
  172. }
  173. return $res;
  174. }
  175. /**
  176. * 根据用户定位批量获取指定物料价格
  177. * @param $params
  178. * @param bool $returnAll
  179. * @return ResultWrapper
  180. * @throws \Exception
  181. */
  182. public function getPrice($params, $returnAll = false)
  183. {
  184. // 初始化所有物料价格
  185. $returnData = [];
  186. $allShopIds = []; // 所有店铺ids
  187. $allGoodsId = []; // 所有商品ids
  188. foreach ($params['material'] as $key => $value) {
  189. $returnData[$key] = (object)[];
  190. $allGoodsId = array_merge($value, $allGoodsId);
  191. $allShopIds[] = $key;
  192. }
  193. // 批量获取这批物料最后生效的价格销售区域类型
  194. $objDLastEffectiveSalePriceAreaType = new DLastEffectiveSalePriceAreaType();
  195. $objDLastEffectiveSalePriceAreaType->setTable('qianniao_lastEffectiveSalePriceAreaType_' . $this->onlineEnterpriseId);
  196. $condition = [
  197. 'goodsId' => array_values(array_unique($allGoodsId)),
  198. 'shopId' => array_values(array_unique($allShopIds)),
  199. ];
  200. $dbResult = $objDLastEffectiveSalePriceAreaType->select($condition, 'lastEffectiveSalePriceAreaType,goodsId,shopId');
  201. if ($dbResult === false) {
  202. return ResultWrapper::fail($objDLastEffectiveSalePriceAreaType->error(), ErrorCode::$dberror);
  203. }
  204. if (empty($dbResult)) {
  205. return ResultWrapper::success([]);
  206. }
  207. // 进行生效价格区域类型分组
  208. $materieLastEffectiveSalePriceAreaType = [];
  209. foreach ($dbResult as $k => $v) {
  210. $materieLastEffectiveSalePriceAreaType[$v['lastEffectiveSalePriceAreaType']][$v['shopId']][] = $v['goodsId'];
  211. }
  212. // 按组获取组内各物料的价格
  213. $newmaterielPriceData = [];
  214. foreach ($materieLastEffectiveSalePriceAreaType as $k => $v) {
  215. switch ($k) {
  216. case StatusCode::$salePriceAreaType['nationalUnifiedPrice']:
  217. $materielPriceData = self::getNationalUnifiedPrice($materieLastEffectiveSalePriceAreaType[StatusCode::$salePriceAreaType['nationalUnifiedPrice']]);
  218. break;
  219. case StatusCode::$salePriceAreaType['areaPrice']:
  220. $materielPriceData = self::getAreaPrice($materieLastEffectiveSalePriceAreaType[StatusCode::$salePriceAreaType['areaPrice']], $params, false);
  221. break;
  222. }
  223. if (!$materielPriceData->isSuccess()) {
  224. return ResultWrapper::fail($materielPriceData->getData(), $materielPriceData->getErrorCode());
  225. }
  226. $materielPriceData = $materielPriceData->getData();
  227. foreach ($materielPriceData as $key => $value) {
  228. foreach ($value as $a => $b) {
  229. $newmaterielPriceData[$key][$a] = !empty($b) ? $b : (object)[];
  230. }
  231. }
  232. }
  233. // 查询客户调价单当前客户是否有特殊调价
  234. if (!isset($params['customerId'])) {
  235. return ResultWrapper::success($newmaterielPriceData);
  236. }
  237. //查询当前客户的客户类型是否有特殊调价
  238. $objDCustomer = new DCustomer();
  239. $objDCustomer->setTable('qianniao_customer_' . $this->onlineEnterpriseId);
  240. $customer = $objDCustomer->get(['id' => $params['customerId']], 'id,type,name');
  241. if ($customer === false) {
  242. return ResultWrapper::fail($objDCustomer->error(), ErrorCode::$dberror);
  243. }
  244. if (empty($customer['type'])) {
  245. //客户未设置客户类型
  246. return ResultWrapper::success($newmaterielPriceData);
  247. }
  248. $customerType = $customer['type'];//客户类型
  249. // 获取指定商品指定类型指定店铺下的客户类型调价数据
  250. $shopBindGoddsIds = [];
  251. foreach ($newmaterielPriceData as $key => $value){ // 店铺维度循环
  252. foreach ($value as $k => $v){ // 店铺下商品维度
  253. $shopBindGoddsIds[$key][] = $k;
  254. }
  255. }
  256. if(empty($shopBindGoddsIds)){
  257. return ResultWrapper::success($newmaterielPriceData);
  258. }
  259. // 获取对应商品的客户类型调价数据
  260. $objMCustomerTypePriceAdjustment = new MCustomerTypePriceAdjustment($this->onlineUserId, $this->onlineEnterpriseId);
  261. $objMCustomerPriceAdjustment = new MCustomerPriceAdjustment($this->onlineUserId, $this->onlineEnterpriseId);
  262. foreach ($shopBindGoddsIds as $shopkey => $goodsvalue){
  263. if(empty($shopBindGoddsIds[$shopkey])){
  264. continue;
  265. }
  266. // 查询客户价格数据
  267. $result = $objMCustomerPriceAdjustment->getCustomerPriceByIds($key, $params['customerId'], $shopBindGoddsIds[$shopkey]);
  268. if (!$result->isSuccess()) {
  269. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  270. }
  271. $customerPrice = $result->getData();
  272. if (!empty($customerPrice)) {
  273. $returnData = self::commonSpecailData($customerPrice, $newmaterielPriceData, $shopkey, []);
  274. $newmaterielPriceData = $returnData['data'];
  275. continue;
  276. }
  277. // 查询客户类型价格数据
  278. unset($result);
  279. $result = $objMCustomerTypePriceAdjustment->getCustomerTypePriceByIds($shopkey, $customerType, $shopBindGoddsIds[$shopkey]);
  280. if (!$result->isSuccess()) {
  281. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  282. }
  283. $customerTypePrice = $result->getData();
  284. if (empty($customerTypePrice)) {
  285. continue;
  286. }
  287. $returnData = self::commonSpecailData($customerTypePrice, $newmaterielPriceData, $shopkey, $returnData['skuIds']);
  288. $newmaterielPriceData = $returnData['data'];
  289. }
  290. return ResultWrapper::success($newmaterielPriceData);
  291. }
  292. /**
  293. * 统一加减乘操作
  294. */
  295. public function commonSpecailData($priceData, $newmaterielPriceData, $shopkey, $isHaveSkuIds =[])
  296. {
  297. // 循环客户类型调价数据对返回的价格数据处理
  298. foreach ($priceData as $customerTypePriceKey => $customerTypePriceValue){
  299. // 处理返回数据价格
  300. $salePrice = json_decode($customerTypePriceValue['salePrice'], true);
  301. // 按照skuid维度进行价格处理
  302. foreach ($salePrice as $key => $value){
  303. if(in_array($value['skuId'], $isHaveSkuIds)){
  304. continue;
  305. }
  306. // 如果有阶梯价
  307. if ( isset($value['ladderPrice']) && !empty($value['ladderPrice']) ){
  308. foreach ($value['ladderPrice'] as $k => $v){
  309. $beforePrice = $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['ladderPrice'][$k]['price'];
  310. // 根据标识判断做对应处理
  311. switch (intval($v['adjPricetag'])){
  312. case 1: // 减法
  313. $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['ladderPrice'][$k]['price'] = bcsub($beforePrice,$v['adjPrice'],2);
  314. break;
  315. case 2: // 加法
  316. $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['ladderPrice'][$k]['price'] = bcadd($beforePrice,$v['adjPrice'],2);
  317. break;
  318. case 3: // 乘法
  319. $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['ladderPrice'][$k]['price'] = bcmul($beforePrice,$v['adjPrice'],2);
  320. break;
  321. }
  322. }
  323. }else{
  324. $beforeSalePrice = $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['salePrice']; //处理前销售价格
  325. $beforeMarketPrice = $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['marketPrice']; //处理前市场价格
  326. // 根据标识判断做对应处理
  327. switch (intval($value['adjPricetag'])){
  328. case 1: // 减法
  329. $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['salePrice'] = bcsub($beforeSalePrice,$value['price'],2);
  330. $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['marketPrice'] = bcsub($beforeMarketPrice,$value['price'],2);
  331. break;
  332. case 2: // 加法
  333. $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['salePrice'] = bcadd($beforeSalePrice,$value['price'],2);
  334. $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['marketPrice'] = bcadd($beforeMarketPrice,$value['price'],2);
  335. break;
  336. case 3: // 乘法
  337. $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['salePrice'] = bcmul($beforeSalePrice,$value['price'],2);
  338. $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['marketPrice'] = bcmul($beforeMarketPrice,$value['price'],2);
  339. break;
  340. }
  341. }
  342. $isHaveSkuIds[] = $value['skuId'];
  343. }
  344. }
  345. return [
  346. 'data' => $newmaterielPriceData,
  347. 'skuIds' => $isHaveSkuIds
  348. ];
  349. }
  350. /**
  351. * 获取全国标准价
  352. * @param $materialCodes
  353. * @return ResultWrapper
  354. * @throws \Exception
  355. */
  356. public function getNationalUnifiedPrice($material)
  357. {
  358. $objDNationalUnifiedPrice = new DNationalUnifiedPrice();
  359. $objDNationalUnifiedPrice->setTable('qianniao_nationalUnifiedPrice_' . $this->onlineEnterpriseId);
  360. $nationalUnifiedPriceData = [];
  361. foreach ($material as $key => $value) {
  362. $goodsIds = array_unique($value);
  363. foreach ($goodsIds as $k => $v) {
  364. $dbResult = $objDNationalUnifiedPrice->select(['shopId' => $key, 'goodsId' => $v], 'salePriceType,salePrice');
  365. if ($dbResult === false) {
  366. return ResultWrapper::fail($objDNationalUnifiedPrice->error(), ErrorCode::$dberror);
  367. }
  368. $nationalUnifiedPriceData[$key][$v] = [];
  369. if (!empty($dbResult[0]['salePrice'])) {
  370. $nationalUnifiedPriceData[$key][$v] = self::formatPrice($dbResult[0]['salePriceType'], $dbResult[0]['salePrice']);
  371. }
  372. }
  373. }
  374. return ResultWrapper::success($nationalUnifiedPriceData);
  375. }
  376. /**
  377. * 获取指定物料指定店铺下对应区域的区域销售价价格
  378. * @param $materialCodes array 店铺对应的物料编码
  379. * @param $params array 请求参数
  380. * @param $returnAll boolean 是否返回所有区域价格
  381. *
  382. * @return ResultWrapper
  383. */
  384. public function getAreaPrice($materialCodes, $params, $returnAll = false)
  385. {
  386. if ($returnAll) {
  387. return self::getAllAreaPrice($materialCodes, $params);
  388. }
  389. $objDAreaPrice = new DAreaPrice();
  390. // 处理多个店铺下的多个物料
  391. foreach ($materialCodes as $key => $value) {
  392. $materialCodes = array_unique($value);
  393. // 先查询全国价
  394. foreach ($materialCodes as $k => $v) {
  395. $areaPriceData[$key][$v] = [];
  396. $nationalUnifiedPriceParams[$key][] = $v;
  397. $result = self::getNationalUnifiedPrice($nationalUnifiedPriceParams);
  398. if (!$result->isSuccess()) {
  399. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  400. }
  401. $nationalUnifiedPriceData = $result->getData();
  402. if (!empty($nationalUnifiedPriceData)) {
  403. $nationalUnifiedPrice = $nationalUnifiedPriceData[$key][$v];
  404. $areaPriceData[$key][$v] = $nationalUnifiedPrice;
  405. }
  406. }
  407. // 按照企业分表
  408. $objDAreaPrice->setTable('qianniao_areaPrice_' . $this->onlineEnterpriseId);
  409. // 优化一次性取区一级价格 城市一级价格 大区一级价格
  410. foreach ($materialCodes as $k => $v) {
  411. $sql = 'select salePrice->\'$."' . $params['province'] . '-' . $params['city'] . '-' . $params['district'] . '"\' as districtSalePrice,salePrice->\'$."' . $params['province'] . '-' . $params['city'] . '-0"\' as citySalePrice,salePrice->\'$."' . $params['province'] . '-0-0"\' as provinceSalePrice,salePriceType from ' . 'qianniao_areaPrice_' . $this->onlineEnterpriseId . ' where shopId = ' . $key . ' and goodsId = "' . $v . '" and salePriceType =' . StatusCode::$salePriceType['salePrice'];
  412. $dbResult = $objDAreaPrice->query($sql);
  413. if ($dbResult === false) {
  414. return ResultWrapper::fail($objDAreaPrice->error(), ErrorCode::$dberror);
  415. }
  416. // 优先生效区一级价格 区一级未定价生效市一级 市一级未定价生效大区价
  417. if (!empty($dbResult[0])) {
  418. if (!empty($dbResult[0]['districtSalePrice'])) {
  419. $areaPriceData[$key][$v] = self::formatPrice($dbResult[0]['salePriceType'], $dbResult[0]['districtSalePrice']);
  420. unset($materialCodes[$k]);
  421. continue;
  422. } else if (!empty($dbResult[0]['citySalePrice'])) {
  423. $areaPriceData[$key][$v] = self::formatPrice($dbResult[0]['salePriceType'], $dbResult[0]['CitySalePrice']);
  424. unset($materialCodes[$k]);
  425. continue;
  426. } else if (!empty($dbResult[0]['provinceSalePrice'])) {
  427. $areaPriceData[$key][$v] = self::formatPrice($dbResult[0]['salePriceType'], $dbResult[0]['regionalDepartmentSalePrice']);
  428. unset($materialCodes[$k]);
  429. continue;
  430. }
  431. }
  432. }
  433. }
  434. return ResultWrapper::success($areaPriceData);
  435. }
  436. /**
  437. * @param $selectParams
  438. * @return ResultWrapper
  439. * @throws \Exception
  440. */
  441. public function getAllGoodsPrice($selectParams)
  442. {
  443. $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId);
  444. $selectParams = parent::getShopIdQueryParams($selectParams);
  445. $dbResult = $objMGoods->getAllGoods($selectParams);
  446. if (!$dbResult->isSuccess()) {
  447. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  448. }
  449. $result = $dbResult->getData();
  450. $goodsData = [];
  451. $total = 0;
  452. if (!empty($result)) {
  453. $goodsData = $result['data'];
  454. $total = $result['total'];
  455. }
  456. $goodsData = self::format($goodsData);
  457. $return = [
  458. 'data' => $goodsData,
  459. 'total' => $total,
  460. ];
  461. return ResultWrapper::success($return);
  462. }
  463. /**
  464. * 价格管理搜索
  465. * @param array $selectParams 过滤条件
  466. * @return ResultWrapper
  467. * @throws \Exception
  468. */
  469. public function search($selectParams)
  470. {
  471. $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId);
  472. $result = $objMGoods->search($selectParams);
  473. if (!$result->isSuccess()) {
  474. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  475. }
  476. $resultData = $result->getData();
  477. $return = [
  478. 'data' => self::format($resultData['data']),
  479. 'total' => $resultData['total'],
  480. ];
  481. return ResultWrapper::success($return);
  482. }
  483. /**
  484. * @param $selectParams
  485. * @return array|ResultWrapper
  486. * @throws \Exception
  487. */
  488. private function setWhere($selectParams)
  489. {
  490. $defaultDSL = [
  491. 'from' => $selectParams['offset'],
  492. 'size' => $selectParams['limit'],
  493. 'sort' => [
  494. 'sort' => [
  495. 'order' => 'asc'
  496. ],
  497. 'createTime' => [
  498. 'order' => 'desc'
  499. ],
  500. ],
  501. ];
  502. $dsl = [];
  503. $dsl['query']['bool']['must'][] = [
  504. 'term' => ['enterpriseId' => $this->onlineEnterpriseId],
  505. ];
  506. //去ES的basic类型下查找匹配的basicIds
  507. if (!empty($selectParams['keyword'])
  508. || !empty($selectParams['categoryId'])
  509. ) {
  510. $basicSearchParams = [
  511. 'keyword' => isset($selectParams['keyword']) ? $selectParams['keyword'] : '',
  512. 'categoryId' => isset($selectParams['categoryId']) ? $selectParams['categoryId'] : '',
  513. ];
  514. $objMGoodsBasic = new MGoodsBasic($this->onlineUserId, $this->onlineEnterpriseId);
  515. $goodsBasics = $objMGoodsBasic->searchGoodsBasics($basicSearchParams);
  516. if ($goodsBasics->isSuccess() === false) {
  517. return ResultWrapper::fail('获取基本资料数据失败' . $goodsBasics['error']['reason'], ErrorCode::$apiNotResult);
  518. }
  519. $goodsBasicLists = [];
  520. $goodsBasicData = $goodsBasics->getData();
  521. foreach ($goodsBasicData as $goodsBasic) {
  522. $goodsBasicLists[$goodsBasic['id']] = $goodsBasic;
  523. }
  524. $goodsBasicIds = array_keys($goodsBasicLists);
  525. if (!$goodsBasicIds) {
  526. return ResultWrapper::success([
  527. 'data' => [],
  528. 'total' => 0
  529. ]);
  530. }
  531. $dsl['query']['bool']['must'][] = [
  532. 'terms' => [
  533. 'basicGoodsId' => $goodsBasicIds
  534. ]
  535. ];
  536. }
  537. //按商铺搜索
  538. if (!empty($selectParams['shopId'])) {
  539. $dsl['query']['bool']['must'][] = [
  540. 'term' => ['shopId' => $selectParams['shopId']],
  541. ];
  542. }
  543. $dsl = array_merge($defaultDSL, $dsl);
  544. return $dsl;
  545. }
  546. /**
  547. * @param $data
  548. * @return array
  549. */
  550. public function format($data)
  551. {
  552. if (empty($data)) return $data;
  553. $return = [];
  554. foreach ($data as $key => $val) {
  555. $return[] = [
  556. 'id' => $val['id'],
  557. 'code' => $val['code'],
  558. 'merchantId' => $val['merchantId'],
  559. 'goodsName' => $val['title'],
  560. 'categoryName' => $val['categoryName'],
  561. 'brandName' => $val['brandName'],
  562. 'enableStatus' => $val['enableStatus'],
  563. //'skuData' => $val['skuData'],
  564. //'costPrice' => isset($val['costPrice']) ? $val['costPrice'] : 0,
  565. 'shopName' => $val['shopName'],
  566. 'goodsId' => $val['id'],
  567. 'shopId' => $val['shopId'],
  568. //'specGroup' => $val['specGroup'],
  569. //'specMultiple' => $val['specMultiple'],
  570. 'inventorTotal' => $val['inventorTotal'],
  571. 'specTotal' => $val['specTotal'],
  572. 'masterPrice' => isset($val['masterPrice']) ? $val['masterPrice'] : [],
  573. 'unitData' => isset($val['unitData']) ? $val['unitData'] : []
  574. ];
  575. }
  576. return $return;
  577. }
  578. /**
  579. * 获取指定物料指定店铺下面设置过得大区价格
  580. * @param $materialCodes array 店铺对应的物料编码
  581. * @param $params array 请求参数
  582. * @param $returnAll boolean 是否返回所有区域价格
  583. *
  584. * @return ResultWrapper
  585. */
  586. public function getAllAreaPrice($materialCodes, $params)
  587. {
  588. foreach ($materialCodes as $key => $value) {
  589. foreach ($value as $k => $v) {
  590. $allMaterialCodes[] = $v;
  591. }
  592. $allShopIds[] = $key;
  593. }
  594. // 批量获取这批物料最后生效的价格销售区域类型
  595. $objDLastEffectiveSalePriceAreaType = new DLastEffectiveSalePriceAreaType();
  596. $condition = [
  597. 'marketCode' => $allMaterialCodes,
  598. 'shopId' => $allShopIds,
  599. ];
  600. $dbResult = $objDLastEffectiveSalePriceAreaType->select($condition, 'lastEffectiveSalePriceAreaType,marketCode,shopId');
  601. if ($dbResult === false) {
  602. return ResultWrapper::fail($objDLastEffectiveSalePriceAreaType->error(), ErrorCode::$dberror);
  603. }
  604. if (empty($dbResult)) {
  605. return ResultWrapper::success([]);
  606. }
  607. // 进行生效价格区域类型分组
  608. $materieLastEffectiveSalePriceAreaType = [];
  609. foreach ($dbResult as $k => $v) {
  610. $materieLastEffectiveSalePriceAreaType[$v['shopId']][$v['marketCode']] = $v['lastEffectiveSalePriceAreaType'];
  611. }
  612. $objDAreaPrice = new DAreaPrice();
  613. foreach ($materialCodes as $key => $value) {
  614. // 按照店铺分表
  615. $tableName = 'areaPrice_' . $key;
  616. $objDAreaPrice->setTable($tableName);
  617. $materialCodes = array_unique($value);
  618. foreach ($materialCodes as $k => $v) {
  619. if (isset($materieLastEffectiveSalePriceAreaType[$key][$v]) && $materieLastEffectiveSalePriceAreaType[$key][$v] == StatusCode::$salePriceAreaType['nationalUnifiedPrice']) {
  620. $nationalUnifiedPriceParams[$key][] = $v;
  621. $result = self::getNationalUnifiedPrice($nationalUnifiedPriceParams);
  622. if (!$result->isSuccess()) {
  623. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  624. }
  625. $nationalUnifiedPriceData = $result->getData();
  626. if (!empty($nationalUnifiedPriceData)) {
  627. $nationalUnifiedPrice = $nationalUnifiedPriceData[$params['shopId']][$params['marketCode']];
  628. }
  629. }
  630. $sql = 'select salePrice,salePriceType from ' . $tableName . ' where shopId = ' . $key . ' and marketCode = "' . $v . '" and salePriceType =' . StatusCode::$salePriceType['salePrice'];
  631. $dbResult = $objDAreaPrice->query($sql);
  632. if ($dbResult === false) {
  633. return ResultWrapper::fail($objDAreaPrice->error(), ErrorCode::$dberror);
  634. }
  635. $areaPriceData[$key][$v] = [];
  636. if (!empty($dbResult[0]['salePrice'])) {
  637. // 当前生效的是全国价,替换所有区域价格为全国价
  638. if (!empty($nationalUnifiedPrice)) {
  639. $dbResult[0]['salePrice'] = json_decode($dbResult[0]['salePrice'], true);
  640. foreach ($dbResult[0]['salePrice'] as &$a) {
  641. foreach ($a as &$b) {
  642. $b = $nationalUnifiedPrice;
  643. }
  644. }
  645. $dbResult[0]['salePrice'] = json_encode($dbResult[0]['salePrice']);
  646. }
  647. $areaPriceData[$key][$v] = self::formatPrice($dbResult[0]['salePriceType'], $dbResult[0]['salePrice']);
  648. }
  649. }
  650. }
  651. return ResultWrapper::success($areaPriceData);
  652. }
  653. /**
  654. * 同时获取多个大区部门价格数据
  655. */
  656. public function getAreaPriceByRegionalDepartmentIds($regionalDepartmentIds = [], $shopId, $marketCode)
  657. {
  658. // 按照店铺分表
  659. $objDAreaPrice = new DAreaPrice();
  660. $tableName = 'areaPrice_' . $shopId;
  661. $objDAreaPrice->setTable($tableName);
  662. $selectFeildStr = '';
  663. foreach ($regionalDepartmentIds as $key => $value) {
  664. $selectFeildStr .= 'salePrice->\'$."' . $value . '"."' . $value . '-' . $value . '-' . $value . '"\' as salePrice_' . $value . ',';
  665. }
  666. $sql = 'select ' . $selectFeildStr . 'salePriceType from ' . $tableName . ' where shopId = ' . $shopId . ' and marketCode = "' . $marketCode . '" and salePriceType =' . StatusCode::$salePriceType['salePrice'];
  667. $dbResult = $objDAreaPrice->query($sql);
  668. if ($dbResult === false) {
  669. return ResultWrapper::fail($objDAreaPrice->error(), ErrorCode::$dberror);
  670. }
  671. if (empty($dbResult)) {
  672. return ResultWrapper::success([]);
  673. }
  674. foreach ($dbResult[0] as $key => $value) {
  675. if ($key !== 'salePriceType') {
  676. $dbResult[0][$key] = self::formatPrice($dbResult[0]['salePriceType'], $value);
  677. }
  678. }
  679. return ResultWrapper::success($dbResult[0]);
  680. }
  681. /**
  682. * 同时获取多个物料多个大区部门价格数据
  683. */
  684. public function batchGetAreaPriceByRegionalDepartmentIds($regionalDepartmentIds = [], $shopId, $marketCodes = [])
  685. {
  686. // 按照店铺分表
  687. $objDAreaPrice = new DAreaPrice();
  688. $tableName = 'areaPrice_' . $shopId;
  689. $objDAreaPrice->setTable($tableName);
  690. $selectFeildStr = '';
  691. foreach ($regionalDepartmentIds as $key => $value) {
  692. $selectFeildStr .= 'salePrice->\'$."' . $value . '"."' . $value . '-' . $value . '-' . $value . '"\' as salePrice_' . $value . ',';
  693. }
  694. $sql = 'select ' . $selectFeildStr . 'marketCode from ' . $tableName . ' where shopId = ' . $shopId . ' and marketCode in ("' . implode('","', $marketCodes) . '"' . ') and salePriceType =' . StatusCode::$salePriceType['salePrice'];
  695. $dbResult = $objDAreaPrice->query($sql);
  696. if ($dbResult === false) {
  697. return ResultWrapper::fail($objDAreaPrice->error(), ErrorCode::$dberror);
  698. }
  699. if (empty($dbResult)) {
  700. return ResultWrapper::success([]);
  701. }
  702. $returnData = [];
  703. foreach ($dbResult as $key => $value) {
  704. foreach ($value as $k => $v) {
  705. $returnData[$value['marketCode']] = self::formatPrice(StatusCode::$salePriceType['salePrice'], $v);
  706. }
  707. }
  708. return ResultWrapper::success($returnData);
  709. }
  710. /**
  711. * 格式化价格
  712. */
  713. public function formatPrice($salePriceType, $salePrice)
  714. {
  715. $price = json_decode($salePrice, true);
  716. return $price;
  717. }
  718. /**
  719. * 根据省市区获取大区价格
  720. */
  721. public function getRegionalPriceByArea($materialCodes, $params)
  722. {
  723. $objDRegionalDepartmentPrice = new DRegionalDepartmentPrice();
  724. // 获取省市区在不同店铺下的不同大区id
  725. $regionalPriceData = [];
  726. $regionalDepartmentId = 0;
  727. $objMRegionalManage = new MRegionalManage();
  728. $result = $objMRegionalManage->getRegionalDepartmentId($params['province'], $params['city'], $params['district']);
  729. if (!$result->isSuccess()) {
  730. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  731. }
  732. $regionalDepartmentData = $result->getData();
  733. if (empty($regionalDepartmentData)) {
  734. return ResultWrapper::fail('当前省市区没有对应部门', ErrorCode::$contentNotExists);
  735. }
  736. foreach ($regionalDepartmentData as $key => $value) {
  737. $newRegionalDepartmentData[$value['shopId']] = $value['id'];
  738. }
  739. foreach ($materialCodes as $key => $value) {
  740. if (!isset($newRegionalDepartmentData[$params['shop']])) {
  741. return ResultWrapper::fail('当前省市区没有对应部门', ErrorCode::$contentNotExists);
  742. }
  743. $regionalDepartmentId = $newRegionalDepartmentData[$params['shop']];
  744. // 按照店铺分表
  745. $tableName = 'regionalDepartmentPrice_' . $key;
  746. $objDRegionalDepartmentPrice->setTable($tableName);
  747. $condition = [
  748. 'materialCode' => array_values($value),
  749. 'regionalDepartmentId' => $regionalDepartmentId,
  750. ];
  751. $dbResult = $objDRegionalDepartmentPrice->select($condition);
  752. if ($dbResult === false) {
  753. return ResultWrapper::fail($objDRegionalDepartmentPrice->error(), ErrorCode::$dberror);
  754. }
  755. if (!empty($dbResult)) {
  756. foreach ($dbResult as $k => $v) {
  757. $regionalPriceData[$key][$v['materialCode']] = ['price' => self::formatPrice($v['materialCode'], $v['salePrice'])];
  758. }
  759. }
  760. }
  761. return ResultWrapper::success($regionalPriceData);
  762. }
  763. /**
  764. * 获取区域价格
  765. */
  766. public function getDistrictPrice($materialCodes, $params)
  767. {
  768. // 直接查询省市区分表
  769. $objDDistrictPriceCity = new DDistrictPriceCity();
  770. $DDistrictPriceProvince = new DDistrictPriceProvince();
  771. // 计算区县分表
  772. $tableName = 'districtPrice_city_' . $params['city'];
  773. $objDDistrictPriceCity->setTable($tableName);
  774. $districtPriceData = [];
  775. foreach ($materialCodes as $key => $value) {
  776. $condition = [
  777. 'shopId' => $key,
  778. 'materialCode' => array_unique(array_values($value)),
  779. ];
  780. $dbResult = $objDDistrictPriceCity->select($condition);
  781. if ($dbResult === false) {
  782. return ResultWrapper::fail($objDDistrictPriceCity->error(), ErrorCode::$dberror);
  783. }
  784. if (!empty($dbResult)) {
  785. foreach ($dbResult as $k => $v) {
  786. $districtPriceData[$key][$v['materialCode']] = ['price' => self::formatPrice($v['materialCode'], $v['salePrice'])];
  787. }
  788. }
  789. }
  790. unset($condition);
  791. // 计算省分表
  792. $tableName = 'districtPrice_province_' . $params['province'];
  793. $DDistrictPriceProvince->setTable($tableName);
  794. foreach ($materialCodes as $key => $value) {
  795. $condition = [
  796. 'shopId' => $key,
  797. 'materialCode' => array_unique(array_values($value)),
  798. ];
  799. $dbResult = $DDistrictPriceProvince->select($condition);
  800. if ($dbResult === false) {
  801. return ResultWrapper::fail($DDistrictPriceProvince->error(), ErrorCode::$dberror);
  802. }
  803. if (!empty($dbResult)) {
  804. foreach ($dbResult as $k => $v) {
  805. // 具体区县级取到数据了,就不取省一级的了
  806. if (isset($districtPriceData[$key][$v['materialCode']])) {
  807. continue;
  808. }
  809. $districtPriceData[$key][$v['materialCode']] = ['price' => self::formatPrice($v['salePriceType'], $v['salePrice'])];
  810. }
  811. }
  812. }
  813. return ResultWrapper::success($districtPriceData);
  814. }
  815. /**
  816. * 价格表列表页
  817. */
  818. public function getAll($params, $authorization)
  819. {
  820. // 获取所有大区数据
  821. $objMRegionalManage = new MRegionalManage();
  822. $result = $objMRegionalManage->getAllRegionalDepartment($params['shopId']);
  823. if (!$result->isSuccess()) {
  824. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  825. }
  826. $allRegionalDepartment = $result->getData();
  827. unset($result);
  828. $regionalDepartmentIds = [];
  829. $newAllRegionalDepartment = [];
  830. $RegionalDepartmentAndDeoptId = []; // 部门和仓库映射关系
  831. foreach ($allRegionalDepartment as $key => $value) {
  832. $newAllRegionalDepartment[$value['id']] = [
  833. 'name' => $value['name'],
  834. 'id' => $value['id'],
  835. 'price' => [],
  836. 'depotId' => $value['depotId'],
  837. ];
  838. $regionalDepartmentIds[] = $value['id'];
  839. $RegionalDepartmentAndDeoptId[$value['id']] = $value['depotId'];
  840. }
  841. // 初始化所有物料价格
  842. $returnDataValue = [
  843. 'cost' => 0,
  844. 'num' => 0,
  845. 'profit' => '0%',
  846. 'kilogramPrice' => '0.00',
  847. 'totalAmount' => '0.00',
  848. 'NationalUnifiedPrice' => (object)[],
  849. 'regionalDepartmentPrice' => $newAllRegionalDepartment,
  850. 'lastUserName' => ''
  851. ];
  852. $nationalUnifiedPriceParams = []; // 查询全国价参数
  853. $marketCodeAndmaterialCode = []; // 基础物料和销售物料映射关系
  854. $allMarketCodes = [];
  855. $marketCodeAndWeight = []; // 销售物料和重量关系
  856. foreach ($params['materialData'] as $key => $value) {
  857. foreach ($value as $k => $v) {
  858. $allMarketCodes[] = $v['marketCode'];
  859. $returnData[$v['marketCode']] = $returnDataValue;
  860. $marketCodeAndmaterialCode[$v['marketCode']] = $v['materialCode'];
  861. $marketCodeAndWeight[$v['marketCode']] = $v['weight'];
  862. $nationalUnifiedPriceParams[$key][] = $v['marketCode'];
  863. }
  864. }
  865. // 组装查询库存和成本数据要的参数
  866. $materielCostData = [
  867. 'cargoOwnerType' => $params['cargoOwnerType'],
  868. 'cargoOwnerCode' => $params['cargoOwnerCode'],
  869. ];
  870. foreach ($params['materialData'] as $key => $value) {
  871. foreach ($value as $k => $v) {
  872. $materielNumData[] = [
  873. 'materielCode' => $v['materialCode'],
  874. 'cargoOwnerCode' => $params['cargoOwnerCode'],
  875. ];
  876. $materielCostData['materielCode'][] = $v['materialCode'];
  877. }
  878. }
  879. // 获取成本和销售数量
  880. $objMOutsideData = new MOutsideData();
  881. $result = $objMOutsideData->getNumAndCost(['materielCostData' => $materielCostData, 'materielNumData' => $materielNumData], $authorization);
  882. if (!$result->isSuccess()) {
  883. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  884. }
  885. $costAndNumData = $result->getData();
  886. // 查询这批物料当前价格生效类型
  887. // 批量获取这批物料最后生效的价格销售区域类型
  888. $objDLastEffectiveSalePriceAreaType = new DLastEffectiveSalePriceAreaType();
  889. $condition = [
  890. 'marketCode' => array_unique($allMarketCodes),
  891. 'shopId' => $params['shopId'],
  892. ];
  893. $dbResult = $objDLastEffectiveSalePriceAreaType->select($condition, 'lastEffectiveSalePriceAreaType,marketCode,shopId,lastUserName');
  894. if ($dbResult === false) {
  895. return ResultWrapper::fail($objDLastEffectiveSalePriceAreaType->error(), ErrorCode::$dberror);
  896. }
  897. if (!empty($dbResult)) {
  898. // 进行生效价格区域类型分组
  899. $materieLastEffectiveSalePriceAreaType = [];
  900. // 映射物料和调价人关系
  901. $materieLastEffectiveLastUserName = [];
  902. foreach ($dbResult as $k => $v) {
  903. $materieLastEffectiveSalePriceAreaType[$v['marketCode']] = $v['lastEffectiveSalePriceAreaType'];
  904. $materieLastEffectiveLastUserName[$v['marketCode']] = $v['lastUserName'];
  905. }
  906. }
  907. // 查询各个物料的标准价
  908. $result = self::getNationalUnifiedPrice($nationalUnifiedPriceParams);
  909. if (!$result->isSuccess()) {
  910. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  911. }
  912. $nationalUnifiedPriceData = $result->getData();
  913. unset($result);
  914. foreach ($nationalUnifiedPriceData as $key => $value) {
  915. foreach ($value as $k => $v) {
  916. if (isset($returnData[$k])) {
  917. $returnData[$k]['NationalUnifiedPrice'] = isset($v['salePrice']) ? $v : [];
  918. }
  919. }
  920. }
  921. // 查询大区的销售价
  922. unset($result);
  923. $result = self::batchGetAreaPriceByRegionalDepartmentIds($regionalDepartmentIds, $params['shopId'], $allMarketCodes);
  924. if (!$result->isSuccess()) {
  925. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  926. }
  927. $regionalDepartmentPrice = $result->getData();
  928. // 如果当前生效全国价大区价=全国价 不然等于各自大区价格
  929. foreach ($returnData as $key => $value) {
  930. foreach ($value['regionalDepartmentPrice'] as $k => $v) {
  931. if (isset($materieLastEffectiveSalePriceAreaType[$key]) && $materieLastEffectiveSalePriceAreaType[$key] == StatusCode::$salePriceAreaType['nationalUnifiedPrice']) {
  932. $returnData[$key]['regionalDepartmentPrice'][$k]['price'] = $returnData[$key]['NationalUnifiedPrice'];
  933. } else {
  934. if (isset($regionalDepartmentPrice[$key])) {
  935. $returnData[$key]['regionalDepartmentPrice'][$k]['price'] = !empty($regionalDepartmentPrice[$key]['salePrice_' . $k]) ? $regionalDepartmentPrice[$key]['salePrice_' . $k] : $returnData[$key]['NationalUnifiedPrice'];
  936. }
  937. }
  938. }
  939. }
  940. foreach ($returnData as $key => $value) {
  941. $returnData[$key]['lastEffectiveSalePriceAreaType'] = isset($materieLastEffectiveSalePriceAreaType[$key]) ? $materieLastEffectiveSalePriceAreaType[$key] : 0;
  942. $returnData[$key]['lastUserName'] = isset($materieLastEffectiveLastUserName[$key]) ? $materieLastEffectiveLastUserName[$key] : '';
  943. $returnData[$key]['cost'] = isset($costAndNumData['costData'][$marketCodeAndmaterialCode[$key]]) ? $costAndNumData['costData'][$marketCodeAndmaterialCode[$key]] : [];
  944. $returnData[$key]['num'] = isset($costAndNumData['stockData'][$marketCodeAndmaterialCode[$key]]) ? $costAndNumData['stockData'][$marketCodeAndmaterialCode[$key]] : [];
  945. $tmpDeoptCostNumDtat = [];
  946. // 转换各个康库重量为数量
  947. $returnData[$key]['totalNum'] = 0;
  948. if (!empty($returnData[$key]['num'])) {
  949. foreach ($returnData[$key]['num'] as $k => $v) {
  950. $returnData[$key]['totalNum'] += $v['stockAvailable'];
  951. $returnData[$key]['num'][$k]['stockAvailable'] = floor($returnData[$key]['num'][$k]['stockAvailable'] / $marketCodeAndWeight[$key]);
  952. $tmpDeoptCostNumDtat[$key][$v['depotId']]['stockAvailable'] = $returnData[$key]['num'][$k]['stockAvailable'];
  953. if (!empty($returnData[$key]['cost']) && isset($returnData[$key]['cost']['depotIdData'])) {
  954. foreach ($returnData[$key]['cost']['depotIdData'] as $m => $j) {
  955. if ($j['depotId'] == $v['depotId']) {
  956. $returnData[$key]['cost']['depotIdData'][$m]['costPriceTotal'] = ($j['costPrice'] * $marketCodeAndWeight[$key]) * $returnData[$key]['num'][$k]['stockAvailable'];
  957. $tmpDeoptCostNumDtat[$key][$j['depotId']]['costPriceTotal'] = $returnData[$key]['cost']['depotIdData'][$m]['costPriceTotal'];
  958. }
  959. }
  960. }
  961. }
  962. $returnData[$key]['totalNum'] = floor($returnData[$key]['totalNum'] / $marketCodeAndWeight[$key]);
  963. }
  964. // 查看全部部门
  965. if ($params['regionalDepartmentId'] == 0) {
  966. if (isset($returnData[$key]['cost']['specCostPrice']) && isset($returnData[$key]['NationalUnifiedPrice']['salePrice'])) {
  967. $costPriceTotal = 0;
  968. if (!empty($tmpDeoptCostNumDtat[$key])) {
  969. foreach ($tmpDeoptCostNumDtat[$key] as $k1 => $v1) {
  970. if (isset($v1['costPriceTotal'])) {
  971. $costPriceTotal += $v1['costPriceTotal'];
  972. }
  973. }
  974. }
  975. $returnData[$key]['profit'] = self::getProfit($returnData[$key]['NationalUnifiedPrice']['salePrice'], $returnData[$key]['totalNum'], $costPriceTotal);
  976. } else {
  977. $returnData[$key]['profit'] = 0.00;
  978. }
  979. if (isset($returnData[$key]['NationalUnifiedPrice']['salePrice'])) {
  980. $returnData[$key]['totalAmount'] = self::getTotalMoney($returnData[$key]['totalNum'], $returnData[$key]['NationalUnifiedPrice']['salePrice']);
  981. $returnData[$key]['kilogramPrice'] = self::getKilogramPrice($marketCodeAndWeight[$key], $returnData[$key]['NationalUnifiedPrice']['salePrice']);
  982. } else {
  983. $returnData[$key]['totalAmount'] = 0.00;
  984. $returnData[$key]['kilogramPrice'] = 0.00;
  985. }
  986. } else {
  987. if (isset($tmpDeoptCostNumDtat[$key][$RegionalDepartmentAndDeoptId[$params['regionalDepartmentId']]]['costPriceTotal']) && isset($returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price']['salePrice'])) {
  988. $returnData[$key]['profit'] = self::getProfit($returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price']['salePrice'], $tmpDeoptCostNumDtat[$key][$RegionalDepartmentAndDeoptId[$params['regionalDepartmentId']]]['stockAvailable'], $tmpDeoptCostNumDtat[$key][$RegionalDepartmentAndDeoptId[$params['regionalDepartmentId']]]['costPriceTotal']);
  989. } else {
  990. $returnData[$key]['profit'] = 0.00;
  991. }
  992. if (isset($returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price']['salePrice'])) {
  993. $returnData[$key]['totalAmount'] = self::getTotalMoney($tmpDeoptCostNumDtat[$key][$RegionalDepartmentAndDeoptId[$params['regionalDepartmentId']]]['stockAvailable'], $returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price']['salePrice']);
  994. $returnData[$key]['kilogramPrice'] = self::getKilogramPrice($marketCodeAndWeight[$key], $returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price']['salePrice']);
  995. } else {
  996. $returnData[$key]['totalAmount'] = 0.00;
  997. $returnData[$key]['kilogramPrice'] = 0.00;
  998. }
  999. }
  1000. if (empty($returnData[$key]['cost'])) {
  1001. $returnData[$key]['cost'] = (object)[];
  1002. }
  1003. if (empty($returnData[$key]['num'])) {
  1004. $returnData[$key]['num'] = (object)[];
  1005. }
  1006. if (empty($returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price'])) {
  1007. $returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price'] = (object)[];
  1008. }
  1009. if (empty($returnData[$key]['NationalUnifiedPrice'])) {
  1010. $returnData[$key]['NationalUnifiedPrice'] = (object)[];
  1011. }
  1012. $returnData[$key]['regionalDepartmentPrice'] = array_values($returnData[$key]['regionalDepartmentPrice']);
  1013. }
  1014. return ResultWrapper::success($returnData);
  1015. }
  1016. /**
  1017. * 计算毛利率
  1018. * (销售总金额-成本总金额)/销售金额)*100%
  1019. * 销售金额 = 销售数量(全部) * 销售价格(全国销售价) / 销售数量(全部) * 销售价格(部门销售价)
  1020. */
  1021. public function getProfit($nowSalePrice, $stockNum, $costPriceTotal)
  1022. {
  1023. $saleMoney = $nowSalePrice * $stockNum;
  1024. if ($saleMoney == 0) {
  1025. return '0.00%';
  1026. }
  1027. $profitPrice = (($saleMoney - $costPriceTotal) / $saleMoney) * 100;
  1028. return number_format($profitPrice, 2) . "%";
  1029. }
  1030. /**
  1031. * 计算销售公斤价
  1032. * 标准价 / 单件重量
  1033. */
  1034. public function getKilogramPrice($weight, $salePrice)
  1035. {
  1036. if (!$salePrice) {
  1037. return 0.00;
  1038. }
  1039. $kilogramPrice = $salePrice / $weight;
  1040. return number_format($kilogramPrice, 2);
  1041. }
  1042. /**
  1043. * 计算可销售总额
  1044. * 可售数量 * 销售价格
  1045. * @param $params
  1046. * @return ResultWrapper
  1047. */
  1048. public function getTotalMoney($stockNum, $salePrice)
  1049. {
  1050. $totalMoney = $stockNum * $salePrice;
  1051. return number_format($totalMoney, 2);
  1052. }
  1053. /*
  1054. * 获取各个店铺下面物料的大区价格
  1055. */
  1056. public function getRegionalPriceByRegionalDepartmentId($params)
  1057. {
  1058. $objDRegionalDepartmentPrice = new DRegionalDepartmentPrice();
  1059. $regionalPriceData = [];
  1060. foreach ($params['materialCode'] as $key => $value) {
  1061. // 按照店铺分表
  1062. $tableName = 'regionalDepartmentPrice_' . $key;
  1063. $objDRegionalDepartmentPrice->setTable($tableName);
  1064. $condition = [
  1065. 'materialCode' => array_values($value),
  1066. ];
  1067. if ($params['regionalDepartmentId']) {
  1068. $condition['regionalDepartmentId'] = $params['regionalDepartmentId'];
  1069. }
  1070. $dbResult = $objDRegionalDepartmentPrice->select($condition, '*', 'regionalDepartmentId asc');
  1071. if ($dbResult === false) {
  1072. return ResultWrapper::fail($objDRegionalDepartmentPrice->error(), ErrorCode::$dberror);
  1073. }
  1074. if (!empty($dbResult)) {
  1075. foreach ($dbResult as $k => $v) {
  1076. $regionalPriceData[$key][$v['materialCode']][] = ['price' => self::formatPrice($v['salePriceType'], $v['salePrice']), 'regionalDepartmentId' => $v['regionalDepartmentId']];
  1077. }
  1078. }
  1079. }
  1080. return ResultWrapper::success($regionalPriceData);
  1081. }
  1082. /**
  1083. * 获取指定店铺下指定物料的大区以及市价格
  1084. */
  1085. public function getAreaPriceByMaterialCode($params, $authorization)
  1086. {
  1087. // 获取物料各个仓库可用库存
  1088. $objMOutsideData = new MOutsideData();
  1089. $materielData[] = [
  1090. 'materielCode' => $params['materialCode'],
  1091. 'cargoOwnerCode' => $params['cargoOwnerCode'],
  1092. ];
  1093. $newStockData = [];
  1094. $result = $objMOutsideData->getNumFromWms($materielData, $authorization);
  1095. if (!$result->isSuccess()) {
  1096. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  1097. }
  1098. $result = $result->getData();
  1099. $stockData = $result[0]['data'];
  1100. foreach ($stockData as $key => $value) {
  1101. $newStockData[$value['depotId']] = $value['stockAvailable'];
  1102. }
  1103. // 获取各个大区下的城市数据
  1104. $objMRegionalManage = new MRegionalManage();
  1105. $result = $objMRegionalManage->getAllRegionalDepartmentCitys($params);
  1106. if (!$result->isSuccess()) {
  1107. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  1108. }
  1109. $allRegionalDepartmentCitys = $result->getData();
  1110. unset($result);
  1111. // 获取这批物料最后生效的价格销售区域类型
  1112. $objDLastEffectiveSalePriceAreaType = new DLastEffectiveSalePriceAreaType();
  1113. $condition = [
  1114. 'marketCode' => $params['marketCode'],
  1115. 'shopId' => $params['shopId'],
  1116. ];
  1117. $dbResult = $objDLastEffectiveSalePriceAreaType->get($condition, 'lastEffectiveSalePriceAreaType,marketCode,shopId');
  1118. if ($dbResult === false) {
  1119. return ResultWrapper::fail($objDLastEffectiveSalePriceAreaType->error(), ErrorCode::$dberror);
  1120. }
  1121. $lastEffectiveSalePriceAreaType = 0;
  1122. if (!empty($dbResult)) {
  1123. $lastEffectiveSalePriceAreaType = $dbResult['lastEffectiveSalePriceAreaType'];
  1124. }
  1125. // 获取价格数据
  1126. $newparams = [
  1127. 'materialCode' => [
  1128. $params['shopId'] => [$params['marketCode']]
  1129. ],
  1130. ];
  1131. $result = self::getPrice($newparams, true);
  1132. if (!$result->isSuccess()) {
  1133. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  1134. }
  1135. $salePriceData = $result->getData();
  1136. $newSalePriceData = [];
  1137. if (!empty($salePriceData)) {
  1138. $salePriceData = $salePriceData[$params['shopId']][$params['marketCode']];
  1139. if ($lastEffectiveSalePriceAreaType == StatusCode::$salePriceAreaType['areaPrice']) {
  1140. foreach ($salePriceData as $key => $value) {
  1141. $newSalePriceData += $value;
  1142. }
  1143. }
  1144. }
  1145. foreach ($allRegionalDepartmentCitys as $key => $value) {
  1146. $allRegionalDepartmentCitys[$key]['price'] = '0.00';
  1147. $allRegionalDepartmentCitys[$key]['stock'] = 0;
  1148. if ($lastEffectiveSalePriceAreaType == StatusCode::$salePriceAreaType['nationalUnifiedPrice']) {
  1149. $allRegionalDepartmentCitys[$key]['price'] = $salePriceData['salePrice'];
  1150. } else {
  1151. if (isset($newSalePriceData[$value['id'] . '-' . $value['id'] . '-' . $value['id']])) {
  1152. $allRegionalDepartmentCitys[$key]['price'] = $newSalePriceData[$value['id'] . '-' . $value['id'] . '-' . $value['id']]['salePrice'];
  1153. } else {
  1154. $nationalUnifiedPriceParams[$params['shopId']][] = $params['marketCode'];
  1155. $result = self::getNationalUnifiedPrice($nationalUnifiedPriceParams);
  1156. if (!$result->isSuccess()) {
  1157. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  1158. }
  1159. $nationalUnifiedPriceData = $result->getData();
  1160. if (!empty($nationalUnifiedPriceData)) {
  1161. $allRegionalDepartmentCitys[$key]['price'] = $nationalUnifiedPriceData[$params['shopId']][$params['marketCode']]['salePrice'];
  1162. }
  1163. }
  1164. }
  1165. if (isset($newStockData[$value['depotId']])) {
  1166. $allRegionalDepartmentCitys[$key]['stock'] = floor($newStockData[$value['depotId']] / $params['weight']);
  1167. }
  1168. foreach ($value['citys'] as $k => $v) {
  1169. $allRegionalDepartmentCitys[$key]['citys'][$k]['id'] = $k;
  1170. $allRegionalDepartmentCitys[$key]['citys'][$k]['price'] = '0.00';
  1171. if ($lastEffectiveSalePriceAreaType == StatusCode::$salePriceAreaType['nationalUnifiedPrice']) {
  1172. $allRegionalDepartmentCitys[$key]['citys'][$k]['price'] = $salePriceData['salePrice'];
  1173. } else {
  1174. if (isset($newSalePriceData[$v['province'] . '-' . $v['city'] . '-0'])) {
  1175. $allRegionalDepartmentCitys[$key]['citys'][$k]['price'] = $newSalePriceData[$v['province'] . '-' . $v['city'] . '-0']['salePrice'];
  1176. } else {
  1177. $allRegionalDepartmentCitys[$key]['citys'][$k]['price'] = $allRegionalDepartmentCitys[$key]['price'];
  1178. }
  1179. }
  1180. }
  1181. $allRegionalDepartmentCitys[$key]['citys'] = array_values($allRegionalDepartmentCitys[$key]['citys']);
  1182. }
  1183. return ResultWrapper::success($allRegionalDepartmentCitys);
  1184. }
  1185. /**
  1186. * 根据销售区域类型获取对应的销售价格
  1187. */
  1188. public function getPriceBySalePriceAreaType($params)
  1189. {
  1190. $priceDataParams = [
  1191. 'materialCode' => [
  1192. $params['shopId'] => [$params['materielCode']]
  1193. ],
  1194. 'regionalDepartmentId' => $params['regionalDepartmentId'],
  1195. ];
  1196. switch ($params['salePriceAreaType']) {
  1197. case StatusCode::$salePriceAreaType['nationalUnifiedPrice']:
  1198. $materielPriceData = self::getNationalUnifiedPrice($priceDataParams);
  1199. break;
  1200. case StatusCode::$salePriceAreaType['regionalPrice']:
  1201. $materielPriceData = self::getRegionalPriceByRegionalDepartmentId($priceDataParams);
  1202. break;
  1203. case StatusCode::$salePriceAreaType['districtPrice']:
  1204. $materielPriceData = self::getDistrictPrice($priceDataParams['materialCode'], $params);
  1205. break;
  1206. }
  1207. return ResultWrapper::success($materielPriceData);
  1208. }
  1209. /**
  1210. * 获取全国标准价和可用库存
  1211. */
  1212. public function getNationalUnifiedPriceAndStock($params, $authorization)
  1213. {
  1214. $returnData = [
  1215. 'nationalUnifiedPrice' => (object)[],
  1216. 'stock' => 0,
  1217. ];
  1218. // 获取全国统一价格
  1219. $newParams = [
  1220. $params['shopId'] => [$params['marketCode']]
  1221. ];
  1222. $result = self::getNationalUnifiedPrice($newParams);
  1223. if (!$result->isSuccess()) {
  1224. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  1225. }
  1226. $nationalUnifiedPriceData = $result->getData();
  1227. unset($result);
  1228. if (!empty($nationalUnifiedPriceData[$params['shopId']][$params['marketCode']])) {
  1229. $returnData['nationalUnifiedPrice'] = $nationalUnifiedPriceData[$params['shopId']][$params['marketCode']];
  1230. }
  1231. unset($result);
  1232. $objMOutsideData = new MOutsideData();
  1233. $materielNumData[] = [
  1234. 'materielCode' => $params['materialCode'],
  1235. 'cargoOwnerCode' => $params['cargoOwnerCode'],
  1236. ];
  1237. $result = $objMOutsideData->getNumFromWms($materielNumData, $authorization);
  1238. if (!$result->isSuccess()) {
  1239. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  1240. }
  1241. $result = $result->getData();
  1242. if (!empty($result)) {
  1243. $allDepotNum = $result[0]['data'];
  1244. $num = 0;
  1245. foreach ($allDepotNum as $key => $value) {
  1246. $num += $value['stockAvailable'];
  1247. }
  1248. if ($num) {
  1249. $num = floor($num / $params['weight']);
  1250. }
  1251. $returnData['stock'] = $num;
  1252. }
  1253. return ResultWrapper::success($returnData);
  1254. }
  1255. /**
  1256. * (废弃)
  1257. * 根据goodsId获取商品最低/高价格
  1258. * @param array $goodsIds
  1259. * @return ResultWrapper
  1260. */
  1261. public function getRangePrice(array $goodsIds)
  1262. {
  1263. if (empty($goodsIds)) {
  1264. return ResultWrapper::success([]);
  1265. }
  1266. $this->objDPriceRangeSheet->setTable($this->objDPriceRangeSheet->get_Table() . '_' . $this->onlineEnterpriseId);
  1267. $result = $this->objDPriceRangeSheet->select(['goodsId' => $goodsIds], 'goodsId,salePrice');
  1268. if ($result === false) {
  1269. return ResultWrapper::fail($this->objDPriceRangeSheet->error(), ErrorCode::$dberror);
  1270. }
  1271. $mapping = [];
  1272. foreach ($result as $row) {
  1273. $salePrice = empty($row['salePrice']) ? [] : json_decode($row['salePrice'], true);
  1274. $mapping[$row['goodsId']] = [
  1275. 'minSalePrice' => $salePrice['minSalePrice'],
  1276. 'maxSalePrice' => $salePrice['maxSalePrice'],
  1277. ];
  1278. }
  1279. return ResultWrapper::success($mapping);
  1280. }
  1281. /**
  1282. * 根据goodsId获取商品的最高/最低价格
  1283. * @param array $goodsIds 商品id集合
  1284. * @param null $customerId 客户id
  1285. * @param $haveActivity boolean 活动价是否参与最高最低价
  1286. * @return ResultWrapper
  1287. */
  1288. public function getPolePrice(array $goodsIds, $customerId = null, $haveActivity = true)
  1289. {
  1290. $isHaveSkuIds = [];
  1291. //获取商品salePrice
  1292. $nationSalePriceResult = self::getNationSalePriceByGoodsIds($goodsIds);
  1293. if (!$nationSalePriceResult->isSuccess()) {
  1294. return ResultWrapper::fail($nationSalePriceResult->getData(), $nationSalePriceResult->getErrorCode());
  1295. }
  1296. $nationSalePrice = $nationSalePriceResult->getData();
  1297. //没有客户id
  1298. if (empty($customerId)) {
  1299. return ResultWrapper::success(self::calcMinAndMaxPrice($nationSalePrice));
  1300. }
  1301. //获取商品客户调价
  1302. $customerAdjResult = self::getCustomerAdjByGoodsIds($goodsIds, $customerId);
  1303. if (!$customerAdjResult->isSuccess()) {
  1304. ResultWrapper::fail($customerAdjResult->getData(), $customerAdjResult->getErrorCode());
  1305. }
  1306. $customerAdj = $customerAdjResult->getData();
  1307. //计算客户调价
  1308. foreach ($nationSalePrice as $goodsId => $salePrice) {
  1309. foreach ($salePrice as $skuId => $row) {
  1310. if (isset($customerAdj[$goodsId][$skuId])) {
  1311. $nowCustomerAdj = array_shift($customerAdj[$goodsId][$skuId]);//sku调价信息
  1312. $result = self::commonPriceData($nowCustomerAdj, $nationSalePrice[$goodsId][$skuId], $skuId, $isHaveSkuIds);
  1313. $nationSalePrice[$goodsId][$skuId]['salePrice'] = $result['salePrice'];
  1314. $nationSalePrice[$goodsId][$skuId]['marketPrice'] = $result['marketPrice'];
  1315. $nationSalePrice[$goodsId][$skuId]['ladderPrice'] = $result['ladderPrice'];
  1316. $isHaveSkuIds = $result['skuIds'];
  1317. }
  1318. }
  1319. }
  1320. //查询当前客户的客户类型是否有特殊调价
  1321. $objDCustomer = new DCustomer();
  1322. $objDCustomer->setTable('qianniao_customer_' . $this->onlineEnterpriseId);
  1323. $customer = $objDCustomer->get(['id' => $customerId], 'id,type,name');
  1324. if ($customer === false) {
  1325. return ResultWrapper::fail($customer->error(), ErrorCode::$dberror);
  1326. }
  1327. $customerType = $customer['type'];//客户类型
  1328. //获取客户类型调价
  1329. if (!empty($customerType)){
  1330. $customerTypeAdjResult = self::getCustomerTypeAdjByGoodsIds($goodsIds, $customerType);
  1331. if (!$customerTypeAdjResult->isSuccess()) {
  1332. return ResultWrapper::fail($customerTypeAdjResult->getData(), $customerTypeAdjResult->getErrorCode());
  1333. }
  1334. $customerTypeAdj = $customerTypeAdjResult->getData();
  1335. //计算客户类型调价
  1336. foreach ($nationSalePrice as $goodsId => $salePrice) {
  1337. foreach ($salePrice as $skuId => $row) {
  1338. if (isset($customerTypeAdj[$goodsId][$skuId])) {
  1339. // skuid 有客户调价以后,客户类型就不调价了
  1340. if(in_array($skuId, $isHaveSkuIds)){
  1341. continue;
  1342. }
  1343. $nowCustomerTypeAdj = array_shift($customerTypeAdj[$goodsId][$skuId]);
  1344. $result = self::commonPriceData($nowCustomerTypeAdj, $nationSalePrice[$goodsId][$skuId], $skuId,$isHaveSkuIds);
  1345. $nationSalePrice[$goodsId][$skuId]['salePrice'] = $result['salePrice'];
  1346. $nationSalePrice[$goodsId][$skuId]['marketPrice'] = $result['marketPrice'];
  1347. $nationSalePrice[$goodsId][$skuId]['ladderPrice'] = $result['ladderPrice'];
  1348. }
  1349. }
  1350. }
  1351. }
  1352. if($haveActivity){
  1353. //查询商品活动价
  1354. $activityPriceResult = self::getActivityPriceByGoodsIds($goodsIds,$customerType);
  1355. if (!$activityPriceResult->isSuccess()){
  1356. return ResultWrapper::fail($activityPriceResult->getData(), $activityPriceResult->getErrorCode());
  1357. }
  1358. $activityPrice = $activityPriceResult->getData();
  1359. //计算商品活动价 和 计算属性最小单位展示价格
  1360. foreach ($nationSalePrice as $goodsId => $salePrice){
  1361. foreach ($salePrice as $skuId => $row){
  1362. if (isset($activityPrice[$goodsId][$skuId])){
  1363. $nationSalePrice[$goodsId][$skuId]['salePrice'] = $activityPrice[$goodsId][$skuId]['salePrice'];
  1364. }
  1365. if(isset($nationSalePrice[$goodsId][$skuId]['minUnitPriceConvert']) && !empty($nationSalePrice[$goodsId][$skuId]['minUnitPriceConvert'])){
  1366. $nationSalePrice[$goodsId][$skuId]['minUnitPrice'] = bcdiv($nationSalePrice[$goodsId][$skuId]['salePrice'], $nationSalePrice[$goodsId][$skuId]['minUnitPriceConvert'], 2);
  1367. }
  1368. }
  1369. }
  1370. }
  1371. return ResultWrapper::success(self::calcMinAndMaxPrice($nationSalePrice));
  1372. }
  1373. /**
  1374. * 统一加减乘操作
  1375. */
  1376. public function commonPriceData($priceData, $nationSalePrice, $skuId, $isHaveSkuIds =[])
  1377. {
  1378. if(in_array($skuId, $isHaveSkuIds)){
  1379. return [
  1380. 'minSalePrice' => $priceData['salePrice'],
  1381. 'skuIds' => $isHaveSkuIds
  1382. ];
  1383. }
  1384. // 如果有阶梯价
  1385. if ( isset($priceData['ladderPrice']) && !empty($priceData['ladderPrice']) ){
  1386. foreach ($priceData['ladderPrice'] as $k => $v){
  1387. $beforePrice = $nationSalePrice['ladderPrice'][$k]['price'];
  1388. // 根据标识判断做对应处理
  1389. switch (intval($v['adjPricetag'])){
  1390. case 1: // 减法
  1391. $priceData['ladderPrice'][$k]['price'] = bcsub($beforePrice,$v['adjPrice'],2);
  1392. break;
  1393. case 2: // 加法
  1394. $priceData['ladderPrice'][$k]['price'] = bcadd($beforePrice,$v['adjPrice'],2);
  1395. break;
  1396. case 3: // 乘法
  1397. $priceData['ladderPrice'][$k]['price'] = bcmul($beforePrice,$v['adjPrice'],2);
  1398. break;
  1399. }
  1400. }
  1401. }else{
  1402. $beforeSalePrice = $nationSalePrice['salePrice']; //处理前销售价格
  1403. $beforeMarketPrice = $nationSalePrice['marketPrice']; //处理前市场价格
  1404. // 根据标识判断做对应处理
  1405. switch (intval($priceData['adjPricetag'])){
  1406. case 1: // 减法
  1407. $priceData['salePrice'] = bcsub($beforeSalePrice,$priceData['price'],2);
  1408. $priceData['marketPrice'] = bcsub($beforeMarketPrice,$priceData['price'],2);
  1409. break;
  1410. case 2: // 加法
  1411. $priceData['salePrice'] = bcadd($beforeSalePrice,$priceData['price'],2);
  1412. $priceData['marketPrice'] = bcadd($beforeMarketPrice,$priceData['price'],2);
  1413. break;
  1414. case 3: // 乘法
  1415. $priceData['salePrice'] = bcmul($beforeSalePrice,$priceData['price'],2);
  1416. $priceData['marketPrice'] = bcmul($beforeMarketPrice,$priceData['price'],2);
  1417. break;
  1418. }
  1419. }
  1420. $isHaveSkuIds[] = $skuId;
  1421. return [
  1422. 'ladderPrice' => $priceData['ladderPrice'],
  1423. 'salePrice' => $priceData['salePrice'],
  1424. 'marketPrice' => $priceData['marketPrice'],
  1425. 'skuIds' => $isHaveSkuIds
  1426. ];
  1427. }
  1428. /**
  1429. * 计算最高最低价
  1430. * $data 商品价格数据
  1431. * @param array $data
  1432. * @return array
  1433. */
  1434. public static function calcMinAndMaxPrice(array $data)
  1435. {
  1436. $Mapping = [];
  1437. if (empty($data)) {
  1438. return $Mapping;
  1439. }
  1440. foreach ($data as $goodsId => $item) {
  1441. // 初始化字段默认值
  1442. $Mapping[$goodsId] = [
  1443. 'minSalePrice' => '0.00',
  1444. 'maxSalePrice' => '0.00',
  1445. 'minMarketPrice' => '0.00',
  1446. 'maxMarketPrice' => '0.00',
  1447. 'minMemberPrice' => '0.0',
  1448. 'maxMemberPrice' => '0.0',
  1449. 'minMinUnitPrice' => '0.0',
  1450. 'maxMinUnitPrice' => '0.0',
  1451. ];
  1452. if (empty($item)){
  1453. continue;
  1454. }
  1455. $memberPrice = [];
  1456. $salePrices = [];
  1457. $marketPrices = [];
  1458. $minUnitPrice = [];
  1459. // skuId维度提取所有价格
  1460. foreach ($item as $key => $value){
  1461. if($value['enabledLadder'] && isset($value['ladderPrice']) && !empty($value['ladderPrice'])){
  1462. $salePrices[] = array_column($value['ladderPrice'], 'price');
  1463. }else{
  1464. $salePrices[] = $value['salePrice'];
  1465. $marketPrices[] = $value['marketPrice'];
  1466. $memberPrice[] = getArrayItem($value,'memberPrice',0);
  1467. $minUnitPrice[] = getArrayItem($value,'minUnitPrice',0);
  1468. }
  1469. }
  1470. // 提取所有的销售价
  1471. $allSalePrices = [];
  1472. foreach ($salePrices as $key => $price){
  1473. if (empty($price)){
  1474. unset($salePrices[$key]);
  1475. }
  1476. if(is_array($price)){
  1477. foreach ($price as $k => $v){
  1478. $allSalePrices[] = $v;
  1479. }
  1480. }else{
  1481. $allSalePrices[] = $price;
  1482. }
  1483. }
  1484. foreach ($allSalePrices as $index => $price){
  1485. if (empty($price)){
  1486. unset($allSalePrices[$index]);
  1487. }
  1488. }
  1489. // 提取所有的市场价
  1490. $allMarketPrices = [];
  1491. foreach ($marketPrices as $kk => $vv){
  1492. if (empty($vv)){
  1493. unset($marketPrices[$kk]);
  1494. continue;
  1495. }
  1496. $allMarketPrices[] = $vv;
  1497. }
  1498. // 提取所有的会员价
  1499. $allMemberPrices = [];
  1500. foreach ($memberPrice as $kk => $vv){
  1501. if (empty($vv)){
  1502. unset($memberPrice[$kk]);
  1503. continue;
  1504. }
  1505. $allMemberPrices[] = $vv;
  1506. }
  1507. // 提取所有的属性最小单位展示价
  1508. $allMinUnitPricePrices = [];
  1509. foreach ($minUnitPrice as $kk => $vv){
  1510. if (empty($vv)){
  1511. unset($allMinUnitPricePrices[$kk]);
  1512. continue;
  1513. }
  1514. $allMinUnitPricePrices[] = $vv;
  1515. }
  1516. if (!empty($allSalePrices)){
  1517. $allSalePrices = array_values($allSalePrices);
  1518. $Mapping[$goodsId]['minSalePrice'] = sprintf('%.2f', min($allSalePrices)) ? sprintf('%.2f', min($allSalePrices)) : 0.00;
  1519. $Mapping[$goodsId]['maxSalePrice'] = sprintf('%.2f', max($allSalePrices)) ? sprintf('%.2f', max($allSalePrices)) : 0.00;
  1520. }
  1521. if (!empty($allMarketPrices)){
  1522. $allMarketPrices = array_values($allMarketPrices);
  1523. $Mapping[$goodsId]['minMarketPrice'] = sprintf('%.2f', min($allMarketPrices)) ? sprintf('%.2f', min($allMarketPrices)) : 0.00;
  1524. $Mapping[$goodsId]['maxMarketPrice'] = sprintf('%.2f', max($allMarketPrices)) ? sprintf('%.2f', max($allMarketPrices)) : 0.00;
  1525. }
  1526. if(!empty($allMemberPrices)){
  1527. $allMemberPrices = array_values($allMemberPrices);
  1528. $Mapping[$goodsId]['minMemberPrice'] = sprintf('%.2f', min($allMemberPrices)) ? sprintf('%.2f', min($allMemberPrices)) : 0.00;
  1529. $Mapping[$goodsId]['maxMemberPrice'] = sprintf('%.2f', max($allMemberPrices)) ? sprintf('%.2f', max($allMemberPrices)) : 0.00;
  1530. }
  1531. if(!empty($allMinUnitPricePrices)){
  1532. $allMinUnitPricePrices = array_values($allMinUnitPricePrices);
  1533. $Mapping[$goodsId]['minMinUnitPrice'] = sprintf('%.2f', min($allMinUnitPricePrices)) ? sprintf('%.2f', min($allMinUnitPricePrices)) : 0.00;
  1534. $Mapping[$goodsId]['maxMinUnitPrice'] = sprintf('%.2f', max($allMinUnitPricePrices)) ? sprintf('%.2f', max($allMinUnitPricePrices)) : 0.00;
  1535. }
  1536. }
  1537. return $Mapping;
  1538. }
  1539. /**
  1540. * 获取nation价格信息 mapping
  1541. * @param array $goodsIds
  1542. * @return ResultWrapper
  1543. * @throws \Exception
  1544. */
  1545. public function getNationSalePriceByGoodsIds(array $goodsIds)
  1546. {
  1547. $objPriceCache = new PriceCache($this->onlineEnterpriseId);
  1548. $mapping = [];
  1549. if (empty($goodsIds)) {
  1550. return ResultWrapper::success($mapping);
  1551. }
  1552. //查询缓存
  1553. $needSelectGoodsIds = [];//需要查询
  1554. foreach ($goodsIds as $goodsId) {
  1555. $salePrice = $objPriceCache->getNationSalePrice($goodsId);
  1556. if (empty($salePrice)) {
  1557. $needSelectGoodsIds[] = $goodsId;
  1558. continue;
  1559. }
  1560. $mapping[$goodsId] = $salePrice;
  1561. }
  1562. //缓存中没有,查询数据库
  1563. if (!empty($needSelectGoodsIds)) {
  1564. $objDNationalUnifiedPrice = new DNationalUnifiedPrice();
  1565. $objDNationalUnifiedPrice->setTable('qianniao_nationalUnifiedPrice_' . $this->onlineEnterpriseId);
  1566. $nationalResult = $objDNationalUnifiedPrice->select(['goodsId' => $needSelectGoodsIds], 'id,goodsId,salePrice');
  1567. if ($nationalResult === false) {
  1568. return ResultWrapper::fail($objDNationalUnifiedPrice->error(), ErrorCode::$dberror);
  1569. }
  1570. foreach ($nationalResult as $item) {
  1571. $mapping[$item['goodsId']] = json_decode($item['salePrice'], true);
  1572. //写入缓存
  1573. $objPriceCache->setNationSalePrice($item['goodsId'], json_decode($item['salePrice'], true));
  1574. }
  1575. }
  1576. $mapping = self::formatPriceSku($mapping);
  1577. return ResultWrapper::success($mapping);
  1578. }
  1579. /**
  1580. * 获取客户调价信息 mapping
  1581. * @param array $goodsIds
  1582. * @param int $customerId
  1583. * @return ResultWrapper
  1584. * @throws \Exception
  1585. */
  1586. public function getCustomerAdjByGoodsIds(array $goodsIds, int $customerId)
  1587. {
  1588. $mapping = [];
  1589. $objPriceCache = new PriceCache($this->onlineEnterpriseId);
  1590. if (empty($goodsIds)) {
  1591. return ResultWrapper::success($mapping);
  1592. }
  1593. //查询缓存
  1594. $needSelectGoodsIds = [];
  1595. foreach ($goodsIds as $goodsId) {
  1596. $salePrice = $objPriceCache->getCustomerAdj($goodsId, $customerId);
  1597. if (empty($salePrice)) {
  1598. //缓存中没有
  1599. $needSelectGoodsIds[] = $goodsId;//需要查询
  1600. continue;
  1601. }
  1602. $mapping[$goodsId] = $salePrice;
  1603. }
  1604. //需要查询查询数据库
  1605. if (!empty($needSelectGoodsIds)) {
  1606. $objDCustomerPriceEffective = new DCustomerPriceEffective();
  1607. $objDCustomerPriceEffective->setTable('qianniao_customerPriceEffective_' . $this->onlineEnterpriseId);
  1608. $customerAdjResult = $objDCustomerPriceEffective->select(['goodsId' => $goodsIds, 'customerId' => $customerId], 'id,goodsId,salePrice');
  1609. if ($customerAdjResult === false) {
  1610. return ResultWrapper::fail($objDCustomerPriceEffective->error(), ErrorCode::$dberror);
  1611. }
  1612. foreach ($customerAdjResult as $item) {
  1613. $salePrice = json_decode($item['salePrice'], true);
  1614. $salePriceMapping = [];
  1615. foreach ($salePrice as $value) {
  1616. $salePriceMapping[$value['skuId']][] = $value;
  1617. }
  1618. $mapping[$item['goodsId']] = $salePriceMapping;
  1619. //写入缓存
  1620. $objPriceCache->setCustomerAdj($item['goodsId'], $customerId, $salePriceMapping);
  1621. }
  1622. }
  1623. return ResultWrapper::success($mapping);
  1624. }
  1625. /**
  1626. * 获取客户类型调价信息 mapping
  1627. * @param array $goodsIds
  1628. * @param int $customerType
  1629. * @return ResultWrapper
  1630. * @throws \Exception
  1631. */
  1632. public function getCustomerTypeAdjByGoodsIds(array $goodsIds, int $customerType)
  1633. {
  1634. $mapping = [];
  1635. $objPriceCache = new PriceCache($this->onlineEnterpriseId);
  1636. if (empty($goodsIds)) {
  1637. return ResultWrapper::success($mapping);
  1638. }
  1639. //查询缓存
  1640. $needSelectGoodsIds = [];
  1641. foreach ($goodsIds as $goodsId) {
  1642. $salePrice = $objPriceCache->getCustomerTypeAdj($goodsId, $customerType);
  1643. if (empty($salePrice)) {
  1644. //缓存中没有
  1645. $needSelectGoodsIds[] = $goodsId;//需要查询
  1646. continue;
  1647. }
  1648. $mapping[$goodsId] = $salePrice;
  1649. }
  1650. //查询数据库
  1651. if (!empty($needSelectGoodsIds)) {
  1652. $objDCustomerTypePriceEffective = new DCustomerTypePriceEffective();
  1653. $objDCustomerTypePriceEffective->setTable('qianniao_customerTypePriceEffective_' . $this->onlineEnterpriseId);
  1654. $customerTypeAdjResult = $objDCustomerTypePriceEffective->select(['goodsId' => $goodsIds, 'customerType' => $customerType]);
  1655. if ($customerTypeAdjResult === false) {
  1656. return ResultWrapper::fail($objDCustomerTypePriceEffective->error(), ErrorCode::$dberror);
  1657. }
  1658. foreach ($customerTypeAdjResult as $item) {
  1659. $salePrice = json_decode($item['salePrice'], true);
  1660. $salePriceMapping = [];
  1661. foreach ($salePrice as $value) {
  1662. $salePriceMapping[$value['skuId']][] = $value;
  1663. }
  1664. $mapping[$item['goodsId']] = $salePriceMapping;
  1665. //写入缓存
  1666. $objPriceCache->setCustomerTypeAdj($item['goodsId'], $customerType, $salePriceMapping);
  1667. }
  1668. }
  1669. return ResultWrapper::success($mapping);
  1670. }
  1671. /**
  1672. * 获取商品活动价格信息
  1673. * @param array $goodsIds
  1674. * @param int $customerType
  1675. * @return ResultWrapper
  1676. * @throws \Exception
  1677. */
  1678. public function getActivityPriceByGoodsIds(array $goodsIds,$customerType)
  1679. {
  1680. $mapping = [];
  1681. $objMActivity = new MActivity($this->onlineUserId,$this->onlineEnterpriseId);
  1682. //获取促销活动价格
  1683. $dbResult = $objMActivity->getActivity([
  1684. 'goodsId' => rtrim(implode(',', $goodsIds),','),
  1685. 'customerType' => $customerType,
  1686. ]);
  1687. if (!$dbResult->isSuccess()){
  1688. return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode());
  1689. }
  1690. $activityPrice = $dbResult->getData();
  1691. foreach ($activityPrice as $item){
  1692. $mapping[$item['goodsId']] = [
  1693. $item['skuId'] => [
  1694. 'skuId' => $item['skuId'],
  1695. 'salePrice' => $item['price']
  1696. ]
  1697. ];
  1698. }
  1699. return ResultWrapper::success($mapping);
  1700. }
  1701. public function formatPriceSku($data)
  1702. {
  1703. $skuIds = [];
  1704. foreach ($data as $val){
  1705. foreach ($val as $skuId => $value){
  1706. $skuIds [] = $skuId;
  1707. }
  1708. }
  1709. $objDSku = new DSku();
  1710. $objDSku->setTable('qianniao_sku_'.$this->onlineEnterpriseId);
  1711. $dbResult = $objDSku->select(['id'=>$skuIds,'deleteStatus'=>StatusCode::$standard],'id');
  1712. if ($dbResult === false){
  1713. Logger::logs(E_USER_ERROR,'查询sku错误',__CLASS__,__LINE__,$objDSku->error());
  1714. return $data;
  1715. }
  1716. $allSkuIds = array_column($dbResult,'id');
  1717. foreach ($data as $goodsId => &$val){
  1718. foreach ($val as $skuId => $value){
  1719. if (!in_array($skuId,$allSkuIds)){
  1720. unset($val[$skuId]);
  1721. }
  1722. }
  1723. }
  1724. return $data;
  1725. }
  1726. /**
  1727. * Doc: (des="获取商品的最近调价")
  1728. * User: XMing
  1729. * Date: 2021/3/11
  1730. * Time: 9:50 上午
  1731. * @param int $shopId
  1732. * @param int $goodsId
  1733. * @param string $date
  1734. * @return ResultWrapper
  1735. * @throws \Exception
  1736. */
  1737. public function getPriceSheetByShopIdRelGoodsId(int $shopId,int $goodsId,int $date): ResultWrapper
  1738. {
  1739. $y = date('Y',$date);
  1740. $m = date('m',$date);
  1741. $this->objDPriceAdjustment->setTable('qianniao_priceAdjustmentSheet_' . $this->onlineEnterpriseId . '_' . $y . '_' . ceil($m / 3));
  1742. $sql = 'SELECT `salePrice`,`createTime` FROM '.$this->objDPriceAdjustment->get_Table().' WHERE shopId = '.$shopId.' AND goodsId = '.$goodsId;
  1743. $sql .= ' AND createTime <= '.$date;
  1744. $lists = $this->objDPriceAdjustment->query($sql);
  1745. if ($lists === false){
  1746. Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDPriceAdjustment->error());
  1747. return ResultWrapper::fail($this->objDPriceAdjustment->error(),ErrorCode::$dberror);
  1748. }
  1749. if (empty($lists)){
  1750. $date = strtotime(date('Y-m-d 23:59:59',strtotime("-1 days")));
  1751. $y = date('Y',$date);
  1752. $m = date('m',$date);
  1753. $this->objDPriceAdjustment->setTable('qianniao_priceAdjustmentSheet_' . $this->onlineEnterpriseId . '_' . $y . '_' . ceil($m / 3));
  1754. $sql = 'SELECT `salePrice`,`createTime` FROM '.$this->objDPriceAdjustment->get_Table().' WHERE shopId = '.$shopId.' AND goodsId = '.$goodsId;
  1755. $sql .= ' AND createTime <= '.$date;
  1756. $lists = $this->objDPriceAdjustment->query($sql);
  1757. if ($lists === false){
  1758. Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDPriceAdjustment->error());
  1759. return ResultWrapper::fail($this->objDPriceAdjustment->error(),ErrorCode::$dberror);
  1760. }
  1761. }
  1762. foreach ($lists as &$item){
  1763. $item['salePrice'] = empty($item['salePrice']) ? [] : json_decode($item['salePrice'],true);
  1764. }
  1765. $row = array_shift($lists);
  1766. return ResultWrapper::success($row);
  1767. }
  1768. /**
  1769. * 计算阶梯价公共方法
  1770. * @params array $ladderPrice 阶梯价数据
  1771. * @params float $salePrice 销售价
  1772. * @params float $buyNum 购买数量
  1773. * @return float
  1774. */
  1775. public function getLadderPriceCommon($ladderPrice, $salePrice, $buyNum, $enabledLadder)
  1776. {
  1777. if( empty($ladderPrice) || !$enabledLadder){
  1778. return $salePrice;
  1779. }
  1780. foreach ($ladderPrice as $key => $value){
  1781. if($buyNum >= $value['from'] && $buyNum <= $value['to']){
  1782. return $value['price'];
  1783. }
  1784. }
  1785. return 0.00;
  1786. }
  1787. }