From e64ac50998ba5fe69bac4baa667d0f5a216bc670 Mon Sep 17 00:00:00 2001
From: xiaoyong931011 <15274802129@163.com>
Date: Thu, 19 May 2022 18:17:11 +0800
Subject: [PATCH] Merge branch 'mall-amz' of http://120.27.238.55:7000/r/xc-mall into mall-amz

---
 src/main/java/cc/mrbird/febs/mall/controller/ViewSystemController.java             |   20 +
 src/main/java/cc/mrbird/febs/mall/service/impl/ApiMallOrderInfoServiceImpl.java    |    2 
 src/main/resources/static/febs/lay/modules/febs.js                                 |    9 
 src/main/java/cc/mrbird/febs/mall/entity/MallOrderItem.java                        |    4 
 src/main/java/cc/mrbird/febs/mall/service/impl/ApiMallMemberWalletServiceImpl.java |    5 
 src/main/java/cc/mrbird/febs/common/enumerates/MoneyFlowTypeEnum.java              |    7 
 src/main/java/cc/mrbird/febs/mall/controller/AdminSystemController.java            |   31 ++
 src/main/java/cc/mrbird/febs/mall/service/impl/SystemServiceImpl.java              |   45 ++++
 src/main/java/cc/mrbird/febs/mall/service/IApiMallMemberWalletService.java         |    2 
 src/main/java/cc/mrbird/febs/mall/mapper/DataDictionaryCustomMapper.java           |    3 
 src/main/java/cc/mrbird/febs/common/enumerates/DataDictionaryEnum.java             |    5 
 src/main/resources/mapper/modules/DataDictionaryCustomMapper.xml                   |   14 +
 src/main/resources/mapper/modules/MallMoneyFlowMapper.xml                          |    8 
 src/main/java/cc/mrbird/febs/mall/mapper/MallMoneyFlowMapper.java                  |    2 
 src/main/java/cc/mrbird/febs/mall/mapper/MallOrderInfoMapper.java                  |    2 
 src/main/java/cc/mrbird/febs/mall/service/ISystemService.java                      |    8 
 src/main/java/cc/mrbird/febs/mall/mapper/MallMemberMapper.java                     |    5 
 src/main/java/cc/mrbird/febs/mall/service/impl/MallMoneyFlowServiceImpl.java       |    5 
 src/main/resources/mapper/modules/MallMemberMapper.xml                             |   59 +++-
 src/main/resources/mapper/modules/MallOrderInfoMapper.xml                          |   19 +
 src/main/java/cc/mrbird/febs/mall/service/IMemberProfitService.java                |    9 
 src/main/resources/templates/febs/views/modules/system/profitSetting.html          |  188 +++++++++++++++++
 src/main/java/cc/mrbird/febs/mall/service/impl/MemberProfitServiceImpl.java        |  152 +++++++++++--
 src/main/java/cc/mrbird/febs/mall/service/IMallMoneyFlowService.java               |    2 
 src/main/java/cc/mrbird/febs/mall/controller/AdminCommonController.java            |   29 ++
 25 files changed, 591 insertions(+), 44 deletions(-)

diff --git a/src/main/java/cc/mrbird/febs/common/enumerates/DataDictionaryEnum.java b/src/main/java/cc/mrbird/febs/common/enumerates/DataDictionaryEnum.java
index ce559f7..9914870 100644
--- a/src/main/java/cc/mrbird/febs/common/enumerates/DataDictionaryEnum.java
+++ b/src/main/java/cc/mrbird/febs/common/enumerates/DataDictionaryEnum.java
@@ -10,11 +10,14 @@
     STATIC_BONUS("BONUS_TYPE", "STATIC_BONUS"),
     DYNAMIC_BONUS("BONUS_TYPE", "DYNAMIC_BONUS"),
     INDRECT_BONUS("BONUS_TYPE", "INDRECT_BONUS"),
+    AGENT_BONUS("BONUS_TYPE", "AGENT_BONUS"),
+    THANKFUL_BONUS("BONUS_TYPE", "THANKFUL_BONUS"),
+
     //积分中奖概率
     WIN_SCORE("WIN_PROBABILITY", "WIN_SCORE"),
     //佣金中奖概率
     WIN_CASH("WIN_PROBABILITY", "WIN_CASH"),
-    AGENT_BONUS("BONUS_TYPE", "AGENT_BONUS");
+    RANK_BONUS("BONUS_TYPE", "RANK_BONUS");
 
     private String type;
 
diff --git a/src/main/java/cc/mrbird/febs/common/enumerates/MoneyFlowTypeEnum.java b/src/main/java/cc/mrbird/febs/common/enumerates/MoneyFlowTypeEnum.java
index 8a023ba..d5b8329 100644
--- a/src/main/java/cc/mrbird/febs/common/enumerates/MoneyFlowTypeEnum.java
+++ b/src/main/java/cc/mrbird/febs/common/enumerates/MoneyFlowTypeEnum.java
@@ -73,7 +73,12 @@
     /**
      * 竞猜积分签到
      */
