CommissionLogLogic.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. <?php
  2. namespace addons\BossWeight\common\logic;
  3. use addons\BossWeight\common\enums\BossEnum;
  4. use addons\BossWeight\common\models\AddonsBoss;
  5. use addons\BossWeight\common\models\AddonsBossCommissionJob;
  6. use addons\BossWeight\common\models\AddonsBossCommissionLog;
  7. use addons\BossWeight\common\models\AddonsBossLevel;
  8. use addons\BossWeight\common\models\AddonsBossLevelSetting;
  9. use addons\BossWeight\common\models\AddonsBossPrice;
  10. use addons\BossWeight\common\models\AddonsBossRewardLog;
  11. use addons\BossWeight\common\models\AddonsBossRewardOrderLog;
  12. use common\enums\OrderStatusEnum;
  13. use common\enums\StatusEnum;
  14. use common\enums\UserWalletEnum;
  15. use common\helpers\FormatHelper;
  16. use common\models\mall\Mall;
  17. use common\models\order\Order;
  18. use common\models\order\OrderDetail;
  19. use common\models\user\UserPartitionRelationship;
  20. use common\models\user\UserTeamProfitStatistics;
  21. use common\traits\ErrorTrait;
  22. use Exception;
  23. use services\common\UserWalletService;
  24. use common\models\user\User;
  25. use Yii;
  26. use yii\helpers\Json;
  27. class CommissionLogLogic{
  28. use ErrorTrait;
  29. /**
  30. * 执行分红操作
  31. * @Author: lun
  32. * @DateTime: 2021/11/5 0005 14:27
  33. * @Copyright: copyright (c) 2021 广东七件事集团
  34. * @return bool
  35. */
  36. public function execute()
  37. {
  38. $mall_list = Mall::getEnableMallList(true);
  39. if(!empty($mall_list)){
  40. foreach ($mall_list as $mall){
  41. $mallId = $mall['id'];
  42. // 获取基础配置
  43. $config = Yii::$app->services->setting->addons->get($mallId, 'BossWeight', 'basic');
  44. if ($config['is_enable'] == StatusEnum::ENABLED) {
  45. $continue = false;
  46. // 获取结算周期,0=天,1=周,2=月
  47. $compute_period = $config['compute_period'];
  48. switch ($config['compute_period']) {
  49. case 1:
  50. $start_day = date("Ymd", strtotime("-1 day"));
  51. $end_day = $start_day;
  52. break;
  53. case 2:
  54. if (date('w') != 1) $continue = true;// 非周一直接退出
  55. $start_day = date("Ymd", strtotime("last Monday"));
  56. $end_day = date('Ymd', strtotime('-1 sunday', time()));;
  57. break;
  58. case 3:
  59. if (date('d') != 1) $continue = true;// 非当月1号直接退出
  60. $start_day = date("Ym01", strtotime("-1 month"));
  61. $end_day = date('Ymd', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400);
  62. break;
  63. }
  64. if ($continue) continue;
  65. $date_limit = $start_day . '-' . $end_day;
  66. $job = AddonsBossCommissionJob::findOne(['mall_id' => $mallId, 'compute_period' => $compute_period, 'date_limit' => $date_limit, 'status' => StatusEnum::ENABLED]);
  67. if ($job) continue;
  68. // 生成执行记录
  69. $job = new AddonsBossCommissionJob();
  70. $job->mall_id = $mallId;
  71. $job->date_limit = $date_limit;
  72. $job->compute_period = $compute_period;
  73. if (!$job->save()) throw new Exception($job->getErrorMessage());
  74. $trans = Yii::$app->db->beginTransaction();
  75. try {
  76. $res = $this->addCommissionLog($mallId, $config, $start_day, $end_day);
  77. if($res === false) throw new Exception($this->getError());
  78. $trans->commit();
  79. } catch (Exception $e) {
  80. $trans->rollBack();
  81. }
  82. }
  83. }
  84. return true;
  85. }
  86. }
  87. /**
  88. * 增加boss分红佣金
  89. * @Author: lun
  90. * @DateTime: 2021/11/5 0005 14:27
  91. * @Copyright: copyright (c) 2021 广东七件事集团
  92. * @param $mallId
  93. * @param $config
  94. * @param $start_day
  95. * @param $end_time
  96. * @return bool
  97. */
  98. private function addCommissionLog($mallId, $config, $start_day, $end_day)
  99. {
  100. if ($config['is_enable'] == StatusEnum::DISABLED) {
  101. Yii::error('系统没有开启股东提成');
  102. return true;
  103. }
  104. try {
  105. // 初始化数据
  106. $time = time();
  107. $table_name = AddonsBossCommissionLog::tableName();
  108. // 获取所有股东列表
  109. $boss_list = AddonsBoss::find()->where(['mall_id' => $mallId, 'status' => StatusEnum::ENABLED])->asArray()->all();
  110. if (empty($boss_list)) return true;
  111. foreach ($boss_list as $k => $boss){
  112. /** @var AddonsBossPrice $bossPrice */
  113. $bossPrice = AddonsBossPrice::find()->where([
  114. 'user_id' => $boss['user_id'],
  115. 'level' => $boss['level']
  116. ])->one();
  117. if($bossPrice){
  118. /** @var AddonsBossLevelSetting $levelSetting */
  119. $levelSetting = AddonsBossLevelSetting::find()->where([
  120. 'status' => 1,
  121. 'mall_id'=> $boss['mall_id'],
  122. 'level' => $boss['level']
  123. ])->one();
  124. //如果boss用户的分红金额达到设置的上限金额。就从数组移除,不再往下处理
  125. //如果开启了权重限制并且boss用户权重状态不为0。就从数组移除,不再往下处理
  126. if($levelSetting->weight_max_price && $bossPrice->price > $levelSetting->weight_max_price){
  127. if($levelSetting->weight_is_limit == 0 || ($levelSetting->weight_is_limit == 1 && $boss['boss_weight_status'])){
  128. unset($boss_list[$k]);
  129. }
  130. }
  131. }
  132. }
  133. $boss_arr = array_column($boss_list,'user_id');
  134. //修改加权分红获取方式
  135. $rows = $this->weightCommission($boss_list,$config,$start_day,$end_day,$mallId);
  136. Yii::error("addCommissionLog rows=".var_export($rows,true));
  137. unset($boss_list);
  138. // 获取分红奖励列表
  139. //查询已取消的订单
  140. $cancel_order_ids = AddonsBossRewardLog::find()
  141. ->alias('brl')
  142. ->innerJoin(Order::tableName() . ' as o', 'o.id = brl.order_id')
  143. ->where(['brl.mall_id' => $mallId, 'brl.is_settlement' => StatusEnum::DISABLED, 'brl.status' => StatusEnum::ENABLED,'o.order_status'=>OrderStatusEnum::REPEAL])
  144. ->andFilterWhere(['between', 'brl.date', $start_day, $end_day])
  145. ->select('brl.order_id')
  146. ->column();
  147. $reward_list = AddonsBossRewardLog::find()
  148. ->select('user_id,sum(amounts) amounts,sum(commission) commission,sum(order_price) order_price,sum(settle_price) settle_price,type')
  149. ->where(['mall_id' => $mallId, 'is_settlement' => StatusEnum::DISABLED, 'status' => StatusEnum::ENABLED])
  150. ->andWhere(['not in', 'order_id', $cancel_order_ids])
  151. ->andFilterWhere(['between', 'date', $start_day, $end_day])
  152. ->groupBy('user_id,type')
  153. ->asArray()
  154. ->all();
  155. if($reward_list){
  156. // 生成计算好的结算数据
  157. foreach ($reward_list as $item) {
  158. if (in_array($item['user_id'], $boss_arr)) {
  159. $rows[] = [
  160. 'mall_id' => $mallId,
  161. 'user_id' => $item['user_id'],
  162. 'order_price' => $item['order_price'],
  163. 'settle_price' => $item['settle_price'],
  164. 'amounts' => $item['amounts'],
  165. 'commission' => $item['commission'],
  166. 'type' => $item['type'],
  167. 'compute_period' => $config['compute_period'],
  168. 'start_time' => $start_day,
  169. 'end_time' => $end_day,
  170. 'created_at' => $time,
  171. 'updated_at' => $time,
  172. 'settlement_config' => $item['settlement_config'] ? $item['settlement_config'] : '',
  173. ];
  174. }
  175. }
  176. }
  177. if($cancel_order_ids){
  178. AddonsBossRewardLog::updateAll(
  179. ['status' => StatusEnum::DELETE, 'updated_at' => $time],
  180. ['and', ['mall_id' => $mallId, 'status' => StatusEnum::ENABLED],['in', 'order_id', $cancel_order_ids]]
  181. );
  182. }
  183. if (empty($rows)) return true;
  184. unset($reward_list);
  185. // 生成数据
  186. $field = ['mall_id','user_id','order_price','settle_price','amounts','commission','type','compute_period','start_time','end_time','created_at','updated_at','settlement_config'];
  187. Yii::$app->db->createCommand()->batchInsert($table_name, $field, $rows)->execute();
  188. unset($rows);
  189. // 数据生成完成记录表修改结算状态
  190. AddonsBossRewardLog::updateAll(
  191. ['is_settlement' => StatusEnum::ENABLED, 'updated_at' => $time],
  192. ['and', ['mall_id' => $mallId, 'is_settlement' => StatusEnum::DISABLED],['between', 'date', $start_day, $end_day],['not in', 'order_id', $cancel_order_ids]]
  193. );
  194. // 增加对应股东分佣金额
  195. $log_list = AddonsBossCommissionLog::getBossCommissionLog([['mall_id' => $mallId,'start_time' => $start_day,'end_time' => $end_day]]);
  196. $boss_commission = [];
  197. foreach ($log_list as $item) {
  198. switch ($item['type']){
  199. case 1:
  200. $capital_type = UserWalletEnum::FOREVER;
  201. break;
  202. case 4:
  203. $class = new \ReflectionClass(UserWalletEnum::class);
  204. $var = "BOSS_WIGHT";
  205. if($class->hasConstant($var)){
  206. $capital_type= $class->getConstant($var);
  207. }else{
  208. $capital_type = 'boss_weight';
  209. }
  210. break;
  211. default:
  212. $capital_type = UserWalletEnum::BO_EXTRA;
  213. break;
  214. }
  215. $insert_wallet[] = [
  216. 'mall_id' => $mallId,
  217. 'user_id' => $item['user_id'],
  218. 'is_frozen' => false,
  219. 'wallet_type' => 'commission',
  220. 'money' => $item['commission'],
  221. 'desc' => '加权分红佣金',
  222. 'source_table' => $table_name,
  223. 'source_table_id' => $item['id'],
  224. 'from_type' => BossEnum::ADDONS_NAME,
  225. 'capital_type' => $capital_type,
  226. ];
  227. if ($item['type'] == 1 || $item['type'] == 4) {
  228. $boss_commission[$item['user_id']]['commission'] += $item['commission'];
  229. } else {
  230. $boss_commission[$item['user_id']]['extra_commission'] += $item['commission'];
  231. }
  232. }
  233. if ($insert_wallet) {
  234. $res = UserWalletService::batchHandleByQueue($insert_wallet);
  235. if (empty($res)) throw new \Exception(UserWalletService::getStaticError());
  236. }
  237. unset($insert_wallet);
  238. // 增加用户股东金额
  239. foreach ($boss_commission as $user_id => $commission) {
  240. $boss = AddonsBoss::findOne(['mall_id' => $mallId, 'user_id' => $user_id, 'status' => StatusEnum::ENABLED]);
  241. if(!$boss) continue;
  242. $boss->commission = empty($commission['commission']) ? $boss->commission : $boss->commission + $commission['commission'];
  243. $boss->extra_commission = empty($commission['extra_commission']) ? $boss->extra_commission : $boss->extra_commission + $commission['extra_commission'];
  244. $boss->total_commission = $boss->commission + $boss->extra_commission;
  245. if (!$boss->save()) throw new \Exception($boss->getErrorMessage());
  246. //更新用户股东分红总金额。
  247. /** @var AddonsBossPrice $bossPrice */
  248. //增加金额为0则不执行
  249. $bossPricePrice = $commission['commission'] ? $commission['commission']:0;
  250. if($bossPricePrice){
  251. $bossPrice = AddonsBossPrice::find()->where([
  252. 'user_id' => $boss['user_id'],
  253. 'level' => $boss['level']
  254. ])->one();
  255. if(!$bossPrice){
  256. $bossPrice = new AddonsBossPrice();
  257. $bossPrice->user_id = $boss->user_id;
  258. $bossPrice->level = $boss->level;
  259. }
  260. $bossPrice->price += $bossPricePrice;
  261. if (!$bossPrice->save()) throw new \Exception($bossPrice->getErrorMessage());
  262. }
  263. }
  264. return true;
  265. } catch (Exception $e) {
  266. $exception = FormatHelper::exception($e, "mall_id={$mallId} 股东定时分红任务失败");
  267. echo $exception;
  268. Yii::error($exception);
  269. $this->setError($exception);
  270. return false;
  271. }
  272. }
  273. /**
  274. * 加权分红
  275. * @param AddonsBoss[] $bossList
  276. */
  277. private function weightCommission(array $bossList,array $config, string $start_day, string $end_day,$mall_id){
  278. if($bossList){
  279. $where = [
  280. 'and',
  281. ['mall_id' => $mall_id],
  282. ['status' => StatusEnum::ENABLED],
  283. ['store_id' => 0],
  284. ['mch_id' => 0]
  285. ];
  286. //查询已结算的订单
  287. $reward_order_ids = AddonsBossRewardOrderLog::find()
  288. ->where(['mall_id' => $mall_id])
  289. ->andWhere(['status' => StatusEnum::ENABLED])
  290. ->andWhere([
  291. 'and',
  292. ['>=', 'created_at', strtotime($start_day)],
  293. ['<=', 'created_at', strtotime("$end_day 23:59:59")]
  294. ])
  295. ->select('order_id')
  296. ->column();
  297. if (!empty($reward_order_ids)) {//过滤已结算的订单
  298. $where[] = ['not in', 'id', $reward_order_ids];
  299. }
  300. // 判断结算方式,0=支付完成,1=订单完成
  301. if ($config['settlement_method'] == 0) {
  302. $where[] = ['pay_status' => OrderStatusEnum::PAY];
  303. $where[] = ['not in', 'order_status', [OrderStatusEnum::REPEAL]];
  304. $where[] = [
  305. 'and',
  306. ['>=', 'pay_time', strtotime($start_day)],
  307. ['<=', 'pay_time', strtotime("$end_day 23:59:59")]
  308. ];
  309. } else {
  310. $where[] = ['order_status' => OrderStatusEnum::ACCOMPLISH];
  311. $where[] = [
  312. 'and',
  313. ['>=', 'finish_time', strtotime($start_day)],
  314. ['<=', 'finish_time', strtotime("$end_day 23:59:59")]
  315. ];
  316. }
  317. $order_list = Order::find()->where($where)->all();
  318. if(!$order_list){
  319. return [];
  320. }
  321. $time = time();
  322. $reward_log = [];
  323. //判断结算方式
  324. if($config['compute_type'] == 1){//计算订单利润
  325. $order_ids = array_column($order_list,'id');
  326. //读取商城营业额
  327. $order_profit = OrderDetail::find()
  328. ->select([
  329. 'order_id',
  330. 'total_sum' => 'SUM(cost_price*num + adjust_money)'
  331. ])
  332. ->where(['order_id' => $order_ids])
  333. ->groupBy('order_id')
  334. ->indexBy('order_id')
  335. ->asArray()
  336. ->all();
  337. }
  338. $totalTurnover = 0;//订单计算总金额
  339. $order_price = 0;//订单总金额
  340. //记录订单结算记录
  341. foreach ($order_list as $order){
  342. if($config['compute_type'] == 1){//利润
  343. $amounts = ($order['goods_price'] - $order_profit[$order['id']]['total_sum']);
  344. }elseif ($config['compute_type'] == 2){//售价
  345. $amounts = $order['original_goods_price'];
  346. }else{
  347. $amounts = $order['goods_price'];
  348. }
  349. $reward_log[] = [
  350. 'mall_id' => $mall_id,
  351. 'order_id' => $order['id'],
  352. 'order_no' => $order['order_no'],
  353. 'order_price' => $order['goods_price'],
  354. 'amounts' => $amounts,
  355. 'settlement_method' => $config['settlement_method'],
  356. 'date' => $end_day,
  357. 'created_at' => $time,
  358. 'updated_at' => $time,
  359. ];
  360. $totalTurnover += $amounts;
  361. $order_price += $order['goods_price'];
  362. }
  363. $trans = Yii::$app->db->beginTransaction();
  364. try {
  365. // 生成订单结算记录
  366. $field = ['mall_id','order_id','order_no','order_price','amounts','settlement_method','date','created_at','updated_at'];
  367. Yii::$app->db->createCommand()->batchInsert(AddonsBossRewardOrderLog::tableName(), $field, $reward_log)->execute();
  368. $trans->commit();
  369. } catch (Exception $e) {
  370. $trans->rollBack();
  371. $this->setError($e->getMessage());
  372. return false;
  373. }
  374. $rows = [];
  375. $level_list = array_unique(array_column($bossList,'level'));
  376. $totalWeight_list = [];
  377. foreach($level_list as $level){
  378. $totalWeight_list[$level] = self::getLevelWeight($mall_id,$level);
  379. }
  380. $levelSetting_list = AddonsBossLevelSetting::find()->where([
  381. 'status' => 1,
  382. 'mall_id'=> $mall_id,
  383. 'level' => $level_list
  384. ])->indexBy('level')->asArray()->all();
  385. foreach ($bossList as $boss){
  386. Yii::error("weightCommission boss=".var_export($boss,true));
  387. /** @var AddonsBossLevelSetting $levelSetting */
  388. $levelSetting = $levelSetting_list[$boss['level']];
  389. if(!$levelSetting || !$levelSetting['weight_turnover_ratio'] || !$levelSetting['weight_level_ratio']){
  390. continue ;
  391. }
  392. $levelPrice = bcdiv($totalTurnover * intval($levelSetting['weight_turnover_ratio']) * intval($levelSetting['weight_level_ratio']),10000,2);
  393. Yii::error("weightCommission levelPrice=".$levelPrice);
  394. $userWeight = self::getBossWeight($boss);
  395. Yii::error("weightCommission userWeight=".$userWeight);
  396. $totalWeight = $totalWeight_list[$boss['level']];
  397. Yii::error("weightCommission totalWeight=".$totalWeight);
  398. $commission = 0;
  399. if($totalWeight > 0){
  400. $commission = bcdiv($totalTurnover*intval($levelSetting['weight_turnover_ratio'])*intval($levelSetting['weight_level_ratio'])/10000 *$userWeight,$totalWeight,2);
  401. }
  402. Yii::error("weightCommission commissin=".$commission);
  403. if($commission){
  404. $settlement_config = [
  405. 'settlement_method' => $config['settlement_method'],
  406. 'compute_type' => $config['compute_type'],
  407. 'weight_turnover_ratio' => $levelSetting['weight_turnover_ratio'],
  408. 'weight_level_ratio' => $levelSetting['weight_level_ratio'],
  409. 'total_weight' => $totalWeight,
  410. 'user_weight' => $userWeight,
  411. 'level' => $boss['level'],
  412. ];
  413. $rows[] = [
  414. 'mall_id' => $boss['mall_id'],
  415. 'user_id' => $boss['user_id'],
  416. 'order_price' => $order_price,//订单总支付金额
  417. 'settle_price' => $levelPrice,//总结算金额
  418. 'amounts' => $totalTurnover,//订单总计算金额
  419. 'commission' => $commission,
  420. 'type' => 4,//加权分红
  421. 'compute_period' => $config['compute_period'],
  422. 'start_time' => $start_day,
  423. 'end_time' => $end_day,
  424. 'created_at' => time(),
  425. 'updated_at' => $time,
  426. 'settlement_config' => Json::encode($settlement_config),
  427. ];
  428. }
  429. }
  430. return $rows;
  431. }
  432. }
  433. //获取boss权重分红的份额数量
  434. public static function getBossWeight(array $boss):int{
  435. /** @var AddonsBossLevelSetting $levelSetting */
  436. $levelSetting = AddonsBossLevelSetting::find()->where([
  437. 'status' => 1,
  438. 'mall_id'=> $boss['mall_id'],
  439. 'level' => $boss['level']
  440. ])->one();
  441. if(!$levelSetting) return 0;
  442. if(!$levelSetting->weight_status) return 0;
  443. // if(!$levelSetting->weight_member_num) return 0;
  444. // if(!$levelSetting->weight_num) return 0;
  445. //开启权重限制且股东权重状态不为0,则该股东权重为0
  446. if($levelSetting->weight_is_limit == 1 && $boss['boss_weight_status']) return 0;
  447. //权重数量
  448. $BossWeight = 0;
  449. $userChilds =UserPartitionRelationship::getChildIdArr($boss['user_id'],1);
  450. $userChildsSecond = $userChilds;
  451. if($levelSetting->weight_product_num > 0){
  452. foreach ($userChilds as $k=>&$child){
  453. /** @var OrderDetail[] $orderDetails */
  454. $orderDetails = OrderDetail::find()->with('order')->where([
  455. 'status' => 1,
  456. 'user_id' => $child
  457. ])->andWhere(['>','order_status',0])->all();
  458. //删除不满足条件的下级
  459. if(!$orderDetails){
  460. unset($userChilds[$k]);
  461. continue ;
  462. }
  463. $total_goods_num = 0;//任意商品总数量
  464. foreach ($orderDetails as $detail){
  465. $total_goods_num += $detail->num;
  466. }
  467. //删除不满足条件的下级
  468. if($total_goods_num < $levelSetting->weight_product_num){
  469. unset($userChilds[$k]);
  470. }
  471. }
  472. }
  473. if(!$levelSetting->weight_member_num || !$levelSetting->weight_num){
  474. $BossWeight = 0;
  475. }else{
  476. $BossWeight = floor( count($userChilds) / intval($levelSetting->weight_member_num) ) * intval($levelSetting->weight_num);
  477. }
  478. if($levelSetting->weight_member_num_second > 0){
  479. $level_num = User::find()->where(['id'=>$userChildsSecond,'level'=>$levelSetting->weight_member_level_second,'status'=>1])->count();
  480. $BossWeight += intval($level_num / $levelSetting->weight_member_num_second) * $levelSetting->weight_num_second;
  481. }
  482. if($levelSetting->weight_member_num_team > 0){
  483. //获取直推用户id
  484. $direct_child_ids = UserPartitionRelationship::getChildIdArr($boss['user_id'], 1);
  485. if (!empty($direct_child_ids)) {
  486. //获取哪些市场超过指定业绩
  487. $where = [
  488. 'and',
  489. ['user_id' => $direct_child_ids],
  490. ['>','team_order_pay_achievement',$levelSetting->weight_member_num_team * 10000],
  491. ];
  492. $count = UserTeamProfitStatistics::find()->where($where)->count();
  493. if($count>0){
  494. $BossWeight += $count * $levelSetting->weight_num_team;
  495. }
  496. }
  497. }
  498. //权重数量 = 固定权重 + 条件权重
  499. $BossWeight += $boss['fixed_weight'];
  500. if($BossWeight < 0) $BossWeight = 0;
  501. return $BossWeight;
  502. }
  503. //获取平台权重总份额
  504. public static function getTotalWeight(int $mallId){
  505. /** @var AddonsBoss[] $boss_list */
  506. $boss_list = AddonsBoss::find()->where(['mall_id' => $mallId, 'status' => StatusEnum::ENABLED])->asArray()->all();
  507. if(!$boss_list) return 0;
  508. $total_weight_num = 0;
  509. foreach ($boss_list as $boss){
  510. $total_weight_num += self::getBossWeight($boss);
  511. }
  512. return $total_weight_num;
  513. }
  514. //获取指定等级权重总份额
  515. public static function getLevelWeight(int $mallId,int $level){
  516. /** @var AddonsBoss[] $boss_list */
  517. $boss_list = AddonsBoss::find()
  518. ->where(['mall_id' => $mallId,'level'=>$level, 'status' => StatusEnum::ENABLED])
  519. ->asArray()->all();
  520. if(!$boss_list) return 0;
  521. $total_weight_num = 0;
  522. foreach ($boss_list as $boss){
  523. $total_weight_num += self::getBossWeight($boss);
  524. }
  525. return $total_weight_num;
  526. }
  527. //获取boss权重分红的份额数量(不包含股东失效情况)
  528. public static function getBossWeightOutStatus(array $boss):int{
  529. /** @var AddonsBossLevelSetting $levelSetting */
  530. $levelSetting = AddonsBossLevelSetting::find()->where([
  531. 'status' => 1,
  532. 'mall_id'=> $boss['mall_id'],
  533. 'level' => $boss['level']
  534. ])->one();
  535. if(!$levelSetting) return 0;
  536. if(!$levelSetting->weight_status) return 0;
  537. // if(!$levelSetting->weight_member_num) return 0;
  538. // if(!$levelSetting->weight_num) return 0;
  539. //权重数量
  540. $BossWeight = 0;
  541. $userChilds =UserPartitionRelationship::getChildIdArr($boss['user_id'],1);
  542. $userChildsSecond = $userChilds;
  543. if($levelSetting->weight_product_num > 0){
  544. foreach ($userChilds as $k=>&$child){
  545. /** @var OrderDetail[] $orderDetails */
  546. $orderDetails = OrderDetail::find()->with('order')->where([
  547. 'status' => 1,
  548. 'user_id' => $child
  549. ])->andWhere(['>','order_status',0])->all();
  550. //删除不满足条件的下级
  551. if(!$orderDetails){
  552. unset($userChilds[$k]);
  553. continue ;
  554. }
  555. $total_goods_num = 0;//任意商品总数量
  556. foreach ($orderDetails as $detail){
  557. $total_goods_num += $detail->num;
  558. }
  559. //删除不满足条件的下级
  560. if($total_goods_num < $levelSetting->weight_product_num){
  561. unset($userChilds[$k]);
  562. }
  563. }
  564. }
  565. if(!$levelSetting->weight_member_num || !$levelSetting->weight_num){
  566. $BossWeight = 0;
  567. }else{
  568. $BossWeight = floor( count($userChilds) / intval($levelSetting->weight_member_num) ) * intval($levelSetting->weight_num);
  569. }
  570. if($levelSetting->weight_member_num_second > 0){
  571. $level_num = User::find()->where(['id'=>$userChildsSecond,'level'=>$levelSetting->weight_member_level_second,'status'=>1])->count();
  572. $BossWeight += intval($level_num / $levelSetting->weight_member_num_second) * $levelSetting->weight_num_second;
  573. }
  574. //权重数量 = 固定权重 + 条件权重
  575. $BossWeight += $boss['fixed_weight'];
  576. if($BossWeight < 0) $BossWeight = 0;
  577. return $BossWeight;
  578. }
  579. public static function getComputeTime($mallId){
  580. $config = Yii::$app->services->setting->addons->get($mallId, 'BossWeight', 'basic');
  581. $start_day = 0;
  582. $end_day = 0;
  583. if ($config['is_enable'] == StatusEnum::ENABLED) {
  584. // 获取结算周期,0=天,1=周,2=月
  585. $compute_period = $config['compute_period'];
  586. switch ($config['compute_period']) {
  587. case 1:
  588. $start_day = date("Ymd", time());
  589. $end_day = $start_day;
  590. break;
  591. case 2:
  592. if (date('w') != 1){
  593. $start_day = date("Ymd", strtotime("last Monday"));
  594. }else{
  595. $start_day = date("Ymd", time());
  596. }
  597. $end_day = date('Ymd', strtotime('-6 day', strtotime($start_day)));
  598. break;
  599. case 3:
  600. $start_day = date("Ym01", time());
  601. $end_day = date('Ymt',time());
  602. break;
  603. }
  604. }
  605. return [strtotime($start_day),strtotime($end_day)];
  606. }
  607. }