MPrice.Class.php 83 KB

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