'oneRate', 2 => 'twoRate', 3 => 'threeRate', 'oneRate' => 1, 'twoRate' => 2, 'threeRate' => 3 ]; /** * @var DCommissionBusinessman */ private $objDCommissionBusinessman; /** * @var MCommissionBusinessman */ private $objMCommissionBusinessman; /** * @var int 平台设置分销层级 */ private $level; /** * @var MCommissionGrade */ private $objMCommissionGrade; /** * @var array 需要检测是否达到升级条件的userCenterId */ private $needUserCenterIds = []; /** * @var array 所有等级条件别名 */ private $allAliasCondition = []; /** * @var DCommissionGoodsStatistics */ private $objDCommissionGoodsStatistics; /** * @var DOrder */ private $objDOrder; /** * @var DCommissionOrderIndex */ private $objDCommissionOrderIndex; /** * @var DCommissionFlow */ private $objDCommissionFlow; /** * @var array 分销设置 */ private $setting; /** * @var array 当前订单信息 */ private $orderData; /** * @var array 当前订单商品 */ private $orderGoods; /** * @var int 是否开启自购 */ private $isRetSelf; /** * MCommissionCalculate constructor. * @param $onlineEnterpriseId * @param $onlineUserId * @throws \Exception */ public function __construct($onlineEnterpriseId, $onlineUserId) { $this->onlineUserId = $onlineUserId; $this->onlineEnterpriseId = $onlineEnterpriseId; $this->objDCommissionOrder = new DCommissionOrder(); $this->objDCommissionOrder->setTable('qianniao_commission_order_' . $this->onlineEnterpriseId . '_' . date('Y') . '_' . ceil(date('m') / 3)); $this->objDCustomer = new DCustomer(); $this->objDCustomer->setTable('qianniao_customer_' . $this->onlineEnterpriseId); $this->objMCommissionSetting = new MCommissionSetting($this->onlineEnterpriseId, $this->onlineUserId); $this->objDOrderIndex = new DOrderIndex(); $this->objDOrderIndex->setTable('qianniao_order_index_' . $this->onlineEnterpriseId); $this->objDOrderGoods = new DOrderGoods(); $this->objDOrder = new DOrder(); $this->objDGoods = new DGoods(); $this->objDGoods->setTable('qianniao_goods_' . $this->onlineEnterpriseId); $this->objDCommissionGoods = new DCommissionGoods(); $this->objDCommissionGoods->setTable('qianniao_commission_goods_' . $this->onlineEnterpriseId); $this->objDCommissionBusinessman = new DCommissionBusinessman(); $this->objDCommissionBusinessman->setTable('qianniao_commission_businessman_' . $this->onlineEnterpriseId); $this->objMCommissionBusinessman = new MCommissionBusinessman($this->onlineEnterpriseId, $this->onlineUserId); $this->objMCommissionGrade = new MCommissionGrade($this->onlineEnterpriseId, $this->onlineUserId); $this->objDCommissionGoodsStatistics = new DCommissionGoodsStatistics(); $this->objDCommissionGoodsStatistics->setTable('qianniao_commission_goods_statistics_'.$this->onlineEnterpriseId); $this->objDCommissionOrderIndex = new DCommissionOrderIndex(); $this->objDCommissionOrderIndex->setTable('qianniao_commission_order_index_'.$this->onlineEnterpriseId); $this->objDCommissionFlow = new DCommissionFlow(); $this->objDCommissionFlow->setTable('qianniao_commission_flow_'.$this->onlineEnterpriseId); $this->needUserCenterIds = []; } /** * 增加分销商品的销量以及分销金额 * @throws \Exception */ public function __destruct() { //todo //在这里判断分销商是否达到升级条件,进行升级 // TODO: Implement __destruct() method. if (!empty($this->insert)) self::incrCommissionGoods($this->insert);//增加销量 if (!empty($this->orderData)){ $result = $this->objMCommissionBusinessman->outSetStatistics( $this->orderData['userCenterId'], [ 'skuIds' => array_column($this->orderGoods,'skuId'), 'statistics'=>[ 'auditOrderTotal' => 1, 'auditTotalMoney' => $this->orderData['payAmount'] ] ] ); if (!$result->isSuccess()){ Logger::logs(E_USER_ERROR,'分销商',__CLASS__,__LINE__,$result->getData()); } } //if (!empty($this->needUserCenterIds)) self::upgrade();//升级 } /** * Doc: (des="创建分销") * User: XMing * Date: 2020/7/23 * Time: 10:46 上午 * @param int $customerId * @param int $orderId * @return ResultWrapper * @throws \Exception */ public function createCommission(int $customerId, int $orderId) { // 查询买家是否有上级,和买家是否是分销商 $customer = $this->objDCustomer->get(['id' => $customerId], 'isCommission,commissionPath'); if ($customer === false) { return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror); } if (empty($customer)) { return ResultWrapper::fail('未查询到客户', ErrorCode::$paramError); } // 获取订单索引数据 $orderIndex = $this->objDOrderIndex->get(['id' => $orderId], 'userCenterId,no'); if ($orderIndex === false) { return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror); } if (empty($orderIndex)) { return ResultWrapper::fail('未查询到指定订单', ErrorCode::$paramError); } // 切表 $fix = ceil($orderIndex['userCenterId'] / $this->cutTable); $this->objDOrderGoods->setTable('qianniao_order_goods_' . $this->onlineEnterpriseId . '_' . $fix); $this->objDOrder->setTable('qianniao_order_'.$this->onlineEnterpriseId.'_'.$fix); // 获取订单数据 $orderData = $this->objDOrder->get(['id'=>$orderId],'id,payAmount,userCenterId,customerId'); if ($orderData === false){ return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } if (empty($orderData)) { return ResultWrapper::fail('订单数据为空', ErrorCode::$paramError); } $this->orderData = $orderData; // 查询订单商品数据 $orderGoods = $this->objDOrderGoods->select(['orderId' => $orderId], 'goodsId,skuId,totalMoney,buyNum,vipDiscount,preferential,goodsName,shopName,unitName,specGroup,goodsImages'); if ($orderGoods === false) { return ResultWrapper::fail($this->objDOrderGoods->error(), ErrorCode::$dberror); } if (empty($orderGoods)) { return ResultWrapper::fail('订单商品数据为空', ErrorCode::$paramError); } $this->orderGoods = $orderGoods; // 判断当前客户是否是分销商 $isCommission = $customer['isCommission'];//是否是分销商 5->分销商 4->不是分销商 $retPath = $customer['commissionPath'];//分销商关系 if ($isCommission == StatusCode::$delete && empty($retPath)) { return ResultWrapper::success('不符合分销条件'); } // 查询分销设置数据 $settingResult = $this->objMCommissionSetting->getSetting(true); if (!$settingResult->isSuccess()) { return ResultWrapper::fail($settingResult->getData(), $settingResult->getErrorCode()); } $setting = $settingResult->getData(); if (!isset($setting['mode'])) { return ResultWrapper::fail('分销佣金计算方式未设置', ErrorCode::$paramError); } $this->setting = $setting; $isRetSelf = $setting['self']; // 自动返佣 $this->mode = $setting['mode']; // 佣金计算方式 $this->level = $setting['level'];//分销等级 三级分销 $this->isRetSelf = $isRetSelf; //组装订单商品数据数据 $commonData = [ 'orderId' => $orderId, 'orderNo' => $orderIndex['no'], 'userCenterId' => $orderIndex['userCenterId'], 'customerId' => $customerId ]; foreach ($orderGoods as &$item) { $item = array_merge($item, $commonData); } $selfOrderInsert = []; // 如果当前客户是分销商且开启自购返佣 if ($isCommission == StatusCode::$standard && $isRetSelf == StatusCode::$standard) { empty($this->needUserCenterIds) && $this->needUserCenterIds = []; $this->needUserCenterIds = array_merge($this->needUserCenterIds, [$orderIndex['userCenterId']]); $selfRetCommission = self::selfRetCommission($orderIndex['userCenterId'], $customerId, $orderGoods); if (!$selfRetCommission->isSuccess()) { return ResultWrapper::fail($selfRetCommission->getData(), $selfRetCommission->getErrorCode()); } $selfOrderInsert = $selfRetCommission->getData(); } // 给上级返佣 $retOrderInsert = []; if (!empty($retPath) && $this->level != 0) { // 所有上级的usercenterid集合 $retPathArr = array_values(json_decode($retPath, true)); empty($this->needUserCenterIds) && $this->needUserCenterIds = []; $this->needUserCenterIds = array_merge($this->needUserCenterIds, $retPathArr); $iterRetCommissionResult = self::iterRetCommission($retPathArr, $orderGoods); if (!$iterRetCommissionResult->isSuccess()) { return ResultWrapper::fail($iterRetCommissionResult->getData(), $iterRetCommissionResult->getErrorCode()); } $retOrderInsert = $iterRetCommissionResult->getData(); } $insert = array_merge($selfOrderInsert, $retOrderInsert); if (empty($insert)) { return ResultWrapper::success('没有需要记录的数据'); } $updateOrderData = self::updateOrderData($selfOrderInsert,$retOrderInsert);//订单佣金拓展字段 $commissionOrderIndex = self::commissionIndexData($selfOrderInsert,$retOrderInsert,$orderData['payAmount']);//分销订单索引数据 $updateCommissionResult = self::updateCommission($insert);//计算分销商的变动数据 if (!$updateCommissionResult->isSuccess()) { return ResultWrapper::fail($updateCommissionResult->getData(), $updateCommissionResult->getErrorCode()); } $updateCommission = $updateCommissionResult->getData(); $statisticsDataResult = self::saveBusinessmanStatistics($commissionOrderIndex,$orderData['payAmount']);//计算要回写的数据 if (!$statisticsDataResult->isSuccess()){ return ResultWrapper::fail($statisticsDataResult->getData(),$statisticsDataResult->getErrorCode()); } $statisticsData = $statisticsDataResult->getData();//要回写的数据 /***************************************写记录start*************************************************************/ $this->objDCommissionOrder->beginTransaction(); foreach ($updateCommission as $key => $value) { $update = $this->objDCommissionBusinessman->update([ 'waitMoney' => $value['waitMoney'], 'updateTime' => $value['updateTime'] ], ['userCenterId' => $value['userCenterId']]); if ($update === false) { $this->objDCommissionOrder->rollBack(); return ResultWrapper::fail($this->objDCommissionBusinessman->error(), ErrorCode::$dberror); } } $insert = self::insertSort($insert); $result = $this->objDCommissionOrder->insert($insert, true); if ($result === false) { $this->objDCommissionOrder->rollBack(); return ResultWrapper::fail($this->objDCommissionOrder->error(), ErrorCode::$dberror); } //回写订单索引表 $updateIndex = $this->objDOrderIndex->update( [ 'isCommission'=> StatusCode::$standard, 'commissionData' => json_encode($updateOrderData), 'updateTime' => time() ], ['id' => $orderId] ); if ($updateIndex === false){ $this->objDCommissionOrder->rollBack(); return ResultWrapper::fail($this->objDOrderIndex->error(),ErrorCode::$dberror); } //写订单表 $updateOrder = $this->objDOrder->update([ 'isCommission'=> StatusCode::$standard, 'commissionData' => json_encode($updateOrderData), 'updateTime' => time() ],['id' => $orderId]); if ($updateOrder === false){ $this->objDCommissionOrder->rollBack(); return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } //分销订单索引数据 $commissionOrderIndex = self::insertSort($commissionOrderIndex); $commissionOrderIndex = $this->objDCommissionOrderIndex->insert($commissionOrderIndex,true); if ($commissionOrderIndex === false){ $this->objDCommissionOrder->rollBack(); return ResultWrapper::fail($this->objDCommissionOrderIndex->error(),ErrorCode::$dberror); } //回写数据 foreach ($statisticsData as $userCenterId => $row){ $outSetStatisticsResult = $this->objMCommissionBusinessman->outSetStatistics($userCenterId,$row); if (!$outSetStatisticsResult->isSuccess()){ $this->objDCommissionOrder->rollBack(); } } $this->objDCommissionOrder->commit(); $this->insert = $insert; return ResultWrapper::success("操作成功"); } /** * Doc: (des="分销订单主索引表") * User: XMing * Date: 2020/7/30 * Time: 11:38 上午 * @param array $selfOrderInsert * @param array $retOrderInsert * @param $payAmount * @return array */ private function commissionIndexData(array $selfOrderInsert,array $retOrderInsert,$payAmount) { $commissionIndexMap = []; //自购返佣 if (!empty($selfOrderInsert)){ //将数据按照订单级别合并 $retMoney = array_sum(array_column($selfOrderInsert,'retMoney')); $commissionIndexMap[] = [ 'userCenterId' => $selfOrderInsert[0]['userCenterId'], 'customerId' => $selfOrderInsert[0]['customerId'], 'orderId' => $selfOrderInsert[0]['orderId'], 'orderNo' => $selfOrderInsert[0]['orderNo'], 'payAmount' => $payAmount, 'retUserCenterId' => $selfOrderInsert[0]['retUserCenterId'], 'retCustomerId' => $selfOrderInsert[0]['retCustomerId'], 'retMoney' => $retMoney, 'retLevel' => $selfOrderInsert[0]['retLevel'], 'retGrade' => $selfOrderInsert[0]['retGrade'] ]; } //三级返佣 if (!empty($retOrderInsert)){ $oneRetMoney = 0; $twoRetMoney = 0; $threeRetMoney = 0; foreach ($retOrderInsert as $item){ $common[$item['retLevel']] = [ 'userCenterId' => $item['userCenterId'], 'customerId' => $item['customerId'], 'orderId' => $item['orderId'], 'orderNo' => $item['orderNo'], 'payAmount' => $payAmount, 'retUserCenterId' => $item['retUserCenterId'], 'retCustomerId' => $item['retCustomerId'], 'retLevel' => $item['retLevel'], 'retGrade' => $item['retGrade'] ]; switch ($item['retLevel']){ case self::$levelMap['oneRate']: $oneRetMoney = bcadd($oneRetMoney,$item['retMoney'],2); break; case self::$levelMap['twoRate']: $twoRetMoney = bcadd($twoRetMoney,$item['retMoney'],2); break; case self::$levelMap['threeRate']: $threeRetMoney = bcadd($threeRetMoney,$item['retMoney'],2); break; } } //一级 if ($oneRetMoney != 0){ $common[self::$levelMap['oneRate']]['retMoney'] = $oneRetMoney; $commissionIndexMap[] = $common[self::$levelMap['oneRate']]; } //二级 if($twoRetMoney != 0){ $common[self::$levelMap['twoRate']]['retMoney'] = $twoRetMoney; $commissionIndexMap[] = $common[self::$levelMap['twoRate']]; } //三级 if ($threeRetMoney != 0){ $common[self::$levelMap['threeRate']]['retMoney'] = $threeRetMoney; $commissionIndexMap[] = $common[self::$levelMap['threeRate']]; } } Logger::logs(E_USER_ERROR,'分销订单索引数据',__CLASS__,__LINE__,$commissionIndexMap); return $commissionIndexMap; } /** * Doc: (des="对插入的二维数组进行排序") * User: XMing * Date: 2020/7/30 * Time: 2:42 下午 * @param array $data * @return array */ private function insertSort(array $data) { foreach ($data as &$value){ ksort($value); } return $data; } /** * Doc: (des="回写订单的分销状态,记录订单分销数据json") * User: XMing * Date: 2020/7/29 * Time: 6:57 下午 * @param array $selfOrderInsert * @param array $retOrderInsert * @example * isCommission 是否是分销订单 5是 4否 * @return array * */ private function updateOrderData(array $selfOrderInsert,array $retOrderInsert) { $commissionMap=[]; //自购返佣 if (!empty($selfOrderInsert)){ $retMoney = array_sum(array_column($selfOrderInsert,'retMoney')); $commissionMap['self'] = [ 'retLevel' => 1, 'retMoney' => $retMoney, 'retCustomerId' => $selfOrderInsert[0]['customerId'], 'retUserCenterId' => $selfOrderInsert[0]['userCenterId'], ]; } //三级返佣 if(!empty($retOrderInsert)){ $oneRetMoney = 0; $twoRetMoney = 0; $threeRetMoney = 0; foreach ($retOrderInsert as $item){ switch ($item['retLevel']){ case self::$levelMap['oneRate']: $oneRetMoney = bcadd($oneRetMoney,$item['retMoney'],2); //一级返佣 $commissionMap['oneRet'] = [ 'retLevel' => self::$levelMap['oneRate'], 'retMoney' => $oneRetMoney, 'retCustomerId' => $item['retCustomerId'], 'retUserCenterId' => $item['retUserCenterId'] ]; break; case self::$levelMap['twoRate']: //二级 $twoRetMoney = bcadd($twoRetMoney,$item['retMoney'],2); $commissionMap['twoRet'] = [ 'retLevel' => self::$levelMap['twoRate'], 'retMoney' => $twoRetMoney, 'retCustomerId' => $item['retCustomerId'], 'retUserCenterId' => $item['retUserCenterId'] ]; break; case self::$levelMap['threeRate']: //三级 $threeRetMoney = bcadd($threeRetMoney,$item['retMoney'],2); $commissionMap['threeRet'] = [ 'retLevel' => self::$levelMap['threeRate'], 'retMoney' => $threeRetMoney, 'retCustomerId' => $item['retCustomerId'], 'retUserCenterId' => $item['retUserCenterId'] ]; break; } } } return $commissionMap; } /** * Doc: (des="计算分销商的更新数据") * User: XMing * Date: 2020/7/24 * Time: 10:21 上午 * @param array $data * @return ResultWrapper */ private function updateCommission(array $data) { //查询分销商记录 $allRetUserCenterIds = []; $changeMap = []; foreach ($data as $item) { $allRetUserCenterIds[] = $item['retUserCenterId']; $changeMap[$item['retUserCenterId']][] = $item['retMoney']; } $businessmanResult = self::getCommissionBusinessman($allRetUserCenterIds); if (!$businessmanResult->isSuccess()){ return ResultWrapper::fail($businessmanResult->getData(),$businessmanResult->getErrorCode()); } $businessman = $businessmanResult->getData(); $update = []; foreach ($businessman as $row) { $oldWaitMoney = $row['waitMoney'];//原金额 //获取当前用户变动金额 $changeMoney = array_sum($changeMap[$row['userCenterId']]);//变动金额 $newWaitMoney = bcadd($oldWaitMoney, $changeMoney, 2);//变动后金额 $update[] = [ 'userCenterId' => $row['userCenterId'], 'waitMoney' => $newWaitMoney, 'updateTime' => time(),//变动时间 ]; } if (!empty($update)){ Logger::logs(E_USER_ERROR,'分销商更新数据',__CLASS__,__LINE__,$update); } return ResultWrapper::success($update); } /** * Doc: (des="获取分销商的信息集合") * User: XMing * Date: 2020/7/31 * Time: 11:30 上午 * @param array $allRetUserCenterIds * @param string $fields * @return ResultWrapper * */ private function getCommissionBusinessman(array $allRetUserCenterIds,string $fields='id,userCenterId,balance,totalMoney,waitMoney') { $businessman = $this->objDCommissionBusinessman->select(['userCenterId' => $allRetUserCenterIds], $fields); if ($businessman === false) { return ResultWrapper::fail($this->objDCommissionBusinessman->error(), ErrorCode::$dberror); } return ResultWrapper::success($businessman); } /** * Doc: (des="分销数据的回写") * User: XMing * Date: 2020/7/28 * Time: 3:23 下午 * @param array $data 分销返佣的数据 * @param float $payAmount * @example * @return ResultWrapper */ private function saveBusinessmanStatistics(array $data,float $payAmount) { //demo /**$params = [ 'balance' => 100.00, //余额 'waitMoney' => 100.00, //待入账金额 'withdraw' => 100.00, //已提现金额 'statistics' => [ 'orderMoney' => 100.00, //分销订单总额 'orderNum' => 100, //分销订单总数 'oneOrderMoney' => 100.00, //一级分销订单总额 'oneOrderNum' => 100, //一级分销订单总数 'selfOrderMoney' => 100.00, //自购订单总额 'selfOrderNum' => 100, //自购订单总数 'sub' => 100, //下线人数 'subBusinessman' => 100, //下线分销商人数 'oneSub' => 100, //一级下线人数 'oneSubBusinessman' => 100, //一级下线分销商 'totalMoney' => 100.00, //累计佣金 ], ];*/ $allRetUserCenterIds = []; $changeMap = []; foreach ($data as $item) { $allRetUserCenterIds[] = $item['retUserCenterId']; $changeMap[$item['retUserCenterId']][] = $item['retMoney']; } $businessmanResult = self::getCommissionBusinessman($allRetUserCenterIds); if (!$businessmanResult->isSuccess()){ return ResultWrapper::fail($businessmanResult->getData(),$businessmanResult->getErrorCode()); } $businessman = $businessmanResult->getData(); $businessmanMap = []; foreach ($businessman as $value){ $businessmanMap[$value['userCenterId']] = $value; } $arrayMap = []; foreach ($data as $key => $item){ if (!isset($businessmanMap[$item['retUserCenterId']])){ return ResultWrapper::fail('分销商数据映射失败',ErrorCode::$paramError); } $oldTotalMoney = $businessmanMap[$item['retUserCenterId']]['totalMoney']; $arrayMap[$item['retUserCenterId']] = [ 'totalMoney' => bcadd($oldTotalMoney,$item['retMoney']), 'statistics' => [ 'orderMoney' => $payAmount, 'orderNum' => 1, ], ];//公共数据 switch ($key){ case 'self': //自购 $arrayMap[$item['retUserCenterId']]['statistics']['selfOrderMoney'] = $payAmount; $arrayMap[$item['retUserCenterId']]['statistics']['selfOrderNum'] = 1; break; case 'oneRet': //一级 $arrayMap[$item['retUserCenterId']]['statistics']['oneOrderMoney'] = $payAmount; $arrayMap[$item['retUserCenterId']]['statistics']['oneOrderNum'] = 1; break; case 'twoRet': //二级 break; case 'threeRet': //三级 break; } } if (!empty($arrayMap)){ Logger::logs(E_USER_ERROR,'回写数据',__CLASS__,__LINE__,$arrayMap); } return ResultWrapper::success($arrayMap); } /** * 上级返佣方法 * @param array $retPathArr 所有上级的usercenterIds * @param array $orderGoodsData 订单商品数据 * @return ResultWrapper */ private function iterRetCommission(array $retPathArr, array $orderGoodsData) { $retGoodsResult = self::getGoodsRule($orderGoodsData); if (!$retGoodsResult->isSuccess()) { return ResultWrapper::fail($retGoodsResult->getData(), $retGoodsResult->getErrorCode()); } $retGoods = $retGoodsResult->getData(); $defaultGoods = $retGoods['defaultGoods']; // 默认返佣规则商品 $defineGoods = $retGoods['defineGoods']; // 自定义佣金规则商品 // 获取分销商等级和等级对应的佣金规则 $gradeResult = self::getGradeRuleBySelect($retPathArr); if (!$gradeResult->isSuccess()) { return ResultWrapper::fail($gradeResult->getData(), $gradeResult->getErrorCode()); } $gradeRule = $gradeResult->getData();//分销商等级佣金比例规则 //$retLevel 当前被返佣分销商所处级别1-3 //$retUserCenterId 当前被返佣分销商的用户id $defaultInsert = []; $defineInsert = []; foreach ($retPathArr as $index => $retUserCenterId) { // 如果开启自购返佣,上一级从第二集开始返佣 if($this->isRetSelf == StatusCode::$standard){ $retLevel = (int)$index + 2; }else{ $retLevel = (int)$index + 1; } // 如果当前分销层级大于后台设置的分销层级则不计算佣金 if ($retLevel > $this->level) { continue; } // 当前路径中的用户id不是分销商,不进行返佣,进入下一级别 if (!isset($gradeRule[$retUserCenterId])) { continue; } $grade = $gradeRule[$retUserCenterId]['grade'];//被返佣用户等级1-10 $retCustomerId = $gradeRule[$retUserCenterId]['customerId'];//被返佣客户id //1.处理默认分销商品 if (!empty($defaultGoods)) { $rate = $gradeRule[$retUserCenterId][self::$levelMap[$retLevel]];//当前等级当前等级比例 if (empty($rate)) { //比率为0 continue; } $rate = bcdiv($rate, 100); //生成数据 $defaultResult = self::createDefaultOrder($defaultGoods, $rate, $grade, $retUserCenterId, $retCustomerId, $retLevel, StatusCode::$delete); $defaultInsert = array_merge($defaultInsert, $defaultResult);//合并每次的结果 } //2.处理自定义分销商品 if (!empty($defineGoods)) { $defineResult = self::createDefineOrder($defineGoods, $grade, $retUserCenterId, $retCustomerId, $retLevel, StatusCode::$delete); $defineInsert = array_merge($defineInsert, $defineResult); } } $return = array_merge($defaultInsert, $defineInsert);//合并最终数据 return ResultWrapper::success($return); } /** * @param array $data 订单商品数据 * @param int $userCenterId 自购分销商用户id * @param int $customerId 自购分销商客户id * @return ResultWrapper 返回数据为自购返佣记录数据 */ private function selfRetCommission(int $userCenterId, int $customerId, array $orderGoodsData) { $retGoodsResult = self::getGoodsRule($orderGoodsData); if (!$retGoodsResult->isSuccess()) { return ResultWrapper::fail($retGoodsResult->getData(), $retGoodsResult->getErrorCode()); } $retGoodsResult = $retGoodsResult->getData(); $defaultGoods = $retGoodsResult['defaultGoods']; // 默认佣金规则的商品 $defineGoods = $retGoodsResult['defineGoods']; // 单独设置佣金规则的商品 // 获取分销商等级佣金规则 $gradeResult = self::getGradeRuleBySelect([$userCenterId]); if (!$gradeResult->isSuccess()) { return ResultWrapper::fail($gradeResult->getData(), $gradeResult->getErrorCode()); } $gradeRule = $gradeResult->getData(); $selfGradeRule = isset($gradeRule[$userCenterId]) ? $gradeRule[$userCenterId] : [];//分销商的等级佣金规则 if (empty($selfGradeRule)) { return ResultWrapper::fail('获取分销等级规则为空', ErrorCode::$paramError); } $grade = $selfGradeRule['grade'];//自购分销商等级0-10 //默认分销佣金商品 $defaultInsert = []; if (!empty($defaultGoods)) { //自购分销商的等级佣金比率 $rate = $this->isRetSelf == StatusCode::$delete ? 0 : bcdiv($selfGradeRule['oneRate'], 100);//自购使用一级分销商的比率,将比率换算成浮点数 $defaultInsert = self::createDefaultOrder($defaultGoods, $rate, $grade, $userCenterId, $customerId, 1, StatusCode::$standard);//自购返佣数据 } // 单独设置佣金规则的商品 $defineInsert = []; if (!empty($defineGoods)) { $defineInsert = self::createDefineOrder($defineGoods, $grade, $userCenterId, $customerId, 1, StatusCode::$standard); } $insert = array_merge($defaultInsert, $defineInsert); return ResultWrapper::success($insert); } /** * 计算单独设置佣金规则商品 * @param array $data 单独设置佣金规则的商品数据 * @param int $grade 被返佣分销商的等级1-10 * @param int $retUserCenterId 被返佣分销商用户id * @param int $retCustomerId 被返佣分销商客户id * @param int $retLevel 被返佣分销商的级别1-3 * @param int $isSelf 是否自购返佣 5是 4否 * * @return array */ private function createDefineOrder(array $data, int $grade, int $retUserCenterId, int $retCustomerId, int $retLevel, int $isSelf) { $insert = []; foreach ($data as $item) { $amount = 0; switch ($this->mode) { case StatusCode::$standard: // 实际支付金额 $amount = bcsub($item['totalMoney'], bcadd($item['vipDiscount'], $item['preferential']), 2); break; case StatusCode::$delete: // 商品折扣价 $amount = bcsub($item['totalMoney'], $item['preferential'],2); break; } $oneRate = isset($item['rule'][$grade][self::$levelMap[$retLevel]]) ? $item['rule'][$grade][self::$levelMap[$retLevel]] : 0;//自购一级佣金比例 if (empty($oneRate)) { continue; } $retRate = 0; // 佣金计算百分比 if($item['retType'] == StatusCode::$standard){ // 返佣方式百分比 $oneRate = bcdiv($oneRate, 100); $retMoney = bcmul($amount, $oneRate, 2); $retRate = bcmul($oneRate, 100); }else{ // 返佣方式固定金额 $retMoney = bcmul($oneRate, $item['buyNum'], 2); } //是自购订单但是未开启自购 if ($isSelf == StatusCode::$standard && $this->isRetSelf == StatusCode::$delete){ $retMoney = 0; } $insert[] = [ 'userCenterId' => $item['userCenterId'], 'customerId' => $item['customerId'], 'orderId' => $item['orderId'], 'orderNo' => $item['orderNo'], 'goodsId' => $item['goodsId'], 'skuId' => $item['skuId'], 'goodsPrice' => $item['totalMoney'], 'retUserCenterId' => $retUserCenterId, 'retCustomerId' => $retCustomerId, 'retMoney' => $retMoney, 'retLevel' => $retLevel, //级别1-3 'retGrade' => $grade, //等级1-10, 'retRate' => $retRate, 'buyNum' => $item['buyNum'], 'goodsName' => $item['goodsName'], 'shopName' => $item['shopName'], 'unitName' => $item['unitName'], 'specGroup' => $item['specGroup'], 'goodsImages' => $item['goodsImages'], 'isSelf' => $isSelf ]; } return $insert; } /** * Doc: (des="生成默认佣金流水记录数据") * User: XMing * Date: 2020/7/23 * Time: 4:45 下午 * @param array $data 分销商品数据 * @param string $rate 被返佣分销商所处等级级别比率 * @param int $grade 被返佣分销商的等级1-10 * @param int $retUserCenterId 被返佣分销商用户id * @param int $retCustomerId 被返佣分销商客户id * @param int $retLevel 被返佣人所处级别1-3 * @param int $isSelf 是否自购返佣 5是 4否 * @return array */ private function createDefaultOrder(array $data, string $rate, int $grade, int $retUserCenterId, int $retCustomerId, int $retLevel, int $isSelf) { $insert = []; foreach ($data as $item) { $amount = 0; switch ($this->mode) { case StatusCode::$standard: //实际支付金额 $amount = bcsub($item['totalMoney'], bcadd($item['vipDiscount'], $item['preferential']), 2); break; case StatusCode::$delete: $amount = bcsub($item['totalMoney'], $item['preferential'],2); break; } $retMoney = bcmul($amount, $rate, 2); $insert[] = [ 'userCenterId' => $item['userCenterId'], 'customerId' => $item['customerId'], 'orderId' => $item['orderId'], 'orderNo' => $item['orderNo'], 'goodsId' => $item['goodsId'], 'skuId' => $item['skuId'], 'goodsPrice' => $item['totalMoney'], 'retUserCenterId' => $retUserCenterId, 'retCustomerId' => $retCustomerId, 'retMoney' => $retMoney, 'retLevel' => $retLevel,//级别1-3 'retGrade' => $grade,//等级1-10, 'retRate' => bcmul($rate, 100), 'buyNum' => $item['buyNum'], 'goodsName' => $item['goodsName'],// 'shopName' => $item['shopName'],// 'unitName' => $item['unitName'],// 'specGroup' => $item['specGroup'],// 'goodsImages' => $item['goodsImages'],// 'isSelf' => $isSelf ]; } return $insert; } /** * 批量获取指定用户的分销商等级 * @param array $params 分销商的userCenterIds * @return ResultWrapper */ private function getGradeRuleBySelect(array $params) { $commissionBusinessmanResult = $this->objMCommissionBusinessman->getBusinessmanGrade($params); if (!$commissionBusinessmanResult->isSuccess()) { return ResultWrapper::fail($commissionBusinessmanResult->getData(), $commissionBusinessmanResult->getErrorCode()); } return ResultWrapper::success($commissionBusinessmanResult->getData()); } /** * 处理单独设置佣金的商品 * @param array $orderGoods 订单商品 * @return ResultWrapper */ private function getGoodsRule(array $orderGoods) { // 提取所有订单商品id并映射 $goodsIds = []; $orderGoodsMap = []; foreach ($orderGoods as $goods) { $goodsIds[] = $goods['goodsId']; $orderGoodsMap[$goods['goodsId']] = $goods; } // 获取商品是否参与分销是否单独有设置比率 $goodsData = $this->objDGoods->select(['id' => $goodsIds], 'id,isJoinCommission,isDefine,retType'); if ($goodsData === false) { return ResultWrapper::fail($this->objDGoods->error(), ErrorCode::$dberror); } if (empty($goodsData)) { return ResultWrapper::fail('获取商品分销设置失败', ErrorCode::$paramError); } // 过滤不参加分销的,并且筛选自定义佣金比例商品 $defineGoods = []; // 自定义佣金商品集合 $deleteGoods = []; // 不参与分销的商品集合 $defaultGoods = []; // 默认佣金商品集合 foreach ($goodsData as $key => $datum) { $orderGoodsMap[$datum['id']]['retType'] = $datum['retType']; // 未参与分销商品 if ($datum['isJoinCommission'] == StatusCode::$delete) { $deleteGoods[] = array_merge($deleteGoods, $orderGoodsMap[$datum['id']]); unset($orderGoodsMap[$datum['id']]); continue; } // 自定义佣金商品 if ($datum['isDefine'] == StatusCode::$standard) { $defineGoods[] = array_merge($defineGoods, $orderGoodsMap[$datum['id']]); unset($orderGoodsMap[$datum['id']]); continue; } //剩下的都是默认的佣金配置 $defaultGoods[] = array_merge($defaultGoods, $orderGoodsMap[$datum['id']]); } // 自定义佣金商品不为空 if (!empty($defineGoods)) { $skuIds = []; foreach ($defineGoods as $item) { $skuIds[] = $item['skuId']; } // 查询单独设置佣金的商品设置内容 $commissionGoods = $this->objDCommissionGoods->select(['skuId' => $skuIds, 'deleteStatus' => StatusCode::$standard], 'commissionRule,goodsId,skuId'); if ($commissionGoods === false) { return ResultWrapper::fail($this->objDCommissionGoods->error(), ErrorCode::$dberror); } if (empty($commissionGoods)) { return ResultWrapper::fail('获取自定义商品佣金比例为空', ErrorCode::$paramError); } $commissionGoodsMap = []; foreach ($commissionGoods as $item) { $commissionGoodsMap[$item['skuId']] = empty($item['commissionRule']) ? [] : json_decode($item['commissionRule'], true); } foreach ($defineGoods as $key => $item) { $defineGoods[$key]['rule'] = isset($commissionGoodsMap[$item['skuId']]) ? $commissionGoodsMap[$item['skuId']] : []; } } $return = [ 'defaultGoods' => $defaultGoods, 'defineGoods' => $defineGoods ]; return ResultWrapper::success($return); } /** * Doc: (des="检测是否达到升级的条件") * User: XMing * Date: 2020/7/25 * Time: 9:49 上午 */ public function upgrade() { //test-demo /*$this->needUserCenterIds = [ 168, 169, 140 ];*/ //获取分销商的等级 //需要检测是否升级的用户id if (empty($this->needUserCenterIds)) { return ResultWrapper::success('没有需要升级的分销商'); } //获取所有等级 $gradeConditionResult = $this->objMCommissionGrade->getAllGradeCondition(['type' => StatusCode::$delete]); if (!$gradeConditionResult->isSuccess()){ return ResultWrapper::fail($gradeConditionResult->getData(),$gradeConditionResult->getErrorCode()); } $gradeCondition = $gradeConditionResult->getData(); if (empty($gradeCondition)){ return ResultWrapper::fail('等级条件未配置',ErrorCode::$paramError); } $this->allAliasCondition = array_column($gradeCondition,'key'); //获取这批用户的当前等级 $commissionBusinessmanResult = $this->objMCommissionBusinessman->getBusinessmanGrade($this->needUserCenterIds); if (!$commissionBusinessmanResult->isSuccess()) { return ResultWrapper::fail($commissionBusinessmanResult->getData(), $commissionBusinessmanResult->getErrorCode()); } $commissionBusinessman = $commissionBusinessmanResult->getData(); //查询等级升级条件 $gradeUpgradeConditionAllResult = $this->objMCommissionGrade->getAllGrade(); if (!$gradeUpgradeConditionAllResult->isSuccess()) { return ResultWrapper::fail($gradeUpgradeConditionAllResult->getData(), $gradeUpgradeConditionAllResult->getErrorCode()); } $gradeUpgradeConditionAll = $gradeUpgradeConditionAllResult->getData(); $gradeUpgradeConditionMap = [];//等级对应升级条件 foreach ($gradeUpgradeConditionAll as $item) { $gradeUpgradeConditionMap[$item['grade']] = $item; } $allUserCenterIds = []; foreach ($commissionBusinessman as $userCenterId => $value) { $nextGrade = (int)$value['grade'] + 1; $commissionBusinessman[$userCenterId]['nextCondition'] = []; if (!isset($gradeUpgradeConditionMap[$nextGrade])) { unset($commissionBusinessman[$userCenterId]); continue; } $commissionBusinessman[$userCenterId]['nextCondition'] = $gradeUpgradeConditionMap[$nextGrade]['upgradeConditionInfo']; $commissionBusinessman[$userCenterId]['nextGrade'] = $nextGrade; $commissionBusinessman[$userCenterId]['upgradeMode'] = $gradeUpgradeConditionMap[$nextGrade]['upgradeMode'];//是否需要满足所有条件 5是 4否 $commissionBusinessman[$userCenterId]['nextGradeId'] = $gradeUpgradeConditionMap[$nextGrade]['id'];//是否需要满足所有条件 5是 4否 $allUserCenterIds[] = $userCenterId; } if (empty($commissionBusinessman)) { return ResultWrapper::success('没有需要升级的分销商'); } //获取分销商的统计数据 $statisticsResult = self::statisticsData($allUserCenterIds); if (!$statisticsResult->isSuccess()) { return ResultWrapper::fail($statisticsResult->getData(), $statisticsResult->getErrorCode()); } $statisticsData = $statisticsResult->getData(); if (empty($statisticsData)){ return ResultWrapper::fail('获取分销商统计数据为空',ErrorCode::$paramError); } $upgradeData = [];//需要升级的分销商数据 foreach ($commissionBusinessman as $userCenterId => $item){ //获取分销商统计数据 if (!isset($statisticsData[$userCenterId])){ continue; } $commissionData = $statisticsData[$userCenterId]; $upgradeBool = self::checkCommissionConditionGrad($item['nextCondition'],$commissionData,$item['upgradeMode']); if ($upgradeBool == false){ //不满足条件 continue; } //升级 $upgradeData[] = [ 'id' => $item['businessmanId'], 'userCenterId' => $item['userCenterId'], 'grade' => $item['nextGrade'], 'gradeId' => $item['nextGradeId'], 'updateTime' => time() ]; } //操作数据库 if(empty($upgradeData)){ return ResultWrapper::success('没有需要升级的分销商'); } $this->objDCommissionBusinessman->beginTransaction(); foreach ($upgradeData as $datum){ $update = $this->objDCommissionBusinessman->update([ 'grade' => $datum['grade'], 'gradeId' => $datum['gradeId'], 'updateTime' => $datum['updateTime'] ],[ 'userCenterId' => $datum['userCenterId']]); if ($update === false){ $this->objDCommissionBusinessman->rollBack(); return ResultWrapper::fail($this->objDCommissionBusinessman->error(),ErrorCode::$dberror); } } $this->objDCommissionBusinessman->commit(); Logger::logs(E_USER_ERROR,'升级的数据',__CLASS__,__LINE__,$upgradeData); return ResultWrapper::success('操作成功'); } /** * Doc: (des="判断分销商是否满足对应条件") * User: XMing * Date: 2020/7/25 * Time: 3:37 下午 * @param array $nextCondition 升到下一级所需要的条件 * @param array $commissionData 分销商的统计数据 * @param int $upgradeMode 是否需要满足所有条件 4:否 5:是 * @return boolean * 升级 => true */ private function checkCommissionConditionGrad(array $nextCondition,array $commissionData,int $upgradeMode) { $num = count($nextCondition); $meet = 0;//满足条件的数目 foreach ($nextCondition as $item){ $data = isset($commissionData[$item['key']]) ? $commissionData[$item['key']] : 0; if ($data >= $item['value']){ //满足条件 if ($upgradeMode == StatusCode::$delete){ //满足任意条件即可 return true; } $meet = $meet + 1; } } //不符合升级条件 if ($meet == 0){ return false; } //满足 4任意条件 / 5全部条件 switch ($upgradeMode){ case StatusCode::$delete: //满足一个条件即可 if ($meet > 0) return true; break; case StatusCode::$standard: if ($meet == $num) return true; break; } return false; } /** * Doc: (des="统计分销商的数据") * User: XMing * Date: 2020/7/25 * Time: 3:30 下午 * * orderMoney 分销订单总额 * orderNum 分销订单总数 * oneOrderMoney 一级分销订单总额 * oneOrderNum 一级分销订单总数 * selfOrderMoney 自购订单总额 * selfOrderNum 自购订单总数 * sub 下线人数 * subBusinessman 下线分销商人数 * oneSub 一级下线人数 * oneSubBusinessman 一级下线分销商人数 * withdraw 已提现金额 * buyCard 购买会员卡 * * @param array $userCenterIds * @return ResultWrapper */ private function statisticsData(array $userCenterIds) { //demo /**$map = [ 168 => [ 'orderMoney' => 100, 'orderNum' => 1, 'oneOrderMoney' => 100, 'oneOrderNum' => 1, 'selfOrderMoney' => 100, 'selfOrderNum' => 1, 'sub' => 10, 'subBusinessman' => 1, 'oneSub' => 10, 'oneSubBusinessman' => 1, 'withdraw' => 100, 'buyCard' => true ] ];*/ $businessmanStatisticsResult = $this->objMCommissionBusinessman->getBusinessmanStatistics($userCenterIds); if (!$businessmanStatisticsResult->isSuccess()){ return ResultWrapper::fail($businessmanStatisticsResult->getData(),$businessmanStatisticsResult->getErrorCode()); } //统计分销商的订单总辆 return ResultWrapper::success($businessmanStatisticsResult->getData()); } /** * Doc: (des="增加分销商品的销量佣金") * User: XMing * Date: 2020/7/28 * Time: 9:15 上午 * @param array $data * @return ResultWrapper */ private function incrCommissionGoods(array $data) { $allSkuIds = []; foreach ($data as $value){ $allSkuIds[] = $value['skuId']; } //获取这批数据记录 $oldCommissionGoodsStatistics = $this->objDCommissionGoodsStatistics->select(['skuId'=>$allSkuIds]); if ($oldCommissionGoodsStatistics === false){ return ResultWrapper::fail($this->objDCommissionGoodsStatistics->error(),ErrorCode::$dberror); } //给对应的商品增加销量以及商品佣金 $commissionGoodsMap = []; foreach ($oldCommissionGoodsStatistics as $item){ $commissionGoodsMap[$item['skuId']] = $item; } $replace = []; foreach ($data as $datum){ $oldSalesNum = isset($commissionGoodsMap[$datum['skuId']]['salesNum']) ? $commissionGoodsMap[$datum['skuId']]['salesNum'] : 0; $oldCommission = isset($commissionGoodsMap[$datum['skuId']]['commission']) ? $commissionGoodsMap[$datum['skuId']]['commission'] : 0; $replace[] = [ 'goodsId' => $datum['goodsId'], 'skuId' => $datum['skuId'], 'salesNum' => bcadd($oldSalesNum,$datum['buyNum']), 'commission' => bcadd($oldCommission,$datum['retMoney']), 'createTime' => time() ]; } if (empty($replace)){ return ResultWrapper::success('没有数据需要更新'); } $replace = $this->objDCommissionGoodsStatistics->replace($replace,true); if ($replace === false){ return ResultWrapper::fail($this->objDCommissionGoodsStatistics->error(),ErrorCode::$dberror); } return ResultWrapper::success('操作成功'); } public function updateBalanceNew(int $orderId){ } /** * Doc: (des="订单完成将等待入账转移到余额") * User: XMing * Date: 2020/7/30 * Time: 5:15 下午 * @param int $orderId * @return ResultWrapper */ public function updateBalance(int $orderId) { $commissionDataResult = self::getOrderIndexData($orderId); if (!$commissionDataResult->isSuccess()){ return ResultWrapper::fail($commissionDataResult->getData(),$commissionDataResult->getErrorCode()); } $commissionData = $commissionDataResult->getData(); $selfCommissionData = isset($commissionData['self']) ? $commissionData['self'] : []; $oneCommissionData = isset($commissionData['oneRet']) ? $commissionData['oneRet'] : []; $twoCommissionData = isset($commissionData['twoRet']) ? $commissionData['twoRet'] : []; $threeCommissionData = isset($commissionData['threeRet']) ? $commissionData['threeRet'] : []; $allUserCenterIds = array_column($commissionData,'retUserCenterId'); //获取分销商的余额 $businessman = $this->objDCommissionBusinessman->select(['userCenterId' => $allUserCenterIds], 'id,userCenterId,customerId,balance,waitMoney'); if ($businessman === false) { return ResultWrapper::fail($this->objDCommissionBusinessman->error(), ErrorCode::$dberror); } if(empty($businessman)){ return ResultWrapper::fail('获取分销商数据为空',ErrorCode::$paramError); } $businessmanMap = []; foreach ($businessman as $value){ $businessmanMap[$value['userCenterId']] = $value; } $updateDataResult = self::buildUpdateData($selfCommissionData,$oneCommissionData,$twoCommissionData,$threeCommissionData,$businessmanMap); if (!$updateDataResult->isSuccess()){ return ResultWrapper::fail($updateDataResult->getData(),$updateDataResult->getErrorCode()); } $updateData = $updateDataResult->getData(); if (empty($updateData)){ return ResultWrapper::fail('组装分销商更新数据失败',ErrorCode::$paramError); } $this->objDCommissionBusinessman->beginTransaction(); foreach ($updateData as $value){ //分销商账户表 $update = $this->objDCommissionBusinessman->update( [ 'balance' => $value['balance'], 'waitMoney' => $value['waitMoney'], 'updateTime' => time(), ], [ 'userCenterId'=> $value['userCenterId'] ] ); if ($update === false){ $this->objDCommissionBusinessman->rollBack(); return ResultWrapper::fail($this->objDCommissionBusinessman->error(),ErrorCode::$dberror); } //资金变动记录表 $logResult = self::changeLog($value, $value['changeMoney'],$value['balance'], StatusCode::$standard, '分佣'); if (!$logResult->isSuccess()){ $this->objDCommissionBusinessman->rollBack(); return ResultWrapper::fail($logResult->getData(),$logResult->getErrorCode()); } } //更新这批分销订单 $updateCommissionOrderIndex = $this->objDCommissionOrderIndex->update( [ 'isAccount' => StatusCode::$standard, 'updateTime'=>time() ], [ 'orderId' => $orderId ] ); if ($updateCommissionOrderIndex === false){ $this->objDCommissionBusinessman->rollBack(); } $this->objDCommissionBusinessman->commit(); return ResultWrapper::success('更新分销商佣金成功'); } /** * Doc: (des="构建分销商更新数据") * User: XMing * Date: 2020/7/30 * Time: 6:09 下午 * @param array $selfCommissionData * @param array $oneCommissionData * @param array $twoCommissionData * @param array $threeCommissionData * @param array $businessmanMap * @return ResultWrapper */ private function buildUpdateData(array $selfCommissionData,array $oneCommissionData,array $twoCommissionData,array $threeCommissionData,array $businessmanMap) { $updateMap = []; if (!empty($selfCommissionData)){ //自购返佣 //原等待入账 if (!isset($businessmanMap[$selfCommissionData['retUserCenterId']])){ return ResultWrapper::fail('获取分销商数据失败',ErrorCode::$paramError); } $oldWaitMoney = $businessmanMap[$selfCommissionData['retUserCenterId']]['waitMoney']; $oldBalance = $businessmanMap[$selfCommissionData['retUserCenterId']]['balance']; $changeMoney = $selfCommissionData['retMoney']; $updateMap[] = [ 'userCenterId' => $selfCommissionData['retUserCenterId'], 'oldBalance' => $oldBalance,//原账户金额 'changeMoney' => $changeMoney,//变动金额 'balance' => bcadd($oldBalance,$changeMoney,2),//变动后金额 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2), 'customerId' => $businessmanMap[$selfCommissionData['retUserCenterId']]['customerId'], 'businessmanId' => $businessmanMap[$selfCommissionData['retUserCenterId']]['id'], 'updateTime' => time(), ]; } if (!empty($oneCommissionData)){ //一级返佣 if (!isset($businessmanMap[$oneCommissionData['retUserCenterId']])){ return ResultWrapper::fail('获取分销商数据失败',ErrorCode::$paramError); } $oldWaitMoney = $businessmanMap[$oneCommissionData['retUserCenterId']]['waitMoney']; $oldBalance = $businessmanMap[$oneCommissionData['retUserCenterId']]['balance']; $changeMoney = $oneCommissionData['retMoney']; $updateMap[] = [ 'userCenterId' => $oneCommissionData['retUserCenterId'], 'oldBalance' => $oldBalance,//原账户金额 'changeMoney' => $changeMoney,//变动金额 'balance' => bcadd($oldBalance,$changeMoney,2), 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2), 'customerId' => $businessmanMap[$oneCommissionData['retUserCenterId']]['customerId'], 'businessmanId' => $businessmanMap[$oneCommissionData['retUserCenterId']]['id'], 'updateTime' => time(), ]; } if (!empty($twoCommissionData)){ //二级返佣 if (!isset($businessmanMap[$twoCommissionData['retUserCenterId']])){ return ResultWrapper::fail('获取分销商数据失败',ErrorCode::$paramError); } $oldWaitMoney = $businessmanMap[$twoCommissionData['retUserCenterId']]['waitMoney']; $oldBalance = $businessmanMap[$twoCommissionData['retUserCenterId']]['balance']; $changeMoney = $twoCommissionData['retMoney']; $updateMap[] = [ 'userCenterId' => $twoCommissionData['retUserCenterId'], 'oldBalance' => $oldBalance,//原账户金额 'changeMoney' => $changeMoney,//变动金额 'balance' => bcadd($oldBalance,$changeMoney,2), 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2), 'customerId' => $businessmanMap[$twoCommissionData['retUserCenterId']]['customerId'], 'businessmanId' => $businessmanMap[$twoCommissionData['retUserCenterId']]['id'], 'updateTime' => time(), ]; } if (!empty($threeCommissionData)){ //三级 if (!isset($businessmanMap[$threeCommissionData['retUserCenterId']])){ return ResultWrapper::fail('获取分销商数据失败',ErrorCode::$paramError); } $oldWaitMoney = $businessmanMap[$threeCommissionData['retUserCenterId']]['waitMoney']; $oldBalance = $businessmanMap[$threeCommissionData['retUserCenterId']]['balance']; $changeMoney = $threeCommissionData['retMoney']; $updateMap[] = [ 'userCenterId' => $threeCommissionData['retUserCenterId'], 'oldBalance' => $oldBalance,//原账户金额 'changeMoney' => $changeMoney,//变动金额 'balance' => bcadd($oldBalance,$changeMoney,2), 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2), 'customerId' => $businessmanMap[$threeCommissionData['retUserCenterId']]['customerId'], 'businessmanId' => $businessmanMap[$threeCommissionData['retUserCenterId']]['id'], 'updateTime' => time(), ]; } if (!empty($updateMap)){ Logger::logs(E_USER_ERROR,'分销商更新数据',__CLASS__,__LINE__,$updateMap); } return ResultWrapper::success($updateMap); } /** * Doc: (des="根据订单id获取订单的分销信息") * User: XMing * Date: 2020/7/31 * Time: 5:15 下午 * @param int $orderId * @param string $fields * @return ResultWrapper */ private function getOrderIndexData(int $orderId,string $fields = 'id,commissionData,isCommission') { $orderIndex = $this->objDOrderIndex->get(['id'=>$orderId],$fields); if ($orderIndex === false){ return ResultWrapper::fail($this->objDOrder->error(),ErrorCode::$dberror); } if (empty($orderIndex)){ return ResultWrapper::fail('获取分销订单数据为空',ErrorCode::$paramError); } if ($orderIndex['isCommission'] != StatusCode::$standard){ return ResultWrapper::fail('不是分销订单',ErrorCode::$paramError); } $commissionData = json_decode($orderIndex['commissionData'],true); if (empty($commissionData)){ return ResultWrapper::fail('返佣数据为空',ErrorCode::$paramError); } return ResultWrapper::success($commissionData); } /** * Doc: (des="分销订单取消,扣除返佣") * User: XMing * Date: 2020/7/31 * Time: 3:51 下午 * @param int $orderId * @example * @return ResultWrapper * */ public function cancelSubCommission(int $orderId) { $commissionDataResult = self::getOrderIndexData($orderId); if (!$commissionDataResult->isSuccess()){ return ResultWrapper::fail($commissionDataResult->getData(),$commissionDataResult->getErrorCode()); } $commissionData = $commissionDataResult->getData(); $selfCommissionData = isset($commissionData['self']) ? $commissionData['self'] : []; $oneCommissionData = isset($commissionData['oneRet']) ? $commissionData['oneRet'] : []; $twoCommissionData = isset($commissionData['twoRet']) ? $commissionData['twoRet'] : []; $threeCommissionData = isset($commissionData['threeRet']) ? $commissionData['threeRet'] : []; $allUserCenterIds = array_column($commissionData,'retUserCenterId'); //获取分销商的余额 $businessman = $this->objDCommissionBusinessman->select(['userCenterId' => $allUserCenterIds], 'id,userCenterId,balance,totalMoney,waitMoney'); if ($businessman === false) { return ResultWrapper::fail($this->objDCommissionBusinessman->error(), ErrorCode::$dberror); } if(empty($businessman)){ return ResultWrapper::fail('获取分销商数据为空',ErrorCode::$paramError); } $businessmanMap = []; foreach ($businessman as $value){ $businessmanMap[$value['userCenterId']] = $value; } $updateDataResult = self::buildCancelData($selfCommissionData,$oneCommissionData,$twoCommissionData,$threeCommissionData,$businessmanMap); if (!$updateDataResult->isSuccess()){ return ResultWrapper::fail($updateDataResult->getData(),$updateDataResult->getErrorCode()); } $updateData = $updateDataResult->getData(); if (empty($updateData)){ return ResultWrapper::fail('组装分销商更新数据失败',ErrorCode::$paramError); } $this->objDCommissionBusinessman->beginTransaction(); foreach ($updateData as $value){ $update = $this->objDCommissionBusinessman->update( [ 'waitMoney' => $value['waitMoney'], 'totalMoney' => $value['totalMoney'], 'updateTime' => time(), ], [ 'userCenterId'=> $value['userCenterId'] ] ); if ($update === false){ $this->objDCommissionBusinessman->rollBack(); return ResultWrapper::fail($this->objDCommissionBusinessman->error(),ErrorCode::$dberror); } } //更新这批分销订单取消 $updateCommissionOrderIndex = $this->objDCommissionOrderIndex->update( [ 'isAccount' => StatusCode::$auditStatus['auditNotPass'],//3已取消 'updateTime'=>time() ], [ 'orderId' => $orderId ] ); if ($updateCommissionOrderIndex === false){ $this->objDCommissionBusinessman->rollBack(); } $this->objDCommissionBusinessman->commit(); return ResultWrapper::success('更新分销商佣金成功'); } /** * Doc: (des="取消分销订单,分销商更新数据") * User: XMing * Date: 2020/7/31 * Time: 5:50 下午 * @param array $selfCommissionData * @param array $oneCommissionData * @param array $twoCommissionData * @param array $threeCommissionData * @param array $businessmanMap * @return ResultWrapper */ private function buildCancelData(array $selfCommissionData,array $oneCommissionData,array $twoCommissionData,array $threeCommissionData,array $businessmanMap) { $updateMap = []; if (!empty($selfCommissionData)){ if (!isset($businessmanMap[$selfCommissionData['retUserCenterId']])){ return ResultWrapper::fail('获取分销商账户失败',ErrorCode::$dberror); } $oldWaitMoney = $businessmanMap[$selfCommissionData['retUserCenterId']]['waitMoney']; $oldTotalMoney = $businessmanMap[$selfCommissionData['retUserCenterId']]['totalMoney']; //获取当前分销商的等待入账金额 $changeMoney = $selfCommissionData['retMoney']; $updateMap[] = [ 'userCenterId' => $selfCommissionData['retUserCenterId'], 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2), 'totalMoney' => bcsub($oldTotalMoney,$changeMoney,2), 'updateTime' => time(), ]; } if (!empty($oneCommissionData)){ if (!isset($businessmanMap[$oneCommissionData['retUserCenterId']])){ return ResultWrapper::fail('获取分销商账户失败',ErrorCode::$dberror); } $oldWaitMoney = $businessmanMap[$oneCommissionData['retUserCenterId']]['waitMoney']; $oldTotalMoney = $businessmanMap[$oneCommissionData['retUserCenterId']]['totalMoney']; //获取当前分销商的等待入账金额 $changeMoney = $oneCommissionData['retMoney']; $updateMap[] = [ 'userCenterId' => $oneCommissionData['retUserCenterId'], 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2), 'totalMoney' => bcsub($oldTotalMoney,$changeMoney,2), 'updateTime' => time(), ]; } if (!empty($twoCommissionData)){ if (!isset($businessmanMap[$twoCommissionData['retUserCenterId']])){ return ResultWrapper::fail('获取分销商账户失败',ErrorCode::$dberror); } $oldWaitMoney = $businessmanMap[$twoCommissionData['retUserCenterId']]['waitMoney']; $oldTotalMoney = $businessmanMap[$twoCommissionData['retUserCenterId']]['totalMoney']; //获取当前分销商的等待入账金额 $changeMoney = $twoCommissionData['retMoney']; $updateMap[] = [ 'userCenterId' => $twoCommissionData['retUserCenterId'], 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2), 'totalMoney' => bcsub($oldTotalMoney,$changeMoney,2), 'updateTime' => time(), ]; } if (!empty($threeCommissionData)){ if (!isset($businessmanMap[$threeCommissionData['retUserCenterId']])){ return ResultWrapper::fail('获取分销商账户失败',ErrorCode::$dberror); } $oldWaitMoney = $businessmanMap[$threeCommissionData['retUserCenterId']]['waitMoney']; $oldTotalMoney = $businessmanMap[$threeCommissionData['retUserCenterId']]['totalMoney']; //获取当前分销商的等待入账金额 $changeMoney = $threeCommissionData['retMoney']; $updateMap[] = [ 'userCenterId' => $threeCommissionData['retUserCenterId'], 'waitMoney' => bcsub($oldWaitMoney,$changeMoney,2), 'totalMoney' => bcsub($oldTotalMoney,$changeMoney,2), 'updateTime' => time(), ]; } if (!empty($updateMap)){ Logger::logs(E_USER_ERROR,'分销订单取消,更新分销商数据',__CLASS__,__LINE__,$updateMap); } return ResultWrapper::success($updateMap); } /** * Doc: (des="提现状态变更,操作分销商数据") * User: XMing * Date: 2020/7/31 * Time: 4:06 下午 * @param array $withdraw * @param int $status * @return ResultWrapper * @example * balance 余额 * waitAuditWithdraw 提现待审核金额 * auditWithdraw 提现待入账金额 * withdraw 已提现金额 */ public function buildWithdraw(array $withdraw,int $status) { $businessman = $this->objDCommissionBusinessman->get(['id'=>$withdraw['businessmanId']],'id,userCenterId,balance,waitAuditWithdraw,auditWithdraw,withdraw'); if ($businessman === false){ return ResultWrapper::fail($this->objDCommissionBusinessman->error(),ErrorCode::$dberror); } if (empty($businessman)){ return ResultWrapper::fail('获取分销商账户信息失败',ErrorCode::$paramError); } $oldBalance = $businessman['balance'];//可提现 $oldWaitAuditWithdraw = $businessman['waitAuditWithdraw'];//提现等待审核 $oldAuditWithdraw = $businessman['auditWithdraw'];//提现待入账金额 $oldWithdraw = $businessman['withdraw'];//已提现金额 $changeMoney = $withdraw['money'];//本次变动金额 $updateMap = [];//需要更新的数据 switch ($status){ case StatusCode::$auditStatus['auditing']: //申请提现操作 if ($oldBalance < $withdraw['money']){ return ResultWrapper::fail('可提现金额不足',ErrorCode::$paramError); } $updateMap = [ 'id' => $businessman['id'], 'updateTime' => time(), 'balance' => bcsub($oldBalance,$changeMoney,2), 'waitAuditWithdraw' => bcadd($oldWaitAuditWithdraw,$changeMoney,2), ]; break; case StatusCode::$auditStatus['auditPass']: //打款成功 if (bcsub($oldAuditWithdraw,$changeMoney,2) < 0){ return ResultWrapper::fail('待入账金额不足',ErrorCode::$paramError); } $updateMap = [ 'id' => $businessman['id'], 'updateTime' => time(), 'auditWithdraw' => bcsub($oldAuditWithdraw,$changeMoney,2), 'withdraw' => bcadd($oldWithdraw,$changeMoney,2), ]; break; case StatusCode::$auditStatus['auditNotPass']: //提现审核拒绝,回到余额 if (bcsub($oldWaitAuditWithdraw,$changeMoney,2) < 0){ return ResultWrapper::fail('待审核金额不足',ErrorCode::$paramError); } $updateMap = [ 'id' => $businessman['id'], 'updateTime' => time(), 'balance' => bcadd($oldBalance,$changeMoney,2), 'waitAuditWithdraw' => bcsub($oldWaitAuditWithdraw,$changeMoney,2), ]; break; case StatusCode::$auditStatus['auditIng']: //等待打款,审核成功 if (bcsub($oldWaitAuditWithdraw,$changeMoney,2) < 0){ return ResultWrapper::fail('待审核金额不足',ErrorCode::$paramError); } $updateMap = [ 'id' => $businessman['id'], 'updateTime' => time(), 'waitAuditWithdraw' => bcsub($oldWaitAuditWithdraw,$changeMoney,2), 'auditWithdraw' => bcadd($oldAuditWithdraw,$changeMoney,2), ]; break; default: return ResultWrapper::fail('状态值有误',ErrorCode::$paramError); break; } if (!empty($updateMap)){ Logger::logs(E_USER_ERROR,'提现变动数据',__CLASS__,__LINE__,$updateMap); } return ResultWrapper::success($updateMap); } /** * Doc: (des="佣金变动记录 balance") * User: XMing * Date: 2020/8/3 * Time: 2:32 下午 * @param array $data * @param float $changeAmount 变动金额 * @param float $balance 变动后金额 * @param int $type +/- * @param string $des 描述 * @return ResultWrapper */ private function changeLog(array $data,float $changeAmount,float $balance,int $type,string $des="") { $insertRes = $this->objDCommissionFlow->insert([ "userCenterId" => $data['userCenterId'] ,//int(10) DEFAULT NULL, "customerId" => $data['customerId'],//int(10) DEFAULT NULL COMMENT '客户id', "businessmanId" => $data['businessmanId'] ,//int(10) DEFAULT NULL COMMENT '分销商id', "amount" => $changeAmount,//decimal(8,2) DEFAULT NULL COMMENT '金额', "changeAmount" => $balance ,//decimal(8,2) DEFAULT NULL COMMENT '变动后金额', "type"=>$type ,//tinyint(1) DEFAULT NULL COMMENT '状态 4:减 5:加', "des" => $des, "createTime" => time(), ]); if ($insertRes === false){ return ResultWrapper::fail($this->objDCommissionFlow->error(),ErrorCode::$dberror); } return ResultWrapper::success('操作成功'); } }