CreditService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Exceptions\BusinessException;
  4. use App\Models\CreditLedgerEntry;
  5. use App\Models\ReadingDaily;
  6. use App\Models\UserInfo;
  7. use App\Models\UserOperationDaily;
  8. use Carbon\CarbonInterface;
  9. use Illuminate\Support\Arr;
  10. use Illuminate\Support\Collection;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Validation\ValidationException;
  13. /**
  14. * AI 对话的额度与积分。
  15. *
  16. * 两个池子:
  17. * - **每日赠送池**(bucket=free):每个 UTC 日按策略送一份,当天用完不累积。赠送本身不入账,
  18. * 「今天还剩多少」= 赠送额 − 当天 free 流水的消耗;
  19. * - **积分余额**(bucket=earned):读经、编辑时长赚来的,加上手工调整,不过期。
  20. *
  21. * 每次提问先扣赠送池,不够再扣积分余额;两者合计不够就拒绝(402)。
  22. * 规则全部来自当前生效的策略 `config('mint.credits.policy')`(公开:`GET /v3/credit-policy`),
  23. * 字段说明见 agent-poc 仓库 docs/credits.md。
  24. */
  25. class CreditService
  26. {
  27. /**
  28. * 当前生效的策略。version 是生效日(YYYYMMDD),记进每笔流水。
  29. *
  30. * @return array{version: int, rules: array<string, mixed>}
  31. */
  32. public function policy(): array
  33. {
  34. $policy = config('mint.credits.policy');
  35. return ['version' => (int) $policy['version'], 'rules' => Arr::except($policy, 'version')];
  36. }
  37. /**
  38. * 某个账号此刻的额度概况。登录用户会先把今天(和昨天)的读经 / 编辑时长结算成积分。
  39. *
  40. * @return array{account_type: string, day: string, resets_at: string, policy_version: int, daily_free: int, free_used: int, free_remaining: int, earned_balance: int, cost: array{normal: int, deep: int}, earned_today: array{reading: int, editing: int}, earn: array<string, mixed>}
  41. */
  42. public function quota(AgentAccount $account): array
  43. {
  44. $today = $this->today();
  45. if ($account->isUser()) {
  46. $this->settleRecent($account->id);
  47. }
  48. $rules = $this->policy()['rules'];
  49. $dailyFree = (int) ($rules['daily_free'][$account->type] ?? 0);
  50. $freeUsed = $this->freeUsed($account, $today);
  51. return [
  52. 'account_type' => $account->type,
  53. 'day' => $today->toDateString(),
  54. 'resets_at' => $today->copy()->addDay()->toIso8601ZuluString(),
  55. 'policy_version' => $this->policy()['version'],
  56. 'daily_free' => $dailyFree,
  57. 'free_used' => $freeUsed,
  58. 'free_remaining' => max(0, $dailyFree - $freeUsed),
  59. 'earned_balance' => $this->earnedBalance($account),
  60. 'cost' => ['normal' => (int) $rules['cost']['normal'], 'deep' => (int) $rules['cost']['deep']],
  61. 'earned_today' => [
  62. 'reading' => $this->earnedOn($account, 'reading', $today),
  63. 'editing' => $this->earnedOn($account, 'editing', $today),
  64. ],
  65. 'earn' => $account->isUser() ? $rules['earn'] : [],
  66. ];
  67. }
  68. /**
  69. * 为一次提问扣费(按 run_id 幂等)。先扣赠送池,再扣积分余额。
  70. *
  71. * @return array{run_id: string, created: bool, cost: int, charged_free: int, charged_earned: int, free_remaining: int, earned_balance: int, policy_version: int}
  72. *
  73. * @throws BusinessException 402:额度不足或游客同 IP 超上限
  74. */
  75. public function charge(AgentAccount $account, string $runId, bool $deep, ?string $clientIp): array
  76. {
  77. if ($account->isUser()) {
  78. $this->settleRecent($account->id);
  79. }
  80. // 游客的同 IP 每日上限靠 IP:拿不到 IP 就不让问,否则上限形同虚设(伪造设备 id 就能无限领赠送额度)
  81. if (! $account->isUser() && blank($clientIp)) {
  82. throw ValidationException::withMessages(['client_ip' => __('messages.agent_client_ip_required')]);
  83. }
  84. $today = $this->today();
  85. ['version' => $version, 'rules' => $rules] = $this->policy();
  86. $clientIp = $account->isUser() ? null : $clientIp;
  87. return DB::transaction(function () use ($account, $runId, $deep, $clientIp, $today, $version, $rules) {
  88. // 同一账号的扣费串行化,避免并发的两次提问都看到「还够」
  89. DB::select('select pg_advisory_xact_lock(hashtext(?))', [$account->key()]);
  90. $existing = CreditLedgerEntry::ownedBy($account)
  91. ->where('source', 'agent_run')->where('ref', $runId)->where('kind', 'spend')->get();
  92. $dailyFree = (int) ($rules['daily_free'][$account->type] ?? 0);
  93. if ($existing->isNotEmpty()) {
  94. return $this->chargeResult($account, $runId, false, $existing, $dailyFree, $today, $version);
  95. }
  96. $cost = (int) ($deep ? $rules['cost']['deep'] : $rules['cost']['normal']);
  97. $freeRemaining = max(0, $dailyFree - $this->freeUsed($account, $today));
  98. $balance = $this->earnedBalance($account);
  99. $ipCap = $rules['guest_ip_daily_cap'] ?? null;
  100. if ($clientIp && $ipCap !== null && $this->ipSpent($clientIp, $today) + $cost > (int) $ipCap) {
  101. throw $this->exhausted('ip_cap', $cost, $freeRemaining, $balance);
  102. }
  103. if ($freeRemaining + $balance < $cost) {
  104. // 游客读经不给积分,提示登录;登录用户提示读经
  105. throw $this->exhausted('insufficient', $cost, $freeRemaining, $balance, $account->type);
  106. }
  107. $fromFree = min($cost, $freeRemaining);
  108. $rows = collect(['free' => $fromFree, 'earned' => $cost - $fromFree])
  109. ->filter(fn (int $amount) => $amount > 0)
  110. ->map(fn (int $amount, string $bucket) => CreditLedgerEntry::create([
  111. ...$account->columns(),
  112. 'delta' => -$amount,
  113. 'kind' => 'spend',
  114. 'bucket' => $bucket,
  115. 'source' => 'agent_run',
  116. 'ref' => $runId,
  117. 'day' => $today->toDateString(),
  118. 'policy_version' => $version,
  119. 'client_ip' => $clientIp,
  120. 'note' => $deep ? 'deep' : null,
  121. ]))->values();
  122. return $this->chargeResult($account, $runId, true, $rows, $dailyFree, $today, $version);
  123. });
  124. }
  125. /**
  126. * 退回某次提问的扣费(服务端出错、回答没生成)。按原消耗逐池退回,day 沿用原消耗那天。
  127. * 没扣过费就什么都不做;重复退款不会退两次。
  128. */
  129. public function refundRun(string $runId): void
  130. {
  131. $spends = CreditLedgerEntry::where('source', 'agent_run')->where('ref', $runId)->where('kind', 'spend')->get();
  132. foreach ($spends as $spend) {
  133. CreditLedgerEntry::createOrFirst([
  134. 'account_type' => $spend->account_type,
  135. 'account_id' => $spend->account_id,
  136. 'source' => 'agent_run',
  137. 'ref' => $runId,
  138. 'kind' => 'refund',
  139. 'bucket' => $spend->bucket,
  140. ], [
  141. 'delta' => -$spend->delta,
  142. 'day' => $spend->day->toDateString(),
  143. 'policy_version' => $spend->policy_version,
  144. 'client_ip' => $spend->client_ip,
  145. ]);
  146. }
  147. }
  148. /**
  149. * 把某个登录用户某一天的读经、编辑时长结算成积分(可重复执行,结果覆盖)。
  150. *
  151. * @return array{reading: int, editing: int}
  152. */
  153. public function settle(string $userUid, CarbonInterface $day): array
  154. {
  155. ['version' => $version, 'rules' => $rules] = $this->policy();
  156. $account = AgentAccount::user($userUid);
  157. $userSn = UserInfo::where('userid', $userUid)->value('id');
  158. $readingSeconds = (int) ReadingDaily::where('user_uid', $userUid)->where('day', $day->toDateString())->value('seconds');
  159. $editingMs = $userSn === null ? 0 : (int) UserOperationDaily::where('user_id', $userSn)
  160. ->whereBetween('date_int', $this->editingWindow($day))
  161. ->sum('duration');
  162. $amounts = [
  163. 'reading' => $this->earnAmount($rules['earn']['reading'] ?? null, intdiv($readingSeconds, 60)),
  164. 'editing' => $this->earnAmount($rules['earn']['editing'] ?? null, intdiv($editingMs, 60_000)),
  165. ];
  166. foreach ($amounts as $source => $amount) {
  167. $keys = [...$account->columns(), 'source' => $source, 'ref' => $day->toDateString(), 'kind' => 'earn', 'bucket' => 'earned'];
  168. if ($amount > 0 || CreditLedgerEntry::where($keys)->exists()) {
  169. $entry = CreditLedgerEntry::updateOrCreate($keys, [
  170. 'delta' => $amount,
  171. 'day' => $day->toDateString(),
  172. 'policy_version' => $version,
  173. ]);
  174. // updated_at=最后一次结算的时间:数额没变也要记下「结算过了」,
  175. // 否则当天中途结算的那笔永远被 settleMissing 当成没结清
  176. if (! $entry->wasRecentlyCreated && ! $entry->wasChanged()) {
  177. $entry->touch();
  178. }
  179. }
  180. }
  181. return $amounts;
  182. }
  183. /**
  184. * 结算某一天所有有活动的登录用户,返回人数。供每日命令使用。
  185. */
  186. /**
  187. * 补齐漏结算的日子:从 $since 到 $until(UTC 日,含两端),找出有活动却没结清的「用户 + 日」重新结算。
  188. * 结算任务漏跑几天都能补上,工作量只跟漏掉的量有关。
  189. *
  190. * 算「没结清」的两种情况(只看至少 1 分钟的活动,不足 1 分钟本来就不给积分):
  191. * - 账单里没有那天这个来源的积分;
  192. * - 有,但最后一次结算早于那天的活动结束——读经按 UTC 日,到次日 0 点;编辑按客户端本地日
  193. * (见 editingWindow),最晚到次日 12:00 UTC。之后又攒的时长要补上。
  194. *
  195. * 补算用当前生效的策略(历史策略不保留,见 config mint.credits.policy)。
  196. *
  197. * @return array{pairs: int, users: int}
  198. */
  199. public function settleMissing(CarbonInterface $since, CarbonInterface $until): array
  200. {
  201. $since = $since->copy()->startOfDay();
  202. $until = $until->copy()->startOfDay();
  203. // 有至少 1 分钟活动的「用户 + 日」,以及那天活动结束的时刻
  204. $activity = [];
  205. ReadingDaily::whereBetween('day', [$since->toDateString(), $until->toDateString()])
  206. ->where('seconds', '>=', 60)
  207. ->get(['user_uid', 'day'])
  208. ->each(function (ReadingDaily $row) use (&$activity) {
  209. $day = $row->day->toDateString();
  210. $activity["{$row->user_uid}|{$day}"]['reading'] = $row->day->copy()->addDay();
  211. });
  212. UserOperationDaily::join('user_infos', 'user_infos.id', '=', 'user_operation_dailies.user_id')
  213. ->whereBetween('user_operation_dailies.date_int', [$this->editingWindow($since)[0], $this->editingWindow($until)[1]])
  214. ->selectRaw("user_infos.userid as user_uid, (to_timestamp((user_operation_dailies.date_int + 43200000) / 1000.0) at time zone 'UTC')::date as local_day")
  215. ->groupByRaw('1, 2')
  216. ->havingRaw('sum(user_operation_dailies.duration) >= 60000')
  217. ->get()
  218. ->each(function ($row) use (&$activity) {
  219. $day = substr((string) $row->local_day, 0, 10);
  220. $activity["{$row->user_uid}|{$day}"]['editing'] = now('UTC')->parse($day)->addDay()->addHours(12);
  221. });
  222. if ($activity === []) {
  223. return ['pairs' => 0, 'users' => 0];
  224. }
  225. // 已有的积分及其最后结算时间
  226. $settled = CreditLedgerEntry::where('account_type', 'user')
  227. ->whereIn('source', ['reading', 'editing'])
  228. ->where('kind', 'earn')
  229. ->whereBetween('day', [$since->toDateString(), $until->toDateString()])
  230. ->get(['account_id', 'source', 'ref', 'updated_at'])
  231. ->mapWithKeys(fn (CreditLedgerEntry $e) => ["{$e->account_id}|{$e->ref}|{$e->source}" => $e->updated_at]);
  232. $pairs = 0;
  233. $users = [];
  234. foreach ($activity as $key => $sources) {
  235. $missing = false;
  236. foreach ($sources as $source => $closesAt) {
  237. $at = $settled["{$key}|{$source}"] ?? null;
  238. if ($at === null || $at->lt($closesAt)) {
  239. $missing = true;
  240. }
  241. }
  242. if (! $missing) {
  243. continue;
  244. }
  245. [$userUid, $day] = explode('|', $key);
  246. $this->settle($userUid, now('UTC')->parse($day)->startOfDay());
  247. $pairs++;
  248. $users[$userUid] = true;
  249. }
  250. return ['pairs' => $pairs, 'users' => count($users)];
  251. }
  252. public function settleDay(CarbonInterface $day): int
  253. {
  254. $fromReading = ReadingDaily::where('day', $day->toDateString())->distinct()->pluck('user_uid');
  255. $editorSns = UserOperationDaily::whereBetween('date_int', $this->editingWindow($day))->distinct()->pluck('user_id');
  256. $fromEditing = UserInfo::whereIn('id', $editorSns)->pluck('userid');
  257. $users = $fromReading->merge($fromEditing)->unique()->values();
  258. foreach ($users as $userUid) {
  259. $this->settle((string) $userUid, $day);
  260. }
  261. return $users->count();
  262. }
  263. /**
  264. * 手工加减积分(积分余额池)。ref 由调用方给,同一 ref 只生效一次。
  265. */
  266. public function adjust(AgentAccount $account, int $delta, string $ref, ?string $note): CreditLedgerEntry
  267. {
  268. return CreditLedgerEntry::createOrFirst([
  269. ...$account->columns(),
  270. 'source' => 'admin',
  271. 'ref' => $ref,
  272. 'kind' => 'adjust',
  273. 'bucket' => 'earned',
  274. ], [
  275. 'delta' => $delta,
  276. 'day' => $this->today()->toDateString(),
  277. 'policy_version' => $this->policy()['version'],
  278. 'note' => $note,
  279. ]);
  280. }
  281. /**
  282. * 今天和昨天都结算一次:昨天深夜的活动在每日命令跑之前也能及时到账。
  283. */
  284. private function settleRecent(string $userUid): void
  285. {
  286. $today = $this->today();
  287. $this->settle($userUid, $today);
  288. $this->settle($userUid, $today->copy()->subDay());
  289. }
  290. /**
  291. * @param array{credits_per_minute?: int, daily_cap?: int|null}|null $rule
  292. */
  293. private function earnAmount(?array $rule, int $minutes): int
  294. {
  295. if (! $rule) {
  296. return 0;
  297. }
  298. $amount = $minutes * (int) ($rule['credits_per_minute'] ?? 0);
  299. $cap = $rule['daily_cap'] ?? null;
  300. return $cap === null ? $amount : min($amount, (int) $cap);
  301. }
  302. /**
  303. * user_operation_dailies.date_int 是「客户端本地日的零点」的毫秒时间戳(随客户端时区漂移)。
  304. * 加 12 小时再落到 UTC 日,就是那个本地日的日期——对 UTC−12 到 UTC+12 都成立,
  305. * 且每行只落进一天,不会重复计。
  306. *
  307. * @return array{0: int, 1: int}
  308. */
  309. private function editingWindow(CarbonInterface $day): array
  310. {
  311. $start = $day->copy()->startOfDay()->getTimestampMs() - 12 * 3600 * 1000;
  312. return [$start, $start + 24 * 3600 * 1000 - 1];
  313. }
  314. private function today(): CarbonInterface
  315. {
  316. return now('UTC')->startOfDay();
  317. }
  318. private function freeUsed(AgentAccount $account, CarbonInterface $day): int
  319. {
  320. return -(int) CreditLedgerEntry::ownedBy($account)
  321. ->where('bucket', 'free')->where('day', $day->toDateString())->sum('delta');
  322. }
  323. private function earnedBalance(AgentAccount $account): int
  324. {
  325. return (int) CreditLedgerEntry::ownedBy($account)->where('bucket', 'earned')->sum('delta');
  326. }
  327. private function earnedOn(AgentAccount $account, string $source, CarbonInterface $day): int
  328. {
  329. return (int) CreditLedgerEntry::ownedBy($account)->where('source', $source)
  330. ->where('kind', 'earn')->where('day', $day->toDateString())->sum('delta');
  331. }
  332. /**
  333. * 同一 IP 下所有游客当天的净消耗(退回的不算)。
  334. */
  335. private function ipSpent(string $clientIp, CarbonInterface $day): int
  336. {
  337. return -(int) CreditLedgerEntry::where('client_ip', $clientIp)->where('day', $day->toDateString())
  338. ->where('account_type', 'guest')->whereIn('kind', ['spend', 'refund'])->sum('delta');
  339. }
  340. /**
  341. * @param Collection<int, CreditLedgerEntry> $rows
  342. * @return array{run_id: string, created: bool, cost: int, charged_free: int, charged_earned: int, free_remaining: int, earned_balance: int, policy_version: int}
  343. */
  344. private function chargeResult(AgentAccount $account, string $runId, bool $created, $rows, int $dailyFree, CarbonInterface $today, int $version): array
  345. {
  346. $free = -(int) $rows->where('bucket', 'free')->sum('delta');
  347. $earned = -(int) $rows->where('bucket', 'earned')->sum('delta');
  348. return [
  349. 'run_id' => $runId,
  350. 'created' => $created,
  351. 'cost' => $free + $earned,
  352. 'charged_free' => $free,
  353. 'charged_earned' => $earned,
  354. 'free_remaining' => max(0, $dailyFree - $this->freeUsed($account, $today)),
  355. 'earned_balance' => $this->earnedBalance($account),
  356. 'policy_version' => $version,
  357. ];
  358. }
  359. private function exhausted(string $reason, int $cost, int $freeRemaining, int $balance, string $accountType = 'guest'): BusinessException
  360. {
  361. $key = $reason === 'insufficient' ? "agent_quota_insufficient_{$accountType}" : "agent_quota_{$reason}";
  362. return new BusinessException(
  363. __("messages.{$key}"),
  364. 402,
  365. 'quota-exceeded',
  366. ['reason' => $reason, 'cost' => $cost, 'free_remaining' => $freeRemaining, 'earned_balance' => $balance],
  367. 'Quota Exceeded',
  368. );
  369. }
  370. }