Merge branch 'test' into feauture-20261104
# Conflicts: # bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcOrderBillMapper.java
This commit is contained in:
@@ -36,6 +36,13 @@ public class ArBill extends BaseEntity {
|
||||
private Long customerId;
|
||||
private String customerCode;
|
||||
private String customerName;
|
||||
/** 创建账单时的客户区域和负责人快照。 */
|
||||
private String profitCustomerArea;
|
||||
private Long profitSalesUserId;
|
||||
private String profitSalesUserCode;
|
||||
private String profitSalesUserName;
|
||||
/** NEW=生成时固化;BACKFILLED=历史补录,来源为补录时可取得的数据。 */
|
||||
private String profitSnapshotSource;
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
/** 账单所属期开始日期,导出模板展示用。 */
|
||||
|
||||
+2
-2
@@ -37,10 +37,10 @@ public class ArBillGeneratePreviewExportRow implements Serializable {
|
||||
@Excel(name = "国家/地区", sort = 6, width = 18)
|
||||
private String countryName;
|
||||
|
||||
@Excel(name = "实际重(kg)", sort = 7, scale = 2, width = 16)
|
||||
@Excel(name = "实际重(kg)", sort = 7, width = 16)
|
||||
private BigDecimal actualWeight;
|
||||
|
||||
@Excel(name = "计费重(kg)", sort = 8, scale = 2, width = 16)
|
||||
@Excel(name = "计费重(kg)", sort = 8, width = 16)
|
||||
private BigDecimal chargeWeight;
|
||||
|
||||
@Excel(name = "应收金额", sort = 9, scale = 2, width = 16)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.bms.ar.mapper;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.bms.ar.profit.ArCommissionRate;
|
||||
import com.bms.ar.profit.ArWriteoffRate;
|
||||
import com.bms.ar.profit.ArCommissionResult;
|
||||
import com.bms.ar.profit.ArCommissionSummary;
|
||||
|
||||
public interface ArCommissionMapper
|
||||
{
|
||||
List<ArCommissionRate> selectRates();
|
||||
ArCommissionRate selectEffective(@Param("salesUserId") Long salesUserId, @Param("at") Date at);
|
||||
int insertRate(ArCommissionRate rate);
|
||||
Long lockSalesUser(@Param("salesUserId") Long salesUserId);
|
||||
int insertWriteoffRate(@Param("writeoffId") Long writeoffId, @Param("salesUserId") Long salesUserId,
|
||||
@Param("rateId") Long rateId, @Param("rate") java.math.BigDecimal rate);
|
||||
int reverseResults(@Param("billId") Long billId, @Param("operator") String operator);
|
||||
List<ArCommissionResult> selectSettlementInputs(@Param("billId") Long billId);
|
||||
int insertResults(@Param("items") List<ArCommissionResult> items, @Param("operator") String operator);
|
||||
List<ArWriteoffRate> selectMissingRates();
|
||||
List<ArWriteoffRate> selectWriteoffRates(@Param("billId") Long billId);
|
||||
Long selectBillIdByWriteoffId(@Param("writeoffId") Long writeoffId);
|
||||
int countMissingRates(@Param("billId") Long billId);
|
||||
int confirmMissingRate(@Param("writeoffId") Long writeoffId, @Param("rate") java.math.BigDecimal rate,
|
||||
@Param("operator") String operator, @Param("remark") String remark);
|
||||
List<ArCommissionResult> selectResults(@Param("billId") Long billId, @Param("includeReversed") boolean includeReversed);
|
||||
List<ArCommissionSummary> selectCommissionSummary(@Param("billId") Long billId);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.bms.ar.mapper;
|
||||
|
||||
import java.util.List;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.bms.ar.profit.ArProfitQuery;
|
||||
import com.bms.ar.profit.ArProfitRow;
|
||||
import com.bms.ar.profit.ArProfitScope;
|
||||
import com.bms.ar.profit.ArProfitSummary;
|
||||
import com.bms.ar.profit.ArProfitSalesOption;
|
||||
import com.bms.ar.domain.ArBillDetailFee;
|
||||
import com.bms.ar.domain.ArBillDetail;
|
||||
|
||||
public interface ArProfitMapper
|
||||
{
|
||||
List<ArProfitRow> selectBills(@Param("query") ArProfitQuery query, @Param("scope") ArProfitScope scope);
|
||||
List<ArProfitSummary> selectSummary(@Param("query") ArProfitQuery query, @Param("scope") ArProfitScope scope);
|
||||
List<ArProfitSalesOption> selectSalesOptions(@Param("keyword") String keyword);
|
||||
List<ArBillDetail> selectBillDetails(@Param("query") ArProfitQuery query, @Param("scope") ArProfitScope scope);
|
||||
List<ArBillDetailFee> selectFees(@Param("query") ArProfitQuery query, @Param("scope") ArProfitScope scope);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
@Data
|
||||
public class ArCommissionRate
|
||||
{
|
||||
private Long rateId;
|
||||
private Long salesUserId;
|
||||
private String salesUserCode;
|
||||
private String salesUserName;
|
||||
private BigDecimal rate;
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date effectiveAt;
|
||||
private String createBy;
|
||||
private String remark;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import lombok.Data;
|
||||
import com.bms.common.annotation.Excel;
|
||||
|
||||
@Data
|
||||
public class ArCommissionResult
|
||||
{
|
||||
private Long resultId;
|
||||
private Long arBillId;
|
||||
private Long detailId;
|
||||
private Long salesUserId;
|
||||
@Excel(name = "账单号", width = 20) private String billNo;
|
||||
@Excel(name = "订单号", width = 22) private String orderNo;
|
||||
@Excel(name = "销售员", width = 16) private String salesUserName;
|
||||
@Excel(name = "币种", width = 10) private String currency;
|
||||
@Excel(name = "销售毛利", scale = 4, width = 16) private BigDecimal grossProfit;
|
||||
@Excel(name = "正式提成", scale = 2, width = 16) private BigDecimal commissionAmount;
|
||||
@Excel(name = "状态", readConverterExp = "READY=已计算,MISSING_RATE=比例待确认,MISSING_PRICE=价格缺失,MISSING_SNAPSHOT=归属或区域缺失,WRITEOFF_MISMATCH=核销金额不一致,REVERSED=已冲回", width = 20) private String resultStatus;
|
||||
private Date createTime;
|
||||
private String reversedBy;
|
||||
private Date reversedTime;
|
||||
private BigDecimal weightedRate;
|
||||
private BigDecimal billAmount;
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import com.bms.ar.domain.ArBalanceWriteoff;
|
||||
import com.bms.ar.domain.ArBill;
|
||||
import com.bms.ar.mapper.ArCommissionMapper;
|
||||
import com.bms.ar.mapper.ArBillMapper;
|
||||
import com.bms.ar.enums.ArBillStatus;
|
||||
import com.bms.ar.enums.ArBillGenerationStatus;
|
||||
import com.bms.ar.security.ArBillRoleKeys;
|
||||
import com.bms.common.exception.ServiceException;
|
||||
import com.bms.common.core.domain.entity.SysUser;
|
||||
import com.bms.common.utils.SecurityUtils;
|
||||
import com.bms.system.mapper.SysUserMapper;
|
||||
|
||||
@Service
|
||||
public class ArCommissionService
|
||||
{
|
||||
private final ArCommissionMapper mapper;
|
||||
private final ArProfitScopeResolver scopeResolver;
|
||||
private final SysUserMapper userMapper;
|
||||
private final ArBillMapper billMapper;
|
||||
|
||||
public ArCommissionService(ArCommissionMapper mapper, ArProfitScopeResolver scopeResolver, SysUserMapper userMapper,
|
||||
ArBillMapper billMapper)
|
||||
{
|
||||
this.mapper = mapper;
|
||||
this.scopeResolver = scopeResolver;
|
||||
this.userMapper = userMapper;
|
||||
this.billMapper = billMapper;
|
||||
}
|
||||
|
||||
public List<ArCommissionRate> selectRates()
|
||||
{
|
||||
requireFinance();
|
||||
return mapper.selectRates();
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void addRate(ArCommissionRate rate)
|
||||
{
|
||||
requireFinance();
|
||||
SysUser sales = rate == null || rate.getSalesUserId() == null ? null : userMapper.selectUserById(rate.getSalesUserId());
|
||||
if (sales == null || !"0".equals(sales.getStatus()) || !"0".equals(sales.getDelFlag())
|
||||
|| sales.getRoles() == null || sales.getRoles().stream().noneMatch(role -> role != null
|
||||
&& "0".equals(role.getStatus()) && ArBillRoleKeys.SALES.equals(role.getRoleKey())))
|
||||
throw new ServiceException("请选择有效销售员");
|
||||
if (rate.getRate() == null || rate.getRate().signum() < 0 || rate.getRate().compareTo(new BigDecimal("100")) > 0
|
||||
|| rate.getRate().scale() > 4)
|
||||
throw new ServiceException("提成比例须为 0 至 100,最多四位小数");
|
||||
if (rate.getRemark() != null && rate.getRemark().length() > 500)
|
||||
throw new ServiceException("备注不能超过 500 字");
|
||||
mapper.lockSalesUser(rate.getSalesUserId());
|
||||
Date now = new Date();
|
||||
if (rate.getEffectiveAt() == null) rate.setEffectiveAt(now);
|
||||
if (rate.getEffectiveAt().before(now)) throw new ServiceException("提成比例生效时间不能早于当前时间");
|
||||
rate.setCreateBy(SecurityUtils.getUsername());
|
||||
mapper.insertRate(rate);
|
||||
}
|
||||
|
||||
/** 在核销事务内固化该次操作时的比例;未配置时保留空值,待财务处理。 */
|
||||
public void snapshotWriteoff(ArBill bill, ArBalanceWriteoff writeoff)
|
||||
{
|
||||
Long salesUserId = bill.getProfitSalesUserId();
|
||||
if (salesUserId != null) mapper.lockSalesUser(salesUserId);
|
||||
ArCommissionRate rate = salesUserId == null ? null : mapper.selectEffective(salesUserId, new Date());
|
||||
mapper.insertWriteoffRate(writeoff.getWriteoffId(), salesUserId,
|
||||
rate == null ? null : rate.getRateId(), rate == null ? null : rate.getRate());
|
||||
}
|
||||
|
||||
/** 完全核销后生成逐单结果;由外部账单锁及核销事务保证并发一致。 */
|
||||
public void createFinalResults(Long billId, String operator)
|
||||
{
|
||||
List<ArCommissionResult> items = mapper.selectSettlementInputs(billId);
|
||||
CommissionCalculator.allocateFinalAmounts(items);
|
||||
for (int offset = 0; offset < items.size(); offset += 300)
|
||||
{
|
||||
mapper.insertResults(items.subList(offset, Math.min(offset + 300, items.size())), operator);
|
||||
}
|
||||
}
|
||||
|
||||
/** 反核销保留原记录并标记冲回。 */
|
||||
public void reverseFinalResults(Long billId, String operator)
|
||||
{
|
||||
mapper.reverseResults(billId, operator);
|
||||
}
|
||||
|
||||
public List<ArWriteoffRate> missingRates()
|
||||
{
|
||||
requireFinance();
|
||||
return mapper.selectMissingRates();
|
||||
}
|
||||
|
||||
public List<ArCommissionResult> results(Long billId, boolean includeReversed)
|
||||
{
|
||||
requireFinance();
|
||||
return mapper.selectResults(billId, includeReversed);
|
||||
}
|
||||
|
||||
public List<ArCommissionSummary> summary(Long billId)
|
||||
{
|
||||
requireFinance();
|
||||
return mapper.selectCommissionSummary(billId);
|
||||
}
|
||||
|
||||
public List<ArWriteoffRate> writeoffRates(Long billId)
|
||||
{
|
||||
requireFinance();
|
||||
return mapper.selectWriteoffRates(billId);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void confirmMissingRate(ArWriteoffRate input)
|
||||
{
|
||||
requireFinance();
|
||||
if (input == null || input.getWriteoffId() == null || input.getRate() == null
|
||||
|| input.getRate().signum() < 0 || input.getRate().compareTo(new BigDecimal("100")) > 0
|
||||
|| input.getRate().scale() > 4 || input.getRemark() == null || input.getRemark().isBlank()
|
||||
|| input.getRemark().length() > 500)
|
||||
throw new ServiceException("请填写 0 至 100 的提成比例及核对说明");
|
||||
Long billId = mapper.selectBillIdByWriteoffId(input.getWriteoffId());
|
||||
ArBill bill = billId == null ? null : billMapper.selectArBillByIdForUpdate(billId);
|
||||
if (bill == null || bill.getProfitSalesUserId() == null)
|
||||
throw new ServiceException("核销记录无效或账单销售员快照缺失");
|
||||
if (!ArBillGenerationStatus.READY.equals(bill.getGenerationStatus())
|
||||
|| !(ArBillStatus.CONFIRMED.getCode().equals(bill.getStatus())
|
||||
|| ArBillStatus.PARTIAL_WRITTEN_OFF.getCode().equals(bill.getStatus())
|
||||
|| ArBillStatus.WRITTEN_OFF.getCode().equals(bill.getStatus())))
|
||||
throw new ServiceException("账单未生成完成或状态不允许确认提成比例");
|
||||
String operator = SecurityUtils.getUsername();
|
||||
if (mapper.confirmMissingRate(input.getWriteoffId(), input.getRate(), operator, input.getRemark().trim()) != 1)
|
||||
throw new ServiceException("比例已确认或核销状态已变化,请刷新");
|
||||
if (ArBillStatus.WRITTEN_OFF.getCode().equals(bill.getStatus()) && mapper.countMissingRates(billId) == 0)
|
||||
{
|
||||
mapper.reverseResults(billId, operator);
|
||||
createFinalResults(billId, operator);
|
||||
}
|
||||
}
|
||||
|
||||
private void requireFinance()
|
||||
{
|
||||
if (!scopeResolver.resolve().all()) throw new ServiceException("仅财务和系统管理员可查看或维护提成");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ArCommissionSummary
|
||||
{
|
||||
private Long salesUserId;
|
||||
private String salesUserName;
|
||||
private String currency;
|
||||
private Long orderCount;
|
||||
private Long pendingCount;
|
||||
private BigDecimal commissionAmount;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
import java.util.Date;
|
||||
import lombok.Data;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
@Data
|
||||
public class ArProfitQuery
|
||||
{
|
||||
private Long customerId;
|
||||
private String billNo;
|
||||
private String orderNo;
|
||||
private String status;
|
||||
private Long salesUserId;
|
||||
private Long arBillId;
|
||||
private Long detailId;
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd")
|
||||
private Date beginBillDate;
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd")
|
||||
private Date endBillDate;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import lombok.Data;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.bms.common.annotation.Excel;
|
||||
|
||||
@Data
|
||||
public class ArProfitRow
|
||||
{
|
||||
private Long arBillId;
|
||||
@Excel(name = "账单号", width = 20) private String billNo;
|
||||
@Excel(name = "客户代码", width = 16) private String customerCode;
|
||||
@Excel(name = "客户名称", width = 24) private String customerName;
|
||||
private String customerArea;
|
||||
@Excel(name = "归属来源", readConverterExp = "NEW=生成时快照,BACKFILLED=历史补录", width = 14) private String snapshotSource;
|
||||
@Excel(name = "销售员", width = 16) private String salesUserName;
|
||||
@Excel(name = "币种", width = 10) private String currency;
|
||||
@Excel(name = "账单状态", readConverterExp = "CONFIRMED=已确认,PARTIAL_WRITTEN_OFF=部分核销,WRITTEN_OFF=已核销", width = 14) private String status;
|
||||
@Excel(name = "账单日期", dateFormat = "yyyy-MM-dd", width = 15)
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private Date billDate;
|
||||
@Excel(name = "销售价", scale = 4, width = 16) private BigDecimal salesAmount;
|
||||
@Excel(name = "产品价", scale = 4, width = 16) private BigDecimal productAmount;
|
||||
@Excel(name = "销售毛利", scale = 4, width = 16) private BigDecimal salesGrossProfit;
|
||||
@Excel(name = "销售毛利率(%)", scale = 4, width = 18) private BigDecimal salesGrossMarginRate;
|
||||
@Excel(name = "账单已核销", scale = 2, width = 16) private BigDecimal writtenOffAmount;
|
||||
@Excel(name = "账单未核销", scale = 2, width = 16) private BigDecimal unwrittenAmount;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ArProfitSalesOption
|
||||
{
|
||||
private Long userId;
|
||||
private String name;
|
||||
private String code;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
/** 后端构造的数据范围,不接收前端传入的权限参数。 */
|
||||
public record ArProfitScope(boolean all, boolean self, boolean department, Long userId, Long deptId)
|
||||
{
|
||||
public boolean isAll() { return all; }
|
||||
public boolean isSelf() { return self; }
|
||||
public boolean isDepartment() { return department; }
|
||||
public Long getUserId() { return userId; }
|
||||
public Long getDeptId() { return deptId; }
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.bms.ar.security.ArBillRoleKeys;
|
||||
import com.bms.common.constant.Constants;
|
||||
import com.bms.common.core.domain.entity.SysRole;
|
||||
import com.bms.common.core.domain.entity.SysUser;
|
||||
import com.bms.common.core.domain.model.LoginUser;
|
||||
import com.bms.common.exception.ServiceException;
|
||||
import com.bms.common.utils.PermissionContext;
|
||||
import com.bms.common.utils.SecurityUtils;
|
||||
|
||||
@Component
|
||||
public class ArProfitScopeResolver
|
||||
{
|
||||
public ArProfitScope resolve()
|
||||
{
|
||||
return resolve(SecurityUtils.getLoginUser(), PermissionContext.get());
|
||||
}
|
||||
|
||||
public ArProfitScope resolve(LoginUser actor, String permission)
|
||||
{
|
||||
if (actor == null || actor.getUser() == null || actor.getUserId() == null)
|
||||
{
|
||||
throw new ServiceException("登录状态无效,请重新登录", 401);
|
||||
}
|
||||
SysUser user = actor.getUser();
|
||||
if (!"0".equals(user.getStatus()) || !"0".equals(user.getDelFlag()))
|
||||
{
|
||||
return new ArProfitScope(false, false, false, actor.getUserId(), actor.getDeptId());
|
||||
}
|
||||
if (user.isAdmin()) return new ArProfitScope(true, false, false, actor.getUserId(), actor.getDeptId());
|
||||
boolean all = false, self = false, department = false;
|
||||
if (permission != null && !permission.isBlank() && user.getRoles() != null)
|
||||
{
|
||||
for (SysRole role : user.getRoles())
|
||||
{
|
||||
if (role == null || !"0".equals(role.getStatus()) || !permits(role.getPermissions(), permission)) continue;
|
||||
String key = role.getRoleKey();
|
||||
all |= ArBillRoleKeys.ALL_DATA_ROLES.contains(key == null ? "" : key);
|
||||
self |= ArBillRoleKeys.SALES.equals(key);
|
||||
department |= ArBillRoleKeys.SALES_MANAGER.equals(key);
|
||||
}
|
||||
}
|
||||
if (!all && !self && !department) throw new ServiceException("无权访问应收账单毛利分析");
|
||||
return new ArProfitScope(all, self && actor.getUserId() > 0,
|
||||
department && actor.getDeptId() != null && actor.getDeptId() > 0,
|
||||
actor.getUserId(), actor.getDeptId());
|
||||
}
|
||||
|
||||
private boolean permits(Set<String> permissions, String required)
|
||||
{
|
||||
return permissions != null && (permissions.contains(Constants.ALL_PERMISSION)
|
||||
|| Arrays.stream(required.split(Constants.PERMISSION_DELIMITER)).map(String::trim).anyMatch(permissions::contains));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
import java.util.List;
|
||||
import org.springframework.stereotype.Service;
|
||||
import com.bms.ar.mapper.ArProfitMapper;
|
||||
import com.bms.ar.domain.ArBillDetailFee;
|
||||
import com.bms.ar.domain.ArBillDetail;
|
||||
|
||||
@Service
|
||||
public class ArProfitService
|
||||
{
|
||||
private final ArProfitMapper mapper;
|
||||
private final ArProfitScopeResolver scopeResolver;
|
||||
|
||||
public ArProfitService(ArProfitMapper mapper, ArProfitScopeResolver scopeResolver)
|
||||
{
|
||||
this.mapper = mapper;
|
||||
this.scopeResolver = scopeResolver;
|
||||
}
|
||||
|
||||
public List<ArProfitRow> selectBills(ArProfitQuery query)
|
||||
{
|
||||
return mapper.selectBills(query == null ? new ArProfitQuery() : query, scopeResolver.resolve());
|
||||
}
|
||||
|
||||
public List<ArProfitSummary> selectSummary(ArProfitQuery query)
|
||||
{
|
||||
return mapper.selectSummary(query == null ? new ArProfitQuery() : query, scopeResolver.resolve());
|
||||
}
|
||||
|
||||
public List<ArProfitSalesOption> selectSalesOptions(String keyword)
|
||||
{
|
||||
ArProfitScope scope = scopeResolver.resolve();
|
||||
if (!scope.all() && !scope.self() && !scope.department())
|
||||
{
|
||||
return List.of();
|
||||
}
|
||||
if (keyword != null)
|
||||
{
|
||||
keyword = keyword.trim();
|
||||
if (keyword.length() > 100) keyword = keyword.substring(0, 100);
|
||||
}
|
||||
return mapper.selectSalesOptions(keyword);
|
||||
}
|
||||
|
||||
public List<ArBillDetailFee> selectFees(Long detailId)
|
||||
{
|
||||
ArProfitQuery query = new ArProfitQuery();
|
||||
query.setDetailId(detailId);
|
||||
return mapper.selectFees(query, scopeResolver.resolve());
|
||||
}
|
||||
|
||||
public List<ArBillDetail> selectBillDetails(Long billId)
|
||||
{
|
||||
ArProfitQuery query = new ArProfitQuery();
|
||||
query.setArBillId(billId);
|
||||
return mapper.selectBillDetails(query, scopeResolver.resolve());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ArProfitSummary
|
||||
{
|
||||
private String currency;
|
||||
private Long billCount;
|
||||
private Long invalidBillCount;
|
||||
private BigDecimal salesAmount;
|
||||
private BigDecimal productAmount;
|
||||
private BigDecimal salesGrossProfit;
|
||||
private BigDecimal salesGrossMarginRate;
|
||||
private BigDecimal writtenOffAmount;
|
||||
private BigDecimal unwrittenAmount;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ArWriteoffRate
|
||||
{
|
||||
private Long writeoffId;
|
||||
private Long arBillId;
|
||||
private String billNo;
|
||||
private String customerName;
|
||||
private Long salesUserId;
|
||||
private String salesUserName;
|
||||
private BigDecimal writeoffAmount;
|
||||
private Date writeoffDate;
|
||||
private BigDecimal rate;
|
||||
private String remark;
|
||||
private String status;
|
||||
private String confirmedBy;
|
||||
private Date confirmedTime;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.bms.ar.profit;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.List;
|
||||
|
||||
/** 根据账单有效核销及当时比例计算单个账单订单的提成。 */
|
||||
public final class CommissionCalculator
|
||||
{
|
||||
private static final BigDecimal HUNDRED = new BigDecimal("100");
|
||||
|
||||
private CommissionCalculator() {}
|
||||
|
||||
/** 比例以百分数表示,10 代表 10%;缺失比例不得按零处理。 */
|
||||
public record Writeoff(BigDecimal amount, BigDecimal rate) {}
|
||||
|
||||
public record Result(BigDecimal estimated, BigDecimal formal, boolean complete) {}
|
||||
|
||||
public static Result calculate(BigDecimal billAmount, BigDecimal orderProfit, List<Writeoff> writeoffs)
|
||||
{
|
||||
if (billAmount == null || billAmount.signum() <= 0 || orderProfit == null || writeoffs == null)
|
||||
{
|
||||
return new Result(null, null, false);
|
||||
}
|
||||
BigDecimal written = BigDecimal.ZERO;
|
||||
BigDecimal weightedRates = BigDecimal.ZERO;
|
||||
boolean hasMissingRate = false;
|
||||
for (Writeoff writeoff : writeoffs)
|
||||
{
|
||||
if (writeoff == null || writeoff.amount() == null || writeoff.amount().signum() <= 0)
|
||||
{
|
||||
throw new IllegalArgumentException("核销金额必须大于零");
|
||||
}
|
||||
written = written.add(writeoff.amount());
|
||||
if (writeoff.rate() == null)
|
||||
{
|
||||
hasMissingRate = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (writeoff.rate().signum() < 0 || writeoff.rate().compareTo(HUNDRED) > 0)
|
||||
{
|
||||
throw new IllegalArgumentException("提成比例必须在 0 至 100 之间");
|
||||
}
|
||||
weightedRates = weightedRates.add(writeoff.amount().multiply(writeoff.rate()));
|
||||
}
|
||||
}
|
||||
if (written.compareTo(billAmount) > 0)
|
||||
{
|
||||
throw new IllegalArgumentException("有效核销金额超过账单金额");
|
||||
}
|
||||
boolean complete = written.compareTo(billAmount) == 0;
|
||||
if (hasMissingRate)
|
||||
{
|
||||
return new Result(null, null, complete);
|
||||
}
|
||||
BigDecimal amount = orderProfit.multiply(weightedRates)
|
||||
.divide(billAmount.multiply(HUNDRED), 2, RoundingMode.HALF_UP);
|
||||
return new Result(amount, complete ? amount : null, complete);
|
||||
}
|
||||
|
||||
/** 对同一账单的结果按明细顺序分配舍入尾差,使逐单金额之和等于该账单精确总额的四舍五入。 */
|
||||
public static void allocateFinalAmounts(List<ArCommissionResult> items)
|
||||
{
|
||||
BigDecimal cumulativeNumerator = BigDecimal.ZERO;
|
||||
BigDecimal allocated = BigDecimal.ZERO;
|
||||
BigDecimal billAmount = null;
|
||||
BigDecimal weightedRate = null;
|
||||
for (ArCommissionResult item : items)
|
||||
{
|
||||
if (!"READY".equals(item.getResultStatus())) continue;
|
||||
if (item.getBillAmount() == null || item.getBillAmount().signum() <= 0
|
||||
|| item.getGrossProfit() == null || item.getWeightedRate() == null)
|
||||
throw new IllegalArgumentException("正式提成计算数据不完整");
|
||||
if (billAmount == null)
|
||||
{
|
||||
billAmount = item.getBillAmount();
|
||||
weightedRate = item.getWeightedRate();
|
||||
}
|
||||
else if (billAmount.compareTo(item.getBillAmount()) != 0 || weightedRate.compareTo(item.getWeightedRate()) != 0)
|
||||
throw new IllegalArgumentException("同一账单的提成计算依据不一致");
|
||||
cumulativeNumerator = cumulativeNumerator.add(item.getGrossProfit().multiply(item.getWeightedRate()));
|
||||
BigDecimal cumulativeAmount = cumulativeNumerator.divide(billAmount.multiply(HUNDRED), 2, RoundingMode.HALF_UP);
|
||||
item.setCommissionAmount(cumulativeAmount.subtract(allocated));
|
||||
allocated = cumulativeAmount;
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
@@ -24,6 +24,7 @@ import com.bms.ar.enums.ArLogResult;
|
||||
import com.bms.ar.mapper.ArBalanceWriteoffMapper;
|
||||
import com.bms.ar.mapper.ArBillMapper;
|
||||
import com.bms.ar.security.ArBillScopeResolver;
|
||||
import com.bms.ar.profit.ArCommissionService;
|
||||
import com.bms.ar.service.IArBalanceWriteoffService;
|
||||
import com.bms.ar.service.IArBillLogService;
|
||||
import com.bms.common.exception.ServiceException;
|
||||
@@ -49,6 +50,8 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService {
|
||||
private ArBillMapper billMapper;
|
||||
@Autowired
|
||||
private ArBillScopeResolver billScope;
|
||||
@Autowired
|
||||
private ArCommissionService commissionService;
|
||||
|
||||
@Autowired
|
||||
private ArBalanceWriteoffMapper writeoffMapper;
|
||||
@@ -141,6 +144,7 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService {
|
||||
writeoff.setCreateUserId(operatorUserId);
|
||||
writeoff.setCreateBy(operator);
|
||||
writeoffMapper.insertArBalanceWriteoff(writeoff);
|
||||
commissionService.snapshotWriteoff(bill, writeoff);
|
||||
|
||||
// 3. 账单核销口径变更(2026-09-23):核销不再变动账户余额与已用额度,
|
||||
// 仅更新账单已核销/未核销金额与状态,资金变动由收款/计费入口产生。
|
||||
@@ -153,6 +157,10 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService {
|
||||
throw new ServiceException("账单状态已发生变化,请刷新后重试");
|
||||
}
|
||||
|
||||
if (ArBillStatus.WRITTEN_OFF.getCode().equals(nextStatus)) {
|
||||
commissionService.createFinalResults(bill.getArBillId(), operator);
|
||||
}
|
||||
|
||||
recordLog(bill.getArBillId(), writeoff.getWriteoffId(), ArLogOperationType.BALANCE_WRITEOFF,
|
||||
"余额核销账单 " + amount.toPlainString() + " " + currency,
|
||||
fromStatus, nextStatus, operator, requestId);
|
||||
@@ -207,6 +215,7 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService {
|
||||
ArBalanceWriteoffStatus.CANCELLED.getCode(), ArBalanceWriteoffStatus.EFFECTIVE.getCode()) != 1) {
|
||||
throw new ServiceException("核销记录状态已变化,请刷新后重试");
|
||||
}
|
||||
commissionService.reverseFinalResults(bill.getArBillId(), operator);
|
||||
recordLog(bill.getArBillId(), writeoffId, ArLogOperationType.CANCEL_BALANCE_WRITEOFF,
|
||||
"反核销取消核销:" + cancelRemark,
|
||||
fromStatus, nextStatus, operator, requestId);
|
||||
|
||||
@@ -73,6 +73,10 @@ import com.bms.ar.mapper.ArBillLogMapper;
|
||||
import com.bms.ar.mapper.ArBillMapper;
|
||||
import com.bms.ar.security.ArBillScopeResolver;
|
||||
import com.bms.customer.customerinfo.domain.BmsCustomerOption;
|
||||
import com.bms.customer.customerinfo.domain.BmsCustomer;
|
||||
import com.bms.customer.customerinfo.mapper.BmsCustomerMapper;
|
||||
import com.bms.common.core.domain.entity.SysUser;
|
||||
import com.bms.system.mapper.SysUserMapper;
|
||||
import com.bms.ar.mapper.ArBillGenerateTaskMapper;
|
||||
import com.bms.ar.mapper.ArBankAccountMapper;
|
||||
import com.bms.ar.mapper.ArExportTemplateMapper;
|
||||
@@ -185,6 +189,10 @@ public class ArBillServiceImpl implements IArBillService {
|
||||
@Autowired
|
||||
private ArBillMapper billMapper;
|
||||
@Autowired
|
||||
private BmsCustomerMapper customerMapper;
|
||||
@Autowired
|
||||
private SysUserMapper sysUserMapper;
|
||||
@Autowired
|
||||
private ArBillScopeResolver billScope;
|
||||
@Autowired
|
||||
private ArBillGenerateTaskMapper generateTaskMapper;
|
||||
@@ -441,6 +449,21 @@ public class ArBillServiceImpl implements IArBillService {
|
||||
String customerName = StringUtils.trim(request.getCustomerName());
|
||||
bill.setCustomerCode(customerCode == null ? "" : customerCode);
|
||||
bill.setCustomerName(customerName == null ? "" : customerName);
|
||||
bill.setProfitSnapshotSource("NEW");
|
||||
// 固定账单生成时的客户归属;无法确定的用户保持为空,由财务核对。
|
||||
BmsCustomer snapshotCustomer = customerMapper.selectBmsCustomerByCustomerId(request.getCustomerId());
|
||||
if (snapshotCustomer != null) {
|
||||
bill.setProfitCustomerArea(snapshotCustomer.getCustomerArea());
|
||||
String salesId = snapshotCustomer.getSalesUserId();
|
||||
if (salesId != null && salesId.matches("[0-9]{1,18}")) {
|
||||
SysUser salesUser = sysUserMapper.selectUserById(Long.valueOf(salesId));
|
||||
if (salesUser != null) {
|
||||
bill.setProfitSalesUserId(salesUser.getUserId());
|
||||
bill.setProfitSalesUserCode(salesUser.getUserName());
|
||||
bill.setProfitSalesUserName(salesUser.getNickName());
|
||||
}
|
||||
}
|
||||
}
|
||||
bill.setBillPeriodStart(request.getBillPeriodEnd());
|
||||
bill.setBillPeriodEnd(request.getBillPeriodEnd());
|
||||
bill.setBillDate(request.getBillDate() == null ? now : request.getBillDate());
|
||||
|
||||
@@ -16,6 +16,11 @@ public enum ProfitAreaRule
|
||||
this.customerArea = customerArea;
|
||||
}
|
||||
|
||||
public String getCustomerArea()
|
||||
{
|
||||
return customerArea;
|
||||
}
|
||||
|
||||
public static ProfitAreaRule fromCustomerArea(String customerArea)
|
||||
{
|
||||
if (customerArea != null)
|
||||
|
||||
@@ -47,7 +47,7 @@ public class OracleOrderBillMapper
|
||||
req.setCountryCode(firstStr(row, "COUNTRY"));
|
||||
String countryName = firstStr(row, "COUNTRY_NAME", "COUNTRY_EINGTH_NAME", "COUNTRY");
|
||||
req.setCountryName(countryName);
|
||||
req.setDestPostcode(firstStr(row, "CONSIGNEE_POSTCODE"));
|
||||
req.setDestPostcode(StringUtils.normalizePostcode(firstStr(row, "CONSIGNEE_POSTCODE")));
|
||||
// Prefer CONFIRM_WEIGHT (customer confirmed); fallback DIMENSIONAL_WEIGHT_FACTOR (charge weight).
|
||||
BigDecimal weight = firstPositiveDecimal(row, "CONFIRM_WEIGHT", "DIMENSIONAL_WEIGHT_FACTOR");
|
||||
req.setWeight(weight);
|
||||
|
||||
@@ -69,8 +69,8 @@ public class EsBillSearchStore implements IBillSearchStore
|
||||
doc.put("bizId", bizId.trim());
|
||||
doc.put("status", StringUtils.isEmpty(status) ? EsBizLogSupport.STATUS_SUCCESS : status.trim());
|
||||
doc.put("error", StringUtils.isEmpty(errorMessage) ? null : errorMessage);
|
||||
doc.put("request", parseOrRaw(requestJson));
|
||||
// Normalize response.ok boolean -> 1/0: index mapping typed response.ok as long.
|
||||
// Index dynamic mapping is strict on a few fields; coerce before PUT.
|
||||
doc.put("request", normalizeRequestForEs(parseOrRaw(requestJson)));
|
||||
doc.put("response", normalizeResponseForEs(parseOrRaw(responseJson)));
|
||||
String ts = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
|
||||
doc.put("updatedAt", ts);
|
||||
@@ -86,7 +86,26 @@ public class EsBillSearchStore implements IBillSearchStore
|
||||
}
|
||||
}
|
||||
|
||||
/** Index historically mapped response.ok as long; coerce boolean to 1/0. */
|
||||
/**
|
||||
* request.bizDate is mapped as date (ISO / epoch only); bill writes "yyyy-MM-dd HH:mm:ss".
|
||||
* request.taskId is mapped as long; UUID strings must not stay under taskId.
|
||||
*/
|
||||
private Object normalizeRequestForEs(Object request)
|
||||
{
|
||||
if (!(request instanceof JSONObject))
|
||||
{
|
||||
return request;
|
||||
}
|
||||
JSONObject obj = (JSONObject) request;
|
||||
normalizeBizDateField(obj);
|
||||
relocateNonNumericTaskId(obj);
|
||||
return obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* response.ok mapped as long; response.success as boolean; response.taskId as long.
|
||||
* Local rebill DONE used UUID taskId + numeric success and was rejected by ES.
|
||||
*/
|
||||
private Object normalizeResponseForEs(Object response)
|
||||
{
|
||||
if (!(response instanceof JSONObject))
|
||||
@@ -99,9 +118,54 @@ public class EsBillSearchStore implements IBillSearchStore
|
||||
{
|
||||
obj.put("ok", Boolean.TRUE.equals(ok) ? Integer.valueOf(1) : Integer.valueOf(0));
|
||||
}
|
||||
Object success = obj.get("success");
|
||||
if (success instanceof Number)
|
||||
{
|
||||
obj.put("success", Boolean.valueOf(((Number) success).intValue() != 0));
|
||||
}
|
||||
relocateNonNumericTaskId(obj);
|
||||
return obj;
|
||||
}
|
||||
|
||||
private void normalizeBizDateField(JSONObject obj)
|
||||
{
|
||||
Object raw = obj.get("bizDate");
|
||||
if (!(raw instanceof String))
|
||||
{
|
||||
return;
|
||||
}
|
||||
String bizDate = ((String) raw).trim();
|
||||
// "yyyy-MM-dd HH:mm:ss" -> ISO-local so ES date mapper accepts it.
|
||||
if (bizDate.length() >= 19 && bizDate.charAt(10) == ' ')
|
||||
{
|
||||
obj.put("bizDate", bizDate.substring(0, 10) + "T" + bizDate.substring(11));
|
||||
}
|
||||
}
|
||||
|
||||
private void relocateNonNumericTaskId(JSONObject obj)
|
||||
{
|
||||
Object taskId = obj.get("taskId");
|
||||
if (!(taskId instanceof String))
|
||||
{
|
||||
return;
|
||||
}
|
||||
String text = ((String) taskId).trim();
|
||||
if (text.isEmpty())
|
||||
{
|
||||
obj.remove("taskId");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
obj.put("taskId", Long.valueOf(Long.parseLong(text)));
|
||||
}
|
||||
catch (NumberFormatException e)
|
||||
{
|
||||
obj.remove("taskId");
|
||||
obj.put("taskIdStr", text);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public BillSyncSnapshot get(String logType, String bizId)
|
||||
{
|
||||
|
||||
+1
-1
@@ -3324,7 +3324,7 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
|
||||
bill.setPkgHeight(request.getPkgHeight());
|
||||
bill.setShipperName(request.getShipperName());
|
||||
bill.setConsigneeName(request.getConsigneeName());
|
||||
bill.setDestPostcode(request.getDestPostcode());
|
||||
bill.setDestPostcode(StringUtils.normalizePostcode(request.getDestPostcode()));
|
||||
bill.setWarehouseCode(request.getWarehouseCode());
|
||||
bill.setOrderTime(request.getOrderTime());
|
||||
applyUpstreamOrderStatus(bill, request);
|
||||
|
||||
+11
-3
@@ -40,6 +40,7 @@ import com.bms.price.domain.PrcSurchargeRel;
|
||||
import com.bms.price.mapper.BmsProductCountryMapper;
|
||||
import com.bms.price.mapper.BmsProductMapper;
|
||||
import com.bms.price.mapper.PrcCustomerPriceSetMapper;
|
||||
import com.bms.price.mapper.PrcOrderBillMapper;
|
||||
import com.bms.price.mapper.PrcPriceSetDetailMapper;
|
||||
import com.bms.price.mapper.PrcPriceSetMapper;
|
||||
import com.bms.price.mapper.PrcPriceSetProductMapper;
|
||||
@@ -141,6 +142,9 @@ public class PrcPriceSetServiceImpl implements IPrcPriceSetService
|
||||
@Autowired
|
||||
private IBmsCustomerService bmsCustomerService;
|
||||
|
||||
@Autowired
|
||||
private PrcOrderBillMapper orderBillMapper;
|
||||
|
||||
@Override
|
||||
public PrcPriceSet selectPrcPriceSetById(Long priceSetId)
|
||||
{
|
||||
@@ -626,7 +630,7 @@ public class PrcPriceSetServiceImpl implements IPrcPriceSetService
|
||||
{
|
||||
throw new ServiceException(MessageUtils.message("price.set.version.notExists"));
|
||||
}
|
||||
// Draft / pending: hard delete; EFFECT: soft delete then reopen previous via refreshVersionStatus
|
||||
// Draft / pending / effect may be deleted; expired stays view-only.
|
||||
if (!VER_DRAFT.equals(version.getStatus())
|
||||
&& !VER_PENDING.equals(version.getStatus())
|
||||
&& !VER_EFFECT.equals(version.getStatus()))
|
||||
@@ -634,9 +638,13 @@ public class PrcPriceSetServiceImpl implements IPrcPriceSetService
|
||||
throw new ServiceException(MessageUtils.message("price.set.version.delete.statusNotAllowed"));
|
||||
}
|
||||
requireSet(version.getPriceSetId());
|
||||
wipeVersionChildren(psvId, version.getStatus());
|
||||
// Products / details / surcharge always physical delete.
|
||||
surchargeRelMapper.physicalDeleteByPsvId(psvId);
|
||||
detailMapper.physicalDeleteByPsvId(psvId);
|
||||
setProductMapper.physicalDeleteByPsvId(psvId);
|
||||
// Version: soft-delete when any order bill references psv_id; otherwise hard-delete.
|
||||
int rows;
|
||||
if (VER_EFFECT.equals(version.getStatus()))
|
||||
if (orderBillMapper.countByPsvId(psvId) > 0)
|
||||
{
|
||||
rows = versionMapper.softDeleteById(psvId, updateBy);
|
||||
}
|
||||
|
||||
+1
-9
@@ -783,15 +783,7 @@ public class PrcZoneServiceImpl implements IPrcZoneService
|
||||
|
||||
private static String normalizePostcode(String postcode)
|
||||
{
|
||||
if (StringUtils.isEmpty(postcode))
|
||||
{
|
||||
return postcode;
|
||||
}
|
||||
if (postcode.endsWith(".0") && postcode.matches("\\d+\\.0"))
|
||||
{
|
||||
return postcode.substring(0, postcode.length() - 2);
|
||||
}
|
||||
return postcode;
|
||||
return StringUtils.normalizePostcode(postcode);
|
||||
}
|
||||
|
||||
private static String normalizeCell(String text)
|
||||
|
||||
+6
-11
@@ -388,7 +388,11 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
|
||||
}
|
||||
// Charge weight keeps 3 decimals; freight unit price keeps 2 (see buildFromRates).
|
||||
BigDecimal weight = request.getWeight().setScale(3, RoundingMode.HALF_UP);
|
||||
String destPostcode = emptyToNull(request.getDestPostcode());
|
||||
String destPostcode = emptyToNull(normalizePostcode(request.getDestPostcode()));
|
||||
if (destPostcode != null)
|
||||
{
|
||||
request.setDestPostcode(destPostcode);
|
||||
}
|
||||
String productName = null;
|
||||
if (request instanceof TmsPriceBillRequest)
|
||||
{
|
||||
@@ -992,16 +996,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
|
||||
|
||||
private static String normalizePostcode(String postcode)
|
||||
{
|
||||
if (StringUtils.isEmpty(postcode))
|
||||
{
|
||||
return postcode;
|
||||
}
|
||||
String n = postcode.trim().replace(" ", "");
|
||||
if (n.endsWith(".0") && n.matches("\\d+\\.0"))
|
||||
{
|
||||
return n.substring(0, n.length() - 2);
|
||||
}
|
||||
return n;
|
||||
return StringUtils.normalizePostcode(postcode);
|
||||
}
|
||||
|
||||
private TmsPriceQuoteResult tryFixed(PrcCustomerPriceSet bind, PrcPriceSet set, PrcPriceSetVersion version,
|
||||
|
||||
@@ -11,6 +11,11 @@
|
||||
<result property="customerId" column="customer_id"/>
|
||||
<result property="customerCode" column="customer_code"/>
|
||||
<result property="customerName" column="customer_name"/>
|
||||
<result property="profitCustomerArea" column="profit_customer_area"/>
|
||||
<result property="profitSalesUserId" column="profit_sales_user_id"/>
|
||||
<result property="profitSalesUserCode" column="profit_sales_user_code"/>
|
||||
<result property="profitSalesUserName" column="profit_sales_user_name"/>
|
||||
<result property="profitSnapshotSource" column="profit_snapshot_source"/>
|
||||
<result property="billPeriodStart" column="bill_period_start"/>
|
||||
<result property="billPeriodEnd" column="bill_period_end"/>
|
||||
<result property="billDate" column="bill_date"/>
|
||||
@@ -48,6 +53,11 @@
|
||||
customer_id,
|
||||
customer_code,
|
||||
customer_name,
|
||||
profit_customer_area,
|
||||
profit_sales_user_id,
|
||||
profit_sales_user_code,
|
||||
profit_sales_user_name,
|
||||
profit_snapshot_source,
|
||||
bill_period_start,
|
||||
bill_period_end,
|
||||
bill_date,
|
||||
@@ -169,13 +179,15 @@
|
||||
</select>
|
||||
|
||||
<insert id="insertArBill" parameterType="ArBill" useGeneratedKeys="true" keyProperty="arBillId">
|
||||
insert into ar_bill (bill_no, bill_name, customer_id, customer_code, customer_name, bill_period_start,
|
||||
insert into ar_bill (bill_no, bill_name, customer_id, customer_code, customer_name,
|
||||
profit_customer_area, profit_sales_user_id, profit_sales_user_code, profit_sales_user_name, profit_snapshot_source, bill_period_start,
|
||||
bill_period_end,
|
||||
bill_date, currency, order_count, total_amount, written_off_amount, unwritten_amount,
|
||||
status, generation_status, bill_version, bank_account_name, bank_account_no, bank_name,
|
||||
remark,
|
||||
confirmed_by, confirmed_time, create_by, create_user_id, create_time, update_by, update_time)
|
||||
values (#{billNo}, #{billName}, #{customerId}, #{customerCode}, #{customerName}, #{billPeriodStart},
|
||||
values (#{billNo}, #{billName}, #{customerId}, #{customerCode}, #{customerName},
|
||||
#{profitCustomerArea}, #{profitSalesUserId}, #{profitSalesUserCode}, #{profitSalesUserName}, #{profitSnapshotSource}, #{billPeriodStart},
|
||||
#{billPeriodEnd},
|
||||
#{billDate}, #{currency}, #{orderCount}, #{totalAmount}, #{writtenOffAmount}, #{unwrittenAmount},
|
||||
#{status}, #{generationStatus}, #{billVersion}, #{bankAccountName}, #{bankAccountNo}, #{bankName},
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.bms.ar.mapper.ArCommissionMapper">
|
||||
<resultMap id="rate" type="com.bms.ar.profit.ArCommissionRate">
|
||||
<id property="rateId" column="rate_id"/><result property="salesUserId" column="sales_user_id"/>
|
||||
<result property="salesUserCode" column="sales_user_code"/><result property="salesUserName" column="sales_user_name"/>
|
||||
<result property="rate" column="rate"/><result property="effectiveAt" column="effective_at"/>
|
||||
<result property="createBy" column="create_by"/><result property="remark" column="remark"/>
|
||||
</resultMap>
|
||||
<resultMap id="missingRate" type="com.bms.ar.profit.ArWriteoffRate">
|
||||
<id property="writeoffId" column="writeoff_id"/><result property="arBillId" column="ar_bill_id"/>
|
||||
<result property="billNo" column="bill_no"/><result property="customerName" column="customer_name"/>
|
||||
<result property="salesUserId" column="sales_user_id"/><result property="salesUserName" column="sales_user_name"/>
|
||||
<result property="writeoffAmount" column="writeoff_amount"/><result property="writeoffDate" column="writeoff_date"/>
|
||||
<result property="rate" column="rate"/>
|
||||
<result property="status" column="status"/><result property="confirmedBy" column="confirmed_by"/>
|
||||
<result property="confirmedTime" column="confirmed_time"/><result property="remark" column="confirm_remark"/>
|
||||
</resultMap>
|
||||
<resultMap id="commissionResult" type="com.bms.ar.profit.ArCommissionResult">
|
||||
<id property="resultId" column="result_id"/><result property="arBillId" column="ar_bill_id"/>
|
||||
<result property="detailId" column="detail_id"/><result property="billNo" column="bill_no"/>
|
||||
<result property="orderNo" column="order_no"/><result property="salesUserName" column="sales_user_name"/>
|
||||
<result property="currency" column="currency"/><result property="grossProfit" column="gross_profit"/>
|
||||
<result property="commissionAmount" column="commission_amount"/><result property="resultStatus" column="result_status"/>
|
||||
<result property="createTime" column="create_time"/>
|
||||
<result property="reversedBy" column="reversed_by"/><result property="reversedTime" column="reversed_time"/>
|
||||
<result property="salesUserId" column="sales_user_id"/><result property="weightedRate" column="weighted_rate"/>
|
||||
<result property="billAmount" column="bill_amount"/>
|
||||
</resultMap>
|
||||
<resultMap id="commissionSummary" type="com.bms.ar.profit.ArCommissionSummary">
|
||||
<result property="salesUserId" column="sales_user_id"/><result property="salesUserName" column="sales_user_name"/>
|
||||
<result property="currency" column="currency"/><result property="orderCount" column="order_count"/>
|
||||
<result property="pendingCount" column="pending_count"/><result property="commissionAmount" column="commission_amount"/>
|
||||
</resultMap>
|
||||
<select id="selectRates" resultMap="rate">
|
||||
select r.rate_id, r.sales_user_id, u.user_name as sales_user_code, u.nick_name as sales_user_name,
|
||||
r.rate, r.effective_at, r.create_by, r.remark
|
||||
from ar_profit_commission_rate r left join sys_user u on u.user_id = r.sales_user_id
|
||||
order by r.sales_user_id, r.effective_at desc, r.rate_id desc
|
||||
</select>
|
||||
<select id="selectEffective" resultMap="rate">
|
||||
select rate_id, sales_user_id, rate, effective_at
|
||||
from ar_profit_commission_rate
|
||||
where sales_user_id = #{salesUserId} and effective_at <= #{at}
|
||||
order by effective_at desc, rate_id desc limit 1 for update
|
||||
</select>
|
||||
<insert id="insertRate" parameterType="com.bms.ar.profit.ArCommissionRate" useGeneratedKeys="true" keyProperty="rateId">
|
||||
insert into ar_profit_commission_rate(sales_user_id, rate, effective_at, create_by, create_time, remark)
|
||||
values(#{salesUserId}, #{rate}, #{effectiveAt}, #{createBy}, sysdate(), #{remark})
|
||||
</insert>
|
||||
<select id="lockSalesUser" resultType="long">
|
||||
select user_id from sys_user where user_id = #{salesUserId} for update
|
||||
</select>
|
||||
<insert id="insertWriteoffRate">
|
||||
insert into ar_profit_writeoff_rate(writeoff_id, sales_user_id, rate_id, rate, create_time)
|
||||
values(#{writeoffId}, #{salesUserId}, #{rateId}, #{rate}, sysdate())
|
||||
</insert>
|
||||
<select id="selectMissingRates" resultMap="missingRate">
|
||||
select w.writeoff_id, b.ar_bill_id, b.bill_no, b.customer_name,
|
||||
b.profit_sales_user_id as sales_user_id, b.profit_sales_user_name as sales_user_name,
|
||||
w.writeoff_amount, w.writeoff_date, r.rate
|
||||
from ar_balance_writeoff w join ar_bill b on b.ar_bill_id = w.ar_bill_id
|
||||
left join ar_profit_writeoff_rate r on r.writeoff_id = w.writeoff_id
|
||||
where w.status = 'EFFECTIVE' and (r.rate is null or r.rate < 0 or r.rate > 100)
|
||||
and b.status in ('CONFIRMED', 'PARTIAL_WRITTEN_OFF', 'WRITTEN_OFF')
|
||||
and b.generation_status = 'READY'
|
||||
order by w.writeoff_date desc, w.writeoff_id desc
|
||||
</select>
|
||||
<select id="selectWriteoffRates" resultMap="missingRate">
|
||||
select w.writeoff_id, b.ar_bill_id, b.bill_no, b.customer_name,
|
||||
b.profit_sales_user_id as sales_user_id, b.profit_sales_user_name as sales_user_name,
|
||||
w.writeoff_amount, w.writeoff_date, w.status, r.rate, r.confirmed_by, r.confirmed_time, r.confirm_remark
|
||||
from ar_balance_writeoff w join ar_bill b on b.ar_bill_id = w.ar_bill_id
|
||||
left join ar_profit_writeoff_rate r on r.writeoff_id = w.writeoff_id
|
||||
where b.ar_bill_id = #{billId} and b.generation_status = 'READY'
|
||||
and b.status in ('CONFIRMED', 'PARTIAL_WRITTEN_OFF', 'WRITTEN_OFF')
|
||||
order by w.create_time, w.writeoff_id
|
||||
</select>
|
||||
<select id="selectBillIdByWriteoffId" resultType="long">
|
||||
select ar_bill_id from ar_balance_writeoff where writeoff_id = #{writeoffId} and status = 'EFFECTIVE'
|
||||
</select>
|
||||
<select id="countMissingRates" resultType="int">
|
||||
select count(*) from ar_balance_writeoff w
|
||||
left join ar_profit_writeoff_rate r on r.writeoff_id = w.writeoff_id
|
||||
where w.ar_bill_id = #{billId} and w.status = 'EFFECTIVE' and (r.rate is null or r.rate < 0 or r.rate > 100)
|
||||
</select>
|
||||
<update id="confirmMissingRate">
|
||||
update ar_profit_writeoff_rate r
|
||||
join ar_balance_writeoff w on w.writeoff_id = r.writeoff_id and w.status = 'EFFECTIVE'
|
||||
join ar_bill b on b.ar_bill_id = w.ar_bill_id
|
||||
set r.sales_user_id = b.profit_sales_user_id, r.rate = #{rate}, r.confirmed_by = #{operator},
|
||||
r.confirmed_time = sysdate(), r.confirm_remark = #{remark}
|
||||
where r.writeoff_id = #{writeoffId} and r.rate is null and b.profit_sales_user_id is not null
|
||||
</update>
|
||||
<select id="selectResults" resultMap="commissionResult">
|
||||
select r.result_id, r.ar_bill_id, r.detail_id, b.bill_no, d.order_no,
|
||||
b.profit_sales_user_name as sales_user_name, r.currency, r.gross_profit,
|
||||
r.commission_amount, r.result_status, r.create_time, r.reversed_by, r.reversed_time
|
||||
from ar_profit_commission_result r join ar_bill b on b.ar_bill_id = r.ar_bill_id
|
||||
join ar_bill_detail d on d.detail_id = r.detail_id
|
||||
where 1 = 1
|
||||
<choose>
|
||||
<when test="includeReversed">and (r.result_status = 'REVERSED' or (b.status = 'WRITTEN_OFF' and b.generation_status = 'READY'))</when>
|
||||
<otherwise>and r.result_status != 'REVERSED' and b.status = 'WRITTEN_OFF' and b.generation_status = 'READY'</otherwise>
|
||||
</choose>
|
||||
<if test="billId != null">and r.ar_bill_id = #{billId}</if>
|
||||
order by r.result_id desc
|
||||
</select>
|
||||
<select id="selectCommissionSummary" resultMap="commissionSummary">
|
||||
select r.sales_user_id, max(b.profit_sales_user_name) as sales_user_name, r.currency,
|
||||
count(*) as order_count,
|
||||
sum(case when r.result_status != 'READY' then 1 else 0 end) as pending_count,
|
||||
<choose>
|
||||
<when test="billId != null">
|
||||
case when sum(case when r.result_status != 'READY' then 1 else 0 end) > 0 then null
|
||||
else sum(case when r.result_status = 'READY' then r.commission_amount else null end) end
|
||||
</when>
|
||||
<otherwise>sum(case when r.result_status = 'READY' then r.commission_amount else null end)</otherwise>
|
||||
</choose> as commission_amount
|
||||
from ar_profit_commission_result r join ar_bill b on b.ar_bill_id = r.ar_bill_id
|
||||
where r.result_status != 'REVERSED' and b.status = 'WRITTEN_OFF' and b.generation_status = 'READY'
|
||||
<if test="billId != null">and r.ar_bill_id = #{billId}</if>
|
||||
group by r.sales_user_id, r.currency
|
||||
order by sales_user_name, r.currency
|
||||
</select>
|
||||
<update id="reverseResults">
|
||||
update ar_profit_commission_result
|
||||
set result_status = 'REVERSED', reversed_by = #{operator}, reversed_time = sysdate()
|
||||
where ar_bill_id = #{billId} and result_status != 'REVERSED'
|
||||
</update>
|
||||
|
||||
<!-- 当且仅当账单全部核销时,以当次费用快照及每笔有效核销的比例生成正式记录。 -->
|
||||
<select id="selectSettlementInputs" resultMap="commissionResult">
|
||||
<bind name="shenzhenArea" value="@com.bms.price.enums.ProfitAreaRule@SHENZHEN.getCustomerArea()"/>
|
||||
<bind name="guangzhouArea" value="@com.bms.price.enums.ProfitAreaRule@GUANGZHOU.getCustomerArea()"/>
|
||||
select x.ar_bill_id, x.detail_id, x.profit_sales_user_id as sales_user_id, x.currency, x.gross_profit,
|
||||
x.weighted_rate, x.total_amount as bill_amount, coalesce(x.issue, 'READY') as result_status
|
||||
from (
|
||||
select b.ar_bill_id, d.detail_id, b.profit_sales_user_id, d.currency, b.total_amount, w.weighted_rate,
|
||||
case when f.currency_count = 1 and f.fee_currency = d.currency and d.currency = b.currency and f.sales_amount = d.total_amount and b.profit_customer_area = #{shenzhenArea} and f.product_complete = 1
|
||||
then f.sales_amount - f.product_amount
|
||||
when f.currency_count = 1 and f.fee_currency = d.currency and d.currency = b.currency and f.sales_amount = d.total_amount and b.profit_customer_area = #{guangzhouArea} and f.redline_complete = 1
|
||||
then f.sales_amount - f.redline_amount else null end as gross_profit,
|
||||
case when b.profit_sales_user_id is null or b.profit_customer_area is null
|
||||
or b.profit_customer_area not in (#{shenzhenArea},#{guangzhouArea}) then 'MISSING_SNAPSHOT'
|
||||
when w.bill_id is null or w.written_amount != b.total_amount then 'WRITEOFF_MISMATCH'
|
||||
when w.missing_rates > 0 then 'MISSING_RATE'
|
||||
when b.total_amount is null or b.total_amount <= 0 or d.total_amount is null
|
||||
or d.currency is null or b.currency is null or f.sales_amount is null
|
||||
or f.currency_count != 1 or f.fee_currency != d.currency or d.currency != b.currency
|
||||
or f.sales_amount != d.total_amount
|
||||
or (b.profit_customer_area = #{shenzhenArea} and coalesce(f.product_complete, 0) = 0)
|
||||
or (b.profit_customer_area = #{guangzhouArea} and coalesce(f.redline_complete, 0) = 0)
|
||||
then 'MISSING_PRICE'
|
||||
else null end as issue
|
||||
from ar_bill b inner join ar_bill_detail d on d.ar_bill_id = b.ar_bill_id
|
||||
left join (
|
||||
select fee.detail_id, case when count(fee.amount) = count(*) then sum(fee.amount) else null end as sales_amount,
|
||||
case when count(fee.currency) = count(*) then count(distinct fee.currency) else 0 end as currency_count, min(fee.currency) as fee_currency,
|
||||
case when count(fee.product_amount) = count(*) then sum(fee.product_amount) else null end as product_amount,
|
||||
case when count(fee.redline_amount) = count(*) then sum(fee.redline_amount) else null end as redline_amount,
|
||||
case when count(fee.product_amount) = count(*) then 1 else 0 end as product_complete,
|
||||
case when count(fee.redline_amount) = count(*) then 1 else 0 end as redline_complete
|
||||
from ar_bill_detail_fee fee join ar_bill_detail detail on detail.detail_id = fee.detail_id
|
||||
where detail.ar_bill_id = #{billId} group by fee.detail_id
|
||||
) f on f.detail_id = d.detail_id
|
||||
left join (
|
||||
select w.ar_bill_id as bill_id, sum(w.writeoff_amount) as written_amount,
|
||||
sum(case when r.rate is null or r.rate < 0 or r.rate > 100 then 1 else 0 end) as missing_rates,
|
||||
sum(w.writeoff_amount * r.rate) as weighted_rate
|
||||
from ar_balance_writeoff w left join ar_profit_writeoff_rate r on r.writeoff_id = w.writeoff_id
|
||||
where w.status = 'EFFECTIVE' and w.ar_bill_id = #{billId}
|
||||
group by w.ar_bill_id
|
||||
) w on w.bill_id = b.ar_bill_id
|
||||
where b.ar_bill_id = #{billId} and b.status = 'WRITTEN_OFF' and b.generation_status = 'READY'
|
||||
) x order by x.detail_id
|
||||
</select>
|
||||
<insert id="insertResults">
|
||||
insert into ar_profit_commission_result
|
||||
(ar_bill_id, detail_id, sales_user_id, currency, gross_profit, commission_amount, result_status, create_by, create_time)
|
||||
values
|
||||
<foreach collection="items" item="item" separator=",">
|
||||
(#{item.arBillId}, #{item.detailId}, #{item.salesUserId}, #{item.currency}, #{item.grossProfit},
|
||||
#{item.commissionAmount}, #{item.resultStatus}, #{operator}, sysdate())
|
||||
</foreach>
|
||||
</insert>
|
||||
</mapper>
|
||||
@@ -0,0 +1,158 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.bms.ar.mapper.ArProfitMapper">
|
||||
<resultMap id="row" type="com.bms.ar.profit.ArProfitRow">
|
||||
<id property="arBillId" column="ar_bill_id"/>
|
||||
<result property="billNo" column="bill_no"/><result property="billDate" column="bill_date"/>
|
||||
<result property="customerCode" column="customer_code"/><result property="customerName" column="customer_name"/>
|
||||
<result property="customerArea" column="customer_area"/><result property="snapshotSource" column="snapshot_source"/>
|
||||
<result property="salesUserName" column="sales_user_name"/><result property="currency" column="currency"/>
|
||||
<result property="status" column="status"/><result property="salesAmount" column="sales_amount"/>
|
||||
<result property="productAmount" column="product_amount"/><result property="salesGrossProfit" column="sales_gross_profit"/>
|
||||
<result property="salesGrossMarginRate" column="sales_gross_margin_rate"/>
|
||||
<result property="writtenOffAmount" column="written_off_amount"/><result property="unwrittenAmount" column="unwritten_amount"/>
|
||||
</resultMap>
|
||||
<resultMap id="summary" type="com.bms.ar.profit.ArProfitSummary">
|
||||
<result property="currency" column="currency"/><result property="billCount" column="bill_count"/>
|
||||
<result property="invalidBillCount" column="invalid_bill_count"/>
|
||||
<result property="salesAmount" column="sales_amount"/><result property="productAmount" column="product_amount"/>
|
||||
<result property="salesGrossProfit" column="sales_gross_profit"/><result property="salesGrossMarginRate" column="sales_gross_margin_rate"/>
|
||||
<result property="writtenOffAmount" column="written_off_amount"/><result property="unwrittenAmount" column="unwritten_amount"/>
|
||||
</resultMap>
|
||||
<resultMap id="detail" type="com.bms.ar.domain.ArBillDetail">
|
||||
<id property="detailId" column="detail_id"/><result property="orderNo" column="order_no"/>
|
||||
<result property="productName" column="product_name"/><result property="currency" column="currency"/>
|
||||
<result property="totalAmount" column="total_amount"/>
|
||||
</resultMap>
|
||||
<resultMap id="fee" type="com.bms.ar.domain.ArBillDetailFee">
|
||||
<id property="detailFeeId" column="detail_fee_id"/><result property="detailId" column="detail_id"/>
|
||||
<result property="feeName" column="fee_name"/><result property="feeType" column="fee_type"/>
|
||||
<result property="amount" column="amount"/><result property="productAmount" column="product_amount"/>
|
||||
<result property="redlineAmount" column="redline_amount"/><result property="currency" column="currency"/>
|
||||
</resultMap>
|
||||
|
||||
<sql id="scopeCondition">
|
||||
<choose>
|
||||
<when test="scope.all"/>
|
||||
<when test="scope.self or scope.department">
|
||||
and (1 = 0
|
||||
<if test="scope.self">or b.profit_sales_user_id = #{scope.userId}</if>
|
||||
<if test="scope.department">
|
||||
or exists (select 1 from sys_user u inner join sys_dept dept on dept.dept_id = u.dept_id
|
||||
where u.user_id = b.profit_sales_user_id and u.del_flag = '0'
|
||||
and (dept.dept_id = #{scope.deptId} or find_in_set(#{scope.deptId}, dept.ancestors)))
|
||||
</if>
|
||||
)
|
||||
</when>
|
||||
<otherwise>and 1 = 0</otherwise>
|
||||
</choose>
|
||||
</sql>
|
||||
<!-- 订单号仅用于筛选账单,不限制该账单内参与计算的明细。 -->
|
||||
<sql id="billConditions">
|
||||
where b.status in ('CONFIRMED', 'PARTIAL_WRITTEN_OFF', 'WRITTEN_OFF') and b.generation_status = 'READY'
|
||||
<include refid="scopeCondition"/>
|
||||
<if test="query.customerId != null">and b.customer_id = #{query.customerId}</if>
|
||||
<if test="query.billNo != null and query.billNo != ''">and b.bill_no like concat('%', #{query.billNo}, '%')</if>
|
||||
<if test="query.arBillId != null">and b.ar_bill_id = #{query.arBillId}</if>
|
||||
<if test="query.orderNo != null and query.orderNo != ''">
|
||||
and exists (select 1 from ar_bill_detail matched where matched.ar_bill_id = b.ar_bill_id
|
||||
and matched.order_no like concat('%', #{query.orderNo}, '%'))
|
||||
</if>
|
||||
<if test="query.status != null and query.status != ''">and b.status = #{query.status}</if>
|
||||
<if test="query.salesUserId != null">and b.profit_sales_user_id = #{query.salesUserId}</if>
|
||||
<if test="query.beginBillDate != null">and b.bill_date >= #{query.beginBillDate}</if>
|
||||
<if test="query.endBillDate != null">and b.bill_date <= #{query.endBillDate}</if>
|
||||
</sql>
|
||||
|
||||
<!-- 按费用快照先聚合到订单,再聚合到完整账单,避免账单金额及费用重复。 -->
|
||||
<sql id="billRows">
|
||||
<bind name="shenzhenArea" value="@com.bms.price.enums.ProfitAreaRule@SHENZHEN.getCustomerArea()"/>
|
||||
<bind name="guangzhouArea" value="@com.bms.price.enums.ProfitAreaRule@GUANGZHOU.getCustomerArea()"/>
|
||||
select b.ar_bill_id, b.bill_no, b.bill_date, b.customer_code, b.customer_name,
|
||||
b.profit_customer_area as customer_area, b.profit_snapshot_source as snapshot_source,
|
||||
b.profit_sales_user_name as sales_user_name, b.currency, b.status,
|
||||
b.total_amount as sales_amount, b.written_off_amount, b.unwritten_amount,
|
||||
case when a.detail_count > 0 and a.invalid_count = 0 and b.total_amount is not null
|
||||
and a.detail_total = b.total_amount then a.product_total else null end as product_amount,
|
||||
case when a.detail_count > 0 and a.invalid_count = 0 and b.total_amount is not null
|
||||
and a.detail_total = b.total_amount then b.total_amount - a.product_total else null end as sales_gross_profit,
|
||||
case when a.detail_count > 0 and a.invalid_count = 0 and b.total_amount is not null
|
||||
and a.detail_total = b.total_amount and b.total_amount != 0
|
||||
then round((b.total_amount - a.product_total) * 100 / b.total_amount, 4) else null end as sales_gross_margin_rate,
|
||||
case when a.detail_count > 0 and a.invalid_count = 0 and b.total_amount is not null
|
||||
and a.detail_total = b.total_amount then 0 else 1 end as profit_incomplete
|
||||
from ar_bill b
|
||||
left join (
|
||||
select d.ar_bill_id, count(*) as detail_count, sum(d.total_amount) as detail_total,
|
||||
sum(case when d.total_amount is not null and d.currency is not null and b.currency is not null
|
||||
and d.currency = b.currency and f.currency_count = 1 and f.fee_currency = d.currency
|
||||
and f.sales_amount is not null and f.sales_amount = d.total_amount
|
||||
and ((b.profit_customer_area = #{shenzhenArea} and f.product_complete = 1)
|
||||
or (b.profit_customer_area = #{guangzhouArea} and f.redline_complete = 1))
|
||||
then 0 else 1 end) as invalid_count,
|
||||
sum(case when b.profit_customer_area = #{shenzhenArea} then f.product_amount
|
||||
when b.profit_customer_area = #{guangzhouArea} then f.redline_amount else null end) as product_total
|
||||
from ar_bill_detail d join ar_bill b on b.ar_bill_id = d.ar_bill_id
|
||||
left join (
|
||||
select fee.detail_id,
|
||||
case when count(fee.amount) = count(*) then sum(fee.amount) else null end as sales_amount,
|
||||
case when count(fee.currency) = count(*) then count(distinct fee.currency) else 0 end as currency_count,
|
||||
min(fee.currency) as fee_currency,
|
||||
case when count(fee.product_amount) = count(*) then sum(fee.product_amount) else null end as product_amount,
|
||||
case when count(fee.redline_amount) = count(*) then sum(fee.redline_amount) else null end as redline_amount,
|
||||
case when count(fee.product_amount) = count(*) then 1 else 0 end as product_complete,
|
||||
case when count(fee.redline_amount) = count(*) then 1 else 0 end as redline_complete
|
||||
from ar_bill_detail_fee fee
|
||||
join ar_bill_detail d on d.detail_id = fee.detail_id
|
||||
join ar_bill b on b.ar_bill_id = d.ar_bill_id
|
||||
<include refid="billConditions"/>
|
||||
group by fee.detail_id
|
||||
) f on f.detail_id = d.detail_id
|
||||
<include refid="billConditions"/>
|
||||
group by d.ar_bill_id
|
||||
) a on a.ar_bill_id = b.ar_bill_id
|
||||
<include refid="billConditions"/>
|
||||
</sql>
|
||||
<select id="selectBills" resultMap="row">
|
||||
<include refid="billRows"/>
|
||||
order by b.bill_date desc, b.ar_bill_id desc
|
||||
</select>
|
||||
<select id="selectSummary" resultMap="summary">
|
||||
select t.currency, count(*) as bill_count, sum(t.profit_incomplete) as invalid_bill_count,
|
||||
sum(t.sales_amount) as sales_amount, sum(t.product_amount) as product_amount,
|
||||
sum(t.sales_gross_profit) as sales_gross_profit,
|
||||
case when sum(case when t.profit_incomplete = 0 then t.sales_amount else null end) = 0 then null
|
||||
else round(sum(t.sales_gross_profit) * 100 /
|
||||
sum(case when t.profit_incomplete = 0 then t.sales_amount else null end), 4) end as sales_gross_margin_rate,
|
||||
sum(t.written_off_amount) as written_off_amount, sum(t.unwritten_amount) as unwritten_amount
|
||||
from (<include refid="billRows"/>) t group by t.currency order by t.currency
|
||||
</select>
|
||||
<select id="selectSalesOptions" resultType="com.bms.ar.profit.ArProfitSalesOption">
|
||||
select u.user_id as userId, u.nick_name as name, u.user_name as code
|
||||
from sys_user u
|
||||
where u.del_flag = '0' and u.status = '0'
|
||||
<if test="keyword != null and keyword != ''">
|
||||
and (u.nick_name like concat('%', #{keyword}, '%')
|
||||
or u.user_name like concat('%', #{keyword}, '%'))
|
||||
</if>
|
||||
order by u.nick_name, u.user_id
|
||||
limit 50
|
||||
</select>
|
||||
<select id="selectBillDetails" resultMap="detail">
|
||||
select d.detail_id, d.order_no, d.product_name, d.currency, d.total_amount
|
||||
from ar_bill_detail d join ar_bill b on b.ar_bill_id = d.ar_bill_id
|
||||
where b.ar_bill_id = #{query.arBillId}
|
||||
and b.status in ('CONFIRMED', 'PARTIAL_WRITTEN_OFF', 'WRITTEN_OFF') and b.generation_status = 'READY'
|
||||
<include refid="scopeCondition"/>
|
||||
order by d.detail_no, d.detail_id
|
||||
</select>
|
||||
<select id="selectFees" resultMap="fee">
|
||||
select f.* from ar_bill_detail_fee f
|
||||
join ar_bill_detail d on d.detail_id = f.detail_id
|
||||
join ar_bill b on b.ar_bill_id = d.ar_bill_id
|
||||
where d.detail_id = #{query.detailId}
|
||||
and b.status in ('CONFIRMED', 'PARTIAL_WRITTEN_OFF', 'WRITTEN_OFF') and b.generation_status = 'READY'
|
||||
<include refid="scopeCondition"/>
|
||||
order by f.fee_no, f.detail_fee_id
|
||||
</select>
|
||||
</mapper>
|
||||
@@ -1077,4 +1077,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
update_time = sysdate()
|
||||
where bill_id = #{billId}
|
||||
</update>
|
||||
|
||||
<select id="countByPsvId" resultType="int">
|
||||
select count(1) from prc_order_bill where psv_id = #{psvId}
|
||||
</select>
|
||||
</mapper>
|
||||
|
||||
Binary file not shown.
Reference in New Issue
Block a user