From 7e96543ae18f8625abefcddc875ef8010d35b28a Mon Sep 17 00:00:00 2001
From: Helius <wangdoubleone@gmail.com>
Date: Sat, 11 Jun 2022 21:22:33 +0800
Subject: [PATCH] fix

---
 src/main/java/cc/mrbird/febs/mall/service/impl/MemberProfitServiceImpl.java |  239 ++++++++++++++++++++++++++++++++++++++++++++++++-----------
 1 files changed, 194 insertions(+), 45 deletions(-)

diff --git a/src/main/java/cc/mrbird/febs/mall/service/impl/MemberProfitServiceImpl.java b/src/main/java/cc/mrbird/febs/mall/service/impl/MemberProfitServiceImpl.java
index c7677fa..f460d01 100644
--- a/src/main/java/cc/mrbird/febs/mall/service/impl/MemberProfitServiceImpl.java
+++ b/src/main/java/cc/mrbird/febs/mall/service/impl/MemberProfitServiceImpl.java
@@ -12,8 +12,12 @@
 import cc.mrbird.febs.mall.service.IMemberProfitService;
 import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.date.DateField;
+import cn.hutool.core.date.DateUnit;
 import cn.hutool.core.date.DateUtil;
 import cn.hutool.core.util.StrUtil;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
@@ -40,6 +44,7 @@
     private final IApiMallMemberWalletService walletService;
     private final IMallMoneyFlowService moneyFlowService;
     private final DataDictionaryCustomMapper dataDictionaryCustomMapper;
+    private final MallMoneyFlowMapper mallMoneyFlowMapper;
 
     @Override
     @Transactional(rollbackFor = Exception.class)
@@ -51,7 +56,7 @@
         }
 
         Date profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
-        BigDecimal totalIncome = mallOrderInfoMapper.selectTotalAmountForDate(profitDate, null);
+        BigDecimal totalIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D");
         if (totalIncome.compareTo(BigDecimal.ZERO) == 0) {
             return;
         }