-    SCORE_SIGN(14);
+    SCORE_SIGN(14),
+
+    /**
+     * 感恩奖
+     */
+    THANKFUL(15);
 
     private final int value;
 
diff --git a/src/main/java/cc/mrbird/febs/mall/controller/AdminCommonController.java b/src/main/java/cc/mrbird/febs/mall/controller/AdminCommonController.java
new file mode 100644
index 0000000..d0517a8
--- /dev/null
+++ b/src/main/java/cc/mrbird/febs/mall/controller/AdminCommonController.java
@@ -0,0 +1,29 @@
+package cc.mrbird.febs.mall.controller;
+
+import cc.mrbird.febs.common.entity.FebsResponse;
+import cc.mrbird.febs.mall.service.ICommonService;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.ibatis.annotations.Param;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@Slf4j
+@Validated
+@RestController
+@RequiredArgsConstructor
+@RequestMapping(value = "/admin/common")
+public class AdminCommonController {
+
+    @Autowired
+    private ICommonService commonService;
+
+    @GetMapping(value = "/findDicByType/{type}")
+    public FebsResponse findDicByType(@PathVariable("type") String type) {
+        return new FebsResponse().success().data(commonService.findDataDicByType(type));
+    }
+}
diff --git a/src/main/java/cc/mrbird/febs/mall/controller/AdminSystemController.java b/src/main/java/cc/mrbird/febs/mall/controller/AdminSystemController.java
new file mode 100644
index 0000000..39725ab
--- /dev/null
+++ b/src/main/java/cc/mrbird/febs/mall/controller/AdminSystemController.java
@@ -0,0 +1,31 @@
+package cc.mrbird.febs.mall.controller;
+
+import cc.mrbird.febs.common.entity.FebsResponse;
+import cc.mrbird.febs.mall.service.ISystemService;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.Map;
+
+@Slf4j
+@Validated
+@RestController
+@RequiredArgsConstructor
+@RequestMapping(value = "/admin/system")
+public class AdminSystemController {
+
+    @Autowired
+    private ISystemService systemService;
+
+    @PostMapping(value = "/bonusSystemSetting")
+    public FebsResponse bonusSystemSetting(@RequestBody Map<String, Object> map) {
+        systemService.bonusSystemSetting(map);
+        return new FebsResponse().success().message("设置成功");
+    }
+}
diff --git a/src/main/java/cc/mrbird/febs/mall/controller/ViewSystemController.java b/src/main/java/cc/mrbird/febs/mall/controller/ViewSystemController.java
new file mode 100644
index 0000000..3bc234b
--- /dev/null
+++ b/src/main/java/cc/mrbird/febs/mall/controller/ViewSystemController.java
@@ -0,0 +1,20 @@
+package cc.mrbird.febs.mall.controller;
+
+import cc.mrbird.febs.common.entity.FebsConstant;
+import cc.mrbird.febs.common.utils.FebsUtil;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+
+@Controller("mallSystemView")
+@RequestMapping(FebsConstant.VIEW_PREFIX + "modules/system")
+@RequiredArgsConstructor
+public class ViewSystemController {
+
+    @GetMapping("profitSetting")
+    public String profitSetting() {
+        return FebsUtil.view("modules/system/profitSetting");
+    }
+}
diff --git a/src/main/java/cc/mrbird/febs/mall/entity/MallOrderItem.java b/src/main/java/cc/mrbird/febs/mall/entity/MallOrderItem.java
index 28e7f3b..0a52615 100644
--- a/src/main/java/cc/mrbird/febs/mall/entity/MallOrderItem.java
+++ b/src/main/java/cc/mrbird/febs/mall/entity/MallOrderItem.java
@@ -33,4 +33,8 @@
     private BigDecimal price;
 
     private BigDecimal amount;
+
+    private BigDecimal costPrice;
+
+    private Integer isNormal;
 }
diff --git a/src/main/java/cc/mrbird/febs/mall/mapper/DataDictionaryCustomMapper.java b/src/main/java/cc/mrbird/febs/mall/mapper/DataDictionaryCustomMapper.java
index df61459..c86b42f 100644
--- a/src/main/java/cc/mrbird/febs/mall/mapper/DataDictionaryCustomMapper.java
+++ b/src/main/java/cc/mrbird/febs/mall/mapper/DataDictionaryCustomMapper.java
@@ -11,6 +11,7 @@
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import org.apache.ibatis.annotations.Param;
 
