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; } }