| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741 |
- <?php
- /**
- * 重庆赤晓店信息科技有限公司
- * https://www.chixiaodian.com
- * Copyright (c) 2023 赤店商城 All rights reserved.
- */
- namespace app\modules\admin\models;
- use app\models\CashExt;
- use yii\base\Model;
- use app\models\Option;
- use app\constants\OptionSetting;
- use app\models\Order;
- use app\models\User;
- use app\models\SaasUser;
- use app\models\Cash;
- use app\models\ShareDetail;
- use app\models\TeamBonusLevel;
- use app\models\TeamBonusGoodsExt;
- use app\models\TeamBonusOrderExt;
- use app\models\Share;
- use app\models\OrderDetail;
- use app\utils\OrderNo;
- class TeamBonusForm extends Model {
- public function test($store_id, $user_id, $depth = 100) {
- $childUserIds = [];
- $cuids = [$user_id];
- $i = 0;
- $depthMax = 100;
- while ($i <= $depth) {
- $i++;
- $cuids = User::find()->where(['old_parent_id' => $cuids, 'store_id' => $store_id])
- // ->andWhere(['team_leader' => 0])
- ->select('id')->column();
- if (empty($cuids)) {
- break;
- }
- $childUserIds = array_unique(array_merge($childUserIds, $cuids));
- }
- if ($i >= $depthMax) {
- debug_log([__METHOD__, __LINE__, $user_id, count($childUserIds)]);
- \Yii::error([__METHOD__, __LINE__, $user_id, count($childUserIds), $cuids]);
- }
- return [
- 'depth' => $i,
- 'list' => array_unique($childUserIds)
- ];
- }
- public $store_id;
- public $saas_id;
- public $user_id;
- public $begin_time;
- public $end_time;
- public $mobile;
- public $id;
- public $ids;
- public $name;
- public $status;
- public $goods_id;
- public $is_delete;
-
- public $team_bonus_leader_level;
- public $team_bonus_leader_status;
- public static $_getTeamBonusChildrenIds;
- public static $_getTeamBonusParentIds;
- public static $_teamBonusSettings;
- public static $_teamBonusLevels;
- public function rules() {
- return [
- [['status', 'id'], 'integer'],
- [['ids', 'name'], 'string'],
- [[
- 'store_id', 'goods_id', 'saas_id', 'user_id', 'is_delete', 'mobile',
- 'begin_time', 'end_time',
- 'team_bonus_leader_level', 'team_bonus_leader_status',
- ], 'safe'],
- ];
- }
- public static function isOpen($store_id) {
- $conf = (new self(['store_id' => $store_id]))->teamBonusSetting()['conf'];
- return $conf['is_open'] ? true : false;
- }
- public static function afterCashSave($insert, $changedAttributes, $cash) {
- try{
- if($insert){
- return;
- }
- $store_id = $cash->store_id;
- if(!self::isOpen($store_id)){
- return;
- }
- $statusFinish = [2, 4];
- if ((in_array($cash->status, $statusFinish)) &&
- (isset($changedAttributes['status']) && ($changedAttributes['status'] != $cash->status))) {
- self::teamUpgrade($cash->user_id);
- }
- } catch (\Exception $ex) {
- \Yii::error($ex);
- debug_log([__FUNCTION__, __LINE__, $ex->getMessage(), $ex->getTrace()], __CLASS__ . '.log');
- }
- }
- public static function afterUserSave($insert, $changedAttributes, $user) {
- try{
- $store_id = $user['store_id'];
- if(!self::isOpen($store_id)){
- return;
- }
- if (($user->init_parent_id > 0) &&
- (isset($changedAttributes['init_parent_id']) && ($changedAttributes['init_parent_id'] != $user->init_parent_id))) {
- self::teamUpgrade($user->init_parent_id);
- }
- if($insert){
- return;
- }
- if (($user->team_bonus_leader_level > 0) &&
- (isset($changedAttributes['team_bonus_leader_level']) && ($changedAttributes['team_bonus_leader_level'] != $user->team_bonus_leader_level))) {
- self::teamBonusUpgradePrice($user, $user->team_bonus_leader_level);
- }
- } catch (\Exception $ex) {
- \Yii::error($ex);
- debug_log([__FUNCTION__, __LINE__, $ex->getMessage(), $ex->getTrace()], __CLASS__ . '.log');
- }
- }
- public static function afterShareSave($insert, $changedAttributes, $share) {
- try{
- $store_id = $share->store_id;
- if(!self::isOpen($store_id)){
- return;
- }
- if($insert){
- if($share->status == 1){
- self::teamUpgrade($share->user_id);
- }
- }else{
- if (($share->status == 1) &&
- (isset($changedAttributes['status']) && ($changedAttributes['status'] != $share->status))) {
- self::teamUpgrade($share->user_id);
- }
- }
- } catch (\Exception $ex) {
- \Yii::error($ex);
- debug_log([__FUNCTION__, __LINE__, $share->id, $ex->getMessage(), $ex->getTrace()], __CLASS__ . '.log');
- }
- }
-
- //处理订单支付后逻辑
- public static function afterOrderComplete($order) {
- try{
- $store_id = $order->store_id;
- if(!self::isOpen($store_id)){
- debug_log([__FUNCTION__, __LINE__, $store_id, $order->id, '00000'], __CLASS__ . '.log');
- return;
- }
- self::teamBonusPrice($order);
- } catch (\Exception $ex) {
- \Yii::error($ex);
- debug_log([__FUNCTION__, __LINE__, $order->store_id, $order->id, $ex->getMessage(), $ex->getTrace()], __CLASS__ . '.log');
- }
- }
-
- //处理订单过售后
- public static function afterOrderSales($order) {
- try{
- $store_id = $order->store_id;
- if(!self::isOpen($store_id)){
- return;
- }
- //冗余设计,如果没发放,再计算一次
- self::teamBonusPrice($order);
-
- self::sendTeamBonusShare($order->id);
- self::teamUpgrade($order->user_id);
- } catch (\Exception $ex) {
- \Yii::error($ex);
- debug_log([__FUNCTION__, __LINE__, $ex->getMessage(), $ex->getTrace()], __CLASS__ . '.log');
- }
- }
- public static function getTeamBonusChildrenIds($store_id, $user_id, $depth = 25) {
- if(isset(self::$_getTeamBonusChildrenIds[$user_id])){
- return self::$_getTeamBonusChildrenIds[$user_id];
- }
- $childUserIds = [];
- $depthUserIds = [];
- $cuids = [$user_id];
- $i = 0;
- $depthMax = 15;
- $time1 = microtime(true);
- while ($i <= $depth) {
- $i++;
- $cuidArr = User::find()->where(['init_parent_id' => $cuids, 'store_id' => $store_id])
- ->select('id')->column();
- $cuids = array_diff($cuidArr, $childUserIds);
- if (empty($cuids)) {
- break;
- }
- $depthUserIds[$i] = $cuids;
- $childUserIds = array_unique(array_merge($childUserIds, $cuids));
- }
- $time2 = microtime(true);
- if ($i >= $depthMax) {
- debug_log([__METHOD__, __LINE__, $user_id, count($childUserIds)], __CLASS__ . '.log');
- \Yii::error([__METHOD__, __LINE__, $user_id, count($childUserIds), $cuids]);
- }
- return self::$_getTeamBonusChildrenIds[$user_id] = [
- 'usetime' => $time2 - $time1,
- 'depth' => $i,
- '$depthUserIds' => $depthUserIds,
- 'list' => array_unique($childUserIds)
- ];
- }
- /**
- *
- * @param type $user_id
- * @param type $onlyTeamBonusLeader
- * @param type $num
- * @param type $depth
- * @return type
- */
- public static function getTeamBonusParentIds($user_id, $onlyTeamBonusLeader = 0, $num = 0, $depth = 15) {
- if(isset(self::$_getTeamBonusParentIds[$user_id][$onlyTeamBonusLeader][$num])){
- return self::$_getTeamBonusParentIds[$user_id][$onlyTeamBonusLeader][$num];
- }
- $parentUserIds = [];
- $teamBonusLeaderUserIds = [];
- $puid = $user_id;
- $i = 0;
- $depthMax = 10;
- $time1 = microtime(true);
- while ($i <= $depth) {
- $i++;
- $pu = User::find()->where(['id' => $puid])
- ->select('id, init_parent_id, is_team_bonus_leader')->asArray()->limit(1)->one();
- if (empty($pu)) {
- break;
- }
- //排除自己
- if($pu['is_team_bonus_leader'] && $pu['id'] != $user_id){
- $teamBonusLeaderUserIds[] = $pu['id'];
- }
- $puid = $pu['init_parent_id'];
- if (empty($puid) || in_array($puid, $parentUserIds)) {
- break;
- }
- $parentUserIds[] = $puid;
- if($num > 0){
- if($onlyTeamBonusLeader){
- if(count($teamBonusLeaderUserIds) >= $num){
- break;
- }
- }else{
- if(count($parentUserIds) >= $num){
- break;
- }
- }
- }
- }
- //最后一个父级循环内没法查询,只能在循环外查询
- if($parentUserIds && $puid != $user_id){
- $pu = User::find()->where(['id' => $puid])
- ->select('id, init_parent_id, is_team_bonus_leader')->asArray()->limit(1)->one();
- if($pu['is_team_bonus_leader']){
- $teamBonusLeaderUserIds[] = $puid;
- }
- }
- $time2 = microtime(true);
- if ($i >= $depthMax) {
- debug_log([__METHOD__, __LINE__, $user_id, count($parentUserIds)], __CLASS__ . '.log');
- \Yii::error([__METHOD__, __LINE__, $user_id, count($parentUserIds), $puid]);
- }
- if($parentUserIds){
- $parentUserIds = array_unique($parentUserIds);
- }
- if($teamBonusLeaderUserIds){
- $teamBonusLeaderUserIds = array_unique($teamBonusLeaderUserIds);
- }
- return self::$_getTeamBonusParentIds[$user_id][$onlyTeamBonusLeader][$num] = [
- 'usetime' => $time2 - $time1,
- 'depth' => $i,
- 'parentUserIds' => $parentUserIds,
- 'teamBonusLeaderUserIds' => $teamBonusLeaderUserIds,
- 'list' => $onlyTeamBonusLeader ? $teamBonusLeaderUserIds : $parentUserIds,
- ];
- }
- public function teamBonusSetting() {
- $store_id = $this->store_id;
- if(isset(self::$_teamBonusSettings[$store_id])){
- return self::$_teamBonusSettings[$store_id];
- }
- $setting = json_decode(Option::get(OptionSetting::TEAM_BONUS_SETTING, $store_id, 'store', '{}')['value'], true);
- $line1 = __LINE__;
- $ret = [
- //基础设置
- 'is_open' => $setting['is_open'] ?? 0, //团队分红开关
- // 'bonus_rate_type' => $setting['bonus_rate_type'] ?? 1, //分红比例;0统一比例 1按队长等级
- // 'bonus_rate' => $setting['bonus_rate'] ?? 0, //统一比例
- 'goods_join_teambonus' => $setting['goods_join_teambonus'] ?? 1, //商品默认 1参与 0不参与
- 'mobile_menu_types' => $setting['mobile_menu_types'] ?? [ShareDetail::TYPE_TEAM_BONUS_RANGE_PROFIT, ShareDetail::TYPE_TEAM_BONUS_SAME_LEVEL],
- //队长设置
- // 'need_apply' => $setting['need_apply'] ?? 1, //是否需要申请 1需要 0不需要
- // 'apply_check' => $setting['apply_check'] ?? 1, //是否需要审核 1需要 0不需要
- // 'apply_condition' => $setting['apply_condition'] ?? 1, //申请门槛 0无(不推荐) 1下线总人数 2下线分销商数 3累计分销佣金 4已提现佣金总额 5购买指定商品 6指定分销商等级
- // 'apply_child' => $setting['apply_child'] ?? 30, //下线总人数
- // 'apply_agent_child' => $setting['apply_agent_child'] ?? 30, //下线分销商数
- // 'apply_commission_total' => $setting['apply_commission_total'] ?? 100, //累计分销佣金
- // 'apply_withdraw_money' => $setting['apply_withdraw_money'] ?? 100, //已提现佣金总额
- // 'apply_commission_level' => $setting['apply_commission_level'] ?? [], //指定分销商等级 [1637, 1638]
- // 'apply_goodsid' => $setting['apply_goodsid'] ?? [], //购买指定商品 id是队长等级 [{id: 0, goods: "8403833,6297930"}, {id: "323", goods: "6995735"}]
- //申请设置
- // 'top_image' => $setting['top_image'] ?? '', //顶部图片
- // 'apply_content' => $setting['apply_content'] ?? '', //正文文本
- // 'apply_button_text' => $setting['apply_button_text'] ?? '立即申请', //申请按钮文案
- // 'need_apply_deal' => $setting['need_apply_deal'] ?? 0, //需要同意协议 1需要 0不需要
- // 'apply_deal_title' => $setting['apply_deal_title'] ?? '', //协议名称
- // 'apply_deal' => $setting['apply_deal'] ?? '', //协议内容
- // 'need_submit_info' => $setting['need_submit_info'] ?? 0, //需要申请人提交信息 1需要 0不需要
- // 'submit_info_form' => $setting['submit_info_form'] ?? [],
- //提现设置
- 'cash_min' => $setting['cash_min'] ?? 10, //最少提现
- 'cash_max_single_day' => $setting['cash_max_single_day'] ?? 100, //每人每日上限 0元表示不限制
- 'cash_max_day' => $setting['cash_max_day'] ?? 100, //平台每日上限 0元表示不限制
- 'cash_type' => $setting['cash_type'] ?? [0], //提现方式 0微信支付 1支付宝支付 2银行卡支付3余额4灵工
- 'cash_rate' => $setting['cash_rate'] ?? 10, //提现手续费佣金比例
- 'cash_price_type' => $setting['cash_price_type'] ?? '1',
- 'cash_price_amount' => $setting['cash_price_amount'] ?? 100,
- 'cash_price_integral' => $setting['cash_price_integral'] ?? 0,
- 'cash_price_balance' => $setting['cash_price_balance'] ?? 0,
- ];
- $line2 = __LINE__;
- $lines = file(__FILE__, FILE_IGNORE_NEW_LINES);
- $str = '';
- for ($i = $line1 + 1; $i < $line2 - 2; $i++) {
- $str .= trim($lines[$i]) . PHP_EOL;
- }
- $types = [
- ShareDetail::TYPE_TEAM_BONUS_RANGE_PROFIT,
- ShareDetail::TYPE_TEAM_BONUS_SAME_LEVEL,
- ShareDetail::TYPE_TEAM_BONUS_PARENT,
- ShareDetail::TYPE_TEAM_BONUS_THANKS,
- ];
- return self::$_teamBonusSettings[$store_id] = [
- 'str' => $str,
- 'conf' => $ret,
- 'ShareDetailTypes' => ShareDetail::typeName($types),
- ];
- }
- public function teamBonusSettingSave($conf = []) {
- // $total_profit = 0;
- // $cash_price_type = explode(',', $conf['cash_price_type']);
- // if (in_array(CashExt::CASH_PRICE_TYPE_AMOUNT, $cash_price_type)) {
- // $total_profit = bcadd($total_profit, $conf['cash_price_amount'], 2);
- // }
- // if (in_array(CashExt::CASH_PRICE_TYPE_INTEGRAL, $cash_price_type)) {
- // $total_profit = bcadd($total_profit, $conf['cash_price_integral'], 2);
- // }
- // if (in_array(CashExt::CASH_PRICE_TYPE_BALANCE, $cash_price_type)) {
- // $total_profit = bcadd($total_profit, $conf['cash_price_balance'], 2);
- // }
- // if ($total_profit != 100) {
- // return [
- // 'code' => 1,
- // 'msg' => '佣金/积分/余额比例设置错误'
- // ];
- // }
- Option::set(OptionSetting::TEAM_BONUS_SETTING, json_encode($conf), $this->store_id, 'store');
- }
- public function teamBonusLevelList() {
- $store_id = $this->store_id;
- if(isset(self::$_teamBonusLevels[$store_id])){
- return self::$_teamBonusLevels[$store_id];
- }
- $query = TeamBonusLevel::find()->where(['store_id' => $store_id]);
- if (!is_null($this->status) && $this->status > -1) {
- $query->andWhere(['status' => $this->status]);
- }
- $query->orderBy('level ASC');
- $list = $query->asArray()->all();
- foreach($list as &$item){
- $item['conditionText'] = self::levelConditionText($item);
- }
- return self::$_teamBonusLevels[$store_id] = [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => $list,
- ];
- }
- /**
- * 队长等级
- */
- public function teamBonusLevelInfo($id) {
- // $store_id = $this->store_id;
- $level = TeamBonusLevel::findOne($id);
- return [
- 'code' => 0,
- 'data' => $level,
- 'conditionText' => self::levelConditionText($level),
- ];
- }
-
- public static function levelConditionText($level){
-
- $conditionText = [];
- $condition_type = $level['condition_type'];
- $glue = $condition_type ? ' 并且 ' : ' 或者 ';
- $condition = json_decode($level['condition'], true);
- //团队交易
- if(isset($condition['teamOrderPrice'])){
- if(isset($condition['teamOrderPrice']['count'])){
- $conditionText[] = '团队订单数量大于' . $condition['teamOrderPrice']['count'];
- }
- if(isset($condition['teamOrderPrice']['price'])){
- $conditionText[] = '团队订单金额大于' . $condition['teamOrderPrice']['price'];
- }
- }
- //自购交易
- if(isset($condition['teamSelfOrderPrice'])){
- if(isset($condition['teamSelfOrderPrice']['count'])){
- $conditionText[] = '自购订单数量大于' . $condition['teamSelfOrderPrice']['count'];
- }
- if(isset($condition['teamSelfOrderPrice']['price'])){
- $conditionText[] = '自购订单金额大于' . $condition['teamSelfOrderPrice']['price'];
- }
- }
- //团队人数
- if(isset($condition['teamChildren'])){
- if(isset($condition['teamChildren']['countAll'])){
- $conditionText[] = '团队总人数大于' . $condition['teamChildren']['countAll'];
- }
- if(isset($condition['teamChildren']['countShare'])){
- $conditionText[] = '团队分销商人数大于' . $condition['teamChildren']['countShare'];
- }
- }
- //提现
- if(isset($condition['teamCash'])){
- if(isset($condition['teamCash']['cash_price'])){
- $conditionText[] = '已提现分红金额大于' . $condition['teamCash']['cash_price'];
- }
- }
- //购买指定商品
- if(isset($condition['teamHasGoods'])){
- // if(isset($condition['teamHasGoods']['goods_ids'])){
- // $conditionText[] = '购买指定商品' . implode(',', $condition['teamHasGoods']['goods_ids']);
- // }
- }
- return implode($glue, $conditionText);
- }
- public function teamBonusLevelSelectList($indexBy = 1) {
- $query = TeamBonusLevel::find()->where(['store_id' => $this->store_id])
- ->select('id,name,level,status,range_rate');
- if ($indexBy) {
- $query->indexBy('id');
- }
- $list = $query->orderBy('level ASC')->asArray()->all();
- foreach ($list as &$item) {
- if (!$item['status']) {
- $item['name'] .= '(已禁用)';
- }
- }
- return [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => $list,
- ];
- }
- /**
- * 团队分红-升级触发分红
- * @param \app\models\User $child_user
- * @return type
- */
- public static function teamBonusUpgradePrice($child_user, $level_id) {
- //感恩奖
- $store_id = $child_user->store_id;
- $child_user_id = $child_user->id;
- $self = new self(['store_id' => $store_id]);
- $level = TeamBonusLevel::findOne(['id' => $level_id, 'status' => 1, 'is_delete' => 0]);
- if ($level && $level->price_thanks > 0) {
- $getTeamBonusParentIds = $self->getTeamBonusParentIds($child_user_id, 1, 1)['list'];
- if (count($getTeamBonusParentIds) > 0) {
- $parent_id = $getTeamBonusParentIds[0];
- $detail = ShareDetail::findOne(['is_delete' => 0, 'type_id' => $child_user_id, 'type' => ShareDetail::TYPE_TEAM_BONUS_THANKS, 'user_id' => $parent_id, 'type_id_ext' => $level['id']]);
- if (!$detail) {
- $detail = new ShareDetail();
- $detail->store_id = $store_id;
- $detail->type_id = $child_user_id;
- $detail->type_id_ext = $level['id'];
- $detail->type = ShareDetail::TYPE_TEAM_BONUS_THANKS;
- $detail->user_id = $parent_id;
- $detail->desc = '下级:' . $child_user->nickname . ';等级:' . $level->name . '(' . $level['id'] . ')' . ';';
- $detail->money = $level->price_thanks;
- $detail->is_send = 0;
- if (!$detail->save()) {
- \Yii::error(['---------------- 团队分红-感恩奖计算入库失败 -------------------', $detail->errors, $child_user, $level_id]);
- debug_log(['---------------- 团队分红-感恩奖计算入库失败 -------------------', $detail->errors, $child_user, $level_id], __CLASS__ . '.log');
- return;
- }
- self::_sendTeamBonusShareItem($detail);
- }
- }
- }
- }
- /**
- * 团队分红-订单触发分红
- * @param \app\models\Order $order |
- * @return type
- */
- public static function teamBonusPrice($order) {
- $t = \Yii::$app->db->beginTransaction();
- try{
- \Yii::warning('---------------- 团队分红-计算开始 -------------------' . $order->id);
- $order_id = $order->id;
- $store_id = $order->store_id;
- $self = new self(['store_id' => $store_id]);
- $levels = array_column($self->teamBonusLevelList()['data'], null, 'id');
- $user_id = $order->user_id;
- $base_price = 0;
- $goodsCanPrice = [];
- $ods = $order->detail;
- $conf = (new self(['store_id' => $store_id]))->teamBonusSetting()['conf'];
- //有独立分红商品
- $odsProfit = [];
- foreach($ods as $od){
- //有独立分红商品
- $goodsExt = TeamBonusGoodsExt::findOne(['store_id' => $store_id, 'goods_id' => $od['goods_id']]);
- if($goodsExt){
- if($goodsExt->status == 1 || ($goodsExt->status == 0 && $conf['goods_join_teambonus'] == 1)){
- $goodsCanPrice[$od['id']] = 1;
- }
- }else{
- if($conf['goods_join_teambonus'] == 1){
- $goodsCanPrice[$od['id']] = 1;
- }
- }
- if($goodsCanPrice[$od['id']]){
- $base_price += $od['total_price'];
- if($goodsExt->is_profit_self){
- $odsProfit[$od['id']] = array_column(json_decode($goodsExt->profit_rule, true), null, 'id');
- }
- }
- }
- if($base_price < 0.02){
- throw new \Exception($order_id . '分红基数小于0.02,或商品不参与分红');
- }
- $getTeamBonusParentIds = $self->getTeamBonusParentIds($user_id, 1)['list'];
- $getTeamBonusParentIds && self::_teamBonusOrderExtSave($order, $getTeamBonusParentIds);
- // 已分销比例
- $share_num = [];
- $level_id = 0;
- //上个用户总佣金
- $priceAllLast = 0;
- foreach($getTeamBonusParentIds as $parent_id) {
- $teamParent = User::findOne($parent_id);
- if ($teamParent->is_delete) {
- continue;
- }
- $level = $levels[$teamParent->team_bonus_leader_level];
- if(!$level || !$level['status'] || $level['is_delete']){
- continue;
- }
- if ($level) {
- // //上个用户总佣金
- // $priceAllLast = 0;
- //此用户总佣金
- $priceAll = 0;
- //是否符合平级奖(一个用户不能同时获得级差奖和平级奖)
- $hasPriceSameLevel = 0;
-
-
-
- //平级奖
- $priceSameLevel = 0;
- if ($level_id == $level['id']) {
- $hasPriceSameLevel = 1;
- $range_rate = $level['equal_rate'];
- $equal_price = round($base_price * $range_rate / 100, 2);
- if ($equal_price >= 0.01) {
- $priceSameLevel = $equal_price;
- $detail = ShareDetail::findOne(['type_id' => $order_id, 'type' => ShareDetail::TYPE_TEAM_BONUS_SAME_LEVEL, 'user_id' => $parent_id]);
- if (!$detail) {
- $detail = new ShareDetail();
- $detail->store_id = $order->store_id;
- $detail->type_id = $order_id;
- $detail->type = ShareDetail::TYPE_TEAM_BONUS_SAME_LEVEL;
- $detail->user_id = $parent_id;
- $detail->desc = '订单号:' . $order->order_no . ' | ' . $range_rate . '%';
- }
- $detail->money = $equal_price;
- $detail->is_send = 0;
- if (!$detail->save()) {
- $t->rollBack();
- \Yii::error(['---------------- 团队分红-平级奖计算入库失败 -------------------', $order_id, $parent_id, $detail->errors]);
- throw new \Exception(array_shift($detail->getFirstErrors()));
- }
- }
- $level_id = 0;
- }
- //级差奖
- $priceLevel = 0;
- if (!$hasPriceSameLevel) {
- $price = 0;
- $range_rates = [];
- foreach($ods as $od){
- $odPrice = $od['total_price'];
- $odId = $od['id'];
- $range_rate = $level['range_rate'] - $share_num[$odId];
- //有独立分红商品
- if($odsProfit[$odId]){
- $range_rate = (isset($odsProfit[$odId][$level['id']]) ? $odsProfit[$odId][$level['id']]['range_rate'] : 0) - $share_num[$odId];
- }
- $range_rates[] = $range_rate;
- if($range_rate <= 0){
- continue;
- }
- if(!$goodsCanPrice[$od['id']]){
- continue;
- }
- $share_num[$odId] += $range_rate;
- $price += round($odPrice * $range_rate / 100, 2);
- }
- if ($price >= 0.01) {
- $priceLevel = $price;
- $detail = ShareDetail::findOne(['type_id' => $order_id, 'type' => ShareDetail::TYPE_TEAM_BONUS_RANGE_PROFIT, 'user_id' => $parent_id]);
- if (!$detail) {
- $detail = new ShareDetail();
- $detail->store_id = $order->store_id;
- $detail->type_id = $order_id;
- $detail->type = ShareDetail::TYPE_TEAM_BONUS_RANGE_PROFIT;
- $detail->user_id = $parent_id;
- $detail->desc = '订单号:' . $order->order_no . ' | ' . implode('+', $range_rates) . '%';
- }
- $level_id = $level['id'];
- $detail->money = $price;
- $detail->is_send = 0;
- if (!$detail->save()) {
- $t->rollBack();
- \Yii::error(['---------------- 团队分红-级差分红计算入库失败 -------------------', $detail->errors]);
- throw new \Exception(array_shift($detail->getFirstErrors()));
- }
- }
- }
- //育人奖
- $priceParent = 0;
- if ($priceAllLast > 0 && $level['range_rate_parent'] > 0) {
- $range_rate = $level['range_rate_parent'];
- $price = round($priceAllLast * $range_rate / 100, 2);
- if ($price >= 0.1) {
- $priceParent = $price;
- $detail = ShareDetail::findOne(['type_id' => $order_id, 'type' => ShareDetail::TYPE_TEAM_BONUS_PARENT, 'user_id' => $parent_id]);
- if (!$detail) {
- $detail = new ShareDetail();
- $detail->store_id = $order->store_id;
- $detail->type_id = $order_id;
- $detail->type = ShareDetail::TYPE_TEAM_BONUS_PARENT;
- $detail->user_id = $parent_id;
- $detail->desc = '订单号:' . $order->order_no . ' | ' . $range_rate . '%';
- }
- $detail->money = $price;
- $detail->is_send = 0;
- if (!$detail->save()) {
- $t->rollBack();
- \Yii::error(['---------------- 团队分红-育人奖计算入库失败 -------------------', $detail->errors]);
- throw new \Exception(array_shift($detail->getFirstErrors()));
- }
- }
- }
- $priceAll += bcadd($priceSameLevel, $priceLevel + $priceParent, 2);
- $priceAllLast = $priceAll;
- }
- }
- $t->commit();
- \Yii::warning('---------------- 团队分红-计算结束 -------------------' . $order->id);
- } catch (\Exception $e) {
- $t->rollBack();
- \Yii::error($e);
- debug_log([__FUNCTION__, $order->store_id, $order->id, $e->getMessage()], __CLASS__ . '.log');
- }
- return;
- }
- /**
- * 发放团队分红 - 订单触发分红
- */
- public static function sendTeamBonusShare($order_id) {
- try{
- $types = [
- ShareDetail::TYPE_TEAM_BONUS_RANGE_PROFIT,
- ShareDetail::TYPE_TEAM_BONUS_SAME_LEVEL,
- ShareDetail::TYPE_TEAM_BONUS_PARENT,
- ];
- $list = ShareDetail::find()->where(['type_id' => $order_id, 'type' => $types, 'is_send' => 0, 'is_delete' => 0])->all();
- if ($list) {
- foreach ($list as $share_detail) {
- $sendTeamBonusShareItem = self::_sendTeamBonusShareItem($share_detail);
- if ($sendTeamBonusShareItem['code']) {
- debug_log([__METHOD__, $order_id, $share_detail->id, $sendTeamBonusShareItem], __CLASS__ . '.log');
- }
- }
- }
- } catch (\Exception $e) {
- \Yii::error($e);
- debug_log([__METHOD__, $order_id, $e->getMessage()], __CLASS__ . '.log');
- }
- }
- /**
- * 发放分红到账户佣金
- */
- public static function _sendTeamBonusShareItem($share_detail) {
- $t = \Yii::$app->db->beginTransaction();
- try{
- $user = User::findOne($share_detail->user_id);
- $user->total_price += $share_detail->money;
- $user->price += $share_detail->money;
- if (!$user->save()) {
- $t->rollBack();
- throw new \Exception(array_shift($user->getFirstErrors()));
- }
- $share_detail->is_send = 1;
- $share_detail->send_time = time();
- if (!$share_detail->save()) {
- $t->rollBack();
- throw new \Exception(array_shift($share_detail->getFirstErrors()));
- }
- } catch (\Exception $e) {
- $t->rollBack();
- \Yii::error($e);
- debug_log([__METHOD__, $share_detail->user_id, $share_detail->type_id, $share_detail->id, $e->getMessage()], __CLASS__ . '.log');
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- $t->commit();
- return [
- 'code' => 0,
- ];
- }
- /**
- * 保存订单扩展信息
- */
- public static function _teamBonusOrderExtSave($order, $parent_ids = []) {
- $store_id = $order->store_id;
- $model = TeamBonusOrderExt::findOne(['store_id' => $store_id, 'order_id' => $order->id]);
- if($model){
- throw new \Exception('分红计算失败,订单已经存在分红' . $order->id);
- }
- $model = new TeamBonusOrderExt();
- $model->store_id = $store_id;
- $model->order_id = $order->id;
- $model->parent_ids = implode(',', $parent_ids);
- $save = $model->save();
- return $save;
- }
- /**
- * 团队内成员历史订单总数
- * @param type $user
- * @return type
- */
- public static function teamOrderPriceHistory($user) {
- $store_id = $user['store_id'];
- $user_id = $user['id'];
- $user_ids = self::getTeamBonusChildrenIds($store_id, $user_id)['list'];
- $query = Order::find()->where(['store_id' => $store_id])
- ->andWhere(['is_sale' => 1])
- ->andWhere(['user_id' => $user_ids]);
- $price = (float)(clone $query)->sum('pay_price');
- $count = (int)(clone $query)->count();
- return [
- 'price' => $price,
- 'count' => $count,
- ];
- }
- /**
- * 团队内订单数据
- * @param type $user
- * @param type $store_id
- * @param type $getList
- * @param type $queryParams
- * @param type $oneUserId 单个下级贡献数据
- * @return type
- */
- public static function teamOrderPrice($user, $store_id = null, $getList = 0, $queryParams = [], $oneUserId = null) {
- $types = [
- ShareDetail::TYPE_TEAM_BONUS_RANGE_PROFIT,
- ShareDetail::TYPE_TEAM_BONUS_SAME_LEVEL,
- ShareDetail::TYPE_TEAM_BONUS_PARENT,
- ];
- if($store_id === null){
- $store_id = $user['store_id'];
- }
- $queryTb = TeamBonusOrderExt::find()->where(['store_id' => $store_id])->select('order_id');
- if($user){
- $queryTb->andWhere('FIND_IN_SET('. $user['id'] .', parent_ids)');
- }
- $query = Order::find()->where(['store_id' => $store_id])
- ->andWhere(['id' => $queryTb]);
- if($oneUserId){
- $query->andWhere(['user_id' => $oneUserId]);
- }
- $price = (float)(clone $query)->andWhere(['is_sale' => 1])->sum('pay_price');
- $count = (int)(clone $query)->andWhere(['is_sale' => 1])->count();
- if($getList){
- if(isset($queryParams['trade_status']) && $queryParams['trade_status'] > -1){
- $query->andWhere(['trade_status' => $queryParams['trade_status']]);
- }
- if($queryParams['order_no']){
- $query->andWhere(['order_no' => trim($queryParams['order_no'])]);
- }
- if($queryParams['name']){
- $query->andWhere(['like', 'name', trim($queryParams['name'])]);
- }
- if($queryParams['goods_name']){
- $query->andWhere(['id' => OrderDetail::find()->select('order_id')->where(['like', 'goods_name', trim($queryParams['goods_name'])])]);
- }
- if (!empty($queryParams['begin_time'])) {
- $query->andWhere(['>=', 'created_at', strtotime($queryParams['begin_time'])]);
- }
- if (!empty($queryParams['end_time'])) {
- $query->andWhere(['<=', 'created_at', strtotime($queryParams['end_time'])]);
- }
- if(isset($queryParams['price_is_send']) && $queryParams['price_is_send'] > -1){
- $query->andWhere(['id' => ShareDetail::find()->select('type_id')->groupBy('type_id')->where(['is_delete' => 0, 'is_send' => $queryParams['price_is_send']])]);
- }
- if($queryParams['team_leader_name']){
- $query->andWhere(['id' => ShareDetail::find()->select('type_id')->groupBy('type_id')->where(['is_delete' => 0, 'user_id' => User::find()->alias('u')->leftJoin(['su' => SaasUser::tableName()], 'u.binding=su.mobile')->select('u.id')->where(['like', 'su.name', trim($queryParams['team_leader_name'])])])]);
- }
- $query->orderBy('id DESC');
- $list = pagination_make($query);
- foreach($list['list'] as &$item){
- $item['od'] = OrderDetail::findAll(['order_id' => $item['id']]);
- $querySd = ShareDetail::find()->where(['store_id' => $store_id, 'is_delete' => 0, 'type' => $types])
- ->andWhere(['type_id' => $item['id']]);
- $item['sd'] = $querySd->asArray()->all();
- $user = User::findOne($item['user_id']);
- $saas_user = SaasUser::findOne(['mobile' => $user['binding']]);
- $item['saas_user'] = $saas_user;
- foreach($item['sd'] as &$sditem){
- $user = User::findOne($sditem['user_id']);
- $saas_user = SaasUser::findOne(['mobile' => $user['binding']]);
- $sditem['saas_user'] = $saas_user;
- $sditem['price_type'] = ShareDetail::typeName($sditem['type']);
- }
- }
- }
- return [
- '$query' => $query->createCommand()->getRawSql(),
- 'price' => $price,
- 'count' => $count,
- 'list' => $list,
- ];
- }
- /**
- * 自购
- * @param type $user
- * @return type
- */
- public static function teamSelfOrderPrice($user) {
- $store_id = $user['store_id'];
- $user_id = $user['id'];
- $query = Order::find()->where(['store_id' => $store_id, 'user_id' => $user_id])
- ->andWhere(['is_sale' => 1]);
- $price = (float)(clone $query)->sum('pay_price');
- $count = (int)(clone $query)->count();
- return [
- 'price' => $price,
- 'count' => $count,
- ];
- }
- /**
- * 下级人员
- * @param type $user
- * @return type
- */
- public static function teamChildren($user) {
- $store_id = $user['store_id'];
- $user_id = $user['id'];
- $user_ids = self::getTeamBonusChildrenIds($store_id, $user_id)['list'];
- $countShare = (int)Share::find()->where(['store_id' => $store_id, 'status' => 1, 'is_delete' => 0, 'user_id' => $user_ids])->count();
- return [
- 'countShare' => $countShare,
- 'countAll' => count($user_ids),
- ];
- }
- public static function teamCash($user) {
- $store_id = $user['store_id'];
- $user_id = $user['id'];
- $cash_price = (float)Cash::find()->where(['store_id' => $store_id, 'user_id' => $user_id])->andWhere(['status' => [2, 4, 5]])->sum('price');
- return [
- 'total_price' => $user['total_price'],
- 'price' => $user['price'],
- 'cash_price' => $cash_price,
- ];
- }
- /**
- * 佣金信息
- * @param type $user
- * @return type
- */
- public static function teamSharePrice($user) {
- $store_id = $user['store_id'];
- $user_id = $user['id'];
- $price = ShareDetail::find()->where(['store_id' => $store_id, 'is_delete' => 0, 'user_id' => $user_id, 'is_send' => 1])
- ->select('type, SUM(money) sum_money')
- ->groupBy('type')->asArray()->all();
- return [
- 'price' => $price,
- ];
- }
- /**
- * 队内成员贡献佣金信息
- * @param type $user
- * @return type
- */
- public static function teamChildrenSharePrice($user, $oneUserId = null) {
- $store_id = $user['store_id'];
- $queryTb = TeamBonusOrderExt::find()
- ->where(['store_id' => $store_id])
- ->andWhere('FIND_IN_SET('. $user->id .', parent_ids)')
- ->andWhere(['order_id' => Order::find()->select('id')->where(['user_id' => $oneUserId])])
- ->select('order_id');
- $price = ShareDetail::find()
- ->where(['store_id' => $store_id, 'is_delete' => 0, 'user_id' => $user->id, 'is_send' => 1])
- ->andWhere(['or', ['type_id' => $queryTb], ['type_id' => $oneUserId]])
- ->select('type, SUM(money) sum_money')
- ->groupBy('type')->asArray()->all();
- return [
- 'price' => $price,
- ];
- }
- public static function teamHasGoods($user, $goods_ids = []) {
- $store_id = $user['store_id'];
- $user_id = $user['id'];
- $orderOne = Order::find()->alias('o')
- ->leftJoin(['od' => OrderDetail::tableName()], 'o.id = od.order_id')
- ->where(['o.store_id' => $store_id, 'o.user_id' => $user_id, 'o.is_sale' => 1])
- ->andWhere(['od.goods_id' => $goods_ids])
- ->select('o.id')->limit(1)->scalar();
- return $orderOne ? true : false;
- }
- /**
- * 升级
- * @param type $user
- */
- public static function teamUpgrade($user) {
- if(!isset($user['id'])){
- $user = User::findOne($user);
- }
- $store_id = $user['store_id'];
- $user_id = $user['id'];
- $self = new self(['store_id' => $store_id]);
- $teamUserIds = array_merge([$user_id], $self->getTeamBonusParentIds($user_id, 1)['list']);
- $levels = $self->teamBonusLevelList()['data'];
- $levelsIndex = array_column($levels, null, 'id');
- foreach($teamUserIds as $uid){
- $userItem = User::findOne($uid);
- if($userItem->is_team_bonus_leader){
- if(!$userItem->team_bonus_leader_status){
- continue;
- }
- if($userItem->team_bonus_leader_level_lock){
- continue;
- }
- }else{
- $share = Share::find()->where(['store_id' => $store_id, 'status' => 1, 'is_delete' => 0, 'user_id' => $uid])->one();
- if(!$share){
- continue;
- }
- }
- foreach($levels as $level){
- if($userItem->team_bonus_leader_level && $levelsIndex[$userItem->team_bonus_leader_level] && $levelsIndex[$userItem->team_bonus_leader_level]['level'] >= $level['level']){
- continue;
- }
- if(!$level['status']){
- continue;
- }
-
- $canUpgrade = self::canUpgrade($level, $userItem);
-
- if(!$canUpgrade){
- break;
- }else{
- //升级
- if(!$userItem->is_team_bonus_leader){
- $userItem->is_team_bonus_leader = 1;
- $userItem->team_bonus_leader_status = 1;
- $userItem->team_bonus_leader_time = time();
- }
- $userItem->team_bonus_leader_level = $level['id'];
- $userSave = $userItem->save();
- if(!$userSave){
- debug_log([__METHOD__, $userItem->team_bonus_leader_time, $userItem->team_bonus_leader_level, $userItem->id, $userItem->getFirstErrors()], __CLASS__ . '.log');
- }
- }
- }
- }
- }
- /**
- * 检测是否符合升级条件
- */
- public static function canUpgrade($level, $userItem, &$userData = []) {
- $canUpgrade = 1;
- $condition_type = $level['condition_type'];
- $condition_type_one = $condition_type == 0;
- //升级逻辑判断
- $condition = json_decode($level['condition'], true);
- //团队交易
- if(isset($condition['teamOrderPrice'])){
- $teamOrderPrice = self::teamOrderPrice($userItem);
- $userData['teamOrderPrice']['count'] = $teamOrderPrice['count'];
- $userData['teamOrderPrice']['price'] = $teamOrderPrice['price'];
- if(isset($condition['teamOrderPrice']['count'])){
- if($condition['teamOrderPrice']['count'] > $teamOrderPrice['count']){
- $canUpgrade = 0;
- if(!$condition_type_one){
- // return $canUpgrade;
- }
- }else{
- if($condition_type_one){
- return true;
- }
- }
- }
- if(isset($condition['teamOrderPrice']['price'])){
- if($condition['teamOrderPrice']['price'] > $teamOrderPrice['price']){
- $canUpgrade = 0;
- if(!$condition_type_one){
- // return $canUpgrade;
- }
- }else{
- if($condition_type_one){
- return true;
- }
- }
- }
- }
- //自购交易
- if(isset($condition['teamSelfOrderPrice'])){
- $teamSelfOrderPrice = self::teamSelfOrderPrice($userItem);
- $userData['teamSelfOrderPrice']['count'] = $teamSelfOrderPrice['count'];
- $userData['teamSelfOrderPrice']['price'] = $teamSelfOrderPrice['price'];
- if(isset($condition['teamSelfOrderPrice']['count'])){
- if($condition['teamSelfOrderPrice']['count'] > $teamSelfOrderPrice['count']){
- $canUpgrade = 0;
- if(!$condition_type_one){
- // return $canUpgrade;
- }
- }else{
- if($condition_type_one){
- return true;
- }
- }
- }
- if(isset($condition['teamSelfOrderPrice']['price'])){
- if($condition['teamSelfOrderPrice']['price'] > $teamSelfOrderPrice['price']){
- $canUpgrade = 0;
- if(!$condition_type_one){
- // return $canUpgrade;
- }
- }else{
- if($condition_type_one){
- return true;
- }
- }
- }
- }
- //团队人数
- if(isset($condition['teamChildren'])){
- $teamChildren = self::teamChildren($userItem);
- $userData['teamChildren']['countAll'] = $teamChildren['countAll'];
- $userData['teamChildren']['countShare'] = $teamChildren['countShare'];
- if(isset($condition['teamChildren']['countAll'])){
- if($condition['teamChildren']['countAll'] > $teamChildren['countAll']){
- $canUpgrade = 0;
- if(!$condition_type_one){
- // return $canUpgrade;
- }
- }else{
- if($condition_type_one){
- return true;
- }
- }
- }
- if(isset($condition['teamChildren']['countShare'])){
- if($condition['teamChildren']['countShare'] > $teamChildren['countShare']){
- $canUpgrade = 0;
- if(!$condition_type_one){
- // return $canUpgrade;
- }
- }else{
- if($condition_type_one){
- return true;
- }
- }
- }
- }
- //提现
- if(isset($condition['teamCash'])){
- $teamCash = self::teamCash($userItem);
- $userData['teamCash']['cash_price'] = $teamCash['cash_price'];
- if(isset($condition['teamCash']['cash_price'])){
- if($condition['teamCash']['cash_price'] > $teamCash['cash_price']){
- $canUpgrade = 0;
- if(!$condition_type_one){
- // return $canUpgrade;
- }
- }else{
- if($condition_type_one){
- return true;
- }
- }
- }
- }
- //购买指定商品
- if(isset($condition['teamHasGoods'])){
- if(isset($condition['teamHasGoods']['goods_ids'])){
- $teamHasGoods = self::teamHasGoods($userItem, $condition['teamHasGoods']['goods_ids']);
- $userData['teamHasGoods']['teamHasGoods'] = $teamHasGoods;
- if(!$teamHasGoods){
- $canUpgrade = 0;
- if(!$condition_type_one){
- // return $canUpgrade;
- }
- }else{
- if($condition_type_one){
- return true;
- }
- }
- }
- }
- return $canUpgrade;
- }
-
-
-
-
-
-
-
-
-
-
-
-
- /**
- * 队长列表
- */
- public function teamLeaderList() {
- try {
- $is_delete = 0;
- if ($this->is_delete == 1) {
- $is_delete = 1;
- }
- $query = User::find()->alias('u')
- ->leftJoin(['su' => SaasUser::tableName()], 'u.binding = su.mobile')
- ->where(['u.is_delete' => $is_delete, 'u.store_id' => $this->store_id, 'u.is_team_bonus_leader' => 1]);
-
- if (!is_null($this->team_bonus_leader_level) && $this->team_bonus_leader_level > 0) {
- $query->andWhere(['u.team_bonus_leader_level' => $this->team_bonus_leader_level]);
- }
- if (!is_null($this->team_bonus_leader_status) && $this->team_bonus_leader_status > -1) {
- $query->andWhere(['u.team_bonus_leader_status' => $this->team_bonus_leader_status]);
- }
- if ($this->id > 0) {
- $query->andWhere(['u.id' => $this->id]);
- }
- if (!empty($this->name)) {
- $query->andWhere(['like', 'su.name', trim($this->name)]);
- }
- if (!empty($this->mobile)) {
- $query->andWhere(['like', 'u.binding', trim($this->binding)]);
- }
- if (!empty($this->begin_time)) {
- $query->andWhere(['>=', 'u.team_bonus_leader_time', strtotime($this->begin_time)]);
- }
- if (!empty($this->end_time)) {
- $query->andWhere(['<=', 'u.team_bonus_leader_time', strtotime($this->end_time)]);
- }
- $query->select('u.*, su.id saas_user_id, su.name, su.avatar');
- $query->orderBy('u.team_bonus_leader_time DESC');
- $pagination = pagination_make($query);
- $teamLevels = array_column($this->teamBonusLevelSelectList()['data'], null, 'id');
- foreach ($pagination['list'] as &$item) {
- $item['team_bonus_leader_level_name'] = $teamLevels[$item['team_bonus_leader_level']] ? $teamLevels[$item['team_bonus_leader_level']]['name'] : '-';
- $saasUser = SaasUser::findOne([$item['saas_user_id']]);
- $item['saas_user'] = $saasUser;
- $item['team_bonus_leader_time'] = date("Y-m-d H:i:s", $item['team_bonus_leader_time']);
-
- $item['teamOrderPrice'] = self::teamOrderPrice($item);
- $item['teamOrderPriceHistory'] = self::teamOrderPriceHistory($item);
- $item['teamSelfOrderPrice'] = self::teamSelfOrderPrice($item);
- $item['teamChildren'] = self::teamChildren($item);
- $item['teamSharePrice'] = self::teamSharePrice($item);
- $item['teamCash'] = self::teamCash($item);
- }
- return [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => $pagination,
- 'q' => $query->createCommand()->getRawSql(),
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- /**
- * 队长保存
- */
- public function teamLeaderSave($data) {
- try {
- $id = $data['id'];
- $user = User::findOne($id);
- if (empty($user)) {
- throw new \Exception('参数错误' . $id);
- }
- if(!$user->is_team_bonus_leader){
- $user->is_team_bonus_leader = 1;
- $user->team_bonus_leader_status = 1;
- $user->team_bonus_leader_time = time();
- }
- $user->team_bonus_leader_level = $data['team_bonus_leader_level'];
- if(isset($data['team_bonus_leader_level_lock']) && $data['team_bonus_leader_level_lock'] > -1){
- $user->team_bonus_leader_level_lock = $data['team_bonus_leader_level_lock'];
- }
- if (!$user->save()) {
- \Yii::error([__METHOD__, $user->attributes]);
- throw new \Exception('保存失败。' . array_shift($user->getFirstErrors()));
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功!'
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- /**
- * 队长状态
- */
- public function teamLeaderStatus() {
- try {
- $status = $this->status;
- $id = $this->id;
- if (!is_array($id)) {
- $id = explode(',', $id);
- }
- foreach ($id as $item) {
- $user = User::findOne($item);
- if (!$user) {
- throw new \Exception('参数错误' . $item);
- }
- $user->team_bonus_leader_status = $status;
- if (!$user->save()) {
- throw new \Exception('保存失败。' . $item . array_shift($user->getFirstErrors()));
- }
- }
- return [
- 'code' => 0,
- 'msg' => 'success',
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- /**
- * 团队成员
- */
- public function teamChildrenList() {
- try {
- $leader = User::findOne($this->user_id);
- $getTeamBonusChildrenIds = self::getTeamBonusChildrenIds($this->store_id, $this->user_id);
- $user_ids = $getTeamBonusChildrenIds['list'];
- $is_delete = 0;
- if ($this->is_delete == 1) {
- $is_delete = 1;
- }
- $query = User::find()->alias('u')
- ->leftJoin(['su' => SaasUser::tableName()], 'u.binding = su.mobile')
- ->where(['u.is_delete' => $is_delete, 'u.store_id' => $this->store_id, 'u.id' => $user_ids]);
-
- if (!is_null($this->team_bonus_leader_level) && $this->team_bonus_leader_level > -1) {
- $query->andWhere(['u.team_bonus_leader_level' => $this->team_bonus_leader_level]);
- }
- if ($this->id > 0) {
- $query->andWhere(['u.id' => $this->id]);
- }
- if (!empty($this->name)) {
- $query->andWhere(['like', 'su.name', trim($this->name)]);
- }
- if (!empty($this->mobile)) {
- $query->andWhere(['like', 'u.binding', trim($this->binding)]);
- }
- if (!empty($this->begin_time)) {
- $query->andWhere(['>=', 'u.team_bonus_leader_time', strtotime($this->begin_time)]);
- }
- if (!empty($this->end_time)) {
- $query->andWhere(['<=', 'u.team_bonus_leader_time', strtotime($this->end_time)]);
- }
- $query->select('u.*, su.id saas_user_id, su.name, su.avatar');
- $query->orderBy('u.id DESC');
- $pagination = pagination_make($query);
- $teamLevels = array_column($this->teamBonusLevelSelectList()['data'], null, 'id');
- $shareLevels = array_column(\app\models\ShareLevel::findAll(['store_id' => $this->store_id, 'is_delete' => 0]), null, 'level');
- foreach ($pagination['list'] as &$item) {
- $item['team_bonus_leader_level_name'] = $teamLevels[$item['team_bonus_leader_level']] ? $teamLevels[$item['team_bonus_leader_level']]['name'] : '-';
- $share = Share::findOne(['user_id' => $item['id']]);
- $item['share'] = $share;
- $item['share_level_name'] = $share ? ($shareLevels[$share['level']] ? $shareLevels[$share['level']]['name'] : '无等级') : '非分销商';
- $saasUser = SaasUser::findOne([$item['saas_user_id']]);
- $item['saas_user'] = $saasUser;
- $item['created_at'] = date("Y-m-d H:i:s", $item['created_at']);
- $item['team_bonus_leader_time'] = date("Y-m-d H:i:s", $item['team_bonus_leader_time']);
-
-
- $item['teamOrderPrice'] = self::teamOrderPrice($leader, null, 0, [], $item['id']);
-
- $item['teamSharePrice'] = self::teamChildrenSharePrice($leader, $item['id']);
- $item['teamCash'] = self::teamCash($item);
- }
- $teamOrderPrice = self::teamOrderPrice($leader);
- return [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => $pagination,
- '$shareLevels' => $shareLevels,
- '$teamLevels' => $teamLevels,
- '$getTeamBonusChildrenIds' => $getTeamBonusChildrenIds,
- 'teamOrderPrice' => $teamOrderPrice,
- // 'q' => $query->createCommand()->getRawSql(),
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- /**
- * 队长等级保存
- */
- public function teamBonusLevelSave($data) {
- try {
- $id = $data['id'];
- $teamBonusLevel = $id ? TeamBonusLevel::findOne(['id' => $id, 'store_id' => $this->store_id]) : new TeamBonusLevel();
- if (empty($teamBonusLevel)) {
- throw new \Exception('参数错误' . $id);
- }
- $teamBonusLevel->setAttributes($data, false);
- $teamBonusLevel->store_id = $this->store_id;
- if (!$teamBonusLevel->save()) {
- \Yii::error([__METHOD__, $teamBonusLevel->attributes]);
- throw new \Exception('保存失败。' . array_shift($teamBonusLevel->getFirstErrors()));
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功!'
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- /**
- * 队长等级状态变更
- */
- public function teamBonusLevelStatus($id, $status) {
- try {
- $teamBonusLevel = TeamBonusLevel::findOne($id);
- if (!$teamBonusLevel) {
- throw new \Exception('参数错误' . $id);
- }
- $teamBonusLevel->status = $status;
- if (!$teamBonusLevel->save()) {
- throw new \Exception('保存失败。' . $id . array_shift($teamBonusLevel->getFirstErrors()));
- }
- return [
- 'code' => 0,
- 'msg' => 'success',
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- /**
- * 团队分红商品保存
- */
- public function teamBonusGoodsExtSave($data) {
- try {
- $goods_id = $data['goods_id'];
- $TeamBonusGoodsExt = TeamBonusGoodsExt::findOne(['goods_id' => $goods_id, 'store_id' => $this->store_id]);
- if (!$TeamBonusGoodsExt) {
- $TeamBonusGoodsExt = new TeamBonusGoodsExt();
- $TeamBonusGoodsExt->store_id = $this->store_id;
- }
- $TeamBonusGoodsExt->setAttributes($data, false);
- $TeamBonusGoodsExt->store_id = $this->store_id;
- if (!$TeamBonusGoodsExt->save(false)) {
- \Yii::error([__METHOD__, $TeamBonusGoodsExt->attributes]);
- throw new \Exception('保存失败。' . array_shift($TeamBonusGoodsExt->getFirstErrors()));
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功!'
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- /**
- * 团队分红商品分红状态
- */
- public function teamBonusGoodsExtStatus() {
- try {
- $status = $this->status;
- $id = $this->goods_id;
- if (!is_array($id)) {
- $id = explode(',', $id);
- }
- foreach ($id as $item) {
- $TeamBonusGoodsExt = TeamBonusGoodsExt::findOne(['goods_id' => $item, 'store_id' => $this->store_id]);
- if (!$TeamBonusGoodsExt) {
- $TeamBonusGoodsExt = new TeamBonusGoodsExt();
- $TeamBonusGoodsExt->store_id = $this->store_id;
- $TeamBonusGoodsExt->goods_id = $item;
- }
- $TeamBonusGoodsExt->status = $status;
- if (!$TeamBonusGoodsExt->save()) {
- throw new \Exception('保存失败。' . $item . array_shift($TeamBonusGoodsExt->getFirstErrors()));
- }
- }
- return [
- 'code' => 0,
- 'msg' => 'success',
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- //商品分红比例最大值
- public static function teamBonusGoodsProfit($store_id, $goods, $teamBonusGoodsExt = false) {
- if(!$goods['id']){
- $goods = \app\models\Goods::findOne($goods);
- }
- $goods_id = $goods['id'];
- $self = new self(['store_id' => $store_id]);
- $levels = $self->teamBonusLevelList()['data'];
- $max = $levels ? max(array_column($levels, 'range_rate')) : 0;
- if($teamBonusGoodsExt === false){
- $teamBonusGoodsExt = TeamBonusGoodsExt::findOne(['goods_id' => $goods_id, 'store_id' => $store_id]);
- }
- if($teamBonusGoodsExt){
- if($teamBonusGoodsExt['is_profit_self']){
- $rule = json_decode($teamBonusGoodsExt['profit_rule'], true);
- $max = $rule ? max(array_column($rule, 'range_rate')) : 0;
- }
- }
- return floatval($max) / 100;
- }
- //提现
- public function cashSubmit($price, $type, $user_id = 0, $name = '', $account = '', $bank = '') {
- $t = \Yii::$app->db->beginTransaction();
- try {
- if ($price <= 0) {
- throw new \Exception('提现金额非法' . $price);
- }
- $store_id = $this->store_id;
- $exit = Cash::find()->andWhere(['=', 'status', 0])->andWhere(['store_id' => $store_id, 'user_id' => $user_id, 'cash_type' => Cash::IS_CASH_TYPE_TEAM_BONUS])->exists();
- if ($exit) {
- // throw new \Exception('尚有未完成的提现申请');
- }
- $user = User::findOne($user_id);
- $conf = $this->teamBonusSetting()['conf'];
- if($conf['cash_min'] > 0 && $price < $conf['cash_min']){
- throw new \Exception('最少提现¥' . $conf['cash_min']);
- }
- if ($conf['cash_max_day']) {
- $cash_sum = Cash::find()->where([
- 'store_id' => $store_id,
- 'is_delete' => 0,
- 'status' => [0, 1, 2, 4, 5],
- ])->andWhere([
- 'AND',
- ['>=', 'created_at', strtotime(date('Y-m-d 00:00:00'))],
- ])->sum('price');
- $cash_max_day = $conf['cash_max_day'] - ($cash_sum ? $cash_sum : 0);
- if ($price > $cash_max_day) {
- throw new \Exception('今日平台限制,提现金额不能超过¥' . $cash_max_day);
- }
- }
- if ($conf['cash_max_single_day']) {
- $cash_sum = Cash::find()->where([
- 'store_id' => $store_id,
- 'is_delete' => 0,
- 'status' => [0, 1, 2, 4, 5],
- 'user_id' => $user_id
- ])->andWhere([
- 'AND',
- ['>=', 'created_at', strtotime(date('Y-m-d 00:00:00'))],
- ])->sum('price');
- $cash_max_single_day_ = $conf['cash_max_single_day'] - ($cash_sum ?: 0);
- if ($price > $cash_max_single_day_) {
- throw new \Exception('今日个人限制,提现金额不能超过¥' . $cash_max_single_day_);
- }
- }
- // $service_charge = $price * $conf['cash_rate'] / 100;
- $cash = new Cash();
- $cash->order_no = OrderNo::getOrderNo(OrderNo::ORDER_CASH);
- $cash->is_delete = 0;
- $cash->status = 0;
- $cash->price = $price;
- $cash->created_at = time();
- $cash->user_id = $user_id;
- $cash->store_id = $store_id;
- $cash->type = $type;
- $cash->name = $name;
- $cash->mobile = $account;
- $cash->bank_name = $bank;
- $cash->pay_time = 0;
- $cash->service_charge = $conf['cash_rate'];
- $cash->cash_type = Cash::IS_CASH_TYPE_TEAM_BONUS;
- if (!$cash->save()) {
- \Yii::error([__METHOD__, $cash->getErrors()]);
- throw new \Exception('团队分红提现保存失败' . array_shift($cash->getFirstErrors()));
- }
-
- $user->price -= $price;
- if($user->price < 0){
- throw new \Exception('用户佣金不足');
- }
- if (!$user->save()) {
- \Yii::error([__METHOD__, $user->getErrors()]);
- throw new \Exception('用户佣金保存失败' . array_shift($user->getFirstErrors()));
- }
- $t->commit();
- return [
- 'code' => 0,
- 'msg' => '操作成功'
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- debug_log([__FUNCTION__, __LINE__, $this->store_id, $price, $type, $user_id, $e->getMessage()], __CLASS__ . '.log');
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '操作失败,' . $e->getMessage()
- ];
- }
- }
- /**
- * 手机端首页
- */
- public function teamBonusIndex($user) {
- try{
- $user_id = $this->user_id;
- $store_id = $this->store_id;
- if($user->is_team_bonus_leader){
- if(!$user->team_bonus_leader_status){
- throw new \Exception('队长状态异常');
- }
- }else{
- throw new \Exception('不是队长,无法进入');
- // $share = Share::find()->where(['store_id' => $store_id, 'status' => 1, 'is_delete' => 0, 'user_id' => $user_id])->one();
- // if(!$share){
- // throw new \Exception('不是队长和分销员,无法进入');
- // }
- }
- $types = [
- ShareDetail::TYPE_TEAM_BONUS_RANGE_PROFIT,
- ShareDetail::TYPE_TEAM_BONUS_SAME_LEVEL,
- ShareDetail::TYPE_TEAM_BONUS_PARENT,
- ShareDetail::TYPE_TEAM_BONUS_THANKS,
- ];
- $sumUnSend = (float)ShareDetail::find()->where(['store_id' => $store_id, 'is_delete' => 0, 'user_id' => $user_id, 'is_send' => 0, 'type' => $types])->sum('money');
- $sumCash = (float)Cash::find()->where(['store_id' => $store_id, 'is_delete' => 0, 'cash_type' => Cash::IS_CASH_TYPE_TEAM_BONUS, 'status' => [0, 1, 2, 4, 5], 'user_id' => $user_id])->sum('price');
- $levels = $this->teamBonusLevelSelectList()['data'];
- $team_bonus_leader_level_name = $levels[$user->team_bonus_leader_level] ? $levels[$user->team_bonus_leader_level]['name'] : '-';
- return [
- 'code' => 0,
- 'data' => [
- 'user' => $user,
- 'saas_user' => SaasUser::findOne(['mobile' => $user['binding']]),
- 'sumUnSend' => $sumUnSend,
- 'sumCash' => $sumCash,
- 'team_bonus_leader_level_name' => $team_bonus_leader_level_name,
- 'share' => $share,
- ],
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- debug_log([__FUNCTION__, __LINE__, $this->store_id, $this->user_id, $e->getMessage()], __CLASS__ . '.log');
- return [
- 'code' => 1,
- 'msg' => '操作失败,' . $e->getMessage()
- ];
- }
- }
- /**
- * 分红记录
- */
- public function teamLeaderShareDetails($params = []) {
- $user_id = $this->user_id;
- if($params['user_id']){
- $user_id = $params['user_id'];
- }
- $store_id = $this->store_id;
- $type = $params['type'];
- $is_send = $params['is_send'];
- $_get_order = $params['_get_order'];
- $types = [
- ShareDetail::TYPE_TEAM_BONUS_RANGE_PROFIT,
- ShareDetail::TYPE_TEAM_BONUS_SAME_LEVEL,
- ShareDetail::TYPE_TEAM_BONUS_PARENT,
- ShareDetail::TYPE_TEAM_BONUS_THANKS,
- ];
- $query = ShareDetail::find()->where(['store_id' => $store_id, 'is_delete' => 0]);
- if($user_id){
- $query->andWhere(['user_id' => $user_id]);
- }
- if($type){
- $query->andWhere(['type' => $type]);
- }else{
- $query->andWhere(['type' => $types]);
- }
- if(isset($is_send) && $is_send > -1){
- $query->andWhere(['is_send' => $is_send]);
- }
- if($params['team_leader_name']){
- $query->andWhere(['user_id' => User::find()->alias('u')->leftJoin(['su' => SaasUser::tableName()], 'u.binding=su.mobile')->select('u.id')->where(['like', 'su.name', trim($params['team_leader_name'])])]);
- }
- if (!empty($params['begin_time'])) {
- $query->andWhere(['>=', 'send_time', strtotime($params['begin_time'])]);
- }
- if (!empty($params['end_time'])) {
- $query->andWhere(['<=', 'send_time', strtotime($params['end_time'])]);
- }
- $query->orderBy('id DESC');
- $list = pagination_make($query);
- if($user_id){
- $user = User::findOne($user_id);
- $saas_user = SaasUser::findOne(['mobile' => $user['binding']]);
- $item_saas_user = $saas_user;
- }
- foreach($list['list'] as &$item){
- $item['type_name'] = ShareDetail::typeName($item['type']);
- if($_get_order){
- $order = Order::findOne($item['type_id']);
- $item['order'] = $order;
- if($order){
- $item['order_detail'] = $order->detail;
- $order_user = User::findOne($order->user_id);
- $item['order_saas_user'] = SaasUser::findOne(['mobile' => $order_user['binding']]);
- }
- }
- if($user_id){
- $item['saas_user'] = $item_saas_user;
- }else{
- $user = User::findOne($item['user_id']);
- $saas_user = SaasUser::findOne(['mobile' => $user['binding']]);
- $item['saas_user'] = $saas_user;
- }
- }
- return [
- 'q' => $query->createCommand()->getRawSql(),
- 'code' => 0,
- 'data' => $list,
- 'types' => ShareDetail::typeName(),
- ];
- }
- }
|