+import javax.validation.constraints.NotBlank;
 import java.util.List;
 
 public interface DataDictionaryCustomMapper extends BaseMapper<DataDictionaryCustom> {
@@ -28,4 +29,6 @@
     List<AdminAgentLevelOptionTreeVo> getAgentLevelOption();
 
     AdminRankAwardUpdateInfoVo getRankAwardUpdateInfoById(@Param("id")long id);
+
+    int updateDicValueByTypeAndCode(@Param("type") String type, @Param("code") String code, @Param("value") String value);
 }
diff --git a/src/main/java/cc/mrbird/febs/mall/mapper/MallMemberMapper.java b/src/main/java/cc/mrbird/febs/mall/mapper/MallMemberMapper.java
index 598055a..c155f00 100644
--- a/src/main/java/cc/mrbird/febs/mall/mapper/MallMemberMapper.java
+++ b/src/main/java/cc/mrbird/febs/mall/mapper/MallMemberMapper.java
@@ -74,4 +74,9 @@
     IPage<MallMember> selectRankListInPage(IPage<MallMember> page, @Param("record") MallMember mallMember);
 
     List<MallMember> selectMemberByName(@Param("name") String name);
+
+    // 查询有下级的用户
+    List<MallMember> selectMemberListHasChild();
+
+    List<MallMember> selectMemberDirectForHasLevel(@Param("inviteId") String inviteId);
 }
diff --git a/src/main/java/cc/mrbird/febs/mall/mapper/MallMoneyFlowMapper.java b/src/main/java/cc/mrbird/febs/mall/mapper/MallMoneyFlowMapper.java
index b3d6d21..eaa05c6 100644
--- a/src/main/java/cc/mrbird/febs/mall/mapper/MallMoneyFlowMapper.java
+++ b/src/main/java/cc/mrbird/febs/mall/mapper/MallMoneyFlowMapper.java
@@ -35,4 +35,6 @@
     BigDecimal selectProfitByDateAndMemberId(Long memberId);
 
     BigDecimal selectCommissionIncome(@Param("type") Integer type, @Param("date") Date date, @Param("memberId") Long memebrid);
+
+    BigDecimal selectThankfulCommission(@Param("date") Date date, @Param("memberId") Long memberId);
 }
diff --git a/src/main/java/cc/mrbird/febs/mall/mapper/MallOrderInfoMapper.java b/src/main/java/cc/mrbird/febs/mall/mapper/MallOrderInfoMapper.java
index 86b842e..3db8173 100644
--- a/src/main/java/cc/mrbird/febs/mall/mapper/MallOrderInfoMapper.java
+++ b/src/main/java/cc/mrbird/febs/mall/mapper/MallOrderInfoMapper.java
@@ -51,5 +51,7 @@
 
     BigDecimal selectTotalAmountForDate(@Param("date") Date date, @Param("member") Long memberId);
 
+    BigDecimal selectTotalAmountUnCostForDate(@Param("date") Date date, @Param("member") Long memberId, @Param("type") String type);
+
     MallOrderInfo selectByOrderNo(@Param("orderNo") String orderNo);
 }
diff --git a/src/main/java/cc/mrbird/febs/mall/service/IApiMallMemberWalletService.java b/src/main/java/cc/mrbird/febs/mall/service/IApiMallMemberWalletService.java
index 5be6491..7a74cb0 100644
--- a/src/main/java/cc/mrbird/febs/mall/service/IApiMallMemberWalletService.java
+++ b/src/main/java/cc/mrbird/febs/mall/service/IApiMallMemberWalletService.java
@@ -20,7 +20,7 @@
 
     void add(BigDecimal amount, Long memberId, String... field);
 
-    void reduce(BigDecimal amount, Long memberId, String field);
+    int reduce(BigDecimal amount, Long memberId, String field);
 
     void commissionChange(CommissionChangeDto commissionChange);
 }
diff --git a/src/main/java/cc/mrbird/febs/mall/service/IMallMoneyFlowService.java b/src/main/java/cc/mrbird/febs/mall/service/IMallMoneyFlowService.java
index 9e890d6..fba7e4a 100644
--- a/src/main/java/cc/mrbird/febs/mall/service/IMallMoneyFlowService.java
+++ b/src/main/java/cc/mrbird/febs/mall/service/IMallMoneyFlowService.java
@@ -11,4 +11,6 @@
 
     void addMoneyFlow(Long memberId, BigDecimal amount, Integer type, String orderNo, Integer flowType);
 
+    void addMoneyFlow(Long memberId, BigDecimal amount, Integer type, String orderNo, Long rtMemberId, Integer flowType);
+
 }
diff --git a/src/main/java/cc/mrbird/febs/mall/service/IMemberProfitService.java b/src/main/java/cc/mrbird/febs/mall/service/IMemberProfitService.java
index 6122c26..c4dccd5 100644
--- a/src/main/java/cc/mrbird/febs/mall/service/IMemberProfitService.java
+++ b/src/main/java/cc/mrbird/febs/mall/service/IMemberProfitService.java
@@ -1,5 +1,7 @@
 package cc.mrbird.febs.mall.service;
 
