!611 分销用户管理、Review代码修改

Merge pull request !611 from 疯狂的世界/brokerate
This commit is contained in:
芋道源码 2023-09-09 00:48:00 +00:00 committed by Gitee
commit 3b5215db21
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
62 changed files with 1488 additions and 1041 deletions

View File

@ -3,8 +3,8 @@ create table trade_config
( (
id bigint auto_increment comment '自增主键' primary key, id bigint auto_increment comment '自增主键' primary key,
brokerage_enabled bit default 1 not null comment '是否启用分佣', brokerage_enabled bit default 1 not null comment '是否启用分佣',
brokerage_enabled_condition tinyint default 0 not null comment '分佣模式0-人人分销 1-指定分销', brokerage_enabled_condition tinyint default 0 not null comment '分佣模式1-人人分销 2-指定分销',
brokerage_bind_mode tinyint default 0 not null comment '分销关系绑定模式: 0-没有推广人1-新用户', brokerage_bind_mode tinyint default 0 not null comment '分销关系绑定模式: 1-没有推广人2-新用户, 3-扫码覆盖',
brokerage_post_urls varchar(2000) default '' null comment '分销海报图地址数组', brokerage_post_urls varchar(2000) default '' null comment '分销海报图地址数组',
brokerage_first_percent int default 0 not null comment '一级返佣比例', brokerage_first_percent int default 0 not null comment '一级返佣比例',
brokerage_second_percent int default 0 not null comment '二级返佣比例', brokerage_second_percent int default 0 not null comment '二级返佣比例',
@ -24,12 +24,12 @@ create table trade_config
create table trade_brokerage_user create table trade_brokerage_user
( (
id bigint auto_increment comment '用户编号' primary key, id bigint auto_increment comment '用户编号' primary key,
brokerage_user_id bigint not null comment '推广员编号', bind_user_id bigint null comment '推广员编号',
brokerage_bind_time datetime null comment '推广员绑定时间', bind_user_time datetime null comment '推广员绑定时间',
brokerage_enabled bit default 1 not null comment '是否成为推广员', brokerage_enabled bit default 1 not null comment '是否成为推广员',
brokerage_time datetime null comment '成为分销员时间', brokerage_time datetime null comment '成为分销员时间',
brokerage_price int default 0 not null comment '可用佣金', price int default 0 not null comment '可用佣金',
frozen_brokerage_price int default 0 not null comment '冻结佣金', frozen_price int default 0 not null comment '冻结佣金',
creator varchar(64) collate utf8mb4_unicode_ci default '' null comment '创建者', creator varchar(64) collate utf8mb4_unicode_ci default '' null comment '创建者',
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
updater varchar(64) collate utf8mb4_unicode_ci default '' null comment '更新者', updater varchar(64) collate utf8mb4_unicode_ci default '' null comment '更新者',
@ -38,7 +38,7 @@ create table trade_brokerage_user
tenant_id bigint default 0 not null comment '租户编号' tenant_id bigint default 0 not null comment '租户编号'
) comment '分销用户'; ) comment '分销用户';
create index idx_invite_user_id on trade_brokerage_user (brokerage_user_id) comment '推广员编号'; create index idx_invite_user_id on trade_brokerage_user (bind_user_id) comment '推广员编号';
create index idx_agent on trade_brokerage_user (brokerage_enabled) comment '是否成为推广员'; create index idx_agent on trade_brokerage_user (brokerage_enabled) comment '是否成为推广员';
@ -104,14 +104,15 @@ create index idx_audit_status on trade_brokerage_withdraw (status) comment '状
insert into system_dict_type(type, name) insert into system_dict_type(type, name)
values ('brokerage_enabled_condition', '分佣模式'); values ('brokerage_enabled_condition', '分佣模式');
insert into system_dict_data(dict_type, label, value, sort, remark) insert into system_dict_data(dict_type, label, value, sort, remark)
values ('brokerage_enabled_condition', '人人分销', 0, 0, '所有用户都可以分销'), values ('brokerage_enabled_condition', '人人分销', 1, 1, '所有用户都可以分销'),
('brokerage_enabled_condition', '指定分销', 1, 1, '仅可后台手动设置推广员'); ('brokerage_enabled_condition', '指定分销', 2, 2, '仅可后台手动设置推广员');
insert into system_dict_type(type, name) insert into system_dict_type(type, name)
values ('brokerage_bind_mode', '分销关系绑定模式'); values ('brokerage_bind_mode', '分销关系绑定模式');
insert into system_dict_data(dict_type, label, value, sort, remark) insert into system_dict_data(dict_type, label, value, sort, remark)
values ('brokerage_bind_mode', '没有推广人', 0, 0, '只要用户没有推广人随时都可以绑定推广关系'), values ('brokerage_bind_mode', '没有推广人', 1, 1, '只要用户没有推广人随时都可以绑定推广关系'),
('brokerage_bind_mode', '新用户', 1, 1, '仅新用户注册时才能绑定推广关系'); ('brokerage_bind_mode', '新用户', 2, 2, '仅新用户注册时才能绑定推广关系'),
('brokerage_bind_mode', '扫码覆盖', 3, 3, '如果用户已经有推广人推广人会被变更');
insert into system_dict_type(type, name) insert into system_dict_type(type, name)
values ('brokerage_withdraw_type', '佣金提现类型'); values ('brokerage_withdraw_type', '佣金提现类型');
@ -124,8 +125,8 @@ values ('brokerage_withdraw_type', '钱包', 1, 1),
insert into system_dict_type(type, name) insert into system_dict_type(type, name)
values ('brokerage_record_biz_type', '佣金记录业务类型'); values ('brokerage_record_biz_type', '佣金记录业务类型');
insert into system_dict_data(dict_type, label, value, sort) insert into system_dict_data(dict_type, label, value, sort)
values ('brokerage_record_biz_type', '订单返佣', 0, 0), values ('brokerage_record_biz_type', '订单返佣', 1, 1),
('brokerage_record_biz_type', '申请提现', 1, 1); ('brokerage_record_biz_type', '申请提现', 2, 2);
insert into system_dict_type(type, name) insert into system_dict_type(type, name)
values ('brokerage_record_status', '佣金记录状态'); values ('brokerage_record_status', '佣金记录状态');
@ -185,12 +186,15 @@ SELECT @parentId := LAST_INSERT_ID();
INSERT INTO system_menu(name, permission, type, sort, parent_id, path, icon, component, status) INSERT INTO system_menu(name, permission, type, sort, parent_id, path, icon, component, status)
VALUES ('分销用户查询', 'trade:brokerage-user:query', 3, 1, @parentId, '', '', '', 0); VALUES ('分销用户查询', 'trade:brokerage-user:query', 3, 1, @parentId, '', '', '', 0);
INSERT INTO system_menu(name, permission, type, sort, parent_id, path, icon, component, status) INSERT INTO system_menu(name, permission, type, sort, parent_id, path, icon, component, status)
VALUES ('分销用户修改推广员', 'trade:brokerage-user:update-brokerage-user', 3, 2, @parentId, '', '', '', 0); VALUES ('分销用户推广人查询', 'trade:brokerage-user:user-query', 3, 2, @parentId, '', '', '', 0);
INSERT INTO system_menu(name, permission, type, sort, parent_id, path, icon, component, status) INSERT INTO system_menu(name, permission, type, sort, parent_id, path, icon, component, status)
VALUES ('分销用户清除推广员', 'trade:brokerage-user:clear-brokerage-user', 3, 3, @parentId, '', '', '', 0); VALUES ('分销用户推广订单查询', 'trade:brokerage-user:order-query', 3, 3, @parentId, '', '', '', 0);
INSERT INTO system_menu(name, permission, type, sort, parent_id, path, icon, component, status) INSERT INTO system_menu(name, permission, type, sort, parent_id, path, icon, component, status)
VALUES ('分销用户修改推广资格', 'trade:brokerage-user:update-brokerage-enable', 3, 4, @parentId, '', '', '', 0); VALUES ('分销用户修改推广资格', 'trade:brokerage-user:update-brokerage-enable', 3, 4, @parentId, '', '', '', 0);
INSERT INTO system_menu(name, permission, type, sort, parent_id, path, icon, component, status)
VALUES ('分销用户修改推广员', 'trade:brokerage-user:update-brokerage-user', 3, 5, @parentId, '', '', '', 0);
INSERT INTO system_menu(name, permission, type, sort, parent_id, path, icon, component, status)
VALUES ('分销用户清除推广员', 'trade:brokerage-user:clear-brokerage-user', 3, 6, @parentId, '', '', '', 0);
-- 增加菜单佣金记录 -- 增加菜单佣金记录
INSERT INTO system_menu(name, permission, type, sort, parent_id, path, icon, component, status, component_name) INSERT INTO system_menu(name, permission, type, sort, parent_id, path, icon, component, status, component_name)

View File

@ -1,4 +1,4 @@
package cn.iocoder.yudao.module.pay.util; package cn.iocoder.yudao.framework.common.util.number;
import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.NumberUtil;
@ -23,6 +23,17 @@ public class MoneyUtils {
return calculateRatePrice(price, rate, 0, RoundingMode.HALF_UP).intValue(); return calculateRatePrice(price, rate, 0, RoundingMode.HALF_UP).intValue();
} }
/**
* 计算百分比金额向下传入
*
* @param price 金额
* @param rate 百分比例如说 56.77% 则传入 56.77
* @return 百分比金额
*/
public static Integer calculateRatePriceFloor(Integer price, Double rate) {
return calculateRatePrice(price, rate, 0, RoundingMode.FLOOR).intValue();
}
/** /**
* 计算百分比金额 * 计算百分比金额
* *

View File

@ -0,0 +1,29 @@
package cn.iocoder.yudao.module.trade.api.brokerage;
import cn.iocoder.yudao.module.trade.api.brokerage.dto.BrokerageUserDTO;
/**
* 分销 API 接口
*
* @author owen
*/
public interface BrokerageApi {
/**
* 获得分销用户
*
* @param userId 用户编号
* @return 分销用户信息
*/
BrokerageUserDTO getBrokerageUser(Long userId);
/**
* 绑定推广员
*
* @param userId 用户编号
* @param bindUserId 推广员编号
* @param isNewUser 是否为新用户
* @return 是否绑定
*/
boolean bindUser(Long userId, Long bindUserId, Boolean isNewUser);
}

View File

@ -0,0 +1,51 @@
package cn.iocoder.yudao.module.trade.api.brokerage.dto;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 分销用户 DTO
*
* @author owen
*/
@Data
public class BrokerageUserDTO {
/**
* 用户编号
* <p>
* 对应 MemberUserDO id 字段
*/
private Long id;
/**
* 推广员编号
* <p>
* 关联 MemberUserDO id 字段
*/
private Long bindUserId;
/**
* 推广员绑定时间
*/
private LocalDateTime bindUserTime;
/**
* 推广资格
*/
private Boolean brokerageEnabled;
/**
* 成为分销员时间
*/
private LocalDateTime brokerageTime;
/**
* 可用佣金
*/
private Integer price;
/**
* 冻结佣金
*/
private Integer frozenPrice;
}

View File

@ -77,5 +77,12 @@ public interface ErrorCodeConstants {
// ========== 分销用户 模块 1011007000 ========== // ========== 分销用户 模块 1011007000 ==========
ErrorCode BROKERAGE_USER_NOT_EXISTS = new ErrorCode(1011007000, "分销用户不存在"); ErrorCode BROKERAGE_USER_NOT_EXISTS = new ErrorCode(1011007000, "分销用户不存在");
ErrorCode BROKERAGE_USER_FROZEN_PRICE_NOT_ENOUGH = new ErrorCode(1011007001, "用户冻结佣金({})数量不足");
ErrorCode BROKERAGE_BIND_SELF = new ErrorCode(1011007002, "不能绑定自己");
ErrorCode BROKERAGE_BIND_USER_NOT_ENABLED = new ErrorCode(1011007003, "绑定用户没有推广资格");
ErrorCode BROKERAGE_BIND_CONDITION_ADMIN = new ErrorCode(1011007004, "仅可在后台绑定推广员");
ErrorCode BROKERAGE_BIND_MODE_REGISTER = new ErrorCode(1011007005, "只有在注册时可以绑定");
ErrorCode BROKERAGE_BIND_OVERRIDE = new ErrorCode(1011007006, "已绑定了推广人");
ErrorCode BROKERAGE_BIND_LOOP = new ErrorCode(1011007007, "下级不能绑定自己的上级");
} }

View File

@ -15,16 +15,18 @@ import java.util.Arrays;
@Getter @Getter
public enum BrokerageBindModeEnum implements IntArrayValuable { public enum BrokerageBindModeEnum implements IntArrayValuable {
// TODO @疯狂要不从 1 开始
/** /**
* 只要用户没有推广人随时都可以绑定分销关系 * 只要用户没有推广人随时都可以绑定分销关系
*/ */
ANYTIME(0, "没有推广人"), ANYTIME(1, "没有推广人"),
/** /**
* 仅新用户注册时才能绑定推广关系 * 仅新用户注册时才能绑定推广关系
*/ */
REGISTER(1, "新用户"), REGISTER(2, "新用户"),
// TODO @疯狂要加个 2每次扫码都覆盖 /**
* 每次扫码都覆盖
*/
OVERRIDE(3, "扫码覆盖"),
; ;
public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(BrokerageBindModeEnum::getMode).toArray(); public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(BrokerageBindModeEnum::getMode).toArray();

View File

@ -15,15 +15,14 @@ import java.util.Arrays;
@Getter @Getter
public enum BrokerageEnabledConditionEnum implements IntArrayValuable { public enum BrokerageEnabledConditionEnum implements IntArrayValuable {
// TODO @疯狂这个也从 1 开始哇
/** /**
* 所有用户都可以分销 * 所有用户都可以分销
*/ */
ALL(0, "人人分销"), ALL(1, "人人分销"),
/** /**
* 仅可后台手动设置推广员 * 仅可后台手动设置推广员
*/ */
ADMIN(1, "指定分销"), ADMIN(2, "指定分销"),
; ;
public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(BrokerageEnabledConditionEnum::getCondition).toArray(); public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(BrokerageEnabledConditionEnum::getCondition).toArray();

View File

@ -15,9 +15,8 @@ import java.util.Arrays;
@Getter @Getter
public enum BrokerageRecordBizTypeEnum implements IntArrayValuable { public enum BrokerageRecordBizTypeEnum implements IntArrayValuable {
// TODO @疯狂这个也从 1 开始哇 ORDER(1, "获得推广佣金", "获得推广佣金 {}", true),
ORDER(0, "获得推广佣金", "获得推广佣金 {}", true), WITHDRAW(2, "提现申请", "提现申请扣除佣金 {}", false),
WITHDRAW(1, "提现申请", "提现申请扣除佣金 {}", false),
; ;
public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(BrokerageRecordBizTypeEnum::getType).toArray(); public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(BrokerageRecordBizTypeEnum::getType).toArray();

View File

@ -0,0 +1,32 @@
package cn.iocoder.yudao.module.trade.api.brokerage;
import cn.iocoder.yudao.module.trade.api.brokerage.dto.BrokerageUserDTO;
import cn.iocoder.yudao.module.trade.convert.brokerage.user.BrokerageUserConvert;
import cn.iocoder.yudao.module.trade.service.brokerage.user.BrokerageUserService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Resource;
/**
* 分销 API 接口实现类
*
* @author owen
*/
@Service
@Validated
public class BrokerageApiImpl implements BrokerageApi {
@Resource
private BrokerageUserService brokerageUserService;
public BrokerageUserDTO getBrokerageUser(Long userId) {
return BrokerageUserConvert.INSTANCE.convertDTO(brokerageUserService.getBrokerageUser(userId));
}
@Override
public boolean bindUser(Long userId, Long bindUserId, Boolean isNewUser) {
return brokerageUserService.bindUser(userId, bindUserId, isNewUser);
}
}

View File

@ -2,11 +2,11 @@ package cn.iocoder.yudao.module.trade.controller.admin.brokerage.record;
import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.TradeBrokerageRecordPageReqVO; import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordPageReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.TradeBrokerageRecordRespVO; import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordRespVO;
import cn.iocoder.yudao.module.trade.convert.brokerage.record.TradeBrokerageRecordConvert; import cn.iocoder.yudao.module.trade.convert.brokerage.record.BrokerageRecordConvert;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.TradeBrokerageRecordDO; import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.BrokerageRecordDO;
import cn.iocoder.yudao.module.trade.service.brokerage.record.TradeBrokerageRecordService; import cn.iocoder.yudao.module.trade.service.brokerage.record.BrokerageRecordService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@ -26,26 +26,26 @@ import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
@RestController @RestController
@RequestMapping("/trade/brokerage-record") @RequestMapping("/trade/brokerage-record")
@Validated @Validated
public class TradeBrokerageRecordController { public class BrokerageRecordController {
@Resource @Resource
private TradeBrokerageRecordService tradeBrokerageRecordService; private BrokerageRecordService brokerageRecordService;
@GetMapping("/get") @GetMapping("/get")
@Operation(summary = "获得佣金记录") @Operation(summary = "获得佣金记录")
@Parameter(name = "id", description = "编号", required = true, example = "1024") @Parameter(name = "id", description = "编号", required = true, example = "1024")
@PreAuthorize("@ss.hasPermission('trade:brokerage-record:query')") @PreAuthorize("@ss.hasPermission('trade:brokerage-record:query')")
public CommonResult<TradeBrokerageRecordRespVO> getBrokerageRecord(@RequestParam("id") Integer id) { public CommonResult<BrokerageRecordRespVO> getBrokerageRecord(@RequestParam("id") Integer id) {
TradeBrokerageRecordDO tradeBrokerageRecord = tradeBrokerageRecordService.getBrokerageRecord(id); BrokerageRecordDO brokerageRecord = brokerageRecordService.getBrokerageRecord(id);
return success(TradeBrokerageRecordConvert.INSTANCE.convert(tradeBrokerageRecord)); return success(BrokerageRecordConvert.INSTANCE.convert(brokerageRecord));
} }
@GetMapping("/page") @GetMapping("/page")
@Operation(summary = "获得佣金记录分页") @Operation(summary = "获得佣金记录分页")
@PreAuthorize("@ss.hasPermission('trade:brokerage-record:query')") @PreAuthorize("@ss.hasPermission('trade:brokerage-record:query')")
public CommonResult<PageResult<TradeBrokerageRecordRespVO>> getBrokerageRecordPage(@Valid TradeBrokerageRecordPageReqVO pageVO) { public CommonResult<PageResult<BrokerageRecordRespVO>> getBrokerageRecordPage(@Valid BrokerageRecordPageReqVO pageVO) {
PageResult<TradeBrokerageRecordDO> pageResult = tradeBrokerageRecordService.getBrokerageRecordPage(pageVO); PageResult<BrokerageRecordDO> pageResult = brokerageRecordService.getBrokerageRecordPage(pageVO);
return success(TradeBrokerageRecordConvert.INSTANCE.convertPage(pageResult)); return success(BrokerageRecordConvert.INSTANCE.convertPage(pageResult));
} }
} }

View File

@ -15,7 +15,7 @@ import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_
* 如果子 VO 存在差异的字段请不要添加到这里影响 Swagger 文档生成 * 如果子 VO 存在差异的字段请不要添加到这里影响 Swagger 文档生成
*/ */
@Data @Data
public class TradeBrokerageRecordBaseVO { public class BrokerageRecordBaseVO {
@Schema(description = "用户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "25973") @Schema(description = "用户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "25973")
@NotNull(message = "用户编号不能为空") @NotNull(message = "用户编号不能为空")

View File

@ -15,7 +15,7 @@ import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true) @ToString(callSuper = true)
public class TradeBrokerageRecordPageReqVO extends PageParam { public class BrokerageRecordPageReqVO extends PageParam {
@Schema(description = "用户编号", example = "25973") @Schema(description = "用户编号", example = "25973")
private Long userId; private Long userId;

View File

@ -11,7 +11,7 @@ import java.time.LocalDateTime;
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true) @ToString(callSuper = true)
public class TradeBrokerageRecordRespVO extends TradeBrokerageRecordBaseVO { public class BrokerageRecordRespVO extends BrokerageRecordBaseVO {
@Schema(description = "编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "28896") @Schema(description = "编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "28896")
private Integer id; private Integer id;

View File

@ -0,0 +1,104 @@
package cn.iocoder.yudao.module.trade.controller.admin.brokerage.user;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.*;
import cn.iocoder.yudao.module.trade.convert.brokerage.user.BrokerageUserConvert;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordStatusEnum;
import cn.iocoder.yudao.module.trade.service.brokerage.record.BrokerageRecordService;
import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserBrokerageSummaryBO;
import cn.iocoder.yudao.module.trade.service.brokerage.user.BrokerageUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;
import java.util.Set;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
@Tag(name = "管理后台 - 分销用户")
@RestController
@RequestMapping("/trade/brokerage-user")
@Validated
public class BrokerageUserController {
@Resource
private BrokerageUserService brokerageUserService;
@Resource
private BrokerageRecordService brokerageRecordService;
@Resource
private MemberUserApi memberUserApi;
@PutMapping("/update-brokerage-user")
@Operation(summary = "修改推广员")
@PreAuthorize("@ss.hasPermission('trade:brokerage-user:update-brokerage-user')")
public CommonResult<Boolean> updateBrokerageUser(@Valid @RequestBody BrokerageUserUpdateBrokerageUserReqVO updateReqVO) {
brokerageUserService.updateBrokerageUserId(updateReqVO.getId(), updateReqVO.getBindUserId());
return success(true);
}
@PutMapping("/clear-brokerage-user")
@Operation(summary = "清除推广员")
@PreAuthorize("@ss.hasPermission('trade:brokerage-user:clear-brokerage-user')")
public CommonResult<Boolean> clearBrokerageUser(@Valid @RequestBody BrokerageUserClearBrokerageUserReqVO updateReqVO) {
brokerageUserService.updateBrokerageUserId(updateReqVO.getId(), null);
return success(true);
}
@PutMapping("/update-brokerage-enable")
@Operation(summary = "修改推广资格")
@PreAuthorize("@ss.hasPermission('trade:brokerage-user:update-brokerage-enable')")
public CommonResult<Boolean> updateBrokerageEnabled(@Valid @RequestBody BrokerageUserUpdateBrokerageEnabledReqVO updateReqVO) {
brokerageUserService.updateBrokerageEnabled(updateReqVO.getId(), updateReqVO.getEnabled());
return success(true);
}
@GetMapping("/get")
@Operation(summary = "获得分销用户")
@Parameter(name = "id", description = "编号", required = true, example = "1024")
@PreAuthorize("@ss.hasPermission('trade:brokerage-user:query')")
public CommonResult<BrokerageUserRespVO> getBrokerageUser(@RequestParam("id") Long id) {
BrokerageUserDO brokerageUser = brokerageUserService.getBrokerageUser(id);
return success(BrokerageUserConvert.INSTANCE.convert(brokerageUser));
}
@GetMapping("/page")
@Operation(summary = "获得分销用户分页")
@PreAuthorize("@ss.hasPermission('trade:brokerage-user:query')")
public CommonResult<PageResult<BrokerageUserRespVO>> getBrokerageUserPage(@Valid BrokerageUserPageReqVO pageVO) {
// 分页查询
PageResult<BrokerageUserDO> pageResult = brokerageUserService.getBrokerageUserPage(pageVO);
// 涉及到的用户
Set<Long> userIds = convertSet(pageResult.getList(), BrokerageUserDO::getId);
// 查询用户信息
Map<Long, MemberUserRespDTO> userMap = memberUserApi.getUserMap(userIds);
// 合计分佣订单
Map<Long, UserBrokerageSummaryBO> userOrderSummaryMap = convertMap(userIds,
userId -> userId,
userId -> brokerageRecordService.summaryByUserIdAndBizTypeAndStatus(userId,
BrokerageRecordBizTypeEnum.ORDER.getType(), BrokerageRecordStatusEnum.SETTLEMENT.getStatus()));
// 合计推广用户数量
Map<Long, Long> brokerageUserCountMap = convertMap(userIds,
userId -> userId,
userId -> brokerageUserService.getCountByBindUserId(userId));
// todo 合计提现
return success(BrokerageUserConvert.INSTANCE.convertPage(pageResult, userMap, brokerageUserCountMap, userOrderSummaryMap));
}
}

View File

@ -1,71 +0,0 @@
package cn.iocoder.yudao.module.trade.controller.admin.brokerage.user;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.*;
import cn.iocoder.yudao.module.trade.convert.brokerage.user.TradeBrokerageUserConvert;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.TradeBrokerageUserDO;
import cn.iocoder.yudao.module.trade.service.brokerage.user.TradeBrokerageUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
@Tag(name = "管理后台 - 分销用户")
@RestController
@RequestMapping("/trade/brokerage-user")
@Validated
public class TradeBrokerageUserController {
@Resource
private TradeBrokerageUserService brokerageUserService;
@PutMapping("/update-brokerage-user")
@Operation(summary = "修改推广员")
@PreAuthorize("@ss.hasPermission('trade:brokerage-user:update-brokerage-user')")
public CommonResult<Boolean> updateBrokerageUser(@Valid @RequestBody TradeBrokerageUserUpdateBrokerageUserReqVO updateReqVO) {
brokerageUserService.updateBrokerageUserId(updateReqVO.getId(), updateReqVO.getBrokerageUserId());
return success(true);
}
@PutMapping("/clear-brokerage-user")
@Operation(summary = "清除推广员")
@PreAuthorize("@ss.hasPermission('trade:brokerage-user:clear-brokerage-user')")
public CommonResult<Boolean> clearBrokerageUser(@Valid @RequestBody TradeBrokerageUserClearBrokerageUserReqVO updateReqVO) {
brokerageUserService.updateBrokerageUserId(updateReqVO.getId(), null);
return success(true);
}
@PutMapping("/update-brokerage-enable")
@Operation(summary = "修改推广资格")
@PreAuthorize("@ss.hasPermission('trade:brokerage-user:update-brokerage-enable')")
public CommonResult<Boolean> updateBrokerageEnabled(@Valid @RequestBody TradeBrokerageUserUpdateBrokerageEnabledReqVO updateReqVO) {
brokerageUserService.updateBrokerageEnabled(updateReqVO.getId(), updateReqVO.getBrokerageEnabled());
return success(true);
}
@GetMapping("/get")
@Operation(summary = "获得分销用户")
@Parameter(name = "id", description = "编号", required = true, example = "1024")
@PreAuthorize("@ss.hasPermission('trade:brokerage-user:query')")
public CommonResult<TradeBrokerageUserRespVO> getBrokerageUser(@RequestParam("id") Long id) {
TradeBrokerageUserDO brokerageUser = brokerageUserService.getBrokerageUser(id);
return success(TradeBrokerageUserConvert.INSTANCE.convert(brokerageUser));
}
@GetMapping("/page")
@Operation(summary = "获得分销用户分页")
@PreAuthorize("@ss.hasPermission('trade:brokerage-user:query')")
public CommonResult<PageResult<TradeBrokerageUserRespVO>> getBrokerageUserPage(@Valid TradeBrokerageUserPageReqVO pageVO) {
PageResult<TradeBrokerageUserDO> pageResult = brokerageUserService.getBrokerageUserPage(pageVO);
return success(TradeBrokerageUserConvert.INSTANCE.convertPage(pageResult));
}
}

View File

@ -14,15 +14,15 @@ import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_
* 如果子 VO 存在差异的字段请不要添加到这里影响 Swagger 文档生成 * 如果子 VO 存在差异的字段请不要添加到这里影响 Swagger 文档生成
*/ */
@Data @Data
public class TradeBrokerageUserBaseVO { public class BrokerageUserBaseVO {
@Schema(description = "推广员编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "4587") @Schema(description = "推广员编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "4587")
@NotNull(message = "推广员编号不能为空") @NotNull(message = "推广员编号不能为空")
private Long brokerageUserId; private Long bindUserId;
@Schema(description = "推广员绑定时间") @Schema(description = "推广员绑定时间")
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) @DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
private LocalDateTime brokerageBindTime; private LocalDateTime bindUserTime;
@Schema(description = "推广资格", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(description = "推广资格", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "推广资格不能为空") @NotNull(message = "推广资格不能为空")
@ -34,10 +34,10 @@ public class TradeBrokerageUserBaseVO {
@Schema(description = "可用佣金", requiredMode = Schema.RequiredMode.REQUIRED, example = "11089") @Schema(description = "可用佣金", requiredMode = Schema.RequiredMode.REQUIRED, example = "11089")
@NotNull(message = "可用佣金不能为空") @NotNull(message = "可用佣金不能为空")
private Integer brokeragePrice; private Integer price;
@Schema(description = "冻结佣金", requiredMode = Schema.RequiredMode.REQUIRED, example = "30916") @Schema(description = "冻结佣金", requiredMode = Schema.RequiredMode.REQUIRED, example = "30916")
@NotNull(message = "冻结佣金不能为空") @NotNull(message = "冻结佣金不能为空")
private Integer frozenBrokeragePrice; private Integer frozenPrice;
} }

View File

@ -9,7 +9,7 @@ import javax.validation.constraints.NotNull;
@Schema(description = "管理后台 - 分销用户 - 清除推广员 Request VO") @Schema(description = "管理后台 - 分销用户 - 清除推广员 Request VO")
@Data @Data
@ToString(callSuper = true) @ToString(callSuper = true)
public class TradeBrokerageUserClearBrokerageUserReqVO { public class BrokerageUserClearBrokerageUserReqVO {
@Schema(description = "用户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "20019") @Schema(description = "用户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "20019")
@NotNull(message = "用户编号不能为空") @NotNull(message = "用户编号不能为空")

View File

@ -15,10 +15,10 @@ import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true) @ToString(callSuper = true)
public class TradeBrokerageUserPageReqVO extends PageParam { public class BrokerageUserPageReqVO extends PageParam {
@Schema(description = "推广员编号", example = "4587") @Schema(description = "推广员编号", example = "4587")
private Long brokerageUserId; private Long bindUserId;
@Schema(description = "推广资格") @Schema(description = "推广资格")
private Boolean brokerageEnabled; private Boolean brokerageEnabled;

View File

@ -0,0 +1,48 @@
package cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.time.LocalDateTime;
@Schema(description = "管理后台 - 分销用户 Response VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class BrokerageUserRespVO extends BrokerageUserBaseVO {
@Schema(description = "用户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "20019")
private Long id;
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED)
private LocalDateTime createTime;
// ========== 用户信息 ==========
@Schema(description = "用户头像", example = "https://www.iocoder.cn/xxx.png")
private String avatar;
@Schema(description = "用户昵称", example = "李四")
private String nickname;
// ========== 推广信息 ==========
@Schema(description = "推广用户数量(一级)", example = "20019")
private Integer brokerageUserCount;
@Schema(description = "推广订单数量", example = "20019")
private Integer brokerageOrderCount;
@Schema(description = "推广订单金额", example = "20019")
private Integer brokerageOrderPrice;
// ========== 提现信息 ==========
@Schema(description = "已提现金额", example = "20019")
private Integer withdrawPrice;
@Schema(description = "已提现次数", example = "20019")
private Integer withdrawCount;
}

View File

@ -9,16 +9,14 @@ import javax.validation.constraints.NotNull;
@Schema(description = "管理后台 - 分销用户 - 修改推广员 Request VO") @Schema(description = "管理后台 - 分销用户 - 修改推广员 Request VO")
@Data @Data
@ToString(callSuper = true) @ToString(callSuper = true)
public class TradeBrokerageUserUpdateBrokerageEnabledReqVO { public class BrokerageUserUpdateBrokerageEnabledReqVO {
@Schema(description = "用户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "20019") @Schema(description = "用户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "20019")
@NotNull(message = "用户编号不能为空") @NotNull(message = "用户编号不能为空")
private Long id; private Long id;
// TODO @疯狂是不是这个字段可以改成 enabled
@Schema(description = "推广资格", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(description = "推广资格", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "推广资格不能为空") @NotNull(message = "推广资格不能为空")
private Boolean brokerageEnabled; private Boolean enabled;
} }

View File

@ -9,7 +9,7 @@ import javax.validation.constraints.NotNull;
@Schema(description = "管理后台 - 分销用户 - 修改推广员 Request VO") @Schema(description = "管理后台 - 分销用户 - 修改推广员 Request VO")
@Data @Data
@ToString(callSuper = true) @ToString(callSuper = true)
public class TradeBrokerageUserUpdateBrokerageUserReqVO { public class BrokerageUserUpdateBrokerageUserReqVO {
@Schema(description = "用户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "20019") @Schema(description = "用户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "20019")
@NotNull(message = "用户编号不能为空") @NotNull(message = "用户编号不能为空")
@ -17,6 +17,6 @@ public class TradeBrokerageUserUpdateBrokerageUserReqVO {
@Schema(description = "推广员编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "4587") @Schema(description = "推广员编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "4587")
@NotNull(message = "推广员编号不能为空") @NotNull(message = "推广员编号不能为空")
private Long brokerageUserId; private Long bindUserId;
} }

View File

@ -1,22 +0,0 @@
package cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.time.LocalDateTime;
@Schema(description = "管理后台 - 分销用户 Response VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class TradeBrokerageUserRespVO extends TradeBrokerageUserBaseVO {
@Schema(description = "用户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "20019")
private Long id;
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED)
private LocalDateTime createTime;
}

View File

@ -54,7 +54,6 @@ public class TradeConfigBaseVO {
@PositiveOrZero(message = "用户提现最低金额不能是负数") @PositiveOrZero(message = "用户提现最低金额不能是负数")
private Integer brokerageWithdrawMinPrice; private Integer brokerageWithdrawMinPrice;
// TODO @疯狂要不要做成字典按道理都可以体现对哇感觉是全局的配置哈
@Schema(description = "提现银行", requiredMode = Schema.RequiredMode.REQUIRED, example = "[0, 1]") @Schema(description = "提现银行", requiredMode = Schema.RequiredMode.REQUIRED, example = "[0, 1]")
@NotEmpty(message = "提现银行不能为空") @NotEmpty(message = "提现银行不能为空")
private List<Integer> brokerageBankNames; private List<Integer> brokerageBankNames;

View File

@ -4,21 +4,22 @@ import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated; import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.*; import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.*;
import cn.iocoder.yudao.module.trade.service.brokerage.user.BrokerageUserService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND; import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
@Tag(name = "用户 APP - 分销用户") @Tag(name = "用户 APP - 分销用户")
@ -27,6 +28,8 @@ import static java.util.Arrays.asList;
@Validated @Validated
@Slf4j @Slf4j
public class AppBrokerageUserController { public class AppBrokerageUserController {
@Resource
private BrokerageUserService brokerageUserService;
// TODO 芋艿临时 mock => // TODO 芋艿临时 mock =>
@GetMapping("/get") @GetMapping("/get")
@ -34,8 +37,8 @@ public class AppBrokerageUserController {
@PreAuthenticated @PreAuthenticated
public CommonResult<AppBrokerageUserRespVO> getBrokerageUser() { public CommonResult<AppBrokerageUserRespVO> getBrokerageUser() {
AppBrokerageUserRespVO respVO = new AppBrokerageUserRespVO() AppBrokerageUserRespVO respVO = new AppBrokerageUserRespVO()
.setBrokeragePrice(2000) .setPrice(2000)
.setFrozenBrokeragePrice(3000); .setFrozenPrice(3000);
return success(respVO); return success(respVO);
} }
@ -45,10 +48,10 @@ public class AppBrokerageUserController {
@PreAuthenticated @PreAuthenticated
public CommonResult<AppBrokerageUserMySummaryRespVO> getBrokerageUserSummary() { public CommonResult<AppBrokerageUserMySummaryRespVO> getBrokerageUserSummary() {
AppBrokerageUserMySummaryRespVO respVO = new AppBrokerageUserMySummaryRespVO() AppBrokerageUserMySummaryRespVO respVO = new AppBrokerageUserMySummaryRespVO()
.setYesterdayBrokeragePrice(1) .setYesterdayPrice(1)
.setBrokeragePrice(2) .setPrice(2)
.setFrozenBrokeragePrice(3) .setFrozenPrice(3)
.setWithdrawBrokeragePrice(4) .setWithdrawPrice(4)
.setFirstBrokerageUserCount(166) .setFirstBrokerageUserCount(166)
.setSecondBrokerageUserCount(233); .setSecondBrokerageUserCount(233);
return success(respVO); return success(respVO);
@ -81,16 +84,16 @@ public class AppBrokerageUserController {
public CommonResult<PageResult<AppBrokerageUserRankByPriceRespVO>> getBrokerageUserChildSummaryPageByPrice(AppBrokerageUserRankPageReqVO pageReqVO) { public CommonResult<PageResult<AppBrokerageUserRankByPriceRespVO>> getBrokerageUserChildSummaryPageByPrice(AppBrokerageUserRankPageReqVO pageReqVO) {
AppBrokerageUserRankByPriceRespVO vo1 = new AppBrokerageUserRankByPriceRespVO() AppBrokerageUserRankByPriceRespVO vo1 = new AppBrokerageUserRankByPriceRespVO()
.setId(1L).setNickname("芋1**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg") .setId(1L).setNickname("芋1**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
.setBrokeragePrice(10); .setPrice(10);
AppBrokerageUserRankByPriceRespVO vo2 = new AppBrokerageUserRankByPriceRespVO() AppBrokerageUserRankByPriceRespVO vo2 = new AppBrokerageUserRankByPriceRespVO()
.setId(2L).setNickname("芋2**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg") .setId(2L).setNickname("芋2**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
.setBrokeragePrice(6); .setPrice(6);
AppBrokerageUserRankByPriceRespVO vo3 = new AppBrokerageUserRankByPriceRespVO() AppBrokerageUserRankByPriceRespVO vo3 = new AppBrokerageUserRankByPriceRespVO()
.setId(3L).setNickname("芋3**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg") .setId(3L).setNickname("芋3**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
.setBrokeragePrice(4); .setPrice(4);
AppBrokerageUserRankByPriceRespVO vo4 = new AppBrokerageUserRankByPriceRespVO() AppBrokerageUserRankByPriceRespVO vo4 = new AppBrokerageUserRankByPriceRespVO()
.setId(3L).setNickname("芋3**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg") .setId(3L).setNickname("芋3**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
.setBrokeragePrice(4); .setPrice(4);
return success(new PageResult<>(asList(vo1, vo2, vo3, vo4), 10L)); return success(new PageResult<>(asList(vo1, vo2, vo3, vo4), 10L));
} }
@ -102,11 +105,11 @@ public class AppBrokerageUserController {
AppBrokerageUserChildSummaryPageReqVO pageReqVO) { AppBrokerageUserChildSummaryPageReqVO pageReqVO) {
AppBrokerageUserChildSummaryRespVO vo1 = new AppBrokerageUserChildSummaryRespVO() AppBrokerageUserChildSummaryRespVO vo1 = new AppBrokerageUserChildSummaryRespVO()
.setId(1L).setNickname("芋1**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg") .setId(1L).setNickname("芋1**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
.setBrokeragePrice(10).setBrokeragePrice(20).setBrokerageOrderCount(30) .setPrice(10).setPrice(20).setBrokerageOrderCount(30)
.setBrokerageTime(LocalDateTime.now()); .setBrokerageTime(LocalDateTime.now());
AppBrokerageUserChildSummaryRespVO vo2 = new AppBrokerageUserChildSummaryRespVO() AppBrokerageUserChildSummaryRespVO vo2 = new AppBrokerageUserChildSummaryRespVO()
.setId(1L).setNickname("芋2**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg") .setId(1L).setNickname("芋2**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
.setBrokeragePrice(20).setBrokeragePrice(30).setBrokerageOrderCount(40) .setPrice(20).setPrice(30).setBrokerageOrderCount(40)
.setBrokerageTime(LocalDateTime.now()); .setBrokerageTime(LocalDateTime.now());
return success(new PageResult<>(asList(vo1, vo2), 10L)); return success(new PageResult<>(asList(vo1, vo2), 10L));
} }
@ -120,4 +123,10 @@ public class AppBrokerageUserController {
return success(1); return success(1);
} }
@PutMapping("/bind-user")
@Operation(summary = "绑定推广员")
public CommonResult<Boolean> getBrokerageUserRankByPrice(@Valid AppBrokerageUserBindReqVO reqVO) {
return success(brokerageUserService.bindUser(getLoginUserId(), reqVO.getBindUserId(), false));
}
} }

View File

@ -1,6 +1,9 @@
package cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.record; package cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.record;
import cn.iocoder.yudao.framework.common.pojo.PageParam; import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.validation.InEnum;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordStatusEnum;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
@ -8,12 +11,12 @@ import lombok.Data;
@Data @Data
public class AppBrokerageRecordPageReqVO extends PageParam { public class AppBrokerageRecordPageReqVO extends PageParam {
// TODO @疯狂要加下枚举校验
@Schema(description = "业务类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") @Schema(description = "业务类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
@InEnum(value = BrokerageRecordBizTypeEnum.class, message = "业务类型必须是 {value}")
private Integer bizType; private Integer bizType;
@Schema(description = "状态", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") @Schema(description = "状态", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
@InEnum(value = BrokerageRecordStatusEnum.class, message = "状态必须是 {value}")
private Integer status; private Integer status;
} }

View File

@ -0,0 +1,17 @@
package cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import javax.validation.constraints.NotNull;
@Schema(description = "应用 App - 绑定推广员 Request VO")
@Data
public class AppBrokerageUserBindReqVO extends PageParam {
@Schema(description = "推广员编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
@NotNull(message = "推广员编号不能为空")
private Long bindUserId;
}

View File

@ -19,7 +19,7 @@ public class AppBrokerageUserChildSummaryRespVO {
private String avatar; private String avatar;
@Schema(description = "佣金金额,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "10") @Schema(description = "佣金金额,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "10")
private Integer brokeragePrice; private Integer price;
@Schema(description = "分销订单数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "20") @Schema(description = "分销订单数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "20")
private Integer brokerageOrderCount; private Integer brokerageOrderCount;

View File

@ -8,16 +8,16 @@ import lombok.Data;
public class AppBrokerageUserMySummaryRespVO { public class AppBrokerageUserMySummaryRespVO {
@Schema(description = "昨天的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "10") @Schema(description = "昨天的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "10")
private Integer yesterdayBrokeragePrice; private Integer yesterdayPrice;
@Schema(description = "提现的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024") @Schema(description = "提现的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
private Integer withdrawBrokeragePrice; private Integer withdrawPrice;
@Schema(description = "可用的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "2408") @Schema(description = "可用的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "2408")
private Integer brokeragePrice; private Integer price;
@Schema(description = "冻结的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "234") @Schema(description = "冻结的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "234")
private Integer frozenBrokeragePrice; private Integer frozenPrice;
@Schema(description = "分销用户数量(一级)", requiredMode = Schema.RequiredMode.REQUIRED, example = "10") @Schema(description = "分销用户数量(一级)", requiredMode = Schema.RequiredMode.REQUIRED, example = "10")
private Integer firstBrokerageUserCount; private Integer firstBrokerageUserCount;

View File

@ -17,6 +17,6 @@ public class AppBrokerageUserRankByPriceRespVO {
private String avatar; private String avatar;
@Schema(description = "佣金金额", requiredMode = Schema.RequiredMode.REQUIRED, example = "10") @Schema(description = "佣金金额", requiredMode = Schema.RequiredMode.REQUIRED, example = "10")
private Integer brokeragePrice; private Integer price;
} }

View File

@ -8,9 +8,9 @@ import lombok.Data;
public class AppBrokerageUserRespVO { public class AppBrokerageUserRespVO {
@Schema(description = "可用的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "2408") @Schema(description = "可用的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "2408")
private Integer brokeragePrice; private Integer price;
@Schema(description = "冻结的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "234") @Schema(description = "冻结的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "234")
private Integer frozenBrokeragePrice; private Integer frozenPrice;
} }

View File

@ -1,29 +1,76 @@
package cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.withdraw; package cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.withdraw;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.framework.common.validation.InEnum;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageWithdrawTypeEnum;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
import org.hibernate.validator.constraints.URL; import org.hibernate.validator.constraints.URL;
import javax.validation.Validator;
import javax.validation.constraints.Min; import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
@Schema(description = "用户 App - 分销提现创建 Request VO") @Schema(description = "用户 App - 分销提现创建 Request VO")
@Data @Data
public class AppBrokerageWithdrawCreateReqVO { public class AppBrokerageWithdrawCreateReqVO {
// TODO @疯狂参数校验逻辑需要根据 type 进行不同的校验感觉可以通过分组
@Schema(description = "提现方式", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") @Schema(description = "提现方式", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
@InEnum(value = BrokerageWithdrawTypeEnum.class, message = "提现方式必须是 {value}")
private Integer type; private Integer type;
@Schema(description = "提现账号", requiredMode = Schema.RequiredMode.REQUIRED, example = "123456789") // 银行卡号/微信账号/支付宝账号 @Schema(description = "提现金额,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "1000")
@Min(value = 1, message = "提现金额不能小于 1")
private Integer price;
// ========== 银行卡微信支付宝 提现相关字段 ==========
@Schema(description = "提现账号", requiredMode = Schema.RequiredMode.REQUIRED, example = "123456789")
@NotBlank(message = "提现账号不能为空", groups = {Bank.class, Wechat.class, Alipay.class})
private String accountNo; private String accountNo;
// ========== 微信支付宝 提现相关字段 ==========
@Schema(description = "收款码的图片", example = "https://www.iocoder.cn/1.png") @Schema(description = "收款码的图片", example = "https://www.iocoder.cn/1.png")
@URL(message = "收款码的图片,必须是一个 URL") @URL(message = "收款码的图片,必须是一个 URL")
private String accountQrCodeUrl; private String accountQrCodeUrl;
@Schema(description = "提现金额,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "1000")
@Min(value = 1, message = "提现金额必须大于 1") // ========== 银行卡 提现相关字段 ==========
private Integer price;
@Schema(description = "持卡人姓名", example = "张三")
@NotBlank(message = "持卡人姓名不能为空", groups = {Bank.class})
private String name;
@Schema(description = "提现银行", example = "1")
@NotBlank(message = "提现银行不能为空", groups = {Bank.class})
private Integer bankName;
@Schema(description = "开户地址", example = "海淀支行")
private String bankAddress;
public interface Wallet {
}
public interface Bank {
}
public interface Wechat {
}
public interface Alipay {
}
public void validate(Validator validator) {
if (BrokerageWithdrawTypeEnum.WALLET.getType().equals(type)) {
ValidationUtils.validate(validator, this, Wallet.class);
} else if (BrokerageWithdrawTypeEnum.BANK.getType().equals(type)) {
ValidationUtils.validate(validator, this, Bank.class);
} else if (BrokerageWithdrawTypeEnum.WECHAT.getType().equals(type)) {
ValidationUtils.validate(validator, this, Wechat.class);
} else if (BrokerageWithdrawTypeEnum.ALIPAY.getType().equals(type)) {
ValidationUtils.validate(validator, this, Alipay.class);
}
}
} }

View File

@ -1,10 +1,11 @@
package cn.iocoder.yudao.module.trade.convert.brokerage.record; package cn.iocoder.yudao.module.trade.convert.brokerage.record;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.TradeBrokerageRecordRespVO; import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordRespVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.TradeBrokerageRecordDO; import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.BrokerageRecordDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.TradeBrokerageUserDO; import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum; import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordStatusEnum; import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordStatusEnum;
import org.mapstruct.Mapper; import org.mapstruct.Mapper;
@ -19,29 +20,32 @@ import java.util.List;
* @author owen * @author owen
*/ */
@Mapper @Mapper
public interface TradeBrokerageRecordConvert { public interface BrokerageRecordConvert {
TradeBrokerageRecordConvert INSTANCE = Mappers.getMapper(TradeBrokerageRecordConvert.class); BrokerageRecordConvert INSTANCE = Mappers.getMapper(BrokerageRecordConvert.class);
TradeBrokerageRecordRespVO convert(TradeBrokerageRecordDO bean); BrokerageRecordRespVO convert(BrokerageRecordDO bean);
List<TradeBrokerageRecordRespVO> convertList(List<TradeBrokerageRecordDO> list); List<BrokerageRecordRespVO> convertList(List<BrokerageRecordDO> list);
PageResult<TradeBrokerageRecordRespVO> convertPage(PageResult<TradeBrokerageRecordDO> page); PageResult<BrokerageRecordRespVO> convertPage(PageResult<BrokerageRecordDO> page);
default TradeBrokerageRecordDO convert(TradeBrokerageUserDO user, String bizId, int brokerageFrozenDays, int brokerage, LocalDateTime unfreezeTime) { default BrokerageRecordDO convert(BrokerageUserDO user, BrokerageRecordBizTypeEnum bizType, String bizId,
Integer brokerageFrozenDays, int brokerage, LocalDateTime unfreezeTime,
String title) {
brokerageFrozenDays = ObjectUtil.defaultIfNull(brokerageFrozenDays, 0);
// 不冻结时佣金直接就是结算状态 // 不冻结时佣金直接就是结算状态
Integer status = brokerageFrozenDays > 0 Integer status = brokerageFrozenDays > 0
? BrokerageRecordStatusEnum.WAIT_SETTLEMENT.getStatus() ? BrokerageRecordStatusEnum.WAIT_SETTLEMENT.getStatus()
: BrokerageRecordStatusEnum.SETTLEMENT.getStatus(); : BrokerageRecordStatusEnum.SETTLEMENT.getStatus();
return new TradeBrokerageRecordDO() return new BrokerageRecordDO()
.setUserId(user.getId()) .setUserId(user.getId())
.setBizType(BrokerageRecordBizTypeEnum.ORDER.getType()) .setBizType(bizType.getType())
.setBizId(bizId) .setBizId(bizId)
.setPrice(brokerage) .setPrice(brokerage)
.setTotalPrice(user.getBrokeragePrice()) .setTotalPrice(user.getPrice())
.setTitle(BrokerageRecordBizTypeEnum.ORDER.getTitle()) // TODO @疯狂可能 title 不是很固化会存在类似沐晴成功购买XXX JVM 实战 .setTitle(title)
.setDescription(StrUtil.format(BrokerageRecordBizTypeEnum.ORDER.getDescription(), String.valueOf(brokerage / 100.0))) .setDescription(StrUtil.format(bizType.getDescription(), String.valueOf(brokerage / 100.0)))
.setStatus(status) .setStatus(status)
.setFrozenDays(brokerageFrozenDays) .setFrozenDays(brokerageFrozenDays)
.setUnfreezeTime(unfreezeTime); .setUnfreezeTime(unfreezeTime);

View File

@ -0,0 +1,64 @@
package cn.iocoder.yudao.module.trade.convert.brokerage.user;
import cn.hutool.core.map.MapUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.trade.api.brokerage.dto.BrokerageUserDTO;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.BrokerageUserRespVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserBrokerageSummaryBO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* 分销用户 Convert
*
* @author owen
*/
@Mapper
public interface BrokerageUserConvert {
BrokerageUserConvert INSTANCE = Mappers.getMapper(BrokerageUserConvert.class);
BrokerageUserRespVO convert(BrokerageUserDO bean);
List<BrokerageUserRespVO> convertList(List<BrokerageUserDO> list);
PageResult<BrokerageUserRespVO> convertPage(PageResult<BrokerageUserDO> page);
default PageResult<BrokerageUserRespVO> convertPage(PageResult<BrokerageUserDO> pageResult,
Map<Long, MemberUserRespDTO> userMap,
Map<Long, Long> brokerageUserCountMap,
Map<Long, UserBrokerageSummaryBO> userOrderSummaryMap) {
PageResult<BrokerageUserRespVO> result = convertPage(pageResult);
for (BrokerageUserRespVO vo : result.getList()) {
// 用户信息
Optional.ofNullable(userMap.get(vo.getId()))
.ifPresent(user -> {
vo.setNickname(user.getNickname());
vo.setAvatar(user.getAvatar());
});
// 推广用户数量一级
vo.setBrokerageUserCount(MapUtil.getInt(brokerageUserCountMap, vo.getId(), 0));
Optional<UserBrokerageSummaryBO> orderSummaryOptional = Optional.ofNullable(userOrderSummaryMap.get(vo.getId()));
// 推广订单数量
vo.setBrokerageOrderCount(orderSummaryOptional.map(UserBrokerageSummaryBO::getCount).orElse(0));
// 推广订单金额
vo.setBrokerageOrderPrice(orderSummaryOptional.map(UserBrokerageSummaryBO::getPrice).orElse(0));
// todo 已提现次数
vo.setWithdrawCount(0);
// todo 已提现金额
vo.setWithdrawPrice(0);
}
return result;
}
BrokerageUserDTO convertDTO(BrokerageUserDO brokerageUser);
}

View File

@ -1,27 +0,0 @@
package cn.iocoder.yudao.module.trade.convert.brokerage.user;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.TradeBrokerageUserRespVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.TradeBrokerageUserDO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.List;
/**
* 分销用户 Convert
*
* @author owen
*/
@Mapper
public interface TradeBrokerageUserConvert {
TradeBrokerageUserConvert INSTANCE = Mappers.getMapper(TradeBrokerageUserConvert.class);
TradeBrokerageUserRespVO convert(TradeBrokerageUserDO bean);
List<TradeBrokerageUserRespVO> convertList(List<TradeBrokerageUserDO> list);
PageResult<TradeBrokerageUserRespVO> convertPage(PageResult<TradeBrokerageUserDO> page);
}

View File

@ -7,7 +7,7 @@ import cn.iocoder.yudao.framework.common.util.string.StrUtils;
import cn.iocoder.yudao.framework.dict.core.util.DictFrameworkUtils; import cn.iocoder.yudao.framework.dict.core.util.DictFrameworkUtils;
import cn.iocoder.yudao.framework.ip.core.utils.AreaUtils; import cn.iocoder.yudao.framework.ip.core.utils.AreaUtils;
import cn.iocoder.yudao.module.member.api.address.dto.AddressRespDTO; import cn.iocoder.yudao.module.member.api.address.dto.AddressRespDTO;
import cn.iocoder.yudao.module.trade.service.brokerage.record.bo.BrokerageAddReqBO; import cn.iocoder.yudao.module.trade.service.brokerage.bo.BrokerageAddReqBO;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO; import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.pay.api.order.dto.PayOrderCreateReqDTO; import cn.iocoder.yudao.module.pay.api.order.dto.PayOrderCreateReqDTO;
import cn.iocoder.yudao.module.pay.enums.DictTypeConstants; import cn.iocoder.yudao.module.pay.enums.DictTypeConstants;
@ -279,8 +279,8 @@ public interface TradeOrderConvert {
default BrokerageAddReqBO convert(TradeOrderItemDO item, ProductSkuRespDTO sku) { default BrokerageAddReqBO convert(TradeOrderItemDO item, ProductSkuRespDTO sku) {
return new BrokerageAddReqBO().setBizId(String.valueOf(item.getId())) return new BrokerageAddReqBO().setBizId(String.valueOf(item.getId()))
.setPayPrice(item.getPayPrice()).setCount(item.getCount()) .setBasePrice(item.getPayPrice() * item.getCount())
.setSkuFirstBrokeragePrice(sku.getSubCommissionFirstPrice()) .setFirstFixedPrice(sku.getSubCommissionFirstPrice())
.setSkuSecondBrokeragePrice(sku.getSubCommissionSecondPrice()); .setSecondFixedPrice(sku.getSubCommissionSecondPrice());
} }
} }

View File

@ -23,7 +23,7 @@ import java.time.LocalDateTime;
@Builder @Builder
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class TradeBrokerageRecordDO extends BaseDO { public class BrokerageRecordDO extends BaseDO {
/** /**
* 编号 * 编号

View File

@ -8,7 +8,6 @@ import lombok.*;
import java.time.LocalDateTime; import java.time.LocalDateTime;
// TODO @疯狂因为独立了表是不是可以把字段的 brokerage 去掉了哈
/** /**
* 分销用户 DO * 分销用户 DO
* *
@ -22,25 +21,26 @@ import java.time.LocalDateTime;
@Builder @Builder
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class TradeBrokerageUserDO extends BaseDO { public class BrokerageUserDO extends BaseDO {
/** /**
* 用户编号 * 用户编号
* <p>
* 对应 MemberUserDO id 字段
*/ */
@TableId @TableId
private Long id; private Long id;
// TODO @疯狂貌似改成 bindUserId更明确
/** /**
* 推广员编号 * 推广员编号
* * <p>
* 关联 MemberUserDO id 字段 * 关联 MemberUserDO id 字段
*/ */
private Long brokerageUserId; private Long bindUserId;
/** /**
* 推广员绑定时间 * 推广员绑定时间
*/ */
private LocalDateTime brokerageBindTime; private LocalDateTime bindUserTime;
/** /**
* 推广资格 * 推广资格
@ -54,10 +54,10 @@ public class TradeBrokerageUserDO extends BaseDO {
/** /**
* 可用佣金 * 可用佣金
*/ */
private Integer brokeragePrice; private Integer price;
/** /**
* 冻结佣金 * 冻结佣金
*/ */
private Integer frozenBrokeragePrice; private Integer frozenPrice;
} }

View File

@ -0,0 +1,55 @@
package cn.iocoder.yudao.module.trade.dal.mysql.brokerage.record;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordPageReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.BrokerageRecordDO;
import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserBrokerageSummaryBO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.time.LocalDateTime;
import java.util.List;
/**
* 佣金记录 Mapper
*
* @author owen
*/
@Mapper
public interface BrokerageRecordMapper extends BaseMapperX<BrokerageRecordDO> {
default PageResult<BrokerageRecordDO> selectPage(BrokerageRecordPageReqVO reqVO) {
return selectPage(reqVO, new LambdaQueryWrapperX<BrokerageRecordDO>()
.eqIfPresent(BrokerageRecordDO::getUserId, reqVO.getUserId())
.eqIfPresent(BrokerageRecordDO::getBizType, reqVO.getBizType())
.eqIfPresent(BrokerageRecordDO::getStatus, reqVO.getStatus())
.betweenIfPresent(BrokerageRecordDO::getCreateTime, reqVO.getCreateTime())
.orderByDesc(BrokerageRecordDO::getId));
}
default List<BrokerageRecordDO> selectListByStatusAndUnfreezeTimeLt(Integer status, LocalDateTime unfreezeTime) {
return selectList(new LambdaQueryWrapper<BrokerageRecordDO>()
.eq(BrokerageRecordDO::getStatus, status)
.lt(BrokerageRecordDO::getUnfreezeTime, unfreezeTime));
}
default int updateByIdAndStatus(Integer id, Integer status, BrokerageRecordDO updateObj) {
return update(updateObj, new LambdaQueryWrapper<BrokerageRecordDO>()
.eq(BrokerageRecordDO::getId, id)
.eq(BrokerageRecordDO::getStatus, status));
}
default BrokerageRecordDO selectByBizTypeAndBizId(Integer bizType, String bizId) {
return selectOne(BrokerageRecordDO::getBizType, bizType,
BrokerageRecordDO::getBizId, bizId);
}
@Select("select count(1), sum(price) from trade_brokerage_record where user_id = #{userId} and biz_type = #{bizType} and status = #{status}")
UserBrokerageSummaryBO selectCountAndSumPriceByUserIdAndBizTypeAndStatus(@Param("userId") Long userId,
@Param("bizType") Integer bizType,
@Param("status") Integer status);
}

View File

@ -1,49 +0,0 @@
package cn.iocoder.yudao.module.trade.dal.mysql.brokerage.record;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.TradeBrokerageRecordPageReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.TradeBrokerageRecordDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Mapper;
import java.time.LocalDateTime;
import java.util.List;
/**
* 佣金记录 Mapper
*
* @author owen
*/
@Mapper
public interface TradeBrokerageRecordMapper extends BaseMapperX<TradeBrokerageRecordDO> {
default PageResult<TradeBrokerageRecordDO> selectPage(TradeBrokerageRecordPageReqVO reqVO) {
return selectPage(reqVO, new LambdaQueryWrapperX<TradeBrokerageRecordDO>()
.eqIfPresent(TradeBrokerageRecordDO::getUserId, reqVO.getUserId())
.eqIfPresent(TradeBrokerageRecordDO::getBizType, reqVO.getBizType())
.eqIfPresent(TradeBrokerageRecordDO::getStatus, reqVO.getStatus())
.betweenIfPresent(TradeBrokerageRecordDO::getCreateTime, reqVO.getCreateTime())
.orderByDesc(TradeBrokerageRecordDO::getId));
}
default List<TradeBrokerageRecordDO> selectListByStatusAndUnfreezeTimeLt(Integer status, LocalDateTime unfreezeTime) {
return selectList(new LambdaQueryWrapper<TradeBrokerageRecordDO>()
.eq(TradeBrokerageRecordDO::getStatus, status)
.lt(TradeBrokerageRecordDO::getUnfreezeTime, unfreezeTime));
}
default int updateByIdAndStatus(Integer id, Integer status, TradeBrokerageRecordDO updateObj) {
return update(updateObj, new LambdaQueryWrapper<TradeBrokerageRecordDO>()
.eq(TradeBrokerageRecordDO::getId, id)
.eq(TradeBrokerageRecordDO::getStatus, status));
}
// TODO @疯狂userId???
default TradeBrokerageRecordDO selectByUserIdAndBizTypeAndBizId(Integer bizType, String bizId) {
return selectOne(TradeBrokerageRecordDO::getBizType, bizType,
TradeBrokerageRecordDO::getBizId, bizId);
}
}

View File

@ -0,0 +1,114 @@
package cn.iocoder.yudao.module.trade.dal.mysql.brokerage.user;
import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.BrokerageUserPageReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 分销用户 Mapper
*
* @author owen
*/
@Mapper
public interface BrokerageUserMapper extends BaseMapperX<BrokerageUserDO> {
default PageResult<BrokerageUserDO> selectPage(BrokerageUserPageReqVO reqVO) {
return selectPage(reqVO, new LambdaQueryWrapperX<BrokerageUserDO>()
.eqIfPresent(BrokerageUserDO::getBindUserId, reqVO.getBindUserId())
.eqIfPresent(BrokerageUserDO::getBrokerageEnabled, reqVO.getBrokerageEnabled())
.betweenIfPresent(BrokerageUserDO::getCreateTime, reqVO.getCreateTime())
.orderByDesc(BrokerageUserDO::getId));
}
/**
* 更新用户可用佣金增加
*
* @param id 用户编号
* @param incrCount 增加佣金正数
*/
default void updatePriceIncr(Long id, Integer incrCount) {
Assert.isTrue(incrCount > 0);
LambdaUpdateWrapper<BrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<BrokerageUserDO>()
.setSql(" price = price + " + incrCount)
.eq(BrokerageUserDO::getId, id);
update(null, lambdaUpdateWrapper);
}
/**
* 更新用户可用佣金减少
* 注意理论上佣金可能已经提现这时会扣出负数确保平台不会造成损失
*
* @param id 用户编号
* @param incrCount 增加佣金负数
*/
default void updatePriceDecr(Long id, Integer incrCount) {
Assert.isTrue(incrCount < 0);
LambdaUpdateWrapper<BrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<BrokerageUserDO>()
.setSql(" price = price + " + incrCount) // 负数所以使用 +
.eq(BrokerageUserDO::getId, id);
update(null, lambdaUpdateWrapper);
}
/**
* 更新用户冻结佣金增加
*
* @param id 用户编号
* @param incrCount 增加冻结佣金正数
*/
default void updateFrozenPriceIncr(Long id, Integer incrCount) {
Assert.isTrue(incrCount > 0);
LambdaUpdateWrapper<BrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<BrokerageUserDO>()
.setSql(" frozen_price = frozen_price + " + incrCount)
.eq(BrokerageUserDO::getId, id);
update(null, lambdaUpdateWrapper);
}
/**
* 更新用户冻结佣金减少
* 注意理论上冻结佣金可能已经解冻这时会扣出负数确保平台不会造成损失
*
* @param id 用户编号
* @param incrCount 减少冻结佣金负数
*/
default void updateFrozenPriceDecr(Long id, Integer incrCount) {
Assert.isTrue(incrCount < 0);
LambdaUpdateWrapper<BrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<BrokerageUserDO>()
.setSql(" frozen_price = frozen_price + " + incrCount) // 负数所以使用 +
.eq(BrokerageUserDO::getId, id);
update(null, lambdaUpdateWrapper);
}
/**
* 更新用户冻结佣金减少, 更新用户佣金增加
*
* @param id 用户编号
* @param incrCount 减少冻结佣金负数
* @return 更新条数
*/
default int updateFrozenPriceDecrAndPriceIncr(Long id, Integer incrCount) {
Assert.isTrue(incrCount < 0);
LambdaUpdateWrapper<BrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<BrokerageUserDO>()
.setSql(" frozen_price = frozen_price + " + incrCount + // 负数所以使用 +
", price = price + " + -incrCount) // 负数所以使用 -
.eq(BrokerageUserDO::getId, id)
.ge(BrokerageUserDO::getFrozenPrice, -incrCount); // cas 逻辑
return update(null, lambdaUpdateWrapper);
}
default void updateBindUserIdAndBindUserTimeToNull(Long id) {
update(null, new LambdaUpdateWrapper<BrokerageUserDO>()
.eq(BrokerageUserDO::getId, id)
.set(BrokerageUserDO::getBindUserId, null).set(BrokerageUserDO::getBindUserTime, null));
}
default void updateEnabledFalseAndBrokerageTimeToNull(Long id) {
update(null, new LambdaUpdateWrapper<BrokerageUserDO>()
.eq(BrokerageUserDO::getId, id)
.set(BrokerageUserDO::getBrokerageEnabled, false).set(BrokerageUserDO::getBrokerageTime, null));
}
}

View File

@ -1,103 +0,0 @@
package cn.iocoder.yudao.module.trade.dal.mysql.brokerage.user;
import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.TradeBrokerageUserPageReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.TradeBrokerageUserDO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 分销用户 Mapper
*
* @author owen
*/
@Mapper
public interface TradeBrokerageUserMapper extends BaseMapperX<TradeBrokerageUserDO> {
default PageResult<TradeBrokerageUserDO> selectPage(TradeBrokerageUserPageReqVO reqVO) {
return selectPage(reqVO, new LambdaQueryWrapperX<TradeBrokerageUserDO>()
.eqIfPresent(TradeBrokerageUserDO::getBrokerageUserId, reqVO.getBrokerageUserId())
.eqIfPresent(TradeBrokerageUserDO::getBrokerageEnabled, reqVO.getBrokerageEnabled())
.betweenIfPresent(TradeBrokerageUserDO::getCreateTime, reqVO.getCreateTime())
.orderByDesc(TradeBrokerageUserDO::getId));
}
/**
* 更新用户可用佣金增加
*
* @param id 用户编号
* @param incrCount 增加佣金正数
*/
default void updateBrokeragePriceIncr(Long id, int incrCount) {
Assert.isTrue(incrCount > 0);
LambdaUpdateWrapper<TradeBrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<TradeBrokerageUserDO>()
.setSql(" brokerage_price = brokerage_price + " + incrCount)
.eq(TradeBrokerageUserDO::getId, id);
update(null, lambdaUpdateWrapper);
}
/**
* 更新用户可用佣金减少
* 注意理论上佣金可能已经提现这时会扣出负数确保平台不会造成损失
*
* @param id 用户编号
* @param incrCount 增加佣金负数
*/
default void updateBrokeragePriceDecr(Long id, int incrCount) {
Assert.isTrue(incrCount < 0);
LambdaUpdateWrapper<TradeBrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<TradeBrokerageUserDO>()
.setSql(" brokerage_price = brokerage_price + " + incrCount) // 负数所以使用 +
.eq(TradeBrokerageUserDO::getId, id);
update(null, lambdaUpdateWrapper);
}
/**
* 更新用户冻结佣金增加
*
* @param id 用户编号
* @param incrCount 增加冻结佣金正数
*/
default void updateFrozenBrokeragePriceIncr(Long id, int incrCount) {
Assert.isTrue(incrCount > 0);
LambdaUpdateWrapper<TradeBrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<TradeBrokerageUserDO>()
.setSql(" frozen_brokerage_price = frozen_brokerage_price + " + incrCount)
.eq(TradeBrokerageUserDO::getId, id);
update(null, lambdaUpdateWrapper);
}
/**
* 更新用户冻结佣金减少
* 注意理论上冻结佣金可能已经解冻这时会扣出负数确保平台不会造成损失
*
* @param id 用户编号
* @param incrCount 减少冻结佣金负数
*/
default void updateFrozenBrokeragePriceDecr(Long id, int incrCount) {
Assert.isTrue(incrCount < 0);
LambdaUpdateWrapper<TradeBrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<TradeBrokerageUserDO>()
.setSql(" frozen_brokerage_price = frozen_brokerage_price + " + incrCount) // 负数所以使用 +
.eq(TradeBrokerageUserDO::getId, id);
update(null, lambdaUpdateWrapper);
}
/**
* 更新用户冻结佣金减少, 更新用户佣金增加
*
* @param id 用户编号
* @param incrCount 减少冻结佣金负数
* @return 更新条数
*/
default int updateFrozenBrokeragePriceDecrAndBrokeragePriceIncr(Long id, int incrCount) {
Assert.isTrue(incrCount < 0);
LambdaUpdateWrapper<TradeBrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<TradeBrokerageUserDO>()
.setSql(" frozen_brokerage_price = frozen_brokerage_price + " + incrCount + // 负数所以使用 +
", brokerage_price = brokerage_price + " + -incrCount) // 负数所以使用 -
.eq(TradeBrokerageUserDO::getId, id)
.ge(TradeBrokerageUserDO::getFrozenBrokeragePrice, -incrCount); // cas 逻辑
return update(null, lambdaUpdateWrapper);
}
}

View File

@ -3,7 +3,7 @@ package cn.iocoder.yudao.module.trade.job.brokerage;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler; import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob; import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.trade.service.brokerage.record.TradeBrokerageRecordService; import cn.iocoder.yudao.module.trade.service.brokerage.record.BrokerageRecordService;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -15,14 +15,14 @@ import javax.annotation.Resource;
*/ */
@Component @Component
@TenantJob @TenantJob
public class TradeBrokerageRecordUnfreezeJob implements JobHandler { public class BrokerageRecordUnfreezeJob implements JobHandler {
@Resource @Resource
private TradeBrokerageRecordService tradeBrokerageRecordService; private BrokerageRecordService brokerageRecordService;
@Override @Override
public String execute(String param) { public String execute(String param) {
int count = tradeBrokerageRecordService.unfreezeRecord(); int count = brokerageRecordService.unfreezeRecord();
return StrUtil.format("解冻佣金 {} 个", count); return StrUtil.format("解冻佣金 {} 个", count);
} }

View File

@ -0,0 +1,37 @@
package cn.iocoder.yudao.module.trade.service.brokerage.bo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank;
/**
* 佣金 增加 Request BO
*
* @author owen
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BrokerageAddReqBO {
/**
* 业务编号
*/
@NotBlank(message = "业务编号不能为空")
private String bizId;
/**
* 佣金基数
*/
private Integer basePrice;
/**
* 一级佣金固定
*/
private Integer firstFixedPrice;
/**
* 二级佣金固定
*/
private Integer secondFixedPrice;
}

View File

@ -0,0 +1,24 @@
package cn.iocoder.yudao.module.trade.service.brokerage.bo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 用户佣金合计 BO
*
* @author owen
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserBrokerageSummaryBO {
/**
* 佣金数量
*/
private Integer count;
/**
* 佣金总额
*/
private Integer price;
}

View File

@ -0,0 +1,70 @@
package cn.iocoder.yudao.module.trade.service.brokerage.record;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordPageReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.BrokerageRecordDO;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
import cn.iocoder.yudao.module.trade.service.brokerage.bo.BrokerageAddReqBO;
import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserBrokerageSummaryBO;
import javax.validation.Valid;
import java.util.List;
/**
* 佣金记录 Service 接口
*
* @author owen
*/
public interface BrokerageRecordService {
/**
* 获得佣金记录
*
* @param id 编号
* @return 佣金记录
*/
BrokerageRecordDO getBrokerageRecord(Integer id);
/**
* 获得佣金记录分页
*
* @param pageReqVO 分页查询
* @return 佣金记录分页
*/
PageResult<BrokerageRecordDO> getBrokerageRecordPage(BrokerageRecordPageReqVO pageReqVO);
/**
* 增加佣金
*
* @param userId 会员编号
* @param bizType 业务类型
* @param list 请求参数列表
*/
void addBrokerage(Long userId, BrokerageRecordBizTypeEnum bizType, @Valid List<BrokerageAddReqBO> list);
/**
* 取消佣金将佣金记录状态修改为已失效
*
* @param userId 会员编号
* @param bizType 业务类型
* @param bizId 业务编号
*/
void cancelBrokerage(Long userId, BrokerageRecordBizTypeEnum bizType, String bizId);
/**
* 解冻佣金将待结算的佣金记录状态修改为已结算
*
* @return 解冻佣金的数量
*/
int unfreezeRecord();
/**
* 汇总用户佣金
*
* @param userId 用户编号
* @param bizType 业务类型
* @param status 佣金状态
* @return 用户佣金汇总
*/
UserBrokerageSummaryBO summaryByUserIdAndBizTypeAndStatus(Long userId, Integer bizType, Integer status);
}

View File

@ -0,0 +1,235 @@
package cn.iocoder.yudao.module.trade.service.brokerage.record;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordPageReqVO;
import cn.iocoder.yudao.module.trade.convert.brokerage.record.BrokerageRecordConvert;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.BrokerageRecordDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.config.TradeConfigDO;
import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.record.BrokerageRecordMapper;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordStatusEnum;
import cn.iocoder.yudao.module.trade.service.brokerage.bo.BrokerageAddReqBO;
import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserBrokerageSummaryBO;
import cn.iocoder.yudao.module.trade.service.brokerage.user.BrokerageUserService;
import cn.iocoder.yudao.module.trade.service.config.TradeConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
/**
* 佣金记录 Service 实现类
*
* @author owen
*/
@Slf4j
@Service
@Validated
public class BrokerageRecordServiceImpl implements BrokerageRecordService {
@Resource
private BrokerageRecordMapper brokerageRecordMapper;
@Resource
private TradeConfigService tradeConfigService;
@Resource
private BrokerageUserService brokerageUserService;
@Override
public BrokerageRecordDO getBrokerageRecord(Integer id) {
return brokerageRecordMapper.selectById(id);
}
@Override
public PageResult<BrokerageRecordDO> getBrokerageRecordPage(BrokerageRecordPageReqVO pageReqVO) {
return brokerageRecordMapper.selectPage(pageReqVO);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void addBrokerage(Long userId, BrokerageRecordBizTypeEnum bizType, List<BrokerageAddReqBO> list) {
TradeConfigDO memberConfig = tradeConfigService.getTradeConfig();
// 0 未启用分销功能
if (memberConfig == null || !BooleanUtil.isTrue(memberConfig.getBrokerageEnabled())) {
log.warn("[addBrokerage][增加佣金失败brokerageEnabled 未配置userId({})", userId);
return;
}
// 1.1 获得一级推广人
BrokerageUserDO firstUser = brokerageUserService.getBindBrokerageUser(userId);
if (firstUser == null || !BooleanUtil.isTrue(firstUser.getBrokerageEnabled())) {
return;
}
// 1.2 计算一级分佣
addBrokerage(firstUser, list, memberConfig.getBrokerageFrozenDays(), memberConfig.getBrokerageFirstPercent(), BrokerageAddReqBO::getFirstFixedPrice, bizType);
// 2.1 获得二级推广员
if (firstUser.getBindUserId() == null) {
return;
}
BrokerageUserDO secondUser = brokerageUserService.getBrokerageUser(firstUser.getBindUserId());
if (secondUser == null || !BooleanUtil.isTrue(secondUser.getBrokerageEnabled())) {
return;
}
// 2.2 计算二级分佣
addBrokerage(secondUser, list, memberConfig.getBrokerageFrozenDays(), memberConfig.getBrokerageSecondPercent(), BrokerageAddReqBO::getSecondFixedPrice, bizType);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void cancelBrokerage(Long userId, BrokerageRecordBizTypeEnum bizType, String bizId) {
BrokerageRecordDO record = brokerageRecordMapper.selectByBizTypeAndBizId(bizType.getType(), bizId);
if (record == null || ObjectUtil.notEqual(record.getUserId(), userId)) {
log.error("[cancelBrokerage][userId({})][bizId({}) 更新为已失效失败:记录不存在]", userId, bizId);
return;
}
// 1. 更新佣金记录为已失效
BrokerageRecordDO updateObj = new BrokerageRecordDO().setStatus(BrokerageRecordStatusEnum.CANCEL.getStatus());
int updateRows = brokerageRecordMapper.updateByIdAndStatus(record.getId(), record.getStatus(), updateObj);
if (updateRows == 0) {
log.error("[cancelBrokerage][record({}) 更新为已失效失败]", record.getId());
return;
}
// 2. 更新用户的佣金
if (BrokerageRecordStatusEnum.WAIT_SETTLEMENT.getStatus().equals(record.getStatus())) {
brokerageUserService.updateUserFrozenPrice(userId, -record.getPrice());
} else if (BrokerageRecordStatusEnum.SETTLEMENT.getStatus().equals(record.getStatus())) {
brokerageUserService.updateUserPrice(userId, -record.getPrice());
}
}
/**
* 计算佣金
*
* @param basePrice 佣金基数
* @param percent 佣金比例
* @param fixedPrice 固定佣金
* @return 佣金
*/
int calculatePrice(Integer basePrice, Integer percent, Integer fixedPrice) {
// 1. 优先使用固定佣金
if (fixedPrice != null && fixedPrice > 0) {
return ObjectUtil.defaultIfNull(fixedPrice, 0);
}
// 2. 根据比例计算佣金
if (basePrice != null && basePrice > 0 && percent != null && percent > 0) {
return MoneyUtils.calculateRatePriceFloor(basePrice, Double.valueOf(percent));
}
return 0;
}
/**
* 增加用户佣金
*
* @param user 用户
* @param list 佣金增加参数列表
* @param brokerageFrozenDays 冻结天数
* @param brokeragePercent 佣金比例
* @param fixedPriceFun 固定佣金
* @param bizType 业务类型
*/
private void addBrokerage(BrokerageUserDO user, List<BrokerageAddReqBO> list, Integer brokerageFrozenDays,
Integer brokeragePercent, Function<BrokerageAddReqBO, Integer> fixedPriceFun,
BrokerageRecordBizTypeEnum bizType) {
// 1.1 处理冻结时间
LocalDateTime unfreezeTime = null;
if (brokerageFrozenDays != null && brokerageFrozenDays > 0) {
unfreezeTime = LocalDateTime.now().plusDays(brokerageFrozenDays);
}
// 1.2 计算分佣
int totalBrokerage = 0;
List<BrokerageRecordDO> records = new ArrayList<>();
for (BrokerageAddReqBO item : list) {
int brokeragePerItem = calculatePrice(item.getBasePrice(), brokeragePercent, fixedPriceFun.apply(item));
if (brokeragePerItem <= 0) {
continue;
}
records.add(BrokerageRecordConvert.INSTANCE.convert(user, bizType, item.getBizId(),
brokerageFrozenDays, brokeragePerItem, unfreezeTime, bizType.getTitle()));
totalBrokerage += brokeragePerItem;
}
if (CollUtil.isEmpty(records)) {
return;
}
// 1.3 保存佣金记录
brokerageRecordMapper.insertBatch(records);
// 2. 更新用户佣金
if (brokerageFrozenDays != null && brokerageFrozenDays > 0) { // 更新用户冻结佣金
brokerageUserService.updateUserFrozenPrice(user.getId(), totalBrokerage);
} else { // 更新用户可用佣金
brokerageUserService.updateUserPrice(user.getId(), totalBrokerage);
}
}
@Override
public int unfreezeRecord() {
// 1. 查询待结算的佣金记录
List<BrokerageRecordDO> records = brokerageRecordMapper.selectListByStatusAndUnfreezeTimeLt(
BrokerageRecordStatusEnum.WAIT_SETTLEMENT.getStatus(), LocalDateTime.now());
if (CollUtil.isEmpty(records)) {
return 0;
}
// 2. 遍历执行
int count = 0;
for (BrokerageRecordDO record : records) {
try {
boolean success = getSelf().unfreezeRecord(record);
if (success) {
count++;
}
} catch (Exception e) {
log.error("[unfreezeRecord][record({}) 更新为已结算失败]", record.getId(), e);
}
}
return count;
}
@Override
public UserBrokerageSummaryBO summaryByUserIdAndBizTypeAndStatus(Long userId, Integer bizType, Integer status) {
UserBrokerageSummaryBO summaryBO = brokerageRecordMapper.selectCountAndSumPriceByUserIdAndBizTypeAndStatus(userId, bizType, status);
return summaryBO == null ? new UserBrokerageSummaryBO(0, 0) : summaryBO;
}
@Transactional(rollbackFor = Exception.class)
public boolean unfreezeRecord(BrokerageRecordDO record) {
// 更新记录状态
BrokerageRecordDO updateObj = new BrokerageRecordDO()
.setStatus(BrokerageRecordStatusEnum.SETTLEMENT.getStatus())
.setUnfreezeTime(LocalDateTime.now());
int updateRows = brokerageRecordMapper.updateByIdAndStatus(record.getId(), record.getStatus(), updateObj);
if (updateRows == 0) {
log.error("[unfreezeRecord][record({}) 更新为已结算失败]", record.getId());
return false;
}
// 更新用户冻结佣金
brokerageUserService.updateFrozenPriceDecrAndPriceIncr(record.getUserId(), -record.getPrice());
log.info("[unfreezeRecord][record({}) 更新为已结算成功]", record.getId());
return true;
}
/**
* 获得自身的代理对象解决 AOP 生效问题
*
* @return 自己
*/
private BrokerageRecordServiceImpl getSelf() {
return SpringUtil.getBean(getClass());
}
}

View File

@ -1,58 +0,0 @@
package cn.iocoder.yudao.module.trade.service.brokerage.record;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.TradeBrokerageRecordDO;
import cn.iocoder.yudao.module.trade.service.brokerage.record.bo.BrokerageAddReqBO;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.TradeBrokerageRecordPageReqVO;
import java.util.List;
/**
* 佣金记录 Service 接口
*
* @author owen
*/
public interface TradeBrokerageRecordService {
/**
* 获得佣金记录
*
* @param id 编号
* @return 佣金记录
*/
TradeBrokerageRecordDO getBrokerageRecord(Integer id);
/**
* 获得佣金记录分页
*
* @param pageReqVO 分页查询
* @return 佣金记录分页
*/
PageResult<TradeBrokerageRecordDO> getBrokerageRecordPage(TradeBrokerageRecordPageReqVO pageReqVO);
// TODO @疯狂是不是 bizType 得加下方便未来拓展哈
/**
* 增加佣金
*
* @param userId 会员编号
* @param list 请求参数列表
*/
void addBrokerage(Long userId, List<BrokerageAddReqBO> list);
// TODO @疯狂是不是 bizType 得加下方便未来拓展哈
/**
* 取消佣金将佣金记录状态修改为已失效
*
* @param userId 会员编号
* @param bizId 业务编号
*/
void cancelBrokerage(Long userId, String bizId);
/**
* 解冻佣金将待结算的佣金记录状态修改为已结算
*
* @return 解冻佣金的数量
*/
int unfreezeRecord();
}

View File

@ -1,233 +0,0 @@
package cn.iocoder.yudao.module.trade.service.brokerage.record;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.TradeBrokerageRecordPageReqVO;
import cn.iocoder.yudao.module.trade.convert.brokerage.record.TradeBrokerageRecordConvert;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.TradeBrokerageRecordDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.TradeBrokerageUserDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.config.TradeConfigDO;
import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.record.TradeBrokerageRecordMapper;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordStatusEnum;
import cn.iocoder.yudao.module.trade.service.brokerage.record.bo.BrokerageAddReqBO;
import cn.iocoder.yudao.module.trade.service.brokerage.user.TradeBrokerageUserService;
import cn.iocoder.yudao.module.trade.service.config.TradeConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Resource;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
/**
* 佣金记录 Service 实现类
*
* @author owen
*/
@Slf4j
@Service
@Validated
public class TradeBrokerageRecordServiceImpl implements TradeBrokerageRecordService {
@Resource
private TradeBrokerageRecordMapper tradeBrokerageRecordMapper;
@Resource
private TradeConfigService tradeConfigService;
@Resource
private TradeBrokerageUserService tradeBrokerageUserService;
@Override
public TradeBrokerageRecordDO getBrokerageRecord(Integer id) {
return tradeBrokerageRecordMapper.selectById(id);
}
@Override
public PageResult<TradeBrokerageRecordDO> getBrokerageRecordPage(TradeBrokerageRecordPageReqVO pageReqVO) {
return tradeBrokerageRecordMapper.selectPage(pageReqVO);
}
// TODO @疯狂buyerId 要不要统一改成 userId
@Override
@Transactional(rollbackFor = Exception.class)
public void addBrokerage(Long buyerId, List<BrokerageAddReqBO> list) {
TradeConfigDO memberConfig = tradeConfigService.getTradeConfig();
// 0 未启用分销功能
// TODO @疯狂BooleanUtil.isFalse()逻辑里尽量不做 !取反这样要多思考一层
if (memberConfig == null || !BooleanUtil.isTrue(memberConfig.getBrokerageEnabled())) {
log.warn("[addBrokerage][增加佣金失败brokerageEnabled 未配置buyerId({})", buyerId);
return;
}
// 1.1 获得一级推广人
TradeBrokerageUserDO firstUser = tradeBrokerageUserService.getInviteBrokerageUser(buyerId);
if (firstUser == null || !BooleanUtil.isTrue(firstUser.getBrokerageEnabled())) {
return;
}
// 1.2 计算一级分佣 // TODO 疯狂类似 1.1 1.2 的空行可以去掉一般在代码里的空行是为了逻辑分块但是分块如果太多就会导致代码里都是空行哈
addBrokerage(firstUser, list, memberConfig.getBrokerageFrozenDays(), memberConfig.getBrokerageFirstPercent(), BrokerageAddReqBO::getSkuFirstBrokeragePrice);
// 2.1 获得二级推广员
// TODO @疯狂这里可以加个 firstUser.getBrokerageUserId() 为空的判断 return
TradeBrokerageUserDO secondUser = tradeBrokerageUserService.getBrokerageUser(firstUser.getBrokerageUserId());
if (secondUser == null || !BooleanUtil.isTrue(secondUser.getBrokerageEnabled())) {
return;
}
// 2.2 计算二级分佣
addBrokerage(secondUser, list, memberConfig.getBrokerageFrozenDays(), memberConfig.getBrokerageSecondPercent(), BrokerageAddReqBO::getSkuSecondBrokeragePrice);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void cancelBrokerage(Long userId, String bizId) {
TradeBrokerageRecordDO record = tradeBrokerageRecordMapper.selectByUserIdAndBizTypeAndBizId(BrokerageRecordBizTypeEnum.ORDER.getType(), bizId);
if (record == null || ObjectUtil.notEqual(record.getUserId(), userId)) {
log.error("[cancelBrokerage][userId({})][bizId({}) 更新为已失效失败:记录不存在]", userId, bizId);
return;
}
// 1. 更新佣金记录为已失效
TradeBrokerageRecordDO updateObj = new TradeBrokerageRecordDO().setStatus(BrokerageRecordStatusEnum.CANCEL.getStatus());
int updateRows = tradeBrokerageRecordMapper.updateByIdAndStatus(record.getId(), record.getStatus(), updateObj);
if (updateRows == 0) {
log.error("[cancelBrokerage][record({}) 更新为已失效失败]", record.getId());
return;
}
// 2. 更新用户的佣金
if (BrokerageRecordStatusEnum.WAIT_SETTLEMENT.getStatus().equals(record.getStatus())) {
tradeBrokerageUserService.updateUserFrozenBrokeragePrice(userId, -record.getPrice());
} else if (BrokerageRecordStatusEnum.SETTLEMENT.getStatus().equals(record.getStatus())) {
tradeBrokerageUserService.updateUserBrokeragePrice(userId, -record.getPrice());
}
}
// TODO @疯狂是不是 calculateBrokeragePrice
/**
* 计算佣金
*
* @param payPrice 订单支付金额
* @param percent 商品 SKU 设置的佣金
* @param skuBrokeragePrice 商品的佣金
* @return 佣金
*/
int calculateBrokerage(Integer payPrice, Integer percent, Integer skuBrokeragePrice) {
// 1. 优先使用商品 SKU 设置的佣金
if (skuBrokeragePrice != null && skuBrokeragePrice > 0) {
return ObjectUtil.defaultIfNull(skuBrokeragePrice, 0);
}
// 2. 根据订单支付金额计算佣金
// TODO @疯狂要不要把 MoneyUtils 抽到 common 然后这里也使用这个类的方法
if (payPrice != null && payPrice > 0 && percent != null && percent > 0) {
return NumberUtil.div(NumberUtil.mul(payPrice, percent), 100, 0, RoundingMode.DOWN).intValue();
}
return 0;
}
/**
* 增加用户佣金
*
* @param user 用户
* @param list 佣金增加参数列表
* @param brokerageFrozenDays 冻结天数
* @param brokeragePercent 佣金比例
* @param skuBrokeragePriceFun 商品 SKU 设置的佣金
*/
private void addBrokerage(TradeBrokerageUserDO user, List<BrokerageAddReqBO> list, Integer brokerageFrozenDays,
Integer brokeragePercent, Function<BrokerageAddReqBO, Integer> skuBrokeragePriceFun) {
// 1.1 处理冻结时间
// TODO @疯狂是不是 brokerageFrozenDays != null && brokerageFrozenDays > 0 然后计算更简洁一点
brokerageFrozenDays = ObjectUtil.defaultIfNull(brokerageFrozenDays, 0);
LocalDateTime unfreezeTime = null;
if (brokerageFrozenDays > 0) {
unfreezeTime = LocalDateTime.now().plusDays(brokerageFrozenDays);
}
// 1.2 计算分佣
int totalBrokerage = 0;
List<TradeBrokerageRecordDO> records = new ArrayList<>();
for (BrokerageAddReqBO item : list) {
int brokeragePerItem = calculateBrokerage(item.getPayPrice(), brokeragePercent, skuBrokeragePriceFun.apply(item));
// TODO @疯狂其实可以 brokeragePerItem <= 0 continue这样 { 层级更少代码更简洁}
if (brokeragePerItem > 0) {
int brokerage = brokeragePerItem * item.getCount();
records.add(TradeBrokerageRecordConvert.INSTANCE.convert(user, item.getBizId(), brokerageFrozenDays, brokerage, unfreezeTime));
totalBrokerage += brokerage;
}
}
if (CollUtil.isEmpty(records)) {
return;
}
// 1.3 保存佣金记录
tradeBrokerageRecordMapper.insertBatch(records);
// 2. 更新用户佣金
if (brokerageFrozenDays > 0) { // 更新用户冻结佣金
tradeBrokerageUserService.updateUserFrozenBrokeragePrice(user.getId(), totalBrokerage);
} else { // 更新用户可用佣金
tradeBrokerageUserService.updateUserBrokeragePrice(user.getId(), totalBrokerage);
}
}
@Override
public int unfreezeRecord() {
// 1. 查询待结算的佣金记录
List<TradeBrokerageRecordDO> records = tradeBrokerageRecordMapper.selectListByStatusAndUnfreezeTimeLt(
BrokerageRecordStatusEnum.WAIT_SETTLEMENT.getStatus(), LocalDateTime.now());
if (CollUtil.isEmpty(records)) {
return 0;
}
// 2. 遍历执行
int count = 0;
for (TradeBrokerageRecordDO record : records) {
try {
boolean success = getSelf().unfreezeRecord(record);
if (success) {
count++;
}
} catch (Exception e) {
log.error("[unfreezeRecord][record({}) 更新为已结算失败]", record.getId(), e);
}
}
return count;
}
@Transactional(rollbackFor = Exception.class)
public boolean unfreezeRecord(TradeBrokerageRecordDO record) {
// 更新记录状态
TradeBrokerageRecordDO updateObj = new TradeBrokerageRecordDO()
.setStatus(BrokerageRecordStatusEnum.SETTLEMENT.getStatus())
.setUnfreezeTime(LocalDateTime.now());
int updateRows = tradeBrokerageRecordMapper.updateByIdAndStatus(record.getId(), record.getStatus(), updateObj);
if (updateRows == 0) {
log.error("[unfreezeRecord][record({}) 更新为已结算失败]", record.getId());
return false;
}
// 更新用户冻结佣金
tradeBrokerageUserService.updateFrozenBrokeragePriceDecrAndBrokeragePriceIncr(record.getUserId(), -record.getPrice());
log.info("[unfreezeRecord][record({}) 更新为已结算成功]", record.getId());
return true;
}
/**
* 获得自身的代理对象解决 AOP 生效问题
*
* @return 自己
*/
private TradeBrokerageRecordServiceImpl getSelf() {
return SpringUtil.getBean(getClass());
}
}

View File

@ -1,43 +0,0 @@
package cn.iocoder.yudao.module.trade.service.brokerage.record.bo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
// TODO @疯狂要不要 service 还是拍平就是都放在 brokerage 包下然后 bo 里面稍微分分
/**
* 佣金 增加 Request BO
*
* @author owen
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BrokerageAddReqBO {
// TODO @疯狂bo 的话也可以考虑加下 @Validated 注解校验下参数防御性下哈虽然不一定用的到
/**
* 业务ID
*/
private String bizId;
// TODO @疯狂不需要 payPrice count计算成 price 就好啦
/**
* 商品支付价格
*/
private Integer payPrice;
// TODO @疯狂可以去掉 sku 更抽象一点
/**
* SKU 一级佣金
*/
private Integer skuFirstBrokeragePrice;
/**
* SKU 二级佣金
*/
private Integer skuSecondBrokeragePrice;
/**
* 购买数量
*/
private Integer count;
}

View File

@ -0,0 +1,106 @@
package cn.iocoder.yudao.module.trade.service.brokerage.user;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.BrokerageUserPageReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
import java.util.Collection;
import java.util.List;
/**
* 分销用户 Service 接口
*
* @author owen
*/
public interface BrokerageUserService {
/**
* 获得分销用户
*
* @param id 编号
* @return 分销用户
*/
BrokerageUserDO getBrokerageUser(Long id);
/**
* 获得分销用户列表
*
* @param ids 编号
* @return 分销用户列表
*/
List<BrokerageUserDO> getBrokerageUserList(Collection<Long> ids);
/**
* 获得分销用户分页
*
* @param pageReqVO 分页查询
* @return 分销用户分页
*/
PageResult<BrokerageUserDO> getBrokerageUserPage(BrokerageUserPageReqVO pageReqVO);
/**
* 修改推广员编号
*
* @param id 用户编号
* @param bindUserId 推广员编号
*/
void updateBrokerageUserId(Long id, Long bindUserId);
/**
* 修改推广资格
*
* @param id 用户编号
* @param enabled 推广资格
*/
void updateBrokerageEnabled(Long id, Boolean enabled);
/**
* 获得用户的推广人
*
* @param id 用户编号
* @return 用户的推广人
*/
BrokerageUserDO getBindBrokerageUser(Long id);
/**
* 更新用户佣金
*
* @param id 用户编号
* @param price 用户可用佣金
*/
void updateUserPrice(Long id, Integer price);
/**
* 更新用户冻结佣金
*
* @param id 用户编号
* @param frozenPrice 用户冻结佣金
*/
void updateUserFrozenPrice(Long id, Integer frozenPrice);
/**
* 更新用户冻结佣金减少, 更新用户佣金增加
*
* @param id 用户编号
* @param frozenPrice 减少冻结佣金负数
*/
void updateFrozenPriceDecrAndPriceIncr(Long id, Integer frozenPrice);
/**
* 获得推广用户数量一级
*
* @param bindUserId 绑定的推广员编号
* @return 推广用户数量
*/
Long getCountByBindUserId(Long bindUserId);
/**
* 会员绑定推广员
*
* @param userId 用户编号
* @param bindUserId 推广员编号
* @param isNewUser 是否为新用户
* @return 是否绑定
*/
boolean bindUser(Long userId, Long bindUserId, Boolean isNewUser);
}

View File

@ -0,0 +1,210 @@
package cn.iocoder.yudao.module.trade.service.brokerage.user;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.BooleanUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.BrokerageUserPageReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.config.TradeConfigDO;
import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.user.BrokerageUserMapper;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageBindModeEnum;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageEnabledConditionEnum;
import cn.iocoder.yudao.module.trade.service.config.TradeConfigService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.*;
/**
* 分销用户 Service 实现类
*
* @author owen
*/
@Service
@Validated
public class BrokerageUserServiceImpl implements BrokerageUserService {
@Resource
private BrokerageUserMapper brokerageUserMapper;
@Resource
private TradeConfigService tradeConfigService;
@Override
public BrokerageUserDO getBrokerageUser(Long id) {
return brokerageUserMapper.selectById(id);
}
@Override
public List<BrokerageUserDO> getBrokerageUserList(Collection<Long> ids) {
return brokerageUserMapper.selectBatchIds(ids);
}
@Override
public PageResult<BrokerageUserDO> getBrokerageUserPage(BrokerageUserPageReqVO pageReqVO) {
return brokerageUserMapper.selectPage(pageReqVO);
}
@Override
public void updateBrokerageUserId(Long id, Long bindUserId) {
// 校验存在
validateBrokerageUserExists(id);
if (bindUserId == null) {
// 清除推广员
brokerageUserMapper.updateBindUserIdAndBindUserTimeToNull(id);
} else {
// 修改推广员
brokerageUserMapper.updateById(new BrokerageUserDO().setId(id)
.setBindUserId(bindUserId).setBindUserTime(LocalDateTime.now()));
}
}
@Override
public void updateBrokerageEnabled(Long id, Boolean enabled) {
// 校验存在
validateBrokerageUserExists(id);
if (BooleanUtil.isTrue(enabled)) {
// 开通推广资格
brokerageUserMapper.updateById(new BrokerageUserDO().setId(id)
.setBrokerageEnabled(true).setBrokerageTime(LocalDateTime.now()));
} else {
// 取消推广资格
brokerageUserMapper.updateEnabledFalseAndBrokerageTimeToNull(id);
}
}
private void validateBrokerageUserExists(Long id) {
if (brokerageUserMapper.selectById(id) == null) {
throw exception(BROKERAGE_USER_NOT_EXISTS);
}
}
@Override
public BrokerageUserDO getBindBrokerageUser(Long id) {
return Optional.ofNullable(id)
.map(this::getBrokerageUser)
.map(BrokerageUserDO::getBindUserId)
.map(this::getBrokerageUser)
.orElse(null);
}
@Override
public void updateUserPrice(Long id, Integer price) {
if (price > 0) {
brokerageUserMapper.updatePriceIncr(id, price);
} else if (price < 0) {
brokerageUserMapper.updatePriceDecr(id, price);
}
}
@Override
public void updateUserFrozenPrice(Long id, Integer frozenPrice) {
if (frozenPrice > 0) {
brokerageUserMapper.updateFrozenPriceIncr(id, frozenPrice);
} else if (frozenPrice < 0) {
brokerageUserMapper.updateFrozenPriceDecr(id, frozenPrice);
}
}
@Override
public void updateFrozenPriceDecrAndPriceIncr(Long id, Integer frozenPrice) {
Assert.isTrue(frozenPrice < 0);
int updateRows = brokerageUserMapper.updateFrozenPriceDecrAndPriceIncr(id, frozenPrice);
if (updateRows == 0) {
throw exception(BROKERAGE_USER_FROZEN_PRICE_NOT_ENOUGH);
}
}
@Override
public Long getCountByBindUserId(Long bindUserId) {
return brokerageUserMapper.selectCount(BrokerageUserDO::getBindUserId, bindUserId);
}
@Override
public boolean bindUser(Long userId, Long bindUserId, Boolean isNewUser) {
if (userId == null) {
throw exception(0);
}
boolean isInsert = false;
BrokerageUserDO brokerageUser = brokerageUserMapper.selectById(userId);
// 分销用户不存在的情况1.新注册 2.旧数据 3.分销功能关闭后又打开
if (brokerageUser == null) {
isInsert = true;
brokerageUser = new BrokerageUserDO().setId(userId).setBrokerageEnabled(false).setPrice(0).setFrozenPrice(0);
}
// 校验能否绑定
boolean validated = validateCanBindUser(brokerageUser, bindUserId, isNewUser);
if (!validated) {
return false;
}
if (isInsert) {
Integer enabledCondition = tradeConfigService.getTradeConfig().getBrokerageEnabledCondition();
if (BrokerageEnabledConditionEnum.ALL.getCondition().equals(enabledCondition)) {
// 人人分销用户默认就有分销资格
brokerageUser.setBrokerageEnabled(true).setBindUserTime(LocalDateTime.now());
}
brokerageUserMapper.insert(brokerageUser);
} else {
brokerageUserMapper.updateById(new BrokerageUserDO().setId(userId)
.setBindUserId(bindUserId).setBindUserTime(LocalDateTime.now()));
}
return true;
}
private boolean validateCanBindUser(BrokerageUserDO user, Long bindUserId, Boolean isNewUser) {
if (bindUserId == null) {
return false;
}
// 校验分销功能是否启用
TradeConfigDO tradeConfig = tradeConfigService.getTradeConfig();
if (tradeConfig == null || !BooleanUtil.isTrue(tradeConfig.getBrokerageEnabled())) {
return false;
}
// 校验绑定自己
if (Objects.equals(user.getId(), bindUserId)) {
throw exception(BROKERAGE_BIND_SELF);
}
// 校验要绑定的用户有无推广资格
BrokerageUserDO bindUser = brokerageUserMapper.selectById(bindUserId);
if (bindUser == null || !BooleanUtil.isTrue(bindUser.getBrokerageEnabled())) {
throw exception(BROKERAGE_BIND_USER_NOT_ENABLED);
}
// 校验分佣模式仅可后台手动设置推广员
if (BrokerageEnabledConditionEnum.ADMIN.getCondition().equals(tradeConfig.getBrokerageEnabledCondition())) {
throw exception(BROKERAGE_BIND_CONDITION_ADMIN);
}
// 校验分销关系绑定模式
if (BrokerageBindModeEnum.REGISTER.getMode().equals(tradeConfig.getBrokerageBindMode())) {
if (!BooleanUtil.isTrue(isNewUser)) {
throw exception(BROKERAGE_BIND_MODE_REGISTER); // 只有在注册时可以绑定
}
} else if (BrokerageBindModeEnum.ANYTIME.getMode().equals(tradeConfig.getBrokerageBindMode())) {
if (user.getBindUserId() != null) {
throw exception(BROKERAGE_BIND_OVERRIDE); // 已绑定了推广人
}
}
// A->B->A下级不能绑定自己的上级, A->B->C->A可以!!
if (Objects.equals(user.getId(), bindUser.getBindUserId())) {
throw exception(BROKERAGE_BIND_LOOP);
}
return true;
}
}

View File

@ -1,91 +0,0 @@
package cn.iocoder.yudao.module.trade.service.brokerage.user;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.TradeBrokerageUserPageReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.TradeBrokerageUserDO;
import java.util.Collection;
import java.util.List;
// TODO @疯狂要不去掉 Trade 前缀哈交易这块我准备除了 tradeorder 保持下类似 aftersale都要取消前缀了tradeorder 保持的原因是避免 payorder 和它重复
/**
* 分销用户 Service 接口
*
* @author owen
*/
public interface TradeBrokerageUserService {
/**
* 获得分销用户
*
* @param id 编号
* @return 分销用户
*/
TradeBrokerageUserDO getBrokerageUser(Long id);
/**
* 获得分销用户列表
*
* @param ids 编号
* @return 分销用户列表
*/
List<TradeBrokerageUserDO> getBrokerageUserList(Collection<Long> ids);
/**
* 获得分销用户分页
*
* @param pageReqVO 分页查询
* @return 分销用户分页
*/
PageResult<TradeBrokerageUserDO> getBrokerageUserPage(TradeBrokerageUserPageReqVO pageReqVO);
/**
* 修改推广员编号
*
* @param id 用户编号
* @param brokerageUserId 推广员编号
*/
void updateBrokerageUserId(Long id, Long brokerageUserId);
/**
* 修改推广资格
*
* @param id 用户编号
* @param brokerageEnabled 推广资格
*/
void updateBrokerageEnabled(Long id, Boolean brokerageEnabled);
/**
* 获得用户的推广人
*
* @param id 用户编号
* @return 用户的推广人
*/
TradeBrokerageUserDO getInviteBrokerageUser(Long id);
/**
* 更新用户佣金
*
* @param id 用户编号
* @param brokeragePrice 用户可用佣金
*/
void updateUserBrokeragePrice(Long id, int brokeragePrice);
// TODO @疯狂int 类型一般不用哈尽量都用封装类型不差这点内存哈
/**
* 更新用户冻结佣金
*
* @param id 用户编号
* @param frozenBrokeragePrice 用户冻结佣金
*/
void updateUserFrozenBrokeragePrice(Long id, int frozenBrokeragePrice);
/**
* 更新用户冻结佣金减少, 更新用户佣金增加
*
* @param id 用户编号
* @param frozenBrokeragePrice 减少冻结佣金负数
*/
void updateFrozenBrokeragePriceDecrAndBrokeragePriceIncr(Long id, int frozenBrokeragePrice);
}

View File

@ -1,112 +0,0 @@
package cn.iocoder.yudao.module.trade.service.brokerage.user;
import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.TradeBrokerageUserPageReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.TradeBrokerageUserDO;
import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.user.TradeBrokerageUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.MEMBER_FROZEN_BROKERAGE_PRICE_NOT_ENOUGH;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.BROKERAGE_USER_NOT_EXISTS;
/**
* 分销用户 Service 实现类
*
* @author owen
*/
@Service
@Validated
public class TradeBrokerageUserServiceImpl implements TradeBrokerageUserService {
@Resource
private TradeBrokerageUserMapper brokerageUserMapper;
@Override
public TradeBrokerageUserDO getBrokerageUser(Long id) {
return brokerageUserMapper.selectById(id);
}
@Override
public List<TradeBrokerageUserDO> getBrokerageUserList(Collection<Long> ids) {
return brokerageUserMapper.selectBatchIds(ids);
}
@Override
public PageResult<TradeBrokerageUserDO> getBrokerageUserPage(TradeBrokerageUserPageReqVO pageReqVO) {
return brokerageUserMapper.selectPage(pageReqVO);
}
@Override
public void updateBrokerageUserId(Long id, Long brokerageUserId) {
// 校验存在
validateBrokerageUserExists(id);
// TODO @疯狂貌似没实现完
}
@Override
public void updateBrokerageEnabled(Long id, Boolean brokerageEnabled) {
// 校验存在
validateBrokerageUserExists(id);
// TODO @疯狂貌似没实现完
}
private void validateBrokerageUserExists(Long id) {
if (brokerageUserMapper.selectById(id) == null) {
throw exception(BROKERAGE_USER_NOT_EXISTS);
}
}
// TODO @疯狂getBindBrokerageUser 会不会好点因为统一使用 Bind 替代了 Invite
@Override
public TradeBrokerageUserDO getInviteBrokerageUser(Long id) {
return Optional.ofNullable(id)
.map(this::getBrokerageUser)
.map(TradeBrokerageUserDO::getBrokerageUserId)
.map(this::getBrokerageUser)
.orElse(null);
}
// TODO @疯狂单个更新不用事务哈
@Override
@Transactional(rollbackFor = Exception.class)
public void updateUserBrokeragePrice(Long id, int brokeragePrice) {
if (brokeragePrice > 0) {
brokerageUserMapper.updateBrokeragePriceIncr(id, brokeragePrice);
} else if (brokeragePrice < 0) {
brokerageUserMapper.updateBrokeragePriceDecr(id, brokeragePrice);
}
}
// TODO @疯狂单个更新不用事务哈
@Override
@Transactional(rollbackFor = Exception.class)
public void updateUserFrozenBrokeragePrice(Long id, int frozenBrokeragePrice) {
if (frozenBrokeragePrice > 0) {
brokerageUserMapper.updateFrozenBrokeragePriceIncr(id, frozenBrokeragePrice);
} else if (frozenBrokeragePrice < 0) {
brokerageUserMapper.updateFrozenBrokeragePriceDecr(id, frozenBrokeragePrice);
}
}
// TODO @疯狂单个更新不用事务哈
@Override
@Transactional(rollbackFor = Exception.class)
public void updateFrozenBrokeragePriceDecrAndBrokeragePriceIncr(Long id, int frozenBrokeragePrice) {
Assert.isTrue(frozenBrokeragePrice < 0);
int updateRows = brokerageUserMapper.updateFrozenBrokeragePriceDecrAndBrokeragePriceIncr(id, frozenBrokeragePrice);
if (updateRows == 0) {
// TODO @疯狂挪到 trade 这变的错误码哈
throw exception(MEMBER_FROZEN_BROKERAGE_PRICE_NOT_ENOUGH);
}
}
}

View File

@ -11,8 +11,6 @@ import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils; import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.member.api.address.AddressApi; import cn.iocoder.yudao.module.member.api.address.AddressApi;
import cn.iocoder.yudao.module.member.api.address.dto.AddressRespDTO; import cn.iocoder.yudao.module.member.api.address.dto.AddressRespDTO;
import cn.iocoder.yudao.module.trade.service.brokerage.record.TradeBrokerageRecordService;
import cn.iocoder.yudao.module.trade.service.brokerage.record.bo.BrokerageAddReqBO;
import cn.iocoder.yudao.module.member.api.level.MemberLevelApi; import cn.iocoder.yudao.module.member.api.level.MemberLevelApi;
import cn.iocoder.yudao.module.member.api.point.MemberPointApi; import cn.iocoder.yudao.module.member.api.point.MemberPointApi;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi; import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
@ -51,9 +49,12 @@ import cn.iocoder.yudao.module.trade.dal.mysql.order.TradeOrderItemMapper;
import cn.iocoder.yudao.module.trade.dal.mysql.order.TradeOrderMapper; import cn.iocoder.yudao.module.trade.dal.mysql.order.TradeOrderMapper;
import cn.iocoder.yudao.module.trade.dal.redis.no.TradeOrderNoRedisDAO; import cn.iocoder.yudao.module.trade.dal.redis.no.TradeOrderNoRedisDAO;
import cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants; import cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
import cn.iocoder.yudao.module.trade.enums.delivery.DeliveryTypeEnum; import cn.iocoder.yudao.module.trade.enums.delivery.DeliveryTypeEnum;
import cn.iocoder.yudao.module.trade.enums.order.*; import cn.iocoder.yudao.module.trade.enums.order.*;
import cn.iocoder.yudao.module.trade.framework.order.config.TradeOrderProperties; import cn.iocoder.yudao.module.trade.framework.order.config.TradeOrderProperties;
import cn.iocoder.yudao.module.trade.service.brokerage.record.BrokerageRecordService;
import cn.iocoder.yudao.module.trade.service.brokerage.bo.BrokerageAddReqBO;
import cn.iocoder.yudao.module.trade.service.cart.CartService; import cn.iocoder.yudao.module.trade.service.cart.CartService;
import cn.iocoder.yudao.module.trade.service.delivery.DeliveryExpressService; import cn.iocoder.yudao.module.trade.service.delivery.DeliveryExpressService;
import cn.iocoder.yudao.module.trade.service.message.TradeMessageService; import cn.iocoder.yudao.module.trade.service.message.TradeMessageService;
@ -128,7 +129,7 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
@Resource @Resource
private MemberPointApi memberPointApi; private MemberPointApi memberPointApi;
@Resource @Resource
private TradeBrokerageRecordService tradeBrokerageRecordService; private BrokerageRecordService brokerageRecordService;
@Resource @Resource
private ProductCommentApi productCommentApi; private ProductCommentApi productCommentApi;
@ -394,7 +395,7 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
// 增加用户经验 // 增加用户经验
getSelf().addUserExperienceAsync(order.getUserId(), order.getPayPrice(), order.getId()); getSelf().addUserExperienceAsync(order.getUserId(), order.getPayPrice(), order.getId());
// 增加用户佣金 // 增加用户佣金
getSelf().addBrokerageAsync(order.getUserId(), order.getId()); getSelf().addBrokerageAsync(order.getUserId(), BrokerageRecordBizTypeEnum.ORDER, order.getId());
} }
/** /**
@ -674,7 +675,7 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
// 扣减用户经验 // 扣减用户经验
getSelf().reduceUserExperienceAsync(order.getUserId(), orderRefundPrice, afterSaleId); getSelf().reduceUserExperienceAsync(order.getUserId(), orderRefundPrice, afterSaleId);
// 更新分佣记录为已失效 // 更新分佣记录为已失效
getSelf().cancelBrokerageAsync(order.getUserId(), id); getSelf().cancelBrokerageAsync(order.getUserId(), BrokerageRecordBizTypeEnum.ORDER, id);
} }
@Override @Override
@ -784,16 +785,16 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
@Async @Async
protected void addBrokerageAsync(Long userId, Long orderId) { protected void addBrokerageAsync(Long userId, BrokerageRecordBizTypeEnum bizType, Long orderId) {
List<TradeOrderItemDO> orderItems = tradeOrderItemMapper.selectListByOrderId(orderId); List<TradeOrderItemDO> orderItems = tradeOrderItemMapper.selectListByOrderId(orderId);
List<BrokerageAddReqBO> list = convertList(orderItems, List<BrokerageAddReqBO> list = convertList(orderItems,
item -> TradeOrderConvert.INSTANCE.convert(item, productSkuApi.getSku(item.getSkuId()))); item -> TradeOrderConvert.INSTANCE.convert(item, productSkuApi.getSku(item.getSkuId())));
tradeBrokerageRecordService.addBrokerage(userId, list); brokerageRecordService.addBrokerage(userId, bizType, list);
} }
@Async @Async
protected void cancelBrokerageAsync(Long userId, Long orderItemId) { protected void cancelBrokerageAsync(Long userId, BrokerageRecordBizTypeEnum bizType, Long orderItemId) {
tradeBrokerageRecordService.cancelBrokerage(userId, String.valueOf(orderItemId)); brokerageRecordService.cancelBrokerage(userId, bizType, String.valueOf(orderItemId));
} }
/** /**

View File

@ -3,10 +3,10 @@ package cn.iocoder.yudao.module.trade.service.brokerage.record;
import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.NumberUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.TradeBrokerageRecordPageReqVO; import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordPageReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.TradeBrokerageRecordDO; import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.BrokerageRecordDO;
import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.record.TradeBrokerageRecordMapper; import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.record.BrokerageRecordMapper;
import cn.iocoder.yudao.module.trade.service.brokerage.user.TradeBrokerageUserService; import cn.iocoder.yudao.module.trade.service.brokerage.user.BrokerageUserService;
import cn.iocoder.yudao.module.trade.service.config.TradeConfigService; import cn.iocoder.yudao.module.trade.service.config.TradeConfigService;
import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -27,51 +27,51 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
// TODO @芋艿单测后续看看 // TODO @芋艿单测后续看看
/** /**
* {@link TradeBrokerageRecordServiceImpl} 的单元测试类 * {@link BrokerageRecordServiceImpl} 的单元测试类
* *
* @author owen * @author owen
*/ */
@Import(TradeBrokerageRecordServiceImpl.class) @Import(BrokerageRecordServiceImpl.class)
public class TradeBrokerageRecordServiceImplTest extends BaseDbUnitTest { public class BrokerageRecordServiceImplTest extends BaseDbUnitTest {
@Resource @Resource
private TradeBrokerageRecordServiceImpl tradeBrokerageRecordService; private BrokerageRecordServiceImpl brokerageRecordService;
@Resource @Resource
private TradeBrokerageRecordMapper tradeBrokerageRecordMapper; private BrokerageRecordMapper brokerageRecordMapper;
@MockBean @MockBean
private TradeConfigService tradeConfigService; private TradeConfigService tradeConfigService;
@MockBean @MockBean
private TradeBrokerageUserService tradeBrokerageUserService; private BrokerageUserService brokerageUserService;
@Test @Test
@Disabled // TODO 请修改 null 为需要的值然后删除 @Disabled 注解 @Disabled // TODO 请修改 null 为需要的值然后删除 @Disabled 注解
public void testGetBrokerageRecordPage() { public void testGetBrokerageRecordPage() {
// mock 数据 // mock 数据
TradeBrokerageRecordDO dbBrokerageRecord = randomPojo(TradeBrokerageRecordDO.class, o -> { // 等会查询到 BrokerageRecordDO dbBrokerageRecord = randomPojo(BrokerageRecordDO.class, o -> { // 等会查询到
o.setUserId(null); o.setUserId(null);
o.setBizType(null); o.setBizType(null);
o.setStatus(null); o.setStatus(null);
o.setCreateTime(null); o.setCreateTime(null);
}); });
tradeBrokerageRecordMapper.insert(dbBrokerageRecord); brokerageRecordMapper.insert(dbBrokerageRecord);
// 测试 userId 不匹配 // 测试 userId 不匹配
tradeBrokerageRecordMapper.insert(cloneIgnoreId(dbBrokerageRecord, o -> o.setUserId(null))); brokerageRecordMapper.insert(cloneIgnoreId(dbBrokerageRecord, o -> o.setUserId(null)));
// 测试 bizType 不匹配 // 测试 bizType 不匹配
tradeBrokerageRecordMapper.insert(cloneIgnoreId(dbBrokerageRecord, o -> o.setBizType(null))); brokerageRecordMapper.insert(cloneIgnoreId(dbBrokerageRecord, o -> o.setBizType(null)));
// 测试 status 不匹配 // 测试 status 不匹配
tradeBrokerageRecordMapper.insert(cloneIgnoreId(dbBrokerageRecord, o -> o.setStatus(null))); brokerageRecordMapper.insert(cloneIgnoreId(dbBrokerageRecord, o -> o.setStatus(null)));
// 测试 createTime 不匹配 // 测试 createTime 不匹配
tradeBrokerageRecordMapper.insert(cloneIgnoreId(dbBrokerageRecord, o -> o.setCreateTime(null))); brokerageRecordMapper.insert(cloneIgnoreId(dbBrokerageRecord, o -> o.setCreateTime(null)));
// 准备参数 // 准备参数
TradeBrokerageRecordPageReqVO reqVO = new TradeBrokerageRecordPageReqVO(); BrokerageRecordPageReqVO reqVO = new BrokerageRecordPageReqVO();
reqVO.setUserId(null); reqVO.setUserId(null);
reqVO.setBizType(null); reqVO.setBizType(null);
reqVO.setStatus(null); reqVO.setStatus(null);
reqVO.setCreateTime(buildBetweenTime(2023, 2, 1, 2023, 2, 28)); reqVO.setCreateTime(buildBetweenTime(2023, 2, 1, 2023, 2, 28));
// 调用 // 调用
PageResult<TradeBrokerageRecordDO> pageResult = tradeBrokerageRecordService.getBrokerageRecordPage(reqVO); PageResult<BrokerageRecordDO> pageResult = brokerageRecordService.getBrokerageRecordPage(reqVO);
// 断言 // 断言
assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size()); assertEquals(1, pageResult.getList().size());
@ -79,38 +79,38 @@ public class TradeBrokerageRecordServiceImplTest extends BaseDbUnitTest {
} }
@Test @Test
public void testCalculateBrokerage_useSkuBrokeragePrice() { public void testCalculatePrice_useFixedPrice() {
// mock 数据 // mock 数据
Integer payPrice = randomInteger(); Integer payPrice = randomInteger();
Integer percent = randomInt(1, 101); Integer percent = randomInt(1, 101);
Integer skuBrokeragePrice = randomInt(); Integer fixedPrice = randomInt();
// 调用 // 调用
int brokerage = tradeBrokerageRecordService.calculateBrokerage(payPrice, percent, skuBrokeragePrice); int brokerage = brokerageRecordService.calculatePrice(payPrice, percent, fixedPrice);
// 断言 // 断言
assertEquals(brokerage, skuBrokeragePrice); assertEquals(brokerage, fixedPrice);
} }
@Test @Test
public void testCalculateBrokerage_usePercent() { public void testCalculatePrice_usePercent() {
// mock 数据 // mock 数据
Integer payPrice = randomInteger(); Integer payPrice = randomInteger();
Integer percent = randomInt(1, 101); Integer percent = randomInt(1, 101);
Integer skuBrokeragePrice = randomEle(new Integer[]{0, null}); Integer fixedPrice = randomEle(new Integer[]{0, null});
System.out.println("skuBrokeragePrice=" + skuBrokeragePrice); System.out.println("fixedPrice=" + fixedPrice);
// 调用 // 调用
int brokerage = tradeBrokerageRecordService.calculateBrokerage(payPrice, percent, skuBrokeragePrice); int brokerage = brokerageRecordService.calculatePrice(payPrice, percent, fixedPrice);
// 断言 // 断言
assertEquals(brokerage, NumberUtil.div(NumberUtil.mul(payPrice, percent), 100, 0, RoundingMode.DOWN).intValue()); assertEquals(brokerage, NumberUtil.div(NumberUtil.mul(payPrice, percent), 100, 0, RoundingMode.DOWN).intValue());
} }
@Test @Test
public void testCalculateBrokerage_equalsZero() { public void testCalculatePrice_equalsZero() {
// mock 数据 // mock 数据
Integer payPrice = null; Integer payPrice = null;
Integer percent = null; Integer percent = null;
Integer skuBrokeragePrice = null; Integer fixedPrice = null;
// 调用 // 调用
int brokerage = tradeBrokerageRecordService.calculateBrokerage(payPrice, percent, skuBrokeragePrice); int brokerage = brokerageRecordService.calculatePrice(payPrice, percent, fixedPrice);
// 断言 // 断言
assertEquals(brokerage, 0); assertEquals(brokerage, 0);
} }

View File

@ -2,9 +2,9 @@ package cn.iocoder.yudao.module.trade.service.brokerage.user;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.TradeBrokerageUserPageReqVO; import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.BrokerageUserPageReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.TradeBrokerageUserDO; import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.user.TradeBrokerageUserMapper; import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.user.BrokerageUserMapper;
import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
@ -19,43 +19,43 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
// TODO @芋艿单测后续看看 // TODO @芋艿单测后续看看
/** /**
* {@link TradeBrokerageUserServiceImpl} 的单元测试类 * {@link BrokerageUserServiceImpl} 的单元测试类
* *
* @author owen * @author owen
*/ */
@Import(TradeBrokerageUserServiceImpl.class) @Import(BrokerageUserServiceImpl.class)
public class TradeBrokerageUserServiceImplTest extends BaseDbUnitTest { public class BrokerageUserServiceImplTest extends BaseDbUnitTest {
@Resource @Resource
private TradeBrokerageUserServiceImpl brokerageUserService; private BrokerageUserServiceImpl brokerageUserService;
@Resource @Resource
private TradeBrokerageUserMapper brokerageUserMapper; private BrokerageUserMapper brokerageUserMapper;
@Test @Test
@Disabled // TODO 请修改 null 为需要的值然后删除 @Disabled 注解 @Disabled // TODO 请修改 null 为需要的值然后删除 @Disabled 注解
public void testGetBrokerageUserPage() { public void testGetBrokerageUserPage() {
// mock 数据 // mock 数据
TradeBrokerageUserDO dbBrokerageUser = randomPojo(TradeBrokerageUserDO.class, o -> { // 等会查询到 BrokerageUserDO dbBrokerageUser = randomPojo(BrokerageUserDO.class, o -> { // 等会查询到
o.setBrokerageUserId(null); o.setBindUserId(null);
o.setBrokerageEnabled(null); o.setBrokerageEnabled(null);
o.setCreateTime(null); o.setCreateTime(null);
}); });
brokerageUserMapper.insert(dbBrokerageUser); brokerageUserMapper.insert(dbBrokerageUser);
// 测试 brokerageUserId 不匹配 // 测试 brokerageUserId 不匹配
brokerageUserMapper.insert(cloneIgnoreId(dbBrokerageUser, o -> o.setBrokerageUserId(null))); brokerageUserMapper.insert(cloneIgnoreId(dbBrokerageUser, o -> o.setBindUserId(null)));
// 测试 brokerageEnabled 不匹配 // 测试 brokerageEnabled 不匹配
brokerageUserMapper.insert(cloneIgnoreId(dbBrokerageUser, o -> o.setBrokerageEnabled(null))); brokerageUserMapper.insert(cloneIgnoreId(dbBrokerageUser, o -> o.setBrokerageEnabled(null)));
// 测试 createTime 不匹配 // 测试 createTime 不匹配
brokerageUserMapper.insert(cloneIgnoreId(dbBrokerageUser, o -> o.setCreateTime(null))); brokerageUserMapper.insert(cloneIgnoreId(dbBrokerageUser, o -> o.setCreateTime(null)));
// 准备参数 // 准备参数
TradeBrokerageUserPageReqVO reqVO = new TradeBrokerageUserPageReqVO(); BrokerageUserPageReqVO reqVO = new BrokerageUserPageReqVO();
reqVO.setBrokerageUserId(null); reqVO.setBindUserId(null);
reqVO.setBrokerageEnabled(null); reqVO.setBrokerageEnabled(null);
reqVO.setCreateTime(buildBetweenTime(2023, 2, 1, 2023, 2, 28)); reqVO.setCreateTime(buildBetweenTime(2023, 2, 1, 2023, 2, 28));
// 调用 // 调用
PageResult<TradeBrokerageUserDO> pageResult = brokerageUserService.getBrokerageUserPage(reqVO); PageResult<BrokerageUserDO> pageResult = brokerageUserService.getBrokerageUserPage(reqVO);
// 断言 // 断言
assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size()); assertEquals(1, pageResult.getList().size());

View File

@ -129,12 +129,12 @@ CREATE TABLE IF NOT EXISTS "trade_after_sale_log" (
CREATE TABLE IF NOT EXISTS "trade_brokerage_user" CREATE TABLE IF NOT EXISTS "trade_brokerage_user"
( (
"id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"brokerage_user_id" bigint NOT NULL, "bind_user_id" bigint NOT NULL,
"brokerage_bind_time" varchar, "bind_user_time" varchar,
"brokerage_enabled" bit NOT NULL, "brokerage_enabled" bit NOT NULL,
"brokerage_time" varchar, "brokerage_time" varchar,
"brokerage_price" int NOT NULL, "price" int NOT NULL,
"frozen_brokerage_price" int NOT NULL, "frozen_price" int NOT NULL,
"creator" varchar DEFAULT '', "creator" varchar DEFAULT '',
"create_time" datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, "create_time" datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updater" varchar DEFAULT '', "updater" varchar DEFAULT '',

View File

@ -13,7 +13,6 @@ public interface ErrorCodeConstants {
ErrorCode USER_NOT_EXISTS = new ErrorCode(1004001000, "用户不存在"); ErrorCode USER_NOT_EXISTS = new ErrorCode(1004001000, "用户不存在");
ErrorCode USER_MOBILE_NOT_EXISTS = new ErrorCode(1004001001, "手机号未注册用户"); ErrorCode USER_MOBILE_NOT_EXISTS = new ErrorCode(1004001001, "手机号未注册用户");
ErrorCode USER_MOBILE_USED = new ErrorCode(1004001002, "修改手机失败,该手机号({})已经被使用"); ErrorCode USER_MOBILE_USED = new ErrorCode(1004001002, "修改手机失败,该手机号({})已经被使用");
ErrorCode MEMBER_FROZEN_BROKERAGE_PRICE_NOT_ENOUGH = new ErrorCode(1004001003, "用户冻结佣金({})数量不足");
// ========== AUTH 模块 1004003000 ========== // ========== AUTH 模块 1004003000 ==========
ErrorCode AUTH_LOGIN_BAD_CREDENTIALS = new ErrorCode(1004003000, "登录失败,账号密码不正确"); ErrorCode AUTH_LOGIN_BAD_CREDENTIALS = new ErrorCode(1004003000, "登录失败,账号密码不正确");

View File

@ -33,6 +33,11 @@
<artifactId>yudao-module-infra-api</artifactId> <artifactId>yudao-module-infra-api</artifactId>
<version>${revision}</version> <version>${revision}</version>
</dependency> </dependency>
<dependency>
<groupId>cn.iocoder.boot</groupId>
<artifactId>yudao-module-trade-api</artifactId>
<version>${revision}</version>
</dependency>
<!-- 业务组件 --> <!-- 业务组件 -->
<dependency> <dependency>

View File

@ -8,6 +8,8 @@ import cn.iocoder.yudao.module.member.dal.dataobject.level.MemberLevelDO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO; import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.service.level.MemberLevelService; import cn.iocoder.yudao.module.member.service.level.MemberLevelService;
import cn.iocoder.yudao.module.member.service.user.MemberUserService; import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import cn.iocoder.yudao.module.trade.api.brokerage.BrokerageApi;
import cn.iocoder.yudao.module.trade.api.brokerage.dto.BrokerageUserDTO;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -16,6 +18,7 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.validation.Valid; import javax.validation.Valid;
import java.util.Optional;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId; import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
@ -33,14 +36,18 @@ public class AppMemberUserController {
@Resource @Resource
private MemberLevelService levelService; private MemberLevelService levelService;
@Resource
private BrokerageApi brokerageApi;
@GetMapping("/get") @GetMapping("/get")
@Operation(summary = "获得基本信息") @Operation(summary = "获得基本信息")
@PreAuthenticated @PreAuthenticated
public CommonResult<AppMemberUserInfoRespVO> getUserInfo() { public CommonResult<AppMemberUserInfoRespVO> getUserInfo() {
MemberUserDO user = userService.getUser(getLoginUserId()); MemberUserDO user = userService.getUser(getLoginUserId());
MemberLevelDO level = levelService.getLevel(user.getLevelId()); MemberLevelDO level = levelService.getLevel(user.getLevelId());
BrokerageUserDTO brokerageUser = brokerageApi.getBrokerageUser(user.getId());
return success(MemberUserConvert.INSTANCE.convert(user, level) return success(MemberUserConvert.INSTANCE.convert(user, level)
.setBrokerageEnabled(true) // TODO @疯狂这里我先写死后面改成 db 返回 .setBrokerageEnabled(Optional.ofNullable(brokerageUser).map(BrokerageUserDTO::getBrokerageEnabled).orElse(false))
); );
} }

View File

@ -136,38 +136,4 @@ public class MemberUserDO extends TenantBaseDO {
*/ */
private Long groupId; private Long groupId;
// TODO @疯狂看看要不要删除掉哈
// ========== 分销相关 ==========
/**
* 推广员编号
*/
@TableField(exist = false) // TODO 芋艿避免报错
private Long brokerageUserId;
/**
* 推广员绑定时间
*/
@TableField(exist = false) // TODO 芋艿避免报错
private LocalDateTime brokerageBindTime;
/**
* 是否成为推广员
*/
@TableField(exist = false) // TODO 芋艿避免报错
private Boolean brokerageEnabled;
/**
* 成为分销员时间
*/
@TableField(exist = false) // TODO 芋艿避免报错
private LocalDateTime brokerageTime;
/**
* 可用佣金
*/
@TableField(exist = false) // TODO 芋艿避免报错
private Integer brokeragePrice;
/**
* 冻结佣金
*/
@TableField(exist = false) // TODO 芋艿避免报错
private Integer frozenBrokeragePrice;
} }

View File

@ -6,6 +6,7 @@ import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil; import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils; import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.framework.pay.core.client.PayClient; import cn.iocoder.yudao.framework.pay.core.client.PayClient;
import cn.iocoder.yudao.framework.pay.core.client.PayClientFactory; import cn.iocoder.yudao.framework.pay.core.client.PayClientFactory;
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO; import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
@ -31,7 +32,6 @@ import cn.iocoder.yudao.module.pay.framework.pay.config.PayProperties;
import cn.iocoder.yudao.module.pay.service.app.PayAppService; import cn.iocoder.yudao.module.pay.service.app.PayAppService;
import cn.iocoder.yudao.module.pay.service.channel.PayChannelService; import cn.iocoder.yudao.module.pay.service.channel.PayChannelService;
import cn.iocoder.yudao.module.pay.service.notify.PayNotifyService; import cn.iocoder.yudao.module.pay.service.notify.PayNotifyService;
import cn.iocoder.yudao.module.pay.util.MoneyUtils;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;