AgentWalletService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. namespace App\Services\Agent;
  3. use App\Models\Agent\Agent;
  4. use App\Models\Agent\AgentBalanceLog;
  5. use App\Models\Agent\AgentProfitCommissionProfile;
  6. use App\Models\Agent\AgentProfitEntry;
  7. use App\Models\Agent\AgentSetting;
  8. use Illuminate\Support\Facades\DB;
  9. /**
  10. * 代理资金唯一入口。
  11. *
  12. * 合营代理:总余额 balance = 保证金本金 margin_amount + 盈亏(可为负)。
  13. * - 充值全部计入保证金本金,不可提现;
  14. * - 盈亏为负时等于从保证金扣除,之后的盈利先补足保证金;
  15. * - 只有超出保证金本金的部分可以提现。
  16. * realtime_balance = balance + 尚未入账的实时分成,是判断「实时保证金」的内部字段,不对代理展示。
  17. */
  18. class AgentWalletService
  19. {
  20. /** 类型 => 方向(1 加,-1 减)。profit_share 单独走 creditProfitShare。 */
  21. private const DIRECTIONS = [
  22. 'credit' => 1, 'debit' => -1, 'recharge' => 1, 'withdraw_refund' => 1,
  23. 'equity_purchase' => -1, 'margin_credit' => 1, 'margin_refund' => -1,
  24. ];
  25. private array $lookups = [];
  26. public const TYPE_NAMES = [
  27. 'credit' => '人工加款', 'debit' => '人工扣款', 'recharge' => '充值', 'withdraw_refund' => '提现退回',
  28. 'withdraw_freeze' => '提现冻结', 'equity_purchase' => '购买股份', 'margin_credit' => '人工增加保证金',
  29. 'margin_refund' => '退还保证金', 'profit_share' => '合营分成', 'commission' => '佣金(旧)',
  30. ];
  31. public function adjust(
  32. int $agentId,
  33. string $amount,
  34. string $type,
  35. string $remark,
  36. string $idempotencyKey,
  37. string $operatorType,
  38. ?int $operatorId,
  39. string $referenceType = '',
  40. ?int $referenceId = null
  41. ): AgentBalanceLog {
  42. if (!isset(self::DIRECTIONS[$type])) {
  43. throw new \InvalidArgumentException('资金变动类型错误');
  44. }
  45. if (bccomp($amount, '0', 4) <= 0) {
  46. throw new \InvalidArgumentException('金额必须大于0');
  47. }
  48. return DB::transaction(function () use ($agentId, $amount, $type, $remark, $idempotencyKey, $operatorType, $operatorId, $referenceType, $referenceId) {
  49. $agent = Agent::query()->lockForUpdate()->findOrFail($agentId);
  50. $existing = AgentBalanceLog::query()->where('idempotency_key', $idempotencyKey)->lockForUpdate()->first();
  51. if ($existing) {
  52. $this->assertSameAdjustment($existing, $agentId, $type, $amount);
  53. return $existing;
  54. }
  55. $signed = self::DIRECTIONS[$type] > 0 ? bcadd($amount, '0', 4) : bcsub('0', $amount, 4);
  56. $before = bcadd((string) $agent->balance, '0', 4);
  57. $after = bcadd($before, $signed, 4);
  58. $realtime = bcadd((string) $agent->realtime_balance, $signed, 4);
  59. // 扣款后,待入账分成按结算日依次入账时余额也不能为负(同时保证实时余额不为负)。
  60. if (self::DIRECTIONS[$type] < 0 && bccomp(bcadd($after, $this->pendingFloor($agent), 4), '0', 4) < 0) {
  61. throw new \RuntimeException('代理余额不足');
  62. }
  63. $agent->balance = $after;
  64. $agent->realtime_balance = $realtime;
  65. if (($type === 'recharge' && $agent->isJoint()) || $type === 'margin_credit') {
  66. $agent->margin_amount = bcadd((string) $agent->margin_amount, $amount, 4);
  67. } elseif ($type === 'margin_refund') {
  68. if (bccomp((string) $agent->margin_amount, $amount, 4) < 0) {
  69. throw new \RuntimeException('退还金额不能超过保证金');
  70. }
  71. $agent->margin_amount = bcsub((string) $agent->margin_amount, $amount, 4);
  72. }
  73. $agent->save();
  74. $log = AgentBalanceLog::query()->create([
  75. 'agent_id' => $agentId, 'type' => $type, 'amount' => $signed,
  76. 'before_balance' => $before, 'after_balance' => $after,
  77. 'operator_type' => $operatorType, 'operator_id' => $operatorId,
  78. 'idempotency_key' => $idempotencyKey, 'remark' => $remark,
  79. 'reference_type' => $referenceType, 'reference_id' => $referenceId,
  80. ]);
  81. $this->evaluateActivation($agent);
  82. return $log;
  83. });
  84. }
  85. /** 每日入账合营分成:实时余额在注单结算时已计入,这里只改 balance。调用方需已在事务内锁住代理。 */
  86. public function creditProfitShare(Agent $agent, string $signed, string $idempotencyKey, int $recordId, string $remark): ?AgentBalanceLog
  87. {
  88. if (bccomp($signed, '0', 4) === 0) return null;
  89. $existing = AgentBalanceLog::query()->where('idempotency_key', $idempotencyKey)->lockForUpdate()->first();
  90. if ($existing) return $existing;
  91. $before = bcadd((string) $agent->balance, '0', 4);
  92. $agent->balance = bcadd($before, $signed, 4);
  93. $agent->save();
  94. return AgentBalanceLog::query()->create([
  95. 'agent_id' => $agent->id, 'type' => 'profit_share', 'amount' => bcadd($signed, '0', 4),
  96. 'before_balance' => $before, 'after_balance' => $agent->balance,
  97. 'operator_type' => 'system', 'operator_id' => null,
  98. 'idempotency_key' => $idempotencyKey, 'remark' => $remark,
  99. 'reference_type' => 'agent_rebate_record', 'reference_id' => $recordId,
  100. ]);
  101. }
  102. /**
  103. * 合营分成开关。实时有效保证金 = min(保证金本金, 实时余额):
  104. * - 达到方案保证金 100% 才开启;
  105. * - 开启后低于方案保证金 × 停止比例(默认 10%)即关闭,之后的注单不再分成。
  106. */
  107. public function evaluateActivation(Agent $agent): bool
  108. {
  109. if (!$agent->isJoint()) {
  110. return $this->setActive($agent, false);
  111. }
  112. $required = $agent->profit_commission_profile_id ? $this->requiredMargin((int) $agent->profit_commission_profile_id) : null;
  113. if ($required === null) {
  114. return $this->setActive($agent, false);
  115. }
  116. $effective = $this->effectiveMargin($agent);
  117. if (!(int) $agent->profit_active) {
  118. return $this->setActive($agent, bccomp($effective, $required, 4) >= 0);
  119. }
  120. $stop = bcdiv(bcmul($required, $this->lookup('stop', fn () => (string) AgentSetting::current()->margin_stop_percent), 8), '100', 4);
  121. return $this->setActive($agent, bccomp($effective, $stop, 4) >= 0);
  122. }
  123. /** 方案要求的保证金;方案不存在返回 null。 */
  124. private function requiredMargin(int $profileId): ?string
  125. {
  126. $margin = $this->lookup('profile:' . $profileId, function () use ($profileId) {
  127. $value = AgentProfitCommissionProfile::query()->whereKey($profileId)->value('margin_amount');
  128. return $value === null ? false : bcadd((string) $value, '0', 4);
  129. });
  130. return $margin === false ? null : $margin;
  131. }
  132. /**
  133. * 方案保证金和停止比例的短时缓存(同一实例内 30 秒),避免实时分成逐笔查询时在代理行锁内反复查库。
  134. * 总后台修改方案或配置在其他请求中完成,最多 30 秒后生效到分成任务。
  135. */
  136. private function lookup(string $key, callable $resolve)
  137. {
  138. $now = time();
  139. if (!isset($this->lookups[$key]) || $this->lookups[$key][1] < $now) {
  140. $this->lookups[$key] = [$resolve(), $now + 30];
  141. }
  142. return $this->lookups[$key][0];
  143. }
  144. public function effectiveMargin(Agent $agent): string
  145. {
  146. $margin = bcadd((string) $agent->margin_amount, '0', 4);
  147. $realtime = bcadd((string) $agent->realtime_balance, '0', 4);
  148. $value = bccomp($realtime, $margin, 4) < 0 ? $realtime : $margin;
  149. return bccomp($value, '0', 4) < 0 ? '0.0000' : $value;
  150. }
  151. /** 代理端可见的资金构成(不含实时余额)。 */
  152. public function funds(Agent $agent): array
  153. {
  154. $balance = bcadd((string) $agent->balance, '0', 4);
  155. $margin = bcadd((string) $agent->margin_amount, '0', 4);
  156. $data = [
  157. 'balance' => $balance,
  158. 'frozen_balance' => bcadd((string) $agent->frozen_balance, '0', 4),
  159. 'withdrawable_amount' => $this->withdrawable($agent),
  160. ];
  161. if ($agent->isJoint()) {
  162. $marginBalance = bccomp($balance, $margin, 4) < 0 ? $balance : $margin;
  163. $data += [
  164. 'margin_amount' => $margin,
  165. 'margin_balance' => bccomp($marginBalance, '0', 4) < 0 ? '0.0000' : $marginBalance,
  166. 'profit_amount' => bcsub($balance, $margin, 4),
  167. ];
  168. } else {
  169. $data['equity_percent'] = bcadd((string) $agent->equity_percent, '0', 4);
  170. }
  171. return $data;
  172. }
  173. /**
  174. * 可提现金额。合营:总余额加上「待入账亏损的最坏情况」后,超出保证金本金的部分;入股:全部余额。
  175. */
  176. public function withdrawable(Agent $agent): string
  177. {
  178. $balance = bcadd((string) $agent->balance, '0', 4);
  179. if (!$agent->isJoint()) {
  180. return bccomp($balance, '0', 4) > 0 ? $balance : '0.0000';
  181. }
  182. $available = bcsub(bcadd($balance, $this->pendingFloor($agent), 4), (string) $agent->margin_amount, 4);
  183. return bccomp($available, '0', 4) > 0 ? $available : '0.0000';
  184. }
  185. /**
  186. * 待入账分成按结算日依次入账时,余额最多会下降多少(≤0)。
  187. * 取未入账分成按结算日的前缀和的最小值;传 $fromDate 时只看该日及之后的入账点
  188. * (新增或修改该日分成会影响这些点),用于限制亏损扣减。
  189. */
  190. public function pendingFloor(Agent $agent, ?string $fromDate = null): string
  191. {
  192. if (!$agent->isJoint()) return '0.0000';
  193. $sums = AgentProfitEntry::query()->toBase()->where('agent_id', $agent->id)
  194. ->where('status', AgentProfitEntry::STATUS_COUNTED)->whereNull('rebate_record_id')
  195. ->groupBy('settle_date')->orderBy('settle_date')
  196. ->selectRaw('settle_date, COALESCE(SUM(share_amount),0) total')->get();
  197. $running = '0.0000';
  198. $floor = $fromDate === null ? '0.0000' : null;
  199. foreach ($sums as $row) {
  200. if ($floor === null && substr((string) $row->settle_date, 0, 10) >= $fromDate) $floor = $running;
  201. $running = bcadd($running, (string) $row->total, 4);
  202. if ($floor !== null && bccomp($running, $floor, 4) < 0) $floor = $running;
  203. }
  204. return $floor ?? $running;
  205. }
  206. private function setActive(Agent $agent, bool $active): bool
  207. {
  208. if ((int) $agent->profit_active !== ($active ? 1 : 0)) {
  209. $agent->profit_active = $active ? 1 : 0;
  210. $agent->profit_active_changed_at = now();
  211. $agent->save();
  212. }
  213. return $active;
  214. }
  215. private function assertSameAdjustment(AgentBalanceLog $log, int $agentId, string $type, string $amount): void
  216. {
  217. $signed = self::DIRECTIONS[$type] > 0 ? bcadd($amount, '0', 4) : bcsub('0', $amount, 4);
  218. if ((int) $log->agent_id !== $agentId || $log->type !== $type || bccomp((string) $log->amount, $signed, 4) !== 0) {
  219. throw new \RuntimeException('request_id 已用于其他资金调整');
  220. }
  221. }
  222. }