+import java.util.Date;
+
 /**
  * @author wzy
  * @date 2022-05-10
@@ -19,10 +21,15 @@
     /**
      * 代理分红
      */
-    void agentProfit();
+    void agentProfit(Date date);
 
     /**
      * 排名分红
      */
     void rankProfit();
+
+    /**
+     * 感恩奖
+     */
+    void thankfulProfit();
 }
diff --git a/src/main/java/cc/mrbird/febs/mall/service/ISystemService.java b/src/main/java/cc/mrbird/febs/mall/service/ISystemService.java
new file mode 100644
index 0000000..60f0ed7
--- /dev/null
+++ b/src/main/java/cc/mrbird/febs/mall/service/ISystemService.java
@@ -0,0 +1,8 @@
+package cc.mrbird.febs.mall.service;
+
+import java.util.Map;
+
+public interface ISystemService {
+
+    void bonusSystemSetting(Map<String, Object> map);
+}
diff --git a/src/main/java/cc/mrbird/febs/mall/service/impl/ApiMallMemberWalletServiceImpl.java b/src/main/java/cc/mrbird/febs/mall/service/impl/ApiMallMemberWalletServiceImpl.java
index 96f94e6..1221e3b 100644
--- a/src/main/java/cc/mrbird/febs/mall/service/impl/ApiMallMemberWalletServiceImpl.java
+++ b/src/main/java/cc/mrbird/febs/mall/service/impl/ApiMallMemberWalletServiceImpl.java
@@ -177,7 +177,7 @@
     }
 
     @Override
-    public void reduce(BigDecimal amount, Long memberId, String field) {
+    public int reduce(BigDecimal amount, Long memberId, String field) {
         int i = 0;
         boolean flag = true;
 
@@ -195,7 +195,7 @@
                 BigDecimal balance = (BigDecimal) declaredField.get(wallet);
 
                 if (amount.compareTo(balance) > 0) {
-                    throw new FebsException("余额不足");
+                    return 2;
                 }
                 declaredField.set(update, balance.subtract(amount));
 
@@ -212,6 +212,7 @@
                 }
             }
         }
+        return 1;
     }
 
     @Override
diff --git a/src/main/java/cc/mrbird/febs/mall/service/impl/ApiMallOrderInfoServiceImpl.java b/src/main/java/cc/mrbird/febs/mall/service/impl/ApiMallOrderInfoServiceImpl.java
index cca6fa4..f1b519b 100644
--- a/src/main/java/cc/mrbird/febs/mall/service/impl/ApiMallOrderInfoServiceImpl.java
+++ b/src/main/java/cc/mrbird/febs/mall/service/impl/ApiMallOrderInfoServiceImpl.java
@@ -142,6 +142,8 @@
                 orderItem.setStyleName(sku.getStyleName());
                 orderItem.setSkuName(sku.getSkuName());
                 orderItem.setSkuImage(sku.getSkuImage());
+                orderItem.setIsNormal(mallGoods.getIsNormal());
+                orderItem.setCostPrice(sku.getCostPrice());
 
                 total = total.add(amount);
 
diff --git a/src/main/java/cc/mrbird/febs/mall/service/impl/MallMoneyFlowServiceImpl.java b/src/main/java/cc/mrbird/febs/mall/service/impl/MallMoneyFlowServiceImpl.java
index c25680c..290b8c9 100644
--- a/src/main/java/cc/mrbird/febs/mall/service/impl/MallMoneyFlowServiceImpl.java
+++ b/src/main/java/cc/mrbird/febs/mall/service/impl/MallMoneyFlowServiceImpl.java
@@ -38,4 +38,9 @@
     public void addMoneyFlow(Long memberId, BigDecimal amount, Integer type, String orderNo, Integer flowType) {
         this.addMoneyFlow(memberId, amount, type, orderNo, null, null, null, null, flowType);
     }
+
+    @Override
+    public void addMoneyFlow(Long memberId, BigDecimal amount, Integer type, String orderNo, Long rtMemberId, Integer flowType) {
+        this.addMoneyFlow(memberId, amount, type, orderNo, null, null, rtMemberId, null, flowType);
+    }
 }
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..3780ec4 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,12 +89,18 @@
     /**
      * 直推20%,隔代收益为直推奖励金额的30%,a_b_c_d,d购买1000套餐,c得200,b得200*30%=60元,a得60*30%=18元。。。
      * 以此类推,结算到一元为止。
+     *
      * @param orderId
      */
     @Override
     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())) {
@@ -103,7 +112,10 @@
         String parent = 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()));
+
+            BigDecimal dynamicProfit = amount.divide(new BigDecimal(dic.getValue()), 2, RoundingMode.HALF_UP);
 
             List<String> parents = StrUtil.split(member.getReferrerIds(), ',');
             List<MallMember> members = mallMemberMapper.selectByInviteIds(parents);
