CreditAdminService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Facades\RedisCache;
  4. use App\Models\CreditLedgerEntry;
  5. use App\Models\UserInfo;
  6. use App\Services\UserService;
  7. use Carbon\CarbonInterface;
  8. use Illuminate\Contracts\Pagination\LengthAwarePaginator;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Str;
  11. use Illuminate\Validation\ValidationException;
  12. /**
  13. * 管理后台的 AI 对话积分管理:账号余额一览、流水、手工加减、手工触发结算。
  14. *
  15. * 余额口径与 {@see CreditService} 一致:积分余额 = bucket=earned 的流水合计;
  16. * 每日赠送池不入账,只看当天 free 流水的消耗。
  17. */
  18. class CreditAdminService
  19. {
  20. /** 最近一次结算的记录(命令行与管理后台都写),只用于显示,丢了不影响结算本身。 */
  21. public const LAST_SETTLEMENT_KEY = '/credits/settlement/last';
  22. /** 概览里按日列出最近多少天的结算结果。 */
  23. public const RECENT_DAYS = 14;
  24. public function __construct(private readonly CreditService $credits) {}
  25. /**
  26. * 概览:策略、全站合计、最近 14 天每天结算出的积分、最近一次结算任务。
  27. *
  28. * @return array{today: string, earn_since: string, policy_version: int, policy: array<string, mixed>, totals: array{user_accounts: int, guest_accounts: int, outstanding_balance: int, earned_total: int, adjusted_total: int, spent_today: int}, recent_days: list<array{day: string, users: int, reading: int, editing: int}>, last_settlement: array<string, mixed>|null}
  29. */
  30. public function overview(): array
  31. {
  32. ['version' => $version, 'rules' => $rules] = $this->credits->policy();
  33. $today = now('UTC')->startOfDay();
  34. $since = $today->copy()->subDays(self::RECENT_DAYS - 1);
  35. $accounts = CreditLedgerEntry::query()
  36. ->selectRaw('account_type, count(distinct account_id) as n')
  37. ->groupBy('account_type')
  38. ->pluck('n', 'account_type');
  39. $byKind = CreditLedgerEntry::query()
  40. ->where('account_type', 'user')->where('bucket', 'earned')
  41. ->selectRaw('kind, sum(delta) as total')
  42. ->groupBy('kind')
  43. ->pluck('total', 'kind');
  44. $spentToday = -(int) CreditLedgerEntry::query()
  45. ->where('day', $today->toDateString())->whereIn('kind', ['spend', 'refund'])
  46. ->sum('delta');
  47. $earned = CreditLedgerEntry::query()
  48. ->where('kind', 'earn')->whereBetween('day', [$since->toDateString(), $today->toDateString()])
  49. ->selectRaw('day, source, count(distinct account_id) as users, sum(delta) as total')
  50. ->groupBy('day', 'source')
  51. ->get();
  52. // 一个人同一天可能读经、编辑都有,人数要按天单独去重
  53. $usersByDay = CreditLedgerEntry::query()
  54. ->where('kind', 'earn')->where('delta', '>', 0)
  55. ->whereBetween('day', [$since->toDateString(), $today->toDateString()])
  56. ->selectRaw('day, count(distinct account_id) as users')
  57. ->groupBy('day')
  58. ->get()
  59. ->mapWithKeys(fn ($row) => [$row->day->toDateString() => (int) $row->users]);
  60. $recent = [];
  61. for ($day = $today->copy(); $day->gte($since); $day = $day->copy()->subDay()) {
  62. $date = $day->toDateString();
  63. $rows = $earned->filter(fn ($row) => $row->day->toDateString() === $date);
  64. $recent[] = [
  65. 'day' => $date,
  66. 'users' => $usersByDay[$date] ?? 0,
  67. 'reading' => (int) $rows->where('source', 'reading')->sum('total'),
  68. 'editing' => (int) $rows->where('source', 'editing')->sum('total'),
  69. ];
  70. }
  71. return [
  72. 'today' => $today->toDateString(),
  73. 'earn_since' => (string) config('mint.credits.earn_since'),
  74. 'policy_version' => $version,
  75. 'policy' => $rules,
  76. 'totals' => [
  77. 'user_accounts' => (int) ($accounts['user'] ?? 0),
  78. 'guest_accounts' => (int) ($accounts['guest'] ?? 0),
  79. 'outstanding_balance' => (int) $byKind->sum(),
  80. 'earned_total' => (int) ($byKind['earn'] ?? 0),
  81. 'adjusted_total' => (int) ($byKind['adjust'] ?? 0),
  82. 'spent_today' => $spentToday,
  83. ],
  84. 'recent_days' => $recent,
  85. 'last_settlement' => RedisCache::get(self::LAST_SETTLEMENT_KEY),
  86. ];
  87. }
  88. /**
  89. * 有积分流水的账号,最近有动静的在前。每行是一个账号的汇总(不是模型行)。
  90. *
  91. * @param array{filter?: array{account_type?: string, q?: string}} $filters
  92. * @return LengthAwarePaginator<int, CreditLedgerEntry>
  93. */
  94. public function accounts(array $filters, int $perPage): LengthAwarePaginator
  95. {
  96. $f = $filters['filter'] ?? [];
  97. $today = now('UTC')->toDateString();
  98. return CreditLedgerEntry::query()
  99. ->with(UserService::eagerLoadActor()[0])
  100. ->select(['account_type', 'account_id'])
  101. ->selectRaw("sum(case when bucket = 'earned' then delta else 0 end) as earned_balance")
  102. ->selectRaw("sum(case when kind = 'earn' then delta else 0 end) as earned_total")
  103. ->selectRaw("sum(case when kind = 'adjust' then delta else 0 end) as adjusted_total")
  104. ->selectRaw("-sum(case when kind in ('spend', 'refund') then delta else 0 end) as spent_total")
  105. ->selectRaw("-sum(case when bucket = 'free' and day = ? then delta else 0 end) as free_used_today", [$today])
  106. ->selectRaw('max(updated_at) as last_activity_at')
  107. ->when($f['account_type'] ?? null, fn ($q, $v) => $q->where('account_type', $v))
  108. ->when($f['q'] ?? null, function ($q, string $v) {
  109. $like = '%'.addcslashes($v, '%_\\').'%';
  110. $users = UserInfo::query()
  111. ->where(fn ($u) => $u->where('username', 'ilike', $like)
  112. ->orWhere('nickname', 'ilike', $like)
  113. ->orWhere('email', 'ilike', $like))
  114. ->limit(200)
  115. ->pluck('userid');
  116. $q->where(fn ($w) => $w
  117. ->where(fn ($u) => $u->where('account_type', 'user')->whereIn('account_id', $users))
  118. ->orWhere(fn ($g) => $g->where('account_type', 'guest')->where('account_id', 'ilike', addcslashes($v, '%_\\').'%')));
  119. })
  120. ->groupBy('account_type', 'account_id')
  121. ->orderByDesc('last_activity_at')
  122. ->orderBy('account_id')
  123. ->paginate($perPage);
  124. }
  125. /**
  126. * 积分流水,最新的在前。
  127. *
  128. * @param array{filter?: array{account_type?: string, account_id?: string, kind?: string, bucket?: string, source?: string, from?: string, to?: string}} $filters
  129. * @return LengthAwarePaginator<int, CreditLedgerEntry>
  130. */
  131. public function ledger(array $filters, int $perPage): LengthAwarePaginator
  132. {
  133. $f = $filters['filter'] ?? [];
  134. return CreditLedgerEntry::query()
  135. ->with([UserService::eagerLoadActor()[0], UserService::eagerLoadActor('operator')[0]])
  136. ->when($f['account_type'] ?? null, fn ($q, $v) => $q->where('account_type', $v))
  137. ->when($f['account_id'] ?? null, fn ($q, $v) => $q->where('account_id', $v))
  138. ->when($f['kind'] ?? null, fn ($q, $v) => $q->where('kind', $v))
  139. ->when($f['bucket'] ?? null, fn ($q, $v) => $q->where('bucket', $v))
  140. ->when($f['source'] ?? null, fn ($q, $v) => $q->where('source', $v))
  141. ->when($f['from'] ?? null, fn ($q, $v) => $q->where('day', '>=', $v))
  142. ->when($f['to'] ?? null, fn ($q, $v) => $q->where('day', '<=', $v))
  143. ->orderByDesc('id')
  144. ->paginate($perPage);
  145. }
  146. /**
  147. * 管理员给某个登录用户加减积分(积分余额池)。同一 ref 只生效一次:重复提交返回原来那条,created=false。
  148. *
  149. * @param string $user 用户 uuid、用户名或邮箱
  150. * @return array{entry: CreditLedgerEntry, created: bool, earned_balance: int}
  151. *
  152. * @throws ValidationException 用户不存在;扣减后余额为负
  153. */
  154. public function adjust(string $operatorUid, string $user, int $delta, string $note, ?string $ref): array
  155. {
  156. $userUid = UserInfo::query()
  157. ->when(Str::isUuid($user),
  158. fn ($q) => $q->where('userid', $user),
  159. fn ($q) => $q->where('username', $user)->orWhereRaw('lower(email) = lower(?)', [$user]))
  160. ->value('userid');
  161. if ($userUid === null) {
  162. throw ValidationException::withMessages(['user' => __('messages.credit_user_not_found')]);
  163. }
  164. $account = AgentAccount::user($userUid);
  165. $ref ??= (string) Str::uuid();
  166. return DB::transaction(function () use ($account, $operatorUid, $delta, $note, $ref) {
  167. // 与扣费同一把锁:扣减时的余额检查不能和并发的提问扣费交错
  168. DB::select('select pg_advisory_xact_lock(hashtext(?))', [$account->key()]);
  169. $balance = (int) CreditLedgerEntry::ownedBy($account)->where('bucket', 'earned')->sum('delta');
  170. $existing = CreditLedgerEntry::ownedBy($account)
  171. ->where(['source' => 'admin', 'ref' => $ref, 'kind' => 'adjust', 'bucket' => 'earned'])->first();
  172. if ($existing === null && $balance + $delta < 0) {
  173. throw ValidationException::withMessages(['delta' => __('messages.credit_balance_negative', ['balance' => $balance])]);
  174. }
  175. $entry = $existing ?? $this->credits->adjust($account, $delta, $ref, $note, $operatorUid);
  176. return [
  177. 'entry' => $entry->load([UserService::eagerLoadActor()[0], UserService::eagerLoadActor('operator')[0]]),
  178. 'created' => $existing === null,
  179. 'earned_balance' => $existing === null ? $balance + $delta : $balance,
  180. ];
  181. });
  182. }
  183. /**
  184. * 手工跑一次结算,与每日任务 `credits:settle-activity` 同一套逻辑,可重复执行、不会重复入账。
  185. *
  186. * - 给 $day:只重算那一天的所有用户(结果覆盖那天的积分);
  187. * - 不给:从积分上线日到昨天,补齐所有漏结算的「用户 + 日」。
  188. *
  189. * @param string|null $operatorUid 管理后台触发时的管理员;命令行(每日任务)为 null
  190. * @return array{mode: string, from: string, to: string, users: int, pairs: int|null, trigger: string, operator: string|null, ran_at: string, seconds: float}
  191. */
  192. public function settle(?CarbonInterface $day, ?string $operatorUid = null): array
  193. {
  194. $started = microtime(true);
  195. if ($day !== null) {
  196. $day = $day->copy()->startOfDay();
  197. $users = $this->credits->settleDay($day);
  198. $result = ['mode' => 'day', 'from' => $day->toDateString(), 'to' => $day->toDateString(), 'users' => $users, 'pairs' => null];
  199. } else {
  200. $since = now('UTC')->parse((string) config('mint.credits.earn_since'))->startOfDay();
  201. $until = now('UTC')->subDay()->startOfDay();
  202. ['pairs' => $pairs, 'users' => $users] = $this->credits->settleMissing($since, $until);
  203. $result = ['mode' => 'missing', 'from' => $since->toDateString(), 'to' => $until->toDateString(), 'users' => $users, 'pairs' => $pairs];
  204. }
  205. $result += [
  206. 'trigger' => $operatorUid === null ? 'cli' : 'admin',
  207. 'operator' => $operatorUid === null ? null : UserInfo::where('userid', $operatorUid)->value('nickname'),
  208. 'ran_at' => now('UTC')->toIso8601ZuluString(),
  209. 'seconds' => round(microtime(true) - $started, 2),
  210. ];
  211. RedisCache::put(self::LAST_SETTLEMENT_KEY, $result, now()->addDays(30));
  212. return $result;
  213. }
  214. }