@@ -69,10 +74,8 @@
             for (MallGoods goods : goodsList) {
                 BigDecimal goodsProfit = goods.getStaticProp().multiply(perProfit);
 
-                try {
-                    walletService.reduce(goodsProfit, member.getId(), "score");
-                } catch (Exception e) {
-                    log.info("静态分红异常:{}, {}", goodsProfit, member.getId());
+                int reduce = walletService.reduce(goodsProfit, member.getId(), "score");
+                if (reduce == 2) {
                     break;
                 }
 
@@ -86,80 +89,128 @@
     /**
      * 直推20%,隔代收益为直推奖励金额的30%,a_b_c_d,d购买1000套餐,c得200,b得200*30%=60元,a得60*30%=18元。。。
      * 以此类推,结算到一元为止。
+     *
      * @param orderId
      */
     @Override
+    @Transactional(rollbackFor = Exception.class)
     public void dynamicProfit(Long orderId) {
         log.info("######直推奖励, 订单ID:{}######", orderId);
         MallOrderInfo orderInfo = mallOrderInfoMapper.selectById(orderId);
+        if (orderInfo.getOrderType() == 2) {
+            log.info("积分订单无返利");
+            return;
+        }
+
         MallMember member = mallMemberMapper.selectById(orderInfo.getMemberId());
 
         if (StrUtil.isBlank(member.getReferrerId())) {
             return;
         }
-        DataDictionaryCustom dic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.DYNAMIC_BONUS.getType(), DataDictionaryEnum.DYNAMIC_BONUS.getCode());
-        DataDictionaryCustom indrectDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.INDRECT_BONUS.getType(), DataDictionaryEnum.INDRECT_BONUS.getCode());
 
-        String parent = member.getReferrerId();
+        // 直推奖励字典
+        DataDictionaryCustom dic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.DYNAMIC_BONUS.getType(), DataDictionaryEnum.DYNAMIC_BONUS.getCode());
+
+        // 直接父级
+        MallMember parent = mallMemberMapper.selectInfoByInviteId(member.getReferrerId());
+
         List<MallOrderItem> items = mallOrderInfoMapper.getMallOrderItemByOrderId(orderId);
         for (MallOrderItem item : items) {
-            BigDecimal dynamicProfit = item.getAmount().multiply(BigDecimal.valueOf(item.getCnt())).divide(new BigDecimal(dic.getValue()), 2, RoundingMode.HALF_UP);
+            // 减去成本后算收益
+            BigDecimal amount = item.getPrice().subtract(item.getCostPrice()).multiply(BigDecimal.valueOf(item.getCnt()));
+            if (amount.compareTo(BigDecimal.ZERO) < 1) {
+                continue;
+            }
 
-            List<String> parents = StrUtil.split(member.getReferrerIds(), ',');
+            Integer isReturn = null;
+            if (item.getIsNormal() == 1) {
+                isReturn = 2;
+            }
+
+            // =======直推返利== start =====
+            // 直接奖励收益
+            BigDecimal dynamicProfit = amount.multiply(new BigDecimal(dic.getValue()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
+
+            if (dynamicProfit.compareTo(BigDecimal.ZERO) < 1) {
+                continue;
+            }
+
+            int reduce = walletService.reduce(dynamicProfit, parent.getId(), "score");
+            if (reduce == 2) {
+                continue;
+            }
+
+            walletService.add(dynamicProfit, parent.getId(), "commission");
+
+            moneyFlowService.addMoneyFlow(parent.getId(), dynamicProfit, MoneyFlowTypeEnum.DYNAMIC_ACHIEVE.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.COMMISSION.getValue(), isReturn);
+            moneyFlowService.addMoneyFlow(parent.getId(), dynamicProfit.negate(), MoneyFlowTypeEnum.DYNAMIC_ACHIEVE.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.SCORE.getValue());
+            // =======直推返利== end =====
+
+            // =======隔代奖== start =====
+            if (StrUtil.isBlank(parent.getReferrerId())) {
+                continue;
+            }
+
+            List<String> parents = StrUtil.split(parent.getReferrerIds(), ',');
             List<MallMember> members = mallMemberMapper.selectByInviteIds(parents);
             if (CollUtil.isEmpty(members)) {
                 return;
             }
 
-            // 隔代比例
-            BigDecimal indrectDicProp = new BigDecimal(indrectDic.getValue());
-
-            // 隔代推荐奖
-            BigDecimal direct = dynamicProfit.divide(indrectDicProp, 2, RoundingMode.HALF_UP);
+            BigDecimal direct = dynamicProfit;
             for (MallMember parentMember : members) {
-                if (parent.equals(parentMember.getInviteId())) {
+                if (parent.getInviteId().equals(parentMember.getInviteId())) {
                     continue;
                 }
 
-                try {
-                    walletService.reduce(direct, parentMember.getId(), "score");
-                } catch (Exception e) {
-                    log.info("隔代推荐奖异常:{}, {}", direct, parentMember.getId());
-                    continue;
-                }
-                walletService.add(direct, parentMember.getId(), "commission");
+                // 直推数量
+                Integer directCnt = mallMemberMapper.selectOwnCntByInviteId(member.getReferrerId());
+                List<DataDictionaryCustom> dataDices = dataDictionaryCustomMapper.selectDicByType(DataDictionaryEnum.INDIRECT_BONUS_SETTING.getType());
 
-                moneyFlowService.addMoneyFlow(parentMember.getId(), direct, MoneyFlowTypeEnum.RECOMMEND_BONUS.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.COMMISSION.getValue());
-                moneyFlowService.addMoneyFlow(parentMember.getId(), direct.negate(), MoneyFlowTypeEnum.RECOMMEND_BONUS.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.SCORE.getValue());
+                directCnt = directCnt == null ? 0 :directCnt;
 
-                if (direct.compareTo(BigDecimal.ONE) < 1) {
-                    break;
+                // 隔代比例
+                BigDecimal indrectDicProp = BigDecimal.ZERO;
+                for (DataDictionaryCustom dataDic : dataDices) {
+                    JSONObject jsonObject = JSONObject.parseObject(dataDic.getValue());
+                    if (directCnt >= jsonObject.getInteger("pushCnt")) {
+                        indrectDicProp = jsonObject.getBigDecimal("prop");
+                    }
                 }
+
+                // 隔代推荐奖 收益
                 direct = direct.divide(indrectDicProp, 2, RoundingMode.HALF_UP);
-            }
 
-            try {
-                walletService.reduce(dynamicProfit, member.getId(), "score");
-            } catch (Exception e) {
-                log.info("直推奖励异常:{}, {}", dynamicProfit, member.getId());
-                continue;
-            }
-            walletService.add(dynamicProfit, member.getId(), "commission");
+                // direct 收益小于1,则跳出
+                if (direct.compareTo(BigDecimal.ONE) < 1) {
+                    continue;
+                }
 
-            moneyFlowService.addMoneyFlow(member.getId(), dynamicProfit, MoneyFlowTypeEnum.DYNAMIC_ACHIEVE.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.COMMISSION.getValue());
-            moneyFlowService.addMoneyFlow(member.getId(), dynamicProfit.negate(), MoneyFlowTypeEnum.DYNAMIC_ACHIEVE.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.SCORE.getValue());
+                int reduceResult =  walletService.reduce(direct, parentMember.getId(), "score");
+                if (reduceResult == 2) {
+                    continue;
+                }
+
+                walletService.add(direct, parentMember.getId(), "commission");
+                moneyFlowService.addMoneyFlow(parentMember.getId(), direct, MoneyFlowTypeEnum.RECOMMEND_BONUS.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.COMMISSION.getValue(), isReturn);
+                moneyFlowService.addMoneyFlow(parentMember.getId(), direct.negate(), MoneyFlowTypeEnum.RECOMMEND_BONUS.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.SCORE.getValue());
+            }
+            // =======隔代奖== end =====
         }
     }
 
     @Override
-    public void agentProfit() {
-        log.info("#####==代理分红==#####");
-        Date profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
-        BigDecimal totalIncome = mallOrderInfoMapper.selectTotalAmountForDate(profitDate, null);
+    @Transactional(rollbackFor = Exception.class)
+    public void agentProfit(Date profitDate) {
+        log.info("#####==代理分红==start==#####");
+        if (profitDate == null) {
+            profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
+        }
+        BigDecimal totalIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D");
 
 
         DataDictionaryCustom dic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.AGENT_BONUS.getType(), DataDictionaryEnum.AGENT_BONUS.getCode());
-        BigDecimal profit = totalIncome.divide(new BigDecimal(dic.getValue()),2, RoundingMode.HALF_UP);
+        BigDecimal profit = totalIncome.divide(new BigDecimal(dic.getValue()), 2, RoundingMode.HALF_UP);
         BigDecimal preProfit = profit.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
 
         List<MallMember> agentMembers = mallMemberMapper.selectByIdAndNoLevel(null, AgentLevelEnum.FIRST_LEVEL.name());
@@ -170,17 +221,115 @@
         for (MallMember agentMember : agentMembers) {
             DataDictionaryCustom agentDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(AppContants.AGENT_LEVEL_REQUIRE, agentMember.getLevel());
 
-            // TODO
+            if (agentDic == null) {
+                continue;
+            }
+
+            JSONObject jsonObject = JSONObject.parseObject(agentDic.getValue());
+            BigDecimal profitProp = jsonObject.getBigDecimal("profitProp");
+            BigDecimal income = preProfit.multiply(profitProp);
+
+            int reduce = walletService.reduce(income, agentMember.getId(), "score");
+            if (reduce == 2) {
+                continue;
+            }
+
+            walletService.add(income, agentMember.getId(), "commission");
+
+            moneyFlowService.addMoneyFlow(agentMember.getId(), income, MoneyFlowTypeEnum.AGENT_BONUS.getValue(), null, FlowTypeEnum.COMMISSION.getValue());
+            moneyFlowService.addMoneyFlow(agentMember.getId(), income.negate(), MoneyFlowTypeEnum.AGENT_BONUS.getValue(), null, FlowTypeEnum.SCORE.getValue());
         }
+
+        log.info("#####==代理分红==end==#####");
     }
 
     @Override
     public void rankProfit() {
         log.info("######==排名分红==####");
+        Page<MallMember> page = new Page<>(1, 5);
+        MallMember query = new MallMember();
+        query.setQuery("2");
+        Date profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
+        query.setCreatedTime(profitDate);
+        IPage<MallMember> rankListInPage = mallMemberMapper.selectRankListInPage(page, query);
 
+        List<MallMember> rankList = rankListInPage.getRecords();
+        if (CollUtil.isEmpty(rankList)) {
+            return;
+        }
+
+        BigDecimal totalIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "M");
+
+        List<DataDictionaryCustom> rankAward = dataDictionaryCustomMapper.selectDicByType("RANK_AWARD");
+        DataDictionaryCustom dic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.RANK_BONUS.getType(), DataDictionaryEnum.RANK_BONUS.getCode());
+
+
+        BigDecimal rankBonusTotal = new BigDecimal(dic.getValue()).divide(totalIncome, 2, RoundingMode.HALF_UP);
+        BigDecimal preBonus = rankBonusTotal.divide(BigDecimal.valueOf(100),2 , RoundingMode.HALF_UP);
+
+        int i = 0;
+        for (MallMember member : rankList) {
+            DataDictionaryCustom rank = rankAward.get(i);
+            i++;
+            BigDecimal bonus = preBonus.multiply(new BigDecimal(rank.getValue()));
+            int reduce = walletService.reduce(bonus, member.getId(), "score");
+            if (reduce == 2) {
+                continue;
+            }
+
+            walletService.add(bonus, member.getId(), "commission");
+
+            moneyFlowService.addMoneyFlow(member.getId(), bonus, MoneyFlowTypeEnum.RANK_BONUS.getValue(), null, FlowTypeEnum.COMMISSION.getValue());
+            moneyFlowService.addMoneyFlow(member.getId(), bonus.negate(), MoneyFlowTypeEnum.RANK_BONUS.getValue(), null, FlowTypeEnum.SCORE.getValue());
+        }
     }
 
-    public static void main(String[] args) {
-        System.out.println(DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1));
+    /**
+     * 拿推荐人收益(代理,直推,排名)的10%加权平分给下面直推
+     */
+    @Override
+    public void thankfulProfit() {
+        log.info("######==感恩奖==start==####");
+        List<MallMember> mallMembers = mallMemberMapper.selectMemberListHasChild();
+        if (CollUtil.isEmpty(mallMembers)) {
+            return;
+        }
+
+        DataDictionaryCustom dic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.THANKFUL_BONUS.getType(), DataDictionaryEnum.THANKFUL_BONUS.getCode());
+        // 感恩奖比例
+        BigDecimal prop = new BigDecimal(dic.getValue()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
+
+        Date date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
+        for (MallMember mallMember : mallMembers) {
+            BigDecimal income = mallMoneyFlowMapper.selectThankfulCommission(date, mallMember.getId());
+            List<MallMember> children = mallMemberMapper.selectMemberDirectForHasLevel(mallMember.getInviteId());
+            if (CollUtil.isEmpty(children)) {
+                continue;
+            }
+
+            BigDecimal reduceProfit = income.multiply(prop);
+            int reduce = walletService.reduce(reduceProfit.negate(), mallMember.getId(), "commission");
+            if (reduce == 2) {
+                continue;
+            }
+
+            moneyFlowService.addMoneyFlow(mallMember.getId(), reduceProfit.negate(), MoneyFlowTypeEnum.THANKFUL.getValue(), null, FlowTypeEnum.COMMISSION.getValue());
+            for (MallMember child : children) {
+                BigDecimal preProfit = income.multiply(prop).divide(BigDecimal.valueOf(children.size()), 2, RoundingMode.HALF_DOWN);
+                if (preProfit.compareTo(BigDecimal.ZERO) < 1) {
+                    continue;
+                }
+
+                int reduce1 = walletService.reduce(preProfit.negate(), child.getId(), "score");
+                if (reduce1 == 2) {
+                    continue;
+                }
+
+                walletService.add(preProfit, child.getId(), "commission");
+                moneyFlowService.addMoneyFlow(child.getId(), preProfit, MoneyFlowTypeEnum.THANKFUL.getValue(), null, mallMember.getId(), FlowTypeEnum.COMMISSION.getValue());
+                moneyFlowService.addMoneyFlow(child.getId(), preProfit.negate(), MoneyFlowTypeEnum.THANKFUL.getValue(), null, mallMember.getId(), FlowTypeEnum.SCORE.getValue());
+            }
+        }
+        log.info("######==感恩奖==end==####");
     }
 }

--
Gitblit v1.9.1