@@ -121,12 +133,11 @@
                     continue;
                 }
 
-                try {
-                    walletService.reduce(direct, parentMember.getId(), "score");
-                } catch (Exception e) {
-                    log.info("隔代推荐奖异常:{}, {}", direct, parentMember.getId());
+                int reduce =  walletService.reduce(direct, parentMember.getId(), "score");
+                if (reduce == 2) {
                     continue;
                 }
+
                 walletService.add(direct, parentMember.getId(), "commission");
 
                 moneyFlowService.addMoneyFlow(parentMember.getId(), direct, MoneyFlowTypeEnum.RECOMMEND_BONUS.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.COMMISSION.getValue());
@@ -138,12 +149,11 @@
                 direct = direct.divide(indrectDicProp, 2, RoundingMode.HALF_UP);
             }
 
-            try {
-                walletService.reduce(dynamicProfit, member.getId(), "score");
-            } catch (Exception e) {
-                log.info("直推奖励异常:{}, {}", dynamicProfit, member.getId());
+            int reduce = walletService.reduce(dynamicProfit, member.getId(), "score");
+            if (reduce == 2) {
                 continue;
             }
+
             walletService.add(dynamicProfit, member.getId(), "commission");
 
             moneyFlowService.addMoneyFlow(member.getId(), dynamicProfit, MoneyFlowTypeEnum.DYNAMIC_ACHIEVE.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.COMMISSION.getValue());
@@ -152,14 +162,16 @@
     }
 
     @Override
-    public void agentProfit() {
-        log.info("#####==代理分红==#####");
-        Date profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
-        BigDecimal totalIncome = mallOrderInfoMapper.selectTotalAmountForDate(profitDate, null);
+    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 +182,113 @@
         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 preProfit = income.multiply(prop).divide(BigDecimal.valueOf(children.size()), 2, RoundingMode.HALF_DOWN);
+
+
+            int reduce = walletService.reduce(preProfit.negate(), mallMember.getId(), "commission");
+            if (reduce == 2) {
+                continue;
+            }
+
+            moneyFlowService.addMoneyFlow(mallMember.getId(), income.negate(), MoneyFlowTypeEnum.THANKFUL.getValue(), null, FlowTypeEnum.COMMISSION.getValue());
+
+            for (MallMember child : children) {
+                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==####");
     }
 }
diff --git a/src/main/java/cc/mrbird/febs/mall/service/impl/SystemServiceImpl.java b/src/main/java/cc/mrbird/febs/mall/service/impl/SystemServiceImpl.java
new file mode 100644
index 0000000..111ef5b
--- /dev/null
+++ b/src/main/java/cc/mrbird/febs/mall/service/impl/SystemServiceImpl.java
@@ -0,0 +1,45 @@
+package cc.mrbird.febs.mall.service.impl;
+
+import cc.mrbird.febs.mall.entity.DataDictionaryCustom;
+import cc.mrbird.febs.mall.mapper.DataDictionaryCustomMapper;
+import cc.mrbird.febs.mall.service.ICommonService;
+import cc.mrbird.febs.mall.service.ISystemService;
+import com.alibaba.fastjson.JSONObject;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author wzy
+ * @date 2022-05-19
+ **/
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class SystemServiceImpl implements ISystemService {
+
+    private final DataDictionaryCustomMapper dictionaryCustomMapper;
+    private final ICommonService commonService;
+
+    @Override
+    public void bonusSystemSetting(Map<String, Object> map) {
+        for (Map.Entry<String, Object> entry : map.entrySet()) {
+            if (entry.getValue() instanceof String) {
+                dictionaryCustomMapper.updateDicValueByTypeAndCode(null, entry.getKey(), (String) entry.getValue());
+            } else {
+                List<LinkedHashMap<String, Object>> value = (List<LinkedHashMap<String, Object>>) entry.getValue();
+
+                for (LinkedHashMap<String, Object> dic : value) {
+                    String type = (String) dic.get("type");
+                    String code = (String) dic.get("code");
+                    String dataValue = (String) dic.get("value");
+                    dictionaryCustomMapper.updateDicValueByTypeAndCode(type, code, dataValue);
+                }
+            }
+        }
+    }
+}
diff --git a/src/main/resources/mapper/modules/DataDictionaryCustomMapper.xml b/src/main/resources/mapper/modules/DataDictionaryCustomMapper.xml
index 59f6bfe..ac88217 100644
--- a/src/main/resources/mapper/modules/DataDictionaryCustomMapper.xml
+++ b/src/main/resources/mapper/modules/DataDictionaryCustomMapper.xml
@@ -39,4 +39,18 @@
         select a.* from data_dictionary_custom a
         where a.id =  #{id}
     </select>
