ProfitPoolService.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package com.etotem.cfc.service;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.etotem.cfc.config.ConfigService;
  4. import com.etotem.cfc.entity.ProfitPoolOrder;
  5. import com.etotem.cfc.entity.ServiceConfigItem;
  6. import com.etotem.cfc.entity.TeamShareRecord;
  7. import com.etotem.cfc.mapper.ProfitPoolOrderMapper;
  8. import com.etotem.cfc.mapper.ServiceConfigItemMapper;
  9. import com.etotem.cfc.mapper.TeamAwardRecordMapper;
  10. import com.etotem.cfc.mapper.TeamShareRecordMapper;
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13. import org.springframework.stereotype.Service;
  14. import javax.annotation.Resource;
  15. import java.util.Arrays;
  16. import java.util.Date;
  17. import java.util.HashSet;
  18. import java.util.Set;
  19. /**
  20. * 单笔订单利润池计算服务(规格 §2.1 总账模型 + §4.7 杠杆 1 收入管道化 + §8.3 幂等)。
  21. *
  22. * <p><b>核心职责(T9 收入管道化,能力键 {@code team.profit.pipeline})</b>:</p>
  23. * <ul>
  24. * <li>分润触发源扩展 {@code membership / subscription / assessment_retest}(§4.7 杠杆 1),
  25. * 续费/复购在推荐关系存续期间持续产生分润;</li>
  26. * <li>按 §2.1 对每笔订单完成利润漏斗核算(S/C/P/O/F/D/R/T + 8 份池 + 团队奖),
  27. * 只扩展触发源、不提高分配比率(§10#5);</li>
  28. * <li>{@code D > 0} 才进入分润流程并生成 {@code team_share_record}(pending),
  29. * {@code D ≤ 0}(低于保本线)整单不分润、仅落 {@code profit_pool_order} 供统计(§9#3);</li>
  30. * <li>重复回调按唯一键 {@code uk_order(order_type, order_id)} 幂等(§8.3),不重复发放;</li>
  31. * <li>未知触发源被拒绝(防误分配)。</li>
  32. * </ul>
  33. *
  34. * <p>配置读取:优先 {@link ConfigService}(缓存 + 兜底),未注入时回退
  35. * {@link ServiceConfigItemMapper} 直读,均缺失则用 §7.8 默认比率
  36. * (ops 10% / cf 1% / referral 70% / team 30% / eight 80% / award 20%)。</p>
  37. *
  38. * <p>规格:docs/superpowers/specs/2026-11-07-referral-team-profit-sharing.md v0.7
  39. * §2.1 + §2.2 + §4.7 杠杆 1 + §7.1 + §7.8 + §8.3 + §9#3 + §10#5 + §12-T9。</p>
  40. */
  41. @Service
  42. public class ProfitPoolService {
  43. private static final Logger log = LoggerFactory.getLogger(ProfitPoolService.class);
  44. /** §7.1 order_type 允许值(§4.7 杠杆 1 扩展 membership/subscription/assessment_retest) */
  45. private static final Set<String> ALLOWED_ORDER_TYPES = new HashSet<>(Arrays.asList(
  46. "product", "service", "assessment", "package",
  47. "membership", "subscription", "assessment_retest"));
  48. // §7.8 默认比率(配置未写入时使用)
  49. private static final double DEFAULT_OPS_RATE = 0.10;
  50. private static final double DEFAULT_CF_COST_RATE = 0.01;
  51. private static final double DEFAULT_REFERRAL_SHARE = 0.70;
  52. private static final double DEFAULT_TEAM_SHARE = 0.30;
  53. private static final double DEFAULT_EIGHT_SHARE_RATIO = 0.80;
  54. private static final double DEFAULT_TEAM_AWARD_RATIO = 0.20;
  55. private static final int DEFAULT_SHARE_TOTAL = 8;
  56. private static final String CFG_OPS_RATE = "referral_profit.ops_rate";
  57. private static final String CFG_CF_COST_RATE = "referral_profit.cf_cost_rate";
  58. private static final String CFG_REFERRAL_SHARE = "referral_profit.referral_share";
  59. private static final String CFG_TEAM_SHARE = "referral_profit.team_share";
  60. private static final String CFG_EIGHT_SHARE_RATIO = "team_profit.eight_share_ratio";
  61. private static final String CFG_TEAM_AWARD_RATIO = "team_profit.team_award_ratio";
  62. private static final String CFG_SHARE_TOTAL = "team_profit.share_total";
  63. @Resource
  64. private ConfigService configService;
  65. @Resource
  66. private ProfitPoolOrderMapper profitPoolOrderMapper;
  67. @Resource
  68. private TeamShareRecordMapper teamShareRecordMapper;
  69. @Resource
  70. private TeamAwardRecordMapper teamAwardRecordMapper;
  71. @Resource
  72. private ServiceConfigItemMapper serviceConfigItemMapper;
  73. /**
  74. * 分润结算入口(§12-T2 契约,能力键 {@code team.profit.settle})。
  75. *
  76. * <p>签名 {@code (Long orderId, String orderType, Long productId, long amountCent, long costCent)}
  77. * 由契约测试 {@code ProfitPoolOrderContractRedTest} 锚定;内部与管道化入口共用核算核心。</p>
  78. */
  79. public ProfitPoolOrder settle(Long orderId, String orderType, Long productId,
  80. long amountCent, long costCent) {
  81. return doSettle(orderId, orderType, productId, amountCent, costCent, null);
  82. }
  83. /**
  84. * 分润结算入口(§4.7 杠杆 1 收入管道化,能力键 {@code team.profit.pipeline})。
  85. *
  86. * <p>触发源扩展 {@code membership / subscription / assessment_retest};{@code memberId}
  87. * 为订单归属成员(服务提供者/推荐链根),用于生成 {@code team_share_record} 流水。</p>
  88. */
  89. public ProfitPoolOrder settle(long orderId, String orderType, long memberId,
  90. int amountCent, int costCent) {
  91. return doSettle(orderId, orderType, null, amountCent, costCent, memberId);
  92. }
  93. /**
  94. * 核算核心:幂等检查 → 触发源校验 → §2.1 利润漏斗 → 落单 → D>0 生成团队分润流水。
  95. */
  96. private ProfitPoolOrder doSettle(Long orderId, String orderType, Long productId,
  97. long amountCent, long costCent, Long memberId) {
  98. // 幂等(§8.3 uk_order):重复回调返回既有记录,不重复发放
  99. ProfitPoolOrder existing = findExisting(orderId, orderType);
  100. if (existing != null) {
  101. return existing;
  102. }
  103. // 未知触发源拒绝(防误分配)
  104. if (orderType == null || !ALLOWED_ORDER_TYPES.contains(orderType)) {
  105. throw new IllegalArgumentException("未知分润触发源: " + orderType);
  106. }
  107. // §2.1 一般化公式(金额单位:分)
  108. double opsRate = rate(CFG_OPS_RATE, DEFAULT_OPS_RATE);
  109. double cfCostRate = rate(CFG_CF_COST_RATE, DEFAULT_CF_COST_RATE);
  110. double referralShare = rate(CFG_REFERRAL_SHARE, DEFAULT_REFERRAL_SHARE);
  111. double teamShare = rate(CFG_TEAM_SHARE, DEFAULT_TEAM_SHARE);
  112. double eightShareRatio = rate(CFG_EIGHT_SHARE_RATIO, DEFAULT_EIGHT_SHARE_RATIO);
  113. // 团队奖按预算守恒取 T−8份池(8份池占 T×80%、团队奖占 T×20%,§2.1 恒等)
  114. long p = amountCent - costCent;
  115. long o = roundPct(p, opsRate);
  116. long f = roundPct(amountCent, cfCostRate);
  117. long d = p - o - f;
  118. long r;
  119. long t;
  120. long eight;
  121. long award;
  122. if (d <= 0) {
  123. // §2.2/§9#3:D≤0 整单不产生推荐人/团队分润,仅落 profit_pool_order 供统计
  124. r = 0;
  125. t = 0;
  126. eight = 0;
  127. award = 0;
  128. } else {
  129. r = roundPct(d, referralShare);
  130. t = roundPct(d, teamShare);
  131. eight = roundPct(t, eightShareRatio);
  132. // 预算守恒:8 份池 + 团队奖 = T(§2.1,不超 D 预算)
  133. award = t - eight;
  134. }
  135. ProfitPoolOrder pool = new ProfitPoolOrder();
  136. pool.setOrderId(orderId);
  137. pool.setOrderType(orderType);
  138. pool.setProductId(productId);
  139. pool.setAmountCent((int) amountCent);
  140. pool.setCostCent((int) costCent);
  141. pool.setPlatformRetainCent((int) p);
  142. pool.setOpsCent((int) o);
  143. pool.setCfCostCent((int) f);
  144. pool.setPoolCent((int) d);
  145. pool.setReferralShareCent((int) r);
  146. pool.setTeamShareCent((int) t);
  147. pool.setTeamEightShareCent((int) eight);
  148. pool.setTeamAwardCent((int) award);
  149. pool.setStatus("pending");
  150. pool.setCreatedAt(new Date());
  151. profitPoolOrderMapper.insert(pool);
  152. if (d > 0) {
  153. // §8.1:D>0 生成团队 8 份分佣流水(pending,冷静期后 settled)
  154. genTeamShareRecord(pool, memberId);
  155. }
  156. return pool;
  157. }
  158. /** 幂等查询:uk_order(order_type, order_id) 既有记录。 */
  159. private ProfitPoolOrder findExisting(Long orderId, String orderType) {
  160. if (profitPoolOrderMapper == null) {
  161. return null;
  162. }
  163. try {
  164. return profitPoolOrderMapper.selectOne(new LambdaQueryWrapper<ProfitPoolOrder>()
  165. .eq(ProfitPoolOrder::getOrderType, orderType)
  166. .eq(ProfitPoolOrder::getOrderId, orderId)
  167. .last("LIMIT 1"));
  168. } catch (Exception e) {
  169. log.warn("查询 profit_pool_order 幂等失败 orderType={} orderId={}: {}",
  170. orderType, orderId, e.getMessage());
  171. return null;
  172. }
  173. }
  174. /**
  175. * 生成团队 8 份分佣流水(§7.3)。管道化(T9)阶段以订单归属成员为第 1 层基础记录,
  176. * 星级/份数/金额的完整分配(§4.2 星级份数 + §4.4 团队奖)由团队分润服务按团队树与
  177. * 星级快照落地(T2),此处仅落 pending 占位流水并保留 8 份池金额。
  178. */
  179. private void genTeamShareRecord(ProfitPoolOrder pool, Long memberId) {
  180. if (teamShareRecordMapper == null) {
  181. return;
  182. }
  183. Long uid = memberId != null ? memberId : 0L;
  184. int shareTotal = intRate(CFG_SHARE_TOTAL, DEFAULT_SHARE_TOTAL);
  185. int shareTotalSafe = Math.max(1, shareTotal);
  186. TeamShareRecord record = new TeamShareRecord();
  187. record.setOrderId(pool.getOrderId());
  188. record.setOrderType(pool.getOrderType());
  189. record.setPoolId(pool.getId());
  190. record.setProviderUserId(uid);
  191. record.setRecipientUserId(uid);
  192. record.setLayer(1);
  193. record.setShares(1);
  194. record.setShareCent(pool.getTeamEightShareCent() / shareTotalSafe);
  195. record.setStatus("pending");
  196. record.setCreatedAt(new Date());
  197. teamShareRecordMapper.insert(record);
  198. }
  199. /** §2.1 金额取整口径(逐项 round,HALF_UP 等价)。 */
  200. private long roundPct(long base, double rate) {
  201. return Math.round(base * rate);
  202. }
  203. /** 读取 double 比率:ConfigService 优先,回退 service_config 直读,再回退默认。 */
  204. private double rate(String key, double def) {
  205. if (configService != null) {
  206. return configService.getDoubleConfig(key, def);
  207. }
  208. return readConfigDouble(key, def);
  209. }
  210. /** 读取 int 配置:ConfigService 优先,回退 service_config 直读,再回退默认。 */
  211. private int intRate(String key, int def) {
  212. if (configService != null) {
  213. return configService.getIntConfig(key, def);
  214. }
  215. return readConfigInt(key, def);
  216. }
  217. private double readConfigDouble(String key, double def) {
  218. String v = readConfigValue(key);
  219. if (v == null) {
  220. return def;
  221. }
  222. try {
  223. return Double.parseDouble(v.trim());
  224. } catch (NumberFormatException e) {
  225. return def;
  226. }
  227. }
  228. private int readConfigInt(String key, int def) {
  229. String v = readConfigValue(key);
  230. if (v == null) {
  231. return def;
  232. }
  233. try {
  234. return Integer.parseInt(v.trim());
  235. } catch (NumberFormatException e) {
  236. return def;
  237. }
  238. }
  239. private String readConfigValue(String key) {
  240. if (serviceConfigItemMapper == null) {
  241. return null;
  242. }
  243. try {
  244. ServiceConfigItem item = serviceConfigItemMapper.selectOne(
  245. new LambdaQueryWrapper<ServiceConfigItem>()
  246. .eq(ServiceConfigItem::getConfigKey, key)
  247. .last("LIMIT 1"));
  248. return item != null ? item.getConfigValue() : null;
  249. } catch (Exception e) {
  250. log.warn("读取团队分润配置失败 key={}: {}", key, e.getMessage());
  251. return null;
  252. }
  253. }
  254. }