12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072 |
- <?php
- /**
- * Created by PhpStorm.
- * User: phperstar
- * Date: 2019/5/9
- * Time: 3:10 PM
- */
- namespace JinDouYun\Model\Price;
- use JinDouYun\Cache\PriceCache;
- use JinDouYun\Controller\Common\Logger;
- use JinDouYun\Dao\Customer\DCustomer;
- use JinDouYun\Dao\Goods\DGoods;
- use JinDouYun\Dao\GoodsManage\DSku;
- use JinDouYun\Dao\Price\DCustomerPriceEffective;
- use JinDouYun\Dao\Price\DCustomerTypePriceEffective;
- use JinDouYun\Dao\Price\DPriceRangeSheet;
- use JinDouYun\Model\Customer\MCustomer;
- use JinDouYun\Model\Market\MActivity;
- use Mall\Framework\Core\ResultWrapper;
- use Mall\Framework\Core\ErrorCode;
- use Mall\Framework\Core\StatusCode;
- use JinDouYun\Model\GoodsManage\MGoodsBasic;
- use JinDouYun\Model\MBaseModel;
- use JinDouYun\Model\Goods\MGoods;
- use JinDouYun\Dao\Price\DPriceAdjustment;
- use JinDouYun\Dao\Price\DNationalUnifiedPrice;
- use JinDouYun\Dao\Price\DLastEffectiveSalePriceAreaType;
- use JinDouYun\Dao\Price\DAreaPrice;
- class MPrice extends MBaseModel
- {
- /**
- * @var int
- */
- private $onlineUserId;
- /**
- * @var int
- */
- private $onlineEnterpriseId;
- /**
- * @var DPriceAdjustment
- */
- private $objDPriceAdjustment;
- /**
- * @var DPriceRangeSheet
- */
- private $objDPriceRangeSheet;
- /**
- * @var $readCache boolean 是否读取缓存
- */
- private static $readCache = false;
- /**
- * MPrice constructor.
- * @param $onlineUserId
- * @param $onlineEnterpriseId
- * @throws \Exception
- */
- public function __construct($onlineUserId, $onlineEnterpriseId)
- {
- $this->onlineUserId = $onlineUserId;
- $this->onlineEnterpriseId = $onlineEnterpriseId;
- parent::__construct($this->onlineEnterpriseId, $this->onlineUserId);
- $this->objDPriceAdjustment = new DPriceAdjustment();
- $this->objDPriceRangeSheet = new DPriceRangeSheet();
- $this->objDPriceAdjustment->setSearchIndex('goods_search')->setType('goods');
- }
- /**
- * 批量调价
- * 批量调价基于基本的运算公式进行调价,举例一个商品的销售价格是100元。通过批量调价,订货价=销售价-1,那么结果就是 98(订货价)=99(销售价 salePrice)-1(调价数字)
- * @param $params
- * @return ResultWrapper
- * @throws \Exception
- */
- public function batchPrice($params)
- {
- $objDNationalUnifiedPrice = new DNationalUnifiedPrice();
- $objDNationalUnifiedPrice->setTable($objDNationalUnifiedPrice->get_Table() . '_' . $this->onlineEnterpriseId);
- //批量获取这些商品的原提交单
- $rows = $params['rows'];
- $oldResult = $objDNationalUnifiedPrice->select(['goodsId' => array_column($rows, 'goodsId'), 'shopId' => array_column($rows, 'shopId')]);
- if ($oldResult === false) {
- return ResultWrapper::fail($objDNationalUnifiedPrice->error(), ErrorCode::$dberror);
- }
- if (empty($oldResult)) {
- return ResultWrapper::fail('未获取到调价数据', ErrorCode::$dberror);
- }
- //在原数据上进行修改
- foreach ($oldResult as $key => $value) {
- $salePrice = json_decode($value['salePrice'], true);
- foreach ($salePrice as $k => &$v) {
- $v['salePrice'] = self::calc($v['salePrice'], $params['sales']['float'], $params['sales']['adj']);
- if ($v['enabledLadder']) {
- foreach ($v['ladderPrice'] as &$ladder) {
- //对阶梯价进行操作
- $ladder['price'] = self::calc($ladder['price'], $params['ladder']['float'], $params['ladder']['adj']);
- }
- }
- }
- $oldResult[$key]['salePrice'] = json_encode($salePrice);
- }
- $log = [
- 'origin' => $oldResult,
- 'action' => $params,
- ];
- //保存修改
- $dbResult = $objDNationalUnifiedPrice->replace($oldResult, true);
- if ($dbResult === false) {
- return ResultWrapper::fail($objDNationalUnifiedPrice->error(), ErrorCode::$dberror);
- }
- self::saveLog([
- 'userCenterId' => $this->onlineUserId,
- 'enterpriseId' => $this->onlineEnterpriseId,
- 'createTime' => time(),
- 'no' => '',
- 'actionType' => '批量调价',
- 'operationData' => $log,
- ]);
- return ResultWrapper::success($dbResult);
- }
- /**
- * 批量调价日志
- * Overrides
- * @param $data
- */
- public static function saveLog($data)
- {
- $i = 1;
- do {
- $postData = [
- 'topicName' => 'MyJob',
- 'topicClass' => 'Jobs\Model\MTopic\Log\MPriceLog',
- 'topicMethon' => 'push',
- 'topicMethonParams' => [
- 'userCenterId' => $data['userCenterId'],
- 'enterpriseId' => $data['enterpriseId'],
- 'createTime' => $data['createTime'],//操作时间
- 'no' => $data['no'], // 如:单据编号D563875634856 订单编号N42332435435
- 'actionType' => $data['actionType'], //批量调价
- 'operationData' => $data['operationData'], //本次操作请求的数据(可空) json格式
- ],
- ];
- $url = QIANNIAO_QUEUE . '/CAddJob/add';
- $result = request($url, $postData);
- $i++;
- } while ($result['httpcode'] != 200 && $i <= 3);
- }
- /**
- * @param $origin
- * @param $float
- * @param $adj
- * @param int $scale
- * @return string
- */
- private static function calc($origin, $float, $adj, $scale = 4)
- {
- $res = 0;
- switch ($adj) {
- case '+'://加法
- $res = bcadd($origin, $float, $scale);
- break;
- case '-'://减法
- $res = bcsub($origin, $float, $scale);
- break;
- case '*'://乘法
- $res = bcmul($origin, $float, $scale);
- break;
- case '/'://除法
- $res = bcdiv($origin, $float, $scale);
- break;
- default:
- $res = 0;
- break;
- }
- return $res;
- }
- /**
- * 根据用户定位批量获取指定物料价格
- * @param $params
- * @param bool $returnAll
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getPrice($params, $returnAll = false)
- {
- // 初始化所有物料价格
- $returnData = [];
- $allShopIds = []; // 所有店铺ids
- $allGoodsId = []; // 所有商品ids
- foreach ($params['material'] as $key => $value) {
- $returnData[$key] = (object)[];
- $allGoodsId = array_merge($value, $allGoodsId);
- $allShopIds[] = $key;
- }
- // 批量获取这批物料最后生效的价格销售区域类型
- $objDLastEffectiveSalePriceAreaType = new DLastEffectiveSalePriceAreaType();
- $objDLastEffectiveSalePriceAreaType->setTable('qianniao_lastEffectiveSalePriceAreaType_' . $this->onlineEnterpriseId);
- $condition = [
- 'goodsId' => array_values(array_unique($allGoodsId)),
- 'shopId' => array_values(array_unique($allShopIds)),
- ];
- $dbResult = $objDLastEffectiveSalePriceAreaType->select($condition, 'lastEffectiveSalePriceAreaType,goodsId,shopId');
- if ($dbResult === false) {
- return ResultWrapper::fail($objDLastEffectiveSalePriceAreaType->error(), ErrorCode::$dberror);
- }
- if (empty($dbResult)) {
- return ResultWrapper::success([]);
- }
- // 进行生效价格区域类型分组
- $materieLastEffectiveSalePriceAreaType = [];
- foreach ($dbResult as $k => $v) {
- $materieLastEffectiveSalePriceAreaType[$v['lastEffectiveSalePriceAreaType']][$v['shopId']][] = $v['goodsId'];
- }
- // 按组获取组内各物料的价格
- $newmaterielPriceData = [];
- foreach ($materieLastEffectiveSalePriceAreaType as $k => $v) {
- switch ($k) {
- case StatusCode::$salePriceAreaType['nationalUnifiedPrice']:
- $materielPriceData = self::getNationalUnifiedPrice($materieLastEffectiveSalePriceAreaType[StatusCode::$salePriceAreaType['nationalUnifiedPrice']]);
- break;
- case StatusCode::$salePriceAreaType['areaPrice']:
- $materielPriceData = self::getAreaPrice($materieLastEffectiveSalePriceAreaType[StatusCode::$salePriceAreaType['areaPrice']], $params, false);
- break;
- }
- if (!$materielPriceData->isSuccess()) {
- return ResultWrapper::fail($materielPriceData->getData(), $materielPriceData->getErrorCode());
- }
- $materielPriceData = $materielPriceData->getData();
- foreach ($materielPriceData as $key => $value) {
- foreach ($value as $a => $b) {
- $newmaterielPriceData[$key][$a] = !empty($b) ? $b : (object)[];
- }
- }
- }
- // 查询客户调价单当前客户是否有特殊调价
- if (!isset($params['customerId'])) {
- return ResultWrapper::success($newmaterielPriceData);
- }
- //查询当前客户的客户类型是否有特殊调价
- $objDCustomer = new DCustomer();
- $objDCustomer->setTable('qianniao_customer_' . $this->onlineEnterpriseId);
- $customer = $objDCustomer->get(['id' => $params['customerId']], 'id,type,name');
- if ($customer === false) {
- return ResultWrapper::fail($objDCustomer->error(), ErrorCode::$dberror);
- }
- if (empty($customer['type'])) {
- //客户未设置客户类型
- return ResultWrapper::success($newmaterielPriceData);
- }
- $customerType = $customer['type'];//客户类型
- // 获取指定商品指定类型指定店铺下的客户类型调价数据
- $shopBindGoddsIds = [];
- foreach ($newmaterielPriceData as $key => $value){ // 店铺维度循环
- foreach ($value as $k => $v){ // 店铺下商品维度
- $shopBindGoddsIds[$key][] = $k;
- }
- }
- if(empty($shopBindGoddsIds)){
- return ResultWrapper::success($newmaterielPriceData);
- }
- // 获取对应商品的客户类型调价数据
- $objMCustomerTypePriceAdjustment = new MCustomerTypePriceAdjustment($this->onlineUserId, $this->onlineEnterpriseId);
- $objMCustomerPriceAdjustment = new MCustomerPriceAdjustment($this->onlineUserId, $this->onlineEnterpriseId);
- foreach ($shopBindGoddsIds as $shopkey => $goodsvalue){
- if(empty($shopBindGoddsIds[$shopkey])){
- continue;
- }
- // 查询客户价格数据
- $result = $objMCustomerPriceAdjustment->getCustomerPriceByIds($key, $params['customerId'], $shopBindGoddsIds[$shopkey]);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $customerPrice = $result->getData();
- if (!empty($customerPrice)) {
- $returnData = self::commonSpecailData($customerPrice, $newmaterielPriceData, $shopkey, []);
- $newmaterielPriceData = $returnData['data'];
- continue;
- }
- // 查询客户类型价格数据
- unset($result);
- $result = $objMCustomerTypePriceAdjustment->getCustomerTypePriceByIds($shopkey, $customerType, $shopBindGoddsIds[$shopkey]);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $customerTypePrice = $result->getData();
- if (empty($customerTypePrice)) {
- continue;
- }
- $returnData = self::commonSpecailData($customerTypePrice, $newmaterielPriceData, $shopkey, $returnData['skuIds']);
- $newmaterielPriceData = $returnData['data'];
- }
- return ResultWrapper::success($newmaterielPriceData);
- }
- /**
- * 统一加减乘操作
- */
- public function commonSpecailData($priceData, $newmaterielPriceData, $shopkey, $isHaveSkuIds =[])
- {
- // 循环客户类型调价数据对返回的价格数据处理
- foreach ($priceData as $customerTypePriceKey => $customerTypePriceValue){
- // 处理返回数据价格
- $salePrice = json_decode($customerTypePriceValue['salePrice'], true);
- // 按照skuid维度进行价格处理
- foreach ($salePrice as $key => $value){
- if(in_array($value['skuId'], $isHaveSkuIds)){
- continue;
- }
- // 如果有阶梯价
- if ( isset($value['ladderPrice']) && !empty($value['ladderPrice']) ){
- foreach ($value['ladderPrice'] as $k => $v){
- $beforePrice = $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['ladderPrice'][$k]['price'];
- // 根据标识判断做对应处理
- switch (intval($v['adjPricetag'])){
- case 1: // 减法
- $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['ladderPrice'][$k]['price'] = bcsub($beforePrice,$v['adjPrice'],2);
- break;
- case 2: // 加法
- $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['ladderPrice'][$k]['price'] = bcadd($beforePrice,$v['adjPrice'],2);
- break;
- case 3: // 乘法
- $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['ladderPrice'][$k]['price'] = bcmul($beforePrice,$v['adjPrice'],2);
- break;
- }
- }
- }else{
- $beforeSalePrice = $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['salePrice']; //处理前销售价格
- $beforeMarketPrice = $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['marketPrice']; //处理前市场价格
- // 根据标识判断做对应处理
- switch (intval($value['adjPricetag'])){
- case 1: // 减法
- $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['salePrice'] = bcsub($beforeSalePrice,$value['price'],2);
- $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['marketPrice'] = bcsub($beforeMarketPrice,$value['price'],2);
- break;
- case 2: // 加法
- $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['salePrice'] = bcadd($beforeSalePrice,$value['price'],2);
- $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['marketPrice'] = bcadd($beforeMarketPrice,$value['price'],2);
- break;
- case 3: // 乘法
- $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['salePrice'] = bcmul($beforeSalePrice,$value['price'],2);
- $newmaterielPriceData[$shopkey][$customerTypePriceValue['goodsId']][$value['skuId']]['marketPrice'] = bcmul($beforeMarketPrice,$value['price'],2);
- break;
- }
- }
- $isHaveSkuIds[] = $value['skuId'];
- }
- }
- return [
- 'data' => $newmaterielPriceData,
- 'skuIds' => $isHaveSkuIds
- ];
- }
- /**
- * 获取全国标准价
- * @param $materialCodes
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getNationalUnifiedPrice($material)
- {
- $objDNationalUnifiedPrice = new DNationalUnifiedPrice();
- $objDNationalUnifiedPrice->setTable('qianniao_nationalUnifiedPrice_' . $this->onlineEnterpriseId);
- $nationalUnifiedPriceData = [];
- foreach ($material as $key => $value) {
- $goodsIds = array_unique($value);
- foreach ($goodsIds as $k => $v) {
- $dbResult = $objDNationalUnifiedPrice->select(['shopId' => $key, 'goodsId' => $v], 'salePriceType,salePrice');
- if ($dbResult === false) {
- return ResultWrapper::fail($objDNationalUnifiedPrice->error(), ErrorCode::$dberror);
- }
- $nationalUnifiedPriceData[$key][$v] = [];
- if (!empty($dbResult[0]['salePrice'])) {
- $nationalUnifiedPriceData[$key][$v] = self::formatPrice($dbResult[0]['salePriceType'], $dbResult[0]['salePrice']);
- }
- }
- }
- return ResultWrapper::success($nationalUnifiedPriceData);
- }
- /**
- * 获取指定物料指定店铺下对应区域的区域销售价价格
- * @param $materialCodes array 店铺对应的物料编码
- * @param $params array 请求参数
- * @param $returnAll boolean 是否返回所有区域价格
- *
- * @return ResultWrapper
- */
- public function getAreaPrice($materialCodes, $params, $returnAll = false)
- {
- if ($returnAll) {
- return self::getAllAreaPrice($materialCodes, $params);
- }
- $objDAreaPrice = new DAreaPrice();
- // 处理多个店铺下的多个物料
- foreach ($materialCodes as $key => $value) {
- $materialCodes = array_unique($value);
- // 先查询全国价
- foreach ($materialCodes as $k => $v) {
- $areaPriceData[$key][$v] = [];
- $nationalUnifiedPriceParams[$key][] = $v;
- $result = self::getNationalUnifiedPrice($nationalUnifiedPriceParams);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $nationalUnifiedPriceData = $result->getData();
- if (!empty($nationalUnifiedPriceData)) {
- $nationalUnifiedPrice = $nationalUnifiedPriceData[$key][$v];
- $areaPriceData[$key][$v] = $nationalUnifiedPrice;
- }
- }
- // 按照企业分表
- $objDAreaPrice->setTable('qianniao_areaPrice_' . $this->onlineEnterpriseId);
- // 优化一次性取区一级价格 城市一级价格 大区一级价格
- foreach ($materialCodes as $k => $v) {
- $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'];
- $dbResult = $objDAreaPrice->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($objDAreaPrice->error(), ErrorCode::$dberror);
- }
- // 优先生效区一级价格 区一级未定价生效市一级 市一级未定价生效大区价
- if (!empty($dbResult[0])) {
- if (!empty($dbResult[0]['districtSalePrice'])) {
- $areaPriceData[$key][$v] = self::formatPrice($dbResult[0]['salePriceType'], $dbResult[0]['districtSalePrice']);
- unset($materialCodes[$k]);
- continue;
- } else if (!empty($dbResult[0]['citySalePrice'])) {
- $areaPriceData[$key][$v] = self::formatPrice($dbResult[0]['salePriceType'], $dbResult[0]['CitySalePrice']);
- unset($materialCodes[$k]);
- continue;
- } else if (!empty($dbResult[0]['provinceSalePrice'])) {
- $areaPriceData[$key][$v] = self::formatPrice($dbResult[0]['salePriceType'], $dbResult[0]['regionalDepartmentSalePrice']);
- unset($materialCodes[$k]);
- continue;
- }
- }
- }
- }
- return ResultWrapper::success($areaPriceData);
- }
- /**
- * @param $selectParams
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getAllGoodsPrice($selectParams)
- {
- $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId);
- $selectParams = parent::getShopIdQueryParams($selectParams);
- $dbResult = $objMGoods->getAllGoods($selectParams);
- if (!$dbResult->isSuccess()) {
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- $result = $dbResult->getData();
- $goodsData = [];
- $total = 0;
- if (!empty($result)) {
- $goodsData = $result['data'];
- $total = $result['total'];
- }
- $goodsData = self::format($goodsData);
- $return = [
- 'data' => $goodsData,
- 'total' => $total,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 价格管理搜索
- * @param array $selectParams 过滤条件
- * @return ResultWrapper
- * @throws \Exception
- */
- public function search($selectParams)
- {
- $objMGoods = new MGoods($this->onlineEnterpriseId, false, $this->onlineUserId);
- $result = $objMGoods->search($selectParams);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $resultData = $result->getData();
- $return = [
- 'data' => self::format($resultData['data']),
- 'total' => $resultData['total'],
- ];
- return ResultWrapper::success($return);
- }
- /**
- * @param $selectParams
- * @return array|ResultWrapper
- * @throws \Exception
- */
- private function setWhere($selectParams)
- {
- $defaultDSL = [
- 'from' => $selectParams['offset'],
- 'size' => $selectParams['limit'],
- 'sort' => [
- 'sort' => [
- 'order' => 'asc'
- ],
- 'createTime' => [
- 'order' => 'desc'
- ],
- ],
- ];
- $dsl = [];
- $dsl['query']['bool']['must'][] = [
- 'term' => ['enterpriseId' => $this->onlineEnterpriseId],
- ];
- //去ES的basic类型下查找匹配的basicIds
- if (!empty($selectParams['keyword'])
- || !empty($selectParams['categoryId'])
- ) {
- $basicSearchParams = [
- 'keyword' => isset($selectParams['keyword']) ? $selectParams['keyword'] : '',
- 'categoryId' => isset($selectParams['categoryId']) ? $selectParams['categoryId'] : '',
- ];
- $objMGoodsBasic = new MGoodsBasic($this->onlineUserId, $this->onlineEnterpriseId);
- $goodsBasics = $objMGoodsBasic->searchGoodsBasics($basicSearchParams);
- if ($goodsBasics->isSuccess() === false) {
- return ResultWrapper::fail('获取基本资料数据失败' . $goodsBasics['error']['reason'], ErrorCode::$apiNotResult);
- }
- $goodsBasicLists = [];
- $goodsBasicData = $goodsBasics->getData();
- foreach ($goodsBasicData as $goodsBasic) {
- $goodsBasicLists[$goodsBasic['id']] = $goodsBasic;
- }
- $goodsBasicIds = array_keys($goodsBasicLists);
- if (!$goodsBasicIds) {
- return ResultWrapper::success([
- 'data' => [],
- 'total' => 0
- ]);
- }
- $dsl['query']['bool']['must'][] = [
- 'terms' => [
- 'basicGoodsId' => $goodsBasicIds
- ]
- ];
- }
- //按商铺搜索
- if (!empty($selectParams['shopId'])) {
- $dsl['query']['bool']['must'][] = [
- 'term' => ['shopId' => $selectParams['shopId']],
- ];
- }
- $dsl = array_merge($defaultDSL, $dsl);
- return $dsl;
- }
- /**
- * @param $data
- * @return array
- */
- public function format($data)
- {
- if (empty($data)) return $data;
- $return = [];
- foreach ($data as $key => $val) {
- $return[] = [
- 'id' => $val['id'],
- 'code' => $val['code'],
- 'merchantId' => $val['merchantId'],
- 'goodsName' => $val['title'],
- 'categoryName' => $val['categoryName'],
- 'brandName' => $val['brandName'],
- 'enableStatus' => $val['enableStatus'],
- //'skuData' => $val['skuData'],
- //'costPrice' => isset($val['costPrice']) ? $val['costPrice'] : 0,
- 'shopName' => $val['shopName'],
- 'goodsId' => $val['id'],
- 'shopId' => $val['shopId'],
- //'specGroup' => $val['specGroup'],
- //'specMultiple' => $val['specMultiple'],
- 'inventorTotal' => $val['inventorTotal'],
- 'specTotal' => $val['specTotal'],
- 'masterPrice' => isset($val['masterPrice']) ? $val['masterPrice'] : [],
- 'unitData' => isset($val['unitData']) ? $val['unitData'] : []
- ];
- }
- return $return;
- }
- /**
- * 获取指定物料指定店铺下面设置过得大区价格
- * @param $materialCodes array 店铺对应的物料编码
- * @param $params array 请求参数
- * @param $returnAll boolean 是否返回所有区域价格
- *
- * @return ResultWrapper
- */
- public function getAllAreaPrice($materialCodes, $params)
- {
- foreach ($materialCodes as $key => $value) {
- foreach ($value as $k => $v) {
- $allMaterialCodes[] = $v;
- }
- $allShopIds[] = $key;
- }
- // 批量获取这批物料最后生效的价格销售区域类型
- $objDLastEffectiveSalePriceAreaType = new DLastEffectiveSalePriceAreaType();
- $condition = [
- 'marketCode' => $allMaterialCodes,
- 'shopId' => $allShopIds,
- ];
- $dbResult = $objDLastEffectiveSalePriceAreaType->select($condition, 'lastEffectiveSalePriceAreaType,marketCode,shopId');
- if ($dbResult === false) {
- return ResultWrapper::fail($objDLastEffectiveSalePriceAreaType->error(), ErrorCode::$dberror);
- }
- if (empty($dbResult)) {
- return ResultWrapper::success([]);
- }
- // 进行生效价格区域类型分组
- $materieLastEffectiveSalePriceAreaType = [];
- foreach ($dbResult as $k => $v) {
- $materieLastEffectiveSalePriceAreaType[$v['shopId']][$v['marketCode']] = $v['lastEffectiveSalePriceAreaType'];
- }
- $objDAreaPrice = new DAreaPrice();
- foreach ($materialCodes as $key => $value) {
- // 按照店铺分表
- $tableName = 'areaPrice_' . $key;
- $objDAreaPrice->setTable($tableName);
- $materialCodes = array_unique($value);
- foreach ($materialCodes as $k => $v) {
- if (isset($materieLastEffectiveSalePriceAreaType[$key][$v]) && $materieLastEffectiveSalePriceAreaType[$key][$v] == StatusCode::$salePriceAreaType['nationalUnifiedPrice']) {
- $nationalUnifiedPriceParams[$key][] = $v;
- $result = self::getNationalUnifiedPrice($nationalUnifiedPriceParams);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $nationalUnifiedPriceData = $result->getData();
- if (!empty($nationalUnifiedPriceData)) {
- $nationalUnifiedPrice = $nationalUnifiedPriceData[$params['shopId']][$params['marketCode']];
- }
- }
- $sql = 'select salePrice,salePriceType from ' . $tableName . ' where shopId = ' . $key . ' and marketCode = "' . $v . '" and salePriceType =' . StatusCode::$salePriceType['salePrice'];
- $dbResult = $objDAreaPrice->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($objDAreaPrice->error(), ErrorCode::$dberror);
- }
- $areaPriceData[$key][$v] = [];
- if (!empty($dbResult[0]['salePrice'])) {
- // 当前生效的是全国价,替换所有区域价格为全国价
- if (!empty($nationalUnifiedPrice)) {
- $dbResult[0]['salePrice'] = json_decode($dbResult[0]['salePrice'], true);
- foreach ($dbResult[0]['salePrice'] as &$a) {
- foreach ($a as &$b) {
- $b = $nationalUnifiedPrice;
- }
- }
- $dbResult[0]['salePrice'] = json_encode($dbResult[0]['salePrice']);
- }
- $areaPriceData[$key][$v] = self::formatPrice($dbResult[0]['salePriceType'], $dbResult[0]['salePrice']);
- }
- }
- }
- return ResultWrapper::success($areaPriceData);
- }
- /**
- * 同时获取多个大区部门价格数据
- */
- public function getAreaPriceByRegionalDepartmentIds($regionalDepartmentIds = [], $shopId, $marketCode)
- {
- // 按照店铺分表
- $objDAreaPrice = new DAreaPrice();
- $tableName = 'areaPrice_' . $shopId;
- $objDAreaPrice->setTable($tableName);
- $selectFeildStr = '';
- foreach ($regionalDepartmentIds as $key => $value) {
- $selectFeildStr .= 'salePrice->\'$."' . $value . '"."' . $value . '-' . $value . '-' . $value . '"\' as salePrice_' . $value . ',';
- }
- $sql = 'select ' . $selectFeildStr . 'salePriceType from ' . $tableName . ' where shopId = ' . $shopId . ' and marketCode = "' . $marketCode . '" and salePriceType =' . StatusCode::$salePriceType['salePrice'];
- $dbResult = $objDAreaPrice->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($objDAreaPrice->error(), ErrorCode::$dberror);
- }
- if (empty($dbResult)) {
- return ResultWrapper::success([]);
- }
- foreach ($dbResult[0] as $key => $value) {
- if ($key !== 'salePriceType') {
- $dbResult[0][$key] = self::formatPrice($dbResult[0]['salePriceType'], $value);
- }
- }
- return ResultWrapper::success($dbResult[0]);
- }
- /**
- * 同时获取多个物料多个大区部门价格数据
- */
- public function batchGetAreaPriceByRegionalDepartmentIds($regionalDepartmentIds = [], $shopId, $marketCodes = [])
- {
- // 按照店铺分表
- $objDAreaPrice = new DAreaPrice();
- $tableName = 'areaPrice_' . $shopId;
- $objDAreaPrice->setTable($tableName);
- $selectFeildStr = '';
- foreach ($regionalDepartmentIds as $key => $value) {
- $selectFeildStr .= 'salePrice->\'$."' . $value . '"."' . $value . '-' . $value . '-' . $value . '"\' as salePrice_' . $value . ',';
- }
- $sql = 'select ' . $selectFeildStr . 'marketCode from ' . $tableName . ' where shopId = ' . $shopId . ' and marketCode in ("' . implode('","', $marketCodes) . '"' . ') and salePriceType =' . StatusCode::$salePriceType['salePrice'];
- $dbResult = $objDAreaPrice->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($objDAreaPrice->error(), ErrorCode::$dberror);
- }
- if (empty($dbResult)) {
- return ResultWrapper::success([]);
- }
- $returnData = [];
- foreach ($dbResult as $key => $value) {
- foreach ($value as $k => $v) {
- $returnData[$value['marketCode']] = self::formatPrice(StatusCode::$salePriceType['salePrice'], $v);
- }
- }
- return ResultWrapper::success($returnData);
- }
- /**
- * 格式化价格
- */
- public function formatPrice($salePriceType, $salePrice)
- {
- $price = json_decode($salePrice, true);
- return $price;
- }
- /**
- * 根据省市区获取大区价格
- */
- public function getRegionalPriceByArea($materialCodes, $params)
- {
- $objDRegionalDepartmentPrice = new DRegionalDepartmentPrice();
- // 获取省市区在不同店铺下的不同大区id
- $regionalPriceData = [];
- $regionalDepartmentId = 0;
- $objMRegionalManage = new MRegionalManage();
- $result = $objMRegionalManage->getRegionalDepartmentId($params['province'], $params['city'], $params['district']);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $regionalDepartmentData = $result->getData();
- if (empty($regionalDepartmentData)) {
- return ResultWrapper::fail('当前省市区没有对应部门', ErrorCode::$contentNotExists);
- }
- foreach ($regionalDepartmentData as $key => $value) {
- $newRegionalDepartmentData[$value['shopId']] = $value['id'];
- }
- foreach ($materialCodes as $key => $value) {
- if (!isset($newRegionalDepartmentData[$params['shop']])) {
- return ResultWrapper::fail('当前省市区没有对应部门', ErrorCode::$contentNotExists);
- }
- $regionalDepartmentId = $newRegionalDepartmentData[$params['shop']];
- // 按照店铺分表
- $tableName = 'regionalDepartmentPrice_' . $key;
- $objDRegionalDepartmentPrice->setTable($tableName);
- $condition = [
- 'materialCode' => array_values($value),
- 'regionalDepartmentId' => $regionalDepartmentId,
- ];
- $dbResult = $objDRegionalDepartmentPrice->select($condition);
- if ($dbResult === false) {
- return ResultWrapper::fail($objDRegionalDepartmentPrice->error(), ErrorCode::$dberror);
- }
- if (!empty($dbResult)) {
- foreach ($dbResult as $k => $v) {
- $regionalPriceData[$key][$v['materialCode']] = ['price' => self::formatPrice($v['materialCode'], $v['salePrice'])];
- }
- }
- }
- return ResultWrapper::success($regionalPriceData);
- }
- /**
- * 获取区域价格
- */
- public function getDistrictPrice($materialCodes, $params)
- {
- // 直接查询省市区分表
- $objDDistrictPriceCity = new DDistrictPriceCity();
- $DDistrictPriceProvince = new DDistrictPriceProvince();
- // 计算区县分表
- $tableName = 'districtPrice_city_' . $params['city'];
- $objDDistrictPriceCity->setTable($tableName);
- $districtPriceData = [];
- foreach ($materialCodes as $key => $value) {
- $condition = [
- 'shopId' => $key,
- 'materialCode' => array_unique(array_values($value)),
- ];
- $dbResult = $objDDistrictPriceCity->select($condition);
- if ($dbResult === false) {
- return ResultWrapper::fail($objDDistrictPriceCity->error(), ErrorCode::$dberror);
- }
- if (!empty($dbResult)) {
- foreach ($dbResult as $k => $v) {
- $districtPriceData[$key][$v['materialCode']] = ['price' => self::formatPrice($v['materialCode'], $v['salePrice'])];
- }
- }
- }
- unset($condition);
- // 计算省分表
- $tableName = 'districtPrice_province_' . $params['province'];
- $DDistrictPriceProvince->setTable($tableName);
- foreach ($materialCodes as $key => $value) {
- $condition = [
- 'shopId' => $key,
- 'materialCode' => array_unique(array_values($value)),
- ];
- $dbResult = $DDistrictPriceProvince->select($condition);
- if ($dbResult === false) {
- return ResultWrapper::fail($DDistrictPriceProvince->error(), ErrorCode::$dberror);
- }
- if (!empty($dbResult)) {
- foreach ($dbResult as $k => $v) {
- // 具体区县级取到数据了,就不取省一级的了
- if (isset($districtPriceData[$key][$v['materialCode']])) {
- continue;
- }
- $districtPriceData[$key][$v['materialCode']] = ['price' => self::formatPrice($v['salePriceType'], $v['salePrice'])];
- }
- }
- }
- return ResultWrapper::success($districtPriceData);
- }
- /**
- * 价格表列表页
- */
- public function getAll($params, $authorization)
- {
- // 获取所有大区数据
- $objMRegionalManage = new MRegionalManage();
- $result = $objMRegionalManage->getAllRegionalDepartment($params['shopId']);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $allRegionalDepartment = $result->getData();
- unset($result);
- $regionalDepartmentIds = [];
- $newAllRegionalDepartment = [];
- $RegionalDepartmentAndDeoptId = []; // 部门和仓库映射关系
- foreach ($allRegionalDepartment as $key => $value) {
- $newAllRegionalDepartment[$value['id']] = [
- 'name' => $value['name'],
- 'id' => $value['id'],
- 'price' => [],
- 'depotId' => $value['depotId'],
- ];
- $regionalDepartmentIds[] = $value['id'];
- $RegionalDepartmentAndDeoptId[$value['id']] = $value['depotId'];
- }
- // 初始化所有物料价格
- $returnDataValue = [
- 'cost' => 0,
- 'num' => 0,
- 'profit' => '0%',
- 'kilogramPrice' => '0.00',
- 'totalAmount' => '0.00',
- 'NationalUnifiedPrice' => (object)[],
- 'regionalDepartmentPrice' => $newAllRegionalDepartment,
- 'lastUserName' => ''
- ];
- $nationalUnifiedPriceParams = []; // 查询全国价参数
- $marketCodeAndmaterialCode = []; // 基础物料和销售物料映射关系
- $allMarketCodes = [];
- $marketCodeAndWeight = []; // 销售物料和重量关系
- foreach ($params['materialData'] as $key => $value) {
- foreach ($value as $k => $v) {
- $allMarketCodes[] = $v['marketCode'];
- $returnData[$v['marketCode']] = $returnDataValue;
- $marketCodeAndmaterialCode[$v['marketCode']] = $v['materialCode'];
- $marketCodeAndWeight[$v['marketCode']] = $v['weight'];
- $nationalUnifiedPriceParams[$key][] = $v['marketCode'];
- }
- }
- // 组装查询库存和成本数据要的参数
- $materielCostData = [
- 'cargoOwnerType' => $params['cargoOwnerType'],
- 'cargoOwnerCode' => $params['cargoOwnerCode'],
- ];
- foreach ($params['materialData'] as $key => $value) {
- foreach ($value as $k => $v) {
- $materielNumData[] = [
- 'materielCode' => $v['materialCode'],
- 'cargoOwnerCode' => $params['cargoOwnerCode'],
- ];
- $materielCostData['materielCode'][] = $v['materialCode'];
- }
- }
- // 获取成本和销售数量
- $objMOutsideData = new MOutsideData();
- $result = $objMOutsideData->getNumAndCost(['materielCostData' => $materielCostData, 'materielNumData' => $materielNumData], $authorization);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $costAndNumData = $result->getData();
- // 查询这批物料当前价格生效类型
- // 批量获取这批物料最后生效的价格销售区域类型
- $objDLastEffectiveSalePriceAreaType = new DLastEffectiveSalePriceAreaType();
- $condition = [
- 'marketCode' => array_unique($allMarketCodes),
- 'shopId' => $params['shopId'],
- ];
- $dbResult = $objDLastEffectiveSalePriceAreaType->select($condition, 'lastEffectiveSalePriceAreaType,marketCode,shopId,lastUserName');
- if ($dbResult === false) {
- return ResultWrapper::fail($objDLastEffectiveSalePriceAreaType->error(), ErrorCode::$dberror);
- }
- if (!empty($dbResult)) {
- // 进行生效价格区域类型分组
- $materieLastEffectiveSalePriceAreaType = [];
- // 映射物料和调价人关系
- $materieLastEffectiveLastUserName = [];
- foreach ($dbResult as $k => $v) {
- $materieLastEffectiveSalePriceAreaType[$v['marketCode']] = $v['lastEffectiveSalePriceAreaType'];
- $materieLastEffectiveLastUserName[$v['marketCode']] = $v['lastUserName'];
- }
- }
- // 查询各个物料的标准价
- $result = self::getNationalUnifiedPrice($nationalUnifiedPriceParams);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $nationalUnifiedPriceData = $result->getData();
- unset($result);
- foreach ($nationalUnifiedPriceData as $key => $value) {
- foreach ($value as $k => $v) {
- if (isset($returnData[$k])) {
- $returnData[$k]['NationalUnifiedPrice'] = isset($v['salePrice']) ? $v : [];
- }
- }
- }
- // 查询大区的销售价
- unset($result);
- $result = self::batchGetAreaPriceByRegionalDepartmentIds($regionalDepartmentIds, $params['shopId'], $allMarketCodes);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $regionalDepartmentPrice = $result->getData();
- // 如果当前生效全国价大区价=全国价 不然等于各自大区价格
- foreach ($returnData as $key => $value) {
- foreach ($value['regionalDepartmentPrice'] as $k => $v) {
- if (isset($materieLastEffectiveSalePriceAreaType[$key]) && $materieLastEffectiveSalePriceAreaType[$key] == StatusCode::$salePriceAreaType['nationalUnifiedPrice']) {
- $returnData[$key]['regionalDepartmentPrice'][$k]['price'] = $returnData[$key]['NationalUnifiedPrice'];
- } else {
- if (isset($regionalDepartmentPrice[$key])) {
- $returnData[$key]['regionalDepartmentPrice'][$k]['price'] = !empty($regionalDepartmentPrice[$key]['salePrice_' . $k]) ? $regionalDepartmentPrice[$key]['salePrice_' . $k] : $returnData[$key]['NationalUnifiedPrice'];
- }
- }
- }
- }
- foreach ($returnData as $key => $value) {
- $returnData[$key]['lastEffectiveSalePriceAreaType'] = isset($materieLastEffectiveSalePriceAreaType[$key]) ? $materieLastEffectiveSalePriceAreaType[$key] : 0;
- $returnData[$key]['lastUserName'] = isset($materieLastEffectiveLastUserName[$key]) ? $materieLastEffectiveLastUserName[$key] : '';
- $returnData[$key]['cost'] = isset($costAndNumData['costData'][$marketCodeAndmaterialCode[$key]]) ? $costAndNumData['costData'][$marketCodeAndmaterialCode[$key]] : [];
- $returnData[$key]['num'] = isset($costAndNumData['stockData'][$marketCodeAndmaterialCode[$key]]) ? $costAndNumData['stockData'][$marketCodeAndmaterialCode[$key]] : [];
- $tmpDeoptCostNumDtat = [];
- // 转换各个康库重量为数量
- $returnData[$key]['totalNum'] = 0;
- if (!empty($returnData[$key]['num'])) {
- foreach ($returnData[$key]['num'] as $k => $v) {
- $returnData[$key]['totalNum'] += $v['stockAvailable'];
- $returnData[$key]['num'][$k]['stockAvailable'] = floor($returnData[$key]['num'][$k]['stockAvailable'] / $marketCodeAndWeight[$key]);
- $tmpDeoptCostNumDtat[$key][$v['depotId']]['stockAvailable'] = $returnData[$key]['num'][$k]['stockAvailable'];
- if (!empty($returnData[$key]['cost']) && isset($returnData[$key]['cost']['depotIdData'])) {
- foreach ($returnData[$key]['cost']['depotIdData'] as $m => $j) {
- if ($j['depotId'] == $v['depotId']) {
- $returnData[$key]['cost']['depotIdData'][$m]['costPriceTotal'] = ($j['costPrice'] * $marketCodeAndWeight[$key]) * $returnData[$key]['num'][$k]['stockAvailable'];
- $tmpDeoptCostNumDtat[$key][$j['depotId']]['costPriceTotal'] = $returnData[$key]['cost']['depotIdData'][$m]['costPriceTotal'];
- }
- }
- }
- }
- $returnData[$key]['totalNum'] = floor($returnData[$key]['totalNum'] / $marketCodeAndWeight[$key]);
- }
- // 查看全部部门
- if ($params['regionalDepartmentId'] == 0) {
- if (isset($returnData[$key]['cost']['specCostPrice']) && isset($returnData[$key]['NationalUnifiedPrice']['salePrice'])) {
- $costPriceTotal = 0;
- if (!empty($tmpDeoptCostNumDtat[$key])) {
- foreach ($tmpDeoptCostNumDtat[$key] as $k1 => $v1) {
- if (isset($v1['costPriceTotal'])) {
- $costPriceTotal += $v1['costPriceTotal'];
- }
- }
- }
- $returnData[$key]['profit'] = self::getProfit($returnData[$key]['NationalUnifiedPrice']['salePrice'], $returnData[$key]['totalNum'], $costPriceTotal);
- } else {
- $returnData[$key]['profit'] = 0.00;
- }
- if (isset($returnData[$key]['NationalUnifiedPrice']['salePrice'])) {
- $returnData[$key]['totalAmount'] = self::getTotalMoney($returnData[$key]['totalNum'], $returnData[$key]['NationalUnifiedPrice']['salePrice']);
- $returnData[$key]['kilogramPrice'] = self::getKilogramPrice($marketCodeAndWeight[$key], $returnData[$key]['NationalUnifiedPrice']['salePrice']);
- } else {
- $returnData[$key]['totalAmount'] = 0.00;
- $returnData[$key]['kilogramPrice'] = 0.00;
- }
- } else {
- if (isset($tmpDeoptCostNumDtat[$key][$RegionalDepartmentAndDeoptId[$params['regionalDepartmentId']]]['costPriceTotal']) && isset($returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price']['salePrice'])) {
- $returnData[$key]['profit'] = self::getProfit($returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price']['salePrice'], $tmpDeoptCostNumDtat[$key][$RegionalDepartmentAndDeoptId[$params['regionalDepartmentId']]]['stockAvailable'], $tmpDeoptCostNumDtat[$key][$RegionalDepartmentAndDeoptId[$params['regionalDepartmentId']]]['costPriceTotal']);
- } else {
- $returnData[$key]['profit'] = 0.00;
- }
- if (isset($returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price']['salePrice'])) {
- $returnData[$key]['totalAmount'] = self::getTotalMoney($tmpDeoptCostNumDtat[$key][$RegionalDepartmentAndDeoptId[$params['regionalDepartmentId']]]['stockAvailable'], $returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price']['salePrice']);
- $returnData[$key]['kilogramPrice'] = self::getKilogramPrice($marketCodeAndWeight[$key], $returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price']['salePrice']);
- } else {
- $returnData[$key]['totalAmount'] = 0.00;
- $returnData[$key]['kilogramPrice'] = 0.00;
- }
- }
- if (empty($returnData[$key]['cost'])) {
- $returnData[$key]['cost'] = (object)[];
- }
- if (empty($returnData[$key]['num'])) {
- $returnData[$key]['num'] = (object)[];
- }
- if (empty($returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price'])) {
- $returnData[$key]['regionalDepartmentPrice'][$params['regionalDepartmentId']]['price'] = (object)[];
- }
- if (empty($returnData[$key]['NationalUnifiedPrice'])) {
- $returnData[$key]['NationalUnifiedPrice'] = (object)[];
- }
- $returnData[$key]['regionalDepartmentPrice'] = array_values($returnData[$key]['regionalDepartmentPrice']);
- }
- return ResultWrapper::success($returnData);
- }
- /**
- * 计算毛利率
- * (销售总金额-成本总金额)/销售金额)*100%
- * 销售金额 = 销售数量(全部) * 销售价格(全国销售价) / 销售数量(全部) * 销售价格(部门销售价)
- */
- public function getProfit($nowSalePrice, $stockNum, $costPriceTotal)
- {
- $saleMoney = $nowSalePrice * $stockNum;
- if ($saleMoney == 0) {
- return '0.00%';
- }
- $profitPrice = (($saleMoney - $costPriceTotal) / $saleMoney) * 100;
- return number_format($profitPrice, 2) . "%";
- }
- /**
- * 计算销售公斤价
- * 标准价 / 单件重量
- */
- public function getKilogramPrice($weight, $salePrice)
- {
- if (!$salePrice) {
- return 0.00;
- }
- $kilogramPrice = $salePrice / $weight;
- return number_format($kilogramPrice, 2);
- }
- /**
- * 计算可销售总额
- * 可售数量 * 销售价格
- * @param $params
- * @return ResultWrapper
- */
- public function getTotalMoney($stockNum, $salePrice)
- {
- $totalMoney = $stockNum * $salePrice;
- return number_format($totalMoney, 2);
- }
- /*
- * 获取各个店铺下面物料的大区价格
- */
- public function getRegionalPriceByRegionalDepartmentId($params)
- {
- $objDRegionalDepartmentPrice = new DRegionalDepartmentPrice();
- $regionalPriceData = [];
- foreach ($params['materialCode'] as $key => $value) {
- // 按照店铺分表
- $tableName = 'regionalDepartmentPrice_' . $key;
- $objDRegionalDepartmentPrice->setTable($tableName);
- $condition = [
- 'materialCode' => array_values($value),
- ];
- if ($params['regionalDepartmentId']) {
- $condition['regionalDepartmentId'] = $params['regionalDepartmentId'];
- }
- $dbResult = $objDRegionalDepartmentPrice->select($condition, '*', 'regionalDepartmentId asc');
- if ($dbResult === false) {
- return ResultWrapper::fail($objDRegionalDepartmentPrice->error(), ErrorCode::$dberror);
- }
- if (!empty($dbResult)) {
- foreach ($dbResult as $k => $v) {
- $regionalPriceData[$key][$v['materialCode']][] = ['price' => self::formatPrice($v['salePriceType'], $v['salePrice']), 'regionalDepartmentId' => $v['regionalDepartmentId']];
- }
- }
- }
- return ResultWrapper::success($regionalPriceData);
- }
- /**
- * 获取指定店铺下指定物料的大区以及市价格
- */
- public function getAreaPriceByMaterialCode($params, $authorization)
- {
- // 获取物料各个仓库可用库存
- $objMOutsideData = new MOutsideData();
- $materielData[] = [
- 'materielCode' => $params['materialCode'],
- 'cargoOwnerCode' => $params['cargoOwnerCode'],
- ];
- $newStockData = [];
- $result = $objMOutsideData->getNumFromWms($materielData, $authorization);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $result = $result->getData();
- $stockData = $result[0]['data'];
- foreach ($stockData as $key => $value) {
- $newStockData[$value['depotId']] = $value['stockAvailable'];
- }
- // 获取各个大区下的城市数据
- $objMRegionalManage = new MRegionalManage();
- $result = $objMRegionalManage->getAllRegionalDepartmentCitys($params);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $allRegionalDepartmentCitys = $result->getData();
- unset($result);
- // 获取这批物料最后生效的价格销售区域类型
- $objDLastEffectiveSalePriceAreaType = new DLastEffectiveSalePriceAreaType();
- $condition = [
- 'marketCode' => $params['marketCode'],
- 'shopId' => $params['shopId'],
- ];
- $dbResult = $objDLastEffectiveSalePriceAreaType->get($condition, 'lastEffectiveSalePriceAreaType,marketCode,shopId');
- if ($dbResult === false) {
- return ResultWrapper::fail($objDLastEffectiveSalePriceAreaType->error(), ErrorCode::$dberror);
- }
- $lastEffectiveSalePriceAreaType = 0;
- if (!empty($dbResult)) {
- $lastEffectiveSalePriceAreaType = $dbResult['lastEffectiveSalePriceAreaType'];
- }
- // 获取价格数据
- $newparams = [
- 'materialCode' => [
- $params['shopId'] => [$params['marketCode']]
- ],
- ];
- $result = self::getPrice($newparams, true);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $salePriceData = $result->getData();
- $newSalePriceData = [];
- if (!empty($salePriceData)) {
- $salePriceData = $salePriceData[$params['shopId']][$params['marketCode']];
- if ($lastEffectiveSalePriceAreaType == StatusCode::$salePriceAreaType['areaPrice']) {
- foreach ($salePriceData as $key => $value) {
- $newSalePriceData += $value;
- }
- }
- }
- foreach ($allRegionalDepartmentCitys as $key => $value) {
- $allRegionalDepartmentCitys[$key]['price'] = '0.00';
- $allRegionalDepartmentCitys[$key]['stock'] = 0;
- if ($lastEffectiveSalePriceAreaType == StatusCode::$salePriceAreaType['nationalUnifiedPrice']) {
- $allRegionalDepartmentCitys[$key]['price'] = $salePriceData['salePrice'];
- } else {
- if (isset($newSalePriceData[$value['id'] . '-' . $value['id'] . '-' . $value['id']])) {
- $allRegionalDepartmentCitys[$key]['price'] = $newSalePriceData[$value['id'] . '-' . $value['id'] . '-' . $value['id']]['salePrice'];
- } else {
- $nationalUnifiedPriceParams[$params['shopId']][] = $params['marketCode'];
- $result = self::getNationalUnifiedPrice($nationalUnifiedPriceParams);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $nationalUnifiedPriceData = $result->getData();
- if (!empty($nationalUnifiedPriceData)) {
- $allRegionalDepartmentCitys[$key]['price'] = $nationalUnifiedPriceData[$params['shopId']][$params['marketCode']]['salePrice'];
- }
- }
- }
- if (isset($newStockData[$value['depotId']])) {
- $allRegionalDepartmentCitys[$key]['stock'] = floor($newStockData[$value['depotId']] / $params['weight']);
- }
- foreach ($value['citys'] as $k => $v) {
- $allRegionalDepartmentCitys[$key]['citys'][$k]['id'] = $k;
- $allRegionalDepartmentCitys[$key]['citys'][$k]['price'] = '0.00';
- if ($lastEffectiveSalePriceAreaType == StatusCode::$salePriceAreaType['nationalUnifiedPrice']) {
- $allRegionalDepartmentCitys[$key]['citys'][$k]['price'] = $salePriceData['salePrice'];
- } else {
- if (isset($newSalePriceData[$v['province'] . '-' . $v['city'] . '-0'])) {
- $allRegionalDepartmentCitys[$key]['citys'][$k]['price'] = $newSalePriceData[$v['province'] . '-' . $v['city'] . '-0']['salePrice'];
- } else {
- $allRegionalDepartmentCitys[$key]['citys'][$k]['price'] = $allRegionalDepartmentCitys[$key]['price'];
- }
- }
- }
- $allRegionalDepartmentCitys[$key]['citys'] = array_values($allRegionalDepartmentCitys[$key]['citys']);
- }
- return ResultWrapper::success($allRegionalDepartmentCitys);
- }
- /**
- * 根据销售区域类型获取对应的销售价格
- */
- public function getPriceBySalePriceAreaType($params)
- {
- $priceDataParams = [
- 'materialCode' => [
- $params['shopId'] => [$params['materielCode']]
- ],
- 'regionalDepartmentId' => $params['regionalDepartmentId'],
- ];
- switch ($params['salePriceAreaType']) {
- case StatusCode::$salePriceAreaType['nationalUnifiedPrice']:
- $materielPriceData = self::getNationalUnifiedPrice($priceDataParams);
- break;
- case StatusCode::$salePriceAreaType['regionalPrice']:
- $materielPriceData = self::getRegionalPriceByRegionalDepartmentId($priceDataParams);
- break;
- case StatusCode::$salePriceAreaType['districtPrice']:
- $materielPriceData = self::getDistrictPrice($priceDataParams['materialCode'], $params);
- break;
- }
- return ResultWrapper::success($materielPriceData);
- }
- /**
- * 获取全国标准价和可用库存
- */
- public function getNationalUnifiedPriceAndStock($params, $authorization)
- {
- $returnData = [
- 'nationalUnifiedPrice' => (object)[],
- 'stock' => 0,
- ];
- // 获取全国统一价格
- $newParams = [
- $params['shopId'] => [$params['marketCode']]
- ];
- $result = self::getNationalUnifiedPrice($newParams);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $nationalUnifiedPriceData = $result->getData();
- unset($result);
- if (!empty($nationalUnifiedPriceData[$params['shopId']][$params['marketCode']])) {
- $returnData['nationalUnifiedPrice'] = $nationalUnifiedPriceData[$params['shopId']][$params['marketCode']];
- }
- unset($result);
- $objMOutsideData = new MOutsideData();
- $materielNumData[] = [
- 'materielCode' => $params['materialCode'],
- 'cargoOwnerCode' => $params['cargoOwnerCode'],
- ];
- $result = $objMOutsideData->getNumFromWms($materielNumData, $authorization);
- if (!$result->isSuccess()) {
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- $result = $result->getData();
- if (!empty($result)) {
- $allDepotNum = $result[0]['data'];
- $num = 0;
- foreach ($allDepotNum as $key => $value) {
- $num += $value['stockAvailable'];
- }
- if ($num) {
- $num = floor($num / $params['weight']);
- }
- $returnData['stock'] = $num;
- }
- return ResultWrapper::success($returnData);
- }
- /**
- * (废弃)
- * 根据goodsId获取商品最低/高价格
- * @param array $goodsIds
- * @return ResultWrapper
- */
- public function getRangePrice(array $goodsIds)
- {
- if (empty($goodsIds)) {
- return ResultWrapper::success([]);
- }
- $this->objDPriceRangeSheet->setTable($this->objDPriceRangeSheet->get_Table() . '_' . $this->onlineEnterpriseId);
- $result = $this->objDPriceRangeSheet->select(['goodsId' => $goodsIds], 'goodsId,salePrice');
- if ($result === false) {
- return ResultWrapper::fail($this->objDPriceRangeSheet->error(), ErrorCode::$dberror);
- }
- $mapping = [];
- foreach ($result as $row) {
- $salePrice = empty($row['salePrice']) ? [] : json_decode($row['salePrice'], true);
- $mapping[$row['goodsId']] = [
- 'minSalePrice' => $salePrice['minSalePrice'],
- 'maxSalePrice' => $salePrice['maxSalePrice'],
- ];
- }
- return ResultWrapper::success($mapping);
- }
- /**
- * 根据goodsId获取商品的最高/最低价格
- * @param array $goodsIds 商品id集合
- * @param null $customerId 客户id
- * @param $haveActivity boolean 活动价是否参与最高最低价
- * @return ResultWrapper
- */
- public function getPolePrice(array $goodsIds, $customerId = null, $haveActivity = true)
- {
- $isHaveSkuIds = [];
- //获取商品salePrice
- $nationSalePriceResult = self::getNationSalePriceByGoodsIds($goodsIds);
- if (!$nationSalePriceResult->isSuccess()) {
- return ResultWrapper::fail($nationSalePriceResult->getData(), $nationSalePriceResult->getErrorCode());
- }
- $nationSalePrice = $nationSalePriceResult->getData();
- //没有客户id
- if (empty($customerId)) {
- return ResultWrapper::success(self::calcMinAndMaxPrice($nationSalePrice));
- }
- //获取商品客户调价
- $customerAdjResult = self::getCustomerAdjByGoodsIds($goodsIds, $customerId);
- if (!$customerAdjResult->isSuccess()) {
- ResultWrapper::fail($customerAdjResult->getData(), $customerAdjResult->getErrorCode());
- }
- $customerAdj = $customerAdjResult->getData();
- //计算客户调价
- foreach ($nationSalePrice as $goodsId => $salePrice) {
- foreach ($salePrice as $skuId => $row) {
- if (isset($customerAdj[$goodsId][$skuId])) {
- $nowCustomerAdj = array_shift($customerAdj[$goodsId][$skuId]);//sku调价信息
- $result = self::commonPriceData($nowCustomerAdj, $nationSalePrice[$goodsId][$skuId], $skuId, $isHaveSkuIds);
- $nationSalePrice[$goodsId][$skuId]['salePrice'] = $result['salePrice'];
- $nationSalePrice[$goodsId][$skuId]['marketPrice'] = $result['marketPrice'];
- $nationSalePrice[$goodsId][$skuId]['ladderPrice'] = $result['ladderPrice'];
- $isHaveSkuIds = $result['skuIds'];
- }
- }
- }
- //查询当前客户的客户类型是否有特殊调价
- $objDCustomer = new DCustomer();
- $objDCustomer->setTable('qianniao_customer_' . $this->onlineEnterpriseId);
- $customer = $objDCustomer->get(['id' => $customerId], 'id,type,name');
- if ($customer === false) {
- return ResultWrapper::fail($customer->error(), ErrorCode::$dberror);
- }
- $customerType = $customer['type'];//客户类型
- //获取客户类型调价
- if (!empty($customerType)){
- $customerTypeAdjResult = self::getCustomerTypeAdjByGoodsIds($goodsIds, $customerType);
- if (!$customerTypeAdjResult->isSuccess()) {
- return ResultWrapper::fail($customerTypeAdjResult->getData(), $customerTypeAdjResult->getErrorCode());
- }
- $customerTypeAdj = $customerTypeAdjResult->getData();
- //计算客户类型调价
- foreach ($nationSalePrice as $goodsId => $salePrice) {
- foreach ($salePrice as $skuId => $row) {
- if (isset($customerTypeAdj[$goodsId][$skuId])) {
- // skuid 有客户调价以后,客户类型就不调价了
- if(in_array($skuId, $isHaveSkuIds)){
- continue;
- }
- $nowCustomerTypeAdj = array_shift($customerTypeAdj[$goodsId][$skuId]);
- $result = self::commonPriceData($nowCustomerTypeAdj, $nationSalePrice[$goodsId][$skuId], $skuId,$isHaveSkuIds);
- $nationSalePrice[$goodsId][$skuId]['salePrice'] = $result['salePrice'];
- $nationSalePrice[$goodsId][$skuId]['marketPrice'] = $result['marketPrice'];
- $nationSalePrice[$goodsId][$skuId]['ladderPrice'] = $result['ladderPrice'];
- }
- }
- }
- }
- if($haveActivity){
- //查询商品活动价
- $activityPriceResult = self::getActivityPriceByGoodsIds($goodsIds,$customerType);
- if (!$activityPriceResult->isSuccess()){
- return ResultWrapper::fail($activityPriceResult->getData(), $activityPriceResult->getErrorCode());
- }
- $activityPrice = $activityPriceResult->getData();
- //计算商品活动价 和 计算属性最小单位展示价格
- foreach ($nationSalePrice as $goodsId => $salePrice){
- foreach ($salePrice as $skuId => $row){
- if (isset($activityPrice[$goodsId][$skuId])){
- $nationSalePrice[$goodsId][$skuId]['salePrice'] = $activityPrice[$goodsId][$skuId]['salePrice'];
- }
- if(isset($nationSalePrice[$goodsId][$skuId]['minUnitPriceConvert']) && !empty($nationSalePrice[$goodsId][$skuId]['minUnitPriceConvert'])){
- $nationSalePrice[$goodsId][$skuId]['minUnitPrice'] = bcdiv($nationSalePrice[$goodsId][$skuId]['salePrice'], $nationSalePrice[$goodsId][$skuId]['minUnitPriceConvert'], 2);
- }
- }
- }
- }
- return ResultWrapper::success(self::calcMinAndMaxPrice($nationSalePrice));
- }
- /**
- * 统一加减乘操作
- */
- public function commonPriceData($priceData, $nationSalePrice, $skuId, $isHaveSkuIds =[])
- {
- if(in_array($skuId, $isHaveSkuIds)){
- return [
- 'minSalePrice' => $priceData['salePrice'],
- 'skuIds' => $isHaveSkuIds
- ];
- }
- // 如果有阶梯价
- if ( isset($priceData['ladderPrice']) && !empty($priceData['ladderPrice']) ){
- foreach ($priceData['ladderPrice'] as $k => $v){
- $beforePrice = $nationSalePrice['ladderPrice'][$k]['price'];
- // 根据标识判断做对应处理
- switch (intval($v['adjPricetag'])){
- case 1: // 减法
- $priceData['ladderPrice'][$k]['price'] = bcsub($beforePrice,$v['adjPrice'],2);
- break;
- case 2: // 加法
- $priceData['ladderPrice'][$k]['price'] = bcadd($beforePrice,$v['adjPrice'],2);
- break;
- case 3: // 乘法
- $priceData['ladderPrice'][$k]['price'] = bcmul($beforePrice,$v['adjPrice'],2);
- break;
- }
- }
- }else{
- $beforeSalePrice = $nationSalePrice['salePrice']; //处理前销售价格
- $beforeMarketPrice = $nationSalePrice['marketPrice']; //处理前市场价格
- // 根据标识判断做对应处理
- switch (intval($priceData['adjPricetag'])){
- case 1: // 减法
- $priceData['salePrice'] = bcsub($beforeSalePrice,$priceData['price'],2);
- $priceData['marketPrice'] = bcsub($beforeMarketPrice,$priceData['price'],2);
- break;
- case 2: // 加法
- $priceData['salePrice'] = bcadd($beforeSalePrice,$priceData['price'],2);
- $priceData['marketPrice'] = bcadd($beforeMarketPrice,$priceData['price'],2);
- break;
- case 3: // 乘法
- $priceData['salePrice'] = bcmul($beforeSalePrice,$priceData['price'],2);
- $priceData['marketPrice'] = bcmul($beforeMarketPrice,$priceData['price'],2);
- break;
- }
- }
- $isHaveSkuIds[] = $skuId;
- return [
- 'ladderPrice' => $priceData['ladderPrice'],
- 'salePrice' => $priceData['salePrice'],
- 'marketPrice' => $priceData['marketPrice'],
- 'skuIds' => $isHaveSkuIds
- ];
- }
- /**
- * 计算最高最低价
- * $data 商品价格数据
- * @param array $data
- * @return array
- */
- public static function calcMinAndMaxPrice(array $data)
- {
- $Mapping = [];
- if (empty($data)) {
- return $Mapping;
- }
- foreach ($data as $goodsId => $item) {
- // 初始化字段默认值
- $Mapping[$goodsId] = [
- 'minSalePrice' => '0.00',
- 'maxSalePrice' => '0.00',
- 'minMarketPrice' => '0.00',
- 'maxMarketPrice' => '0.00',
- 'minMemberPrice' => '0.0',
- 'maxMemberPrice' => '0.0',
- 'minMinUnitPrice' => '0.0',
- 'maxMinUnitPrice' => '0.0',
- ];
- if (empty($item)){
- continue;
- }
- $memberPrice = [];
- $salePrices = [];
- $marketPrices = [];
- $minUnitPrice = [];
- // skuId维度提取所有价格
- foreach ($item as $key => $value){
- if($value['enabledLadder'] && isset($value['ladderPrice']) && !empty($value['ladderPrice'])){
- $salePrices[] = array_column($value['ladderPrice'], 'price');
- }else{
- $salePrices[] = $value['salePrice'];
- $marketPrices[] = $value['marketPrice'];
- $memberPrice[] = getArrayItem($value,'memberPrice',0);
- $minUnitPrice[] = getArrayItem($value,'minUnitPrice',0);
- }
- }
- // 提取所有的销售价
- $allSalePrices = [];
- foreach ($salePrices as $key => $price){
- if (empty($price)){
- unset($salePrices[$key]);
- }
- if(is_array($price)){
- foreach ($price as $k => $v){
- $allSalePrices[] = $v;
- }
- }else{
- $allSalePrices[] = $price;
- }
- }
- foreach ($allSalePrices as $index => $price){
- if (empty($price)){
- unset($allSalePrices[$index]);
- }
- }
- // 提取所有的市场价
- $allMarketPrices = [];
- foreach ($marketPrices as $kk => $vv){
- if (empty($vv)){
- unset($marketPrices[$kk]);
- continue;
- }
- $allMarketPrices[] = $vv;
- }
- // 提取所有的会员价
- $allMemberPrices = [];
- foreach ($memberPrice as $kk => $vv){
- if (empty($vv)){
- unset($memberPrice[$kk]);
- continue;
- }
- $allMemberPrices[] = $vv;
- }
- // 提取所有的属性最小单位展示价
- $allMinUnitPricePrices = [];
- foreach ($minUnitPrice as $kk => $vv){
- if (empty($vv)){
- unset($allMinUnitPricePrices[$kk]);
- continue;
- }
- $allMinUnitPricePrices[] = $vv;
- }
- if (!empty($allSalePrices)){
- $allSalePrices = array_values($allSalePrices);
- $Mapping[$goodsId]['minSalePrice'] = sprintf('%.2f', min($allSalePrices)) ? sprintf('%.2f', min($allSalePrices)) : 0.00;
- $Mapping[$goodsId]['maxSalePrice'] = sprintf('%.2f', max($allSalePrices)) ? sprintf('%.2f', max($allSalePrices)) : 0.00;
- }
- if (!empty($allMarketPrices)){
- $allMarketPrices = array_values($allMarketPrices);
- $Mapping[$goodsId]['minMarketPrice'] = sprintf('%.2f', min($allMarketPrices)) ? sprintf('%.2f', min($allMarketPrices)) : 0.00;
- $Mapping[$goodsId]['maxMarketPrice'] = sprintf('%.2f', max($allMarketPrices)) ? sprintf('%.2f', max($allMarketPrices)) : 0.00;
- }
- if(!empty($allMemberPrices)){
- $allMemberPrices = array_values($allMemberPrices);
- $Mapping[$goodsId]['minMemberPrice'] = sprintf('%.2f', min($allMemberPrices)) ? sprintf('%.2f', min($allMemberPrices)) : 0.00;
- $Mapping[$goodsId]['maxMemberPrice'] = sprintf('%.2f', max($allMemberPrices)) ? sprintf('%.2f', max($allMemberPrices)) : 0.00;
- }
- if(!empty($allMinUnitPricePrices)){
- $allMinUnitPricePrices = array_values($allMinUnitPricePrices);
- $Mapping[$goodsId]['minMinUnitPrice'] = sprintf('%.2f', min($allMinUnitPricePrices)) ? sprintf('%.2f', min($allMinUnitPricePrices)) : 0.00;
- $Mapping[$goodsId]['maxMinUnitPrice'] = sprintf('%.2f', max($allMinUnitPricePrices)) ? sprintf('%.2f', max($allMinUnitPricePrices)) : 0.00;
- }
- }
- return $Mapping;
- }
- /**
- * 获取nation价格信息 mapping
- * @param array $goodsIds
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getNationSalePriceByGoodsIds(array $goodsIds)
- {
- $objPriceCache = new PriceCache($this->onlineEnterpriseId);
- $mapping = [];
- if (empty($goodsIds)) {
- return ResultWrapper::success($mapping);
- }
- //查询缓存
- $needSelectGoodsIds = [];//需要查询
- foreach ($goodsIds as $goodsId) {
- $salePrice = $objPriceCache->getNationSalePrice($goodsId);
- if (empty($salePrice)) {
- $needSelectGoodsIds[] = $goodsId;
- continue;
- }
- $mapping[$goodsId] = $salePrice;
- }
- //缓存中没有,查询数据库
- if (!empty($needSelectGoodsIds)) {
- $objDNationalUnifiedPrice = new DNationalUnifiedPrice();
- $objDNationalUnifiedPrice->setTable('qianniao_nationalUnifiedPrice_' . $this->onlineEnterpriseId);
- $nationalResult = $objDNationalUnifiedPrice->select(['goodsId' => $needSelectGoodsIds], 'id,goodsId,salePrice');
- if ($nationalResult === false) {
- return ResultWrapper::fail($objDNationalUnifiedPrice->error(), ErrorCode::$dberror);
- }
- foreach ($nationalResult as $item) {
- $mapping[$item['goodsId']] = json_decode($item['salePrice'], true);
- //写入缓存
- $objPriceCache->setNationSalePrice($item['goodsId'], json_decode($item['salePrice'], true));
- }
- }
- $mapping = self::formatPriceSku($mapping);
- return ResultWrapper::success($mapping);
- }
- /**
- * 获取客户调价信息 mapping
- * @param array $goodsIds
- * @param int $customerId
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getCustomerAdjByGoodsIds(array $goodsIds, int $customerId)
- {
- $mapping = [];
- $objPriceCache = new PriceCache($this->onlineEnterpriseId);
- if (empty($goodsIds)) {
- return ResultWrapper::success($mapping);
- }
- //查询缓存
- $needSelectGoodsIds = [];
- foreach ($goodsIds as $goodsId) {
- $salePrice = $objPriceCache->getCustomerAdj($goodsId, $customerId);
- if (empty($salePrice)) {
- //缓存中没有
- $needSelectGoodsIds[] = $goodsId;//需要查询
- continue;
- }
- $mapping[$goodsId] = $salePrice;
- }
- //需要查询查询数据库
- if (!empty($needSelectGoodsIds)) {
- $objDCustomerPriceEffective = new DCustomerPriceEffective();
- $objDCustomerPriceEffective->setTable('qianniao_customerPriceEffective_' . $this->onlineEnterpriseId);
- $customerAdjResult = $objDCustomerPriceEffective->select(['goodsId' => $goodsIds, 'customerId' => $customerId], 'id,goodsId,salePrice');
- if ($customerAdjResult === false) {
- return ResultWrapper::fail($objDCustomerPriceEffective->error(), ErrorCode::$dberror);
- }
- foreach ($customerAdjResult as $item) {
- $salePrice = json_decode($item['salePrice'], true);
- $salePriceMapping = [];
- foreach ($salePrice as $value) {
- $salePriceMapping[$value['skuId']][] = $value;
- }
- $mapping[$item['goodsId']] = $salePriceMapping;
- //写入缓存
- $objPriceCache->setCustomerAdj($item['goodsId'], $customerId, $salePriceMapping);
- }
- }
- return ResultWrapper::success($mapping);
- }
- /**
- * 获取客户类型调价信息 mapping
- * @param array $goodsIds
- * @param int $customerType
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getCustomerTypeAdjByGoodsIds(array $goodsIds, int $customerType)
- {
- $mapping = [];
- $objPriceCache = new PriceCache($this->onlineEnterpriseId);
- if (empty($goodsIds)) {
- return ResultWrapper::success($mapping);
- }
- //查询缓存
- $needSelectGoodsIds = [];
- foreach ($goodsIds as $goodsId) {
- $salePrice = $objPriceCache->getCustomerTypeAdj($goodsId, $customerType);
- if (empty($salePrice)) {
- //缓存中没有
- $needSelectGoodsIds[] = $goodsId;//需要查询
- continue;
- }
- $mapping[$goodsId] = $salePrice;
- }
- //查询数据库
- if (!empty($needSelectGoodsIds)) {
- $objDCustomerTypePriceEffective = new DCustomerTypePriceEffective();
- $objDCustomerTypePriceEffective->setTable('qianniao_customerTypePriceEffective_' . $this->onlineEnterpriseId);
- $customerTypeAdjResult = $objDCustomerTypePriceEffective->select(['goodsId' => $goodsIds, 'customerType' => $customerType]);
- if ($customerTypeAdjResult === false) {
- return ResultWrapper::fail($objDCustomerTypePriceEffective->error(), ErrorCode::$dberror);
- }
- foreach ($customerTypeAdjResult as $item) {
- $salePrice = json_decode($item['salePrice'], true);
- $salePriceMapping = [];
- foreach ($salePrice as $value) {
- $salePriceMapping[$value['skuId']][] = $value;
- }
- $mapping[$item['goodsId']] = $salePriceMapping;
- //写入缓存
- $objPriceCache->setCustomerTypeAdj($item['goodsId'], $customerType, $salePriceMapping);
- }
- }
- return ResultWrapper::success($mapping);
- }
- /**
- * 获取商品活动价格信息
- * @param array $goodsIds
- * @param int $customerType
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getActivityPriceByGoodsIds(array $goodsIds,$customerType)
- {
- $mapping = [];
- $objMActivity = new MActivity($this->onlineUserId,$this->onlineEnterpriseId);
- //获取促销活动价格
- $dbResult = $objMActivity->getActivity([
- 'goodsId' => rtrim(implode(',', $goodsIds),','),
- 'customerType' => $customerType,
- ]);
- if (!$dbResult->isSuccess()){
- return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode());
- }
- $activityPrice = $dbResult->getData();
- foreach ($activityPrice as $item){
- $mapping[$item['goodsId']] = [
- $item['skuId'] => [
- 'skuId' => $item['skuId'],
- 'salePrice' => $item['price']
- ]
- ];
- }
- return ResultWrapper::success($mapping);
- }
- public function formatPriceSku($data)
- {
- $skuIds = [];
- foreach ($data as $val){
- foreach ($val as $skuId => $value){
- $skuIds [] = $skuId;
- }
- }
- $objDSku = new DSku();
- $objDSku->setTable('qianniao_sku_'.$this->onlineEnterpriseId);
- $dbResult = $objDSku->select(['id'=>$skuIds,'deleteStatus'=>StatusCode::$standard],'id');
- if ($dbResult === false){
- Logger::logs(E_USER_ERROR,'查询sku错误',__CLASS__,__LINE__,$objDSku->error());
- return $data;
- }
-
- $allSkuIds = array_column($dbResult,'id');
- foreach ($data as $goodsId => &$val){
- foreach ($val as $skuId => $value){
- if (!in_array($skuId,$allSkuIds)){
- unset($val[$skuId]);
- }
- }
- }
- return $data;
- }
- /**
- * Doc: (des="获取商品的最近调价")
- * User: XMing
- * Date: 2021/3/11
- * Time: 9:50 上午
- * @param int $shopId
- * @param int $goodsId
- * @param string $date
- * @return ResultWrapper
- * @throws \Exception
- */
- public function getPriceSheetByShopIdRelGoodsId(int $shopId,int $goodsId,int $date): ResultWrapper
- {
- $y = date('Y',$date);
- $m = date('m',$date);
- $this->objDPriceAdjustment->setTable('qianniao_priceAdjustmentSheet_' . $this->onlineEnterpriseId . '_' . $y . '_' . ceil($m / 3));
- $sql = 'SELECT `salePrice`,`createTime` FROM '.$this->objDPriceAdjustment->get_Table().' WHERE shopId = '.$shopId.' AND goodsId = '.$goodsId;
- $sql .= ' AND createTime <= '.$date;
- $lists = $this->objDPriceAdjustment->query($sql);
- if ($lists === false){
- Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDPriceAdjustment->error());
- return ResultWrapper::fail($this->objDPriceAdjustment->error(),ErrorCode::$dberror);
- }
- if (empty($lists)){
- $date = strtotime(date('Y-m-d 23:59:59',strtotime("-1 days")));
- $y = date('Y',$date);
- $m = date('m',$date);
- $this->objDPriceAdjustment->setTable('qianniao_priceAdjustmentSheet_' . $this->onlineEnterpriseId . '_' . $y . '_' . ceil($m / 3));
- $sql = 'SELECT `salePrice`,`createTime` FROM '.$this->objDPriceAdjustment->get_Table().' WHERE shopId = '.$shopId.' AND goodsId = '.$goodsId;
- $sql .= ' AND createTime <= '.$date;
- $lists = $this->objDPriceAdjustment->query($sql);
- if ($lists === false){
- Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDPriceAdjustment->error());
- return ResultWrapper::fail($this->objDPriceAdjustment->error(),ErrorCode::$dberror);
- }
- }
- foreach ($lists as &$item){
- $item['salePrice'] = empty($item['salePrice']) ? [] : json_decode($item['salePrice'],true);
- }
- $row = array_shift($lists);
- return ResultWrapper::success($row);
- }
- /**
- * 计算阶梯价公共方法
- * @params array $ladderPrice 阶梯价数据
- * @params float $salePrice 销售价
- * @params float $buyNum 购买数量
- * @return float
- */
- public function getLadderPriceCommon($ladderPrice, $salePrice, $buyNum, $enabledLadder)
- {
- if( empty($ladderPrice) || !$enabledLadder){
- return $salePrice;
- }
- foreach ($ladderPrice as $key => $value){
- if($buyNum >= $value['from'] && $buyNum <= $value['to']){
- return $value['price'];
- }
- }
- return 0.00;
- }
- }
|