+
+    <update id="updateDicValueByTypeAndCode">
+        update data_dictionary_custom
+        set value=#{value}
+        <where>
+            1=1
+            <if test="code != null and code != ''">
+                and code = #{code}
+            </if>
+            <if test="type != null and type != ''">
+                and type = #{type}
+            </if>
+        </where>
+    </update>
 </mapper>
\ No newline at end of file
diff --git a/src/main/resources/mapper/modules/MallMemberMapper.xml b/src/main/resources/mapper/modules/MallMemberMapper.xml
index 88e6019..bc28913 100644
--- a/src/main/resources/mapper/modules/MallMemberMapper.xml
+++ b/src/main/resources/mapper/modules/MallMemberMapper.xml
@@ -306,27 +306,54 @@
             DATE_FORMAT(a.CREATED_TIME, '%Y-%m-%d') DESC
     </select>
 
-    <select id="selectRankListInPage" resultType="cc.mrbird.febs.mall.entity.MallMember">
-        select * from (
-          select a.id, a.name, a.invite_id, a.avatar, sum(b.amount) amount,max(order_time) orderTime from mall_member a, mall_order_info b
-          where  a.id=b.member_id and b.status = 4
-        <!-- 日 -->
-        <if test="record.query == '1'">
+<!--    <select id="selectRankListInPage" resultType="cc.mrbird.febs.mall.entity.MallMember">-->
+<!--        select * from (-->
+<!--          select a.id, a.name, a.invite_id, a.avatar, sum(b.amount) amount,max(order_time) orderTime from mall_member a, mall_order_info b-->
+<!--          where  a.id=b.member_id and b.status = 4-->
+<!--        &lt;!&ndash; 日 &ndash;&gt;-->
+<!--        <if test="record.query == '1'">-->
 
-        </if>
-        <!-- 月 -->
-        <if test="record.query == '2'">
-            and date_format(#{record.createdTime},'%Y-%m') = date_format(b.order_time,'%Y-%m')
-        </if>
-        <if test="record.amount != null">
-            and amount = #{record.amount}
-        </if>
-          group by a.id
-      ) a order by amount desc, a.orderTime desc
+<!--        </if>-->
+<!--        &lt;!&ndash; 月 &ndash;&gt;-->
+<!--        <if test="record.query == '2'">-->
+<!--            and date_format(#{record.createdTime},'%Y-%m') = date_format(b.order_time,'%Y-%m')-->
+<!--        </if>-->
+<!--        <if test="record.amount != null">-->
+<!--            and amount = #{record.amount}-->
+<!--        </if>-->
+<!--          group by a.id-->
+<!--      ) a order by amount desc, a.orderTime desc-->
+<!--    </select>-->
+    <select id="selectRankListInPage" resultType="cc.mrbird.febs.mall.entity.MallMember">
+        select a.*, b.*
+        from mall_member a
+            inner join (
+                select b.referrer_id refererId, sum(a.amount) amount, max(a.order_time) orderTime
+                    from mall_order_info a
+                    inner join mall_member b on a.member_id=b.ID
+                    inner join mall_order_item c on a.id = c.order_id and c.is_normal=2
+                where a.status in (2, 3, 4) and a.order_type=1
+                <!-- 月 -->
+                <if test="record.query == '2'">
+                    and date_format(#{record.createdTime},'%Y-%m') = date_format(b.order_time,'%Y-%m')
+                </if>
+                group by b.referrer_id
+            ) b  on a.invite_id=b.refererId
+        order by b.amount desc, b.orderTime desc
     </select>
 
     <select id="selectMemberByName" resultType="cc.mrbird.febs.mall.entity.MallMember">
         select * from mall_member
         where name=#{name}
     </select>
+
+    <select id="selectMemberListHasChild" resultType="cc.mrbird.febs.mall.entity.MallMember">
+        select distinct a.* from mall_member a, mall_member b
+        where a.invite_id=b.referrer_id
+    </select>
+
+    <select id="selectMemberDirectForHasLevel" resultType="cc.mrbird.febs.mall.entity.MallMember">
+        select * from mall_member
+        where referrer_id=#{inviteId} and level != 'ZERO_LEVEL'
+    </select>
 </mapper>
\ No newline at end of file
diff --git a/src/main/resources/mapper/modules/MallMoneyFlowMapper.xml b/src/main/resources/mapper/modules/MallMoneyFlowMapper.xml
index 183418b..ebef8b7 100644
--- a/src/main/resources/mapper/modules/MallMoneyFlowMapper.xml
+++ b/src/main/resources/mapper/modules/MallMoneyFlowMapper.xml
@@ -118,4 +118,12 @@
             and date_format(created_time, '%Y-%m') = date_format(#{date}, '%Y-%m')
         </if>
     </select>
+
+    <select id="selectThankfulCommission" resultType="java.math.BigDecimal">
+        select ifnull(sum(amount),0) from mall_money_flow
+        where flow_type=4 and amount > 0
+          and member_id=#{memberId}
+          and date_format(created_time, '%Y-%m-%d') = date_format(#{date}, '%Y-%m-%d')
+          and type in (2,3,4)
+    </select>
 </mapper>
\ No newline at end of file
diff --git a/src/main/resources/mapper/modules/MallOrderInfoMapper.xml b/src/main/resources/mapper/modules/MallOrderInfoMapper.xml
index aa3e5b0..6707604 100644
--- a/src/main/resources/mapper/modules/MallOrderInfoMapper.xml
+++ b/src/main/resources/mapper/modules/MallOrderInfoMapper.xml
@@ -233,6 +233,25 @@
         </if>
     </select>
 
+    <select id="selectTotalAmountUnCostForDate" resultType="java.math.BigDecimal">
+        select IFNULL(sum(IFNULL(b.amount,0) - IFNULL(b.cost_price*b.cnt, 0)),0)
+        from mall_order_info a
+        inner join mall_order_item b on a.id=b.order_id
+        where a.status in (2, 3, 4) and a.is_normal = 2 and a.order_type=1
+        <if test="member != null">
+            and member_id=#{memberId}
+        </if>
+        <if test="date != null and type == 'D'">
+            and date_format(a.receving_time, '%Y-%m-%d') = date_format(#{date}, '%Y-%m-%d')
+        </if>
+        <if test="date != null and type == 'M'">
+            and date_format(a.receving_time, '%Y-%m') = date_format(#{date}, '%Y-%m')
+        </if>
+        <if test="date != null and type == 'Y'">
+            and date_format(a.receving_time, '%Y') = date_format(#{date}, '%Y')
+        </if>
+    </select>
+
     <select id="selectByOrderNo" resultType="cc.mrbird.febs.mall.entity.MallOrderInfo">
         select * from mall_order_info where order_no=#{orderNo}
     </select>
diff --git a/src/main/resources/static/febs/lay/modules/febs.js b/src/main/resources/static/febs/lay/modules/febs.js
index bbac870..9476243 100644
--- a/src/main/resources/static/febs/lay/modules/febs.js
+++ b/src/main/resources/static/febs/lay/modules/febs.js
@@ -567,6 +567,15 @@
         })
     };
 
+    self.postForJson = function (url, params, success) {
+        if (params) {
+            params.invalidate_ie_cache = new Date();
+        }
+        $.post(url, params, function (r) {
+            resolveResponse(r, success);
+        }, "json")
+    };
+
     // 文件下载
     self.download = function (url, params, fileName) {
         self.view.loadBar.start();
diff --git a/src/main/resources/templates/febs/views/modules/system/profitSetting.html b/src/main/resources/templates/febs/views/modules/system/profitSetting.html
new file mode 100644
index 0000000..bb91556
--- /dev/null
+++ b/src/main/resources/templates/febs/views/modules/system/profitSetting.html
@@ -0,0 +1,188 @@
+<div class="layui-fluid layui-anim febs-anim" id="profit-setting" lay-title="收益设置">
+    <div class="layui-row layui-col-space8 febs-container">
+        <form class="layui-form" action="" lay-filter="profit-setting-form">
+            <div class="layui-card">
+                <div class="layui-card-body">
+                    <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
+                        <ul class="layui-tab-title">
+                            <li class="layui-this">分红设置</li>
+                            <li>代理分红</li>
+                            <li>排名分红</li>
+                        </ul>
+                        <div class="layui-tab-content">
+                            <div class="layui-tab-item layui-show" id="bonus-global-setting">
+                            </div>
+                            <div class="layui-tab-item">
+                                <table id="agentBonus" lay-filter="agentBonus"></table>
+                            </div>
+                            <div class="layui-tab-item">
+                                <table id="rankBonus" lay-filter="rankBonus"></table>
+                            </div>
+                        </div>
+                    </div>
+                </div>
+
+                <div class="layui-card-footer">
+                    <button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="profit-setting-form-submit" id="submit">保存</button>
+                </div>
+            </div>
+        </form>
+
+<!--        <div class="layui-form-item febs-hide">-->
+<!--            <button class="layui-btn" lay-submit="" lay-filter="profit-setting-form-submit" id="submit-form"></button>-->
+<!--            <button type="reset" class="layui-btn" id="reset"></button>-->
+<!--        </div>-->
+    </div>
+</div>
+<style>
+    .layui-form-label {
+        width: 120px;
+    }
+
+    .layui-form-item .layui-input-block {
+        margin-left: 150px;
+    }
+
+    .layui-table-form .layui-form-item {
+        margin-bottom: 20px !important;
+    }
+</style>
+<script type="text/html" id="toolbar">
+    <div class="layui-btn-container">
+        <button class="layui-btn layui-btn-danger layui-btn-sm" type="button" lay-event="delSku">删除</button>
+    </div>
+</script>
+<script type="text/html" id="bonusSystem">
+    {{#  layui.each(d, function(index, item){ }}
+    <div class="layui-form-item">
+        <label class="layui-form-label ">{{item.description}}:</label>
+        <div class="layui-input-block">
+            <input type="text" name="{{item.code}}" lay-verify="number" value="{{item.value}}" autocomplete="off" class="layui-input">
+        </div>
+    </div>
+    {{# }) }}
+</script>
+<script data-th-inline="javascript" type="text/javascript">
+    layui.use(['dropdown', 'jquery', 'validate', 'febs', 'form', 'eleTree', 'laytpl', 'table'], function () {
+        var $ = layui.jquery,
+            febs = layui.febs,
+            form = layui.form,
+            table = layui.table,
+            validate = layui.validate,
+            $view = $('#profit-setting')
+            , templateHtml = bonusSystem.innerHTML
+            , $bonusSystem = $("#bonus-global-setting")
+            , laytpl = layui.laytpl
+            , agentBonusArr
+            , rankBonusArr;
+
+        form.verify(validate);
+        form.render();
+
+        table.render({
+            elem: '#agentBonus'
+            ,cols: [[ //表头
+                {field: 'description', title: '代理', edit:'text'}
+                ,{field: 'prop', title: '返利比例(%)', edit:'text'}
+                ,{field: 'achieve', title: '团队业绩(万元)', edit:'text'}
+                ,{field: 'type', title: '比例', edit:'text', hide:'true'}
+                ,{field: 'code', title: '比例', edit:'text', hide:'true'}
+            ]]
+            ,data: []
+        });
+        table.on('edit(agentBonus)', function(obj){
+            var value = obj.value //得到修改后的值
+                ,data = obj.data //得到所在行所有键值
+                ,field = obj.field; //得到字段
+
+            for (let i = 0; i < agentBonusArr.length; i++) {
+                if (agentBonusArr[i].code === data.code) {
+                    var valueData = {};
+                    valueData.teamIncome = data.achieve;
+                    valueData.profitProp = data.prop
+                    agentBonusArr[i].value = JSON.stringify(valueData);
+                }
+            }
+        });
+
+        table.render({
+            elem: '#rankBonus'
+            ,cols: [[ //表头
+                {field: 'description', title: '排名'}
+                ,{field: 'value', title: '返利比例(%)', edit:'text'}
+                ,{field: 'type', title: '比例', edit:'text', hide:'true'}
+                ,{field: 'code', title: '比例', edit:'text', hide:'true'}
+            ]]
+            ,data: []
+        });
+
+        table.on('edit(rankBonus)', function(obj){
+            var value = obj.value //得到修改后的值
+                ,data = obj.data //得到所在行所有键值
+                ,field = obj.field; //得到字段
+
+            for (let i = 0; i < rankBonusArr.length; i++) {
+                if (rankBonusArr[i].code === data.code) {
+                    rankBonusArr[i].value = value;
+                }
+            }
+        });
+
+        dicDataReq("BONUS_TYPE");
+        dicDataReq("AGENT_LEVEL_REQUIRE");
+        dicDataReq("RANK_AWARD");
+        function dicDataReq(type) {
+            $bonusSystem.empty();
+            $.get(ctx + 'admin/common/findDicByType/' + type, function (r) {
+                if (r.code === 200) {
+                    var data = r.data;
+                    if ("BONUS_TYPE" == type) {
+                        laytpl(templateHtml).render(data, function(html) {
+                            $bonusSystem.append(html);
+                        })
+                    }
+
+                    if ("AGENT_LEVEL_REQUIRE" == type) {
+                        for (let i = 0; i < data.length; i++) {
+                            data[i].prop = JSON.parse(data[i].value).profitProp;
+                            data[i].achieve = JSON.parse(data[i].value).teamIncome;
+                        }
+                        agentBonusArr = data;
+                        table.reload('agentBonus', {
+                            data : data
+                        });
+                    }
+
+                    if ("RANK_AWARD" == type) {
+                        rankBonusArr = data;
+                        table.reload('rankBonus', {
+                            data : data
+                        });
+                    }
+                }
+            });
+        }
+
+        form.on('submit(profit-setting-form-submit)', function (data) {
+            data.field.agentBonus = agentBonusArr;
+            data.field.rankBonus = rankBonusArr;
+            $.ajax({
+                'url':ctx + 'admin/system/bonusSystemSetting',
+                'type':'post',
+                'dataType':'json',
+                'headers' : {'Content-Type' : 'application/json;charset=utf-8'},
+                'traditional': true,
+                'data':JSON.stringify(data.field),
+                'success':function (data) {
+                    if (data.code == 200) {
+                        febs.alert.success(data.message);
+                    }
+                },
+                'error':function () {
+                    febs.alert.warn('服务器繁忙');
+                }
+            })
+            return false;
+        });
+    });
+</script>
\ No newline at end of file

--
Gitblit v1.9.1