AdminCreditV3Test.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. use App\Facades\RedisCache;
  3. use App\Models\CreditLedgerEntry;
  4. use App\Models\ReadingDaily;
  5. use App\Models\UserInfo;
  6. use App\Services\V3\AgentAccount;
  7. use App\Services\V3\CreditAdminService;
  8. use Illuminate\Foundation\Testing\RefreshDatabase;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Str;
  11. uses(RefreshDatabase::class);
  12. /**
  13. * v3 管理后台 AI 对话积分管理(仅 root / administrator):
  14. *
  15. * GET /api/v3/admin/credit-overview 概览
  16. * GET /api/v3/admin/credit-accounts 账号一览
  17. * GET /api/v3/admin/credit-ledger 流水
  18. * POST /api/v3/admin/credit-adjustments 手工加减
  19. * POST /api/v3/admin/credit-settlements 手工结算
  20. *
  21. * 这里断言的是形状而非契约(spectator 尚未安装,见 v3-resource skill 第 3 步)。
  22. */
  23. function creditAdmin(): string
  24. {
  25. $uid = makeStudio('cadmin-'.Str::random(6));
  26. UserInfo::where('userid', $uid)->update(['role' => json_encode(['administrator'])]);
  27. return $uid;
  28. }
  29. function ledgerRow(AgentAccount $account, int $delta, array $extra = []): CreditLedgerEntry
  30. {
  31. return CreditLedgerEntry::create([
  32. ...$account->columns(), 'delta' => $delta, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'reading',
  33. 'ref' => (string) Str::uuid(), 'day' => now('UTC')->toDateString(), 'policy_version' => 1, ...$extra,
  34. ]);
  35. }
  36. /* ------------------------------------------------------------------ 权限 */
  37. it('requires login', function (string $method, string $path) {
  38. $this->json($method, "/api/v3/admin/{$path}")->assertUnauthorized();
  39. })->with([
  40. ['GET', 'credit-overview'], ['GET', 'credit-accounts'], ['GET', 'credit-ledger'],
  41. ['POST', 'credit-adjustments'], ['POST', 'credit-settlements'],
  42. ]);
  43. it('forbids non-admin users', function (string $method, string $path) {
  44. $this->json($method, "/api/v3/admin/{$path}", [], authHeader(makeStudio('plain-'.Str::random(5))))->assertForbidden();
  45. })->with([
  46. ['GET', 'credit-overview'], ['GET', 'credit-accounts'], ['GET', 'credit-ledger'],
  47. ['POST', 'credit-adjustments'], ['POST', 'credit-settlements'],
  48. ]);
  49. /* ------------------------------------------------------------------ 概览 */
  50. it('summarises balances and recent settlements', function () {
  51. $user = AgentAccount::user(makeStudio('reader-'.Str::random(5)));
  52. ledgerRow($user, 40);
  53. ledgerRow($user, -10, ['kind' => 'spend', 'source' => 'agent_run']);
  54. ledgerRow(AgentAccount::guest((string) Str::uuid()), -10, ['kind' => 'spend', 'bucket' => 'free', 'source' => 'agent_run']);
  55. $data = $this->getJson('/api/v3/admin/credit-overview', authHeader(creditAdmin()))->assertOk()->json('data');
  56. expect($data['totals'])->toMatchArray([
  57. 'user_accounts' => 1, 'guest_accounts' => 1, 'outstanding_balance' => 30, 'earned_total' => 40, 'spent_today' => 20,
  58. ])
  59. ->and($data['recent_days'])->toHaveCount(CreditAdminService::RECENT_DAYS)
  60. ->and($data['recent_days'][0])->toMatchArray(['day' => now('UTC')->toDateString(), 'users' => 1, 'reading' => 40])
  61. ->and($data['last_settlement'])->toBeNull()
  62. ->and($data['policy'])->toHaveKeys(['daily_free', 'cost', 'earn']);
  63. });
  64. /* ------------------------------------------------------------------ 账号一览 */
  65. it('lists accounts with their balances, searchable by user name', function () {
  66. $alice = makeStudio('alice-'.Str::random(5));
  67. $bob = makeStudio('bob-'.Str::random(5));
  68. ledgerRow(AgentAccount::user($alice), 50);
  69. ledgerRow(AgentAccount::user($alice), -10, ['kind' => 'spend', 'source' => 'agent_run']);
  70. ledgerRow(AgentAccount::user($alice), -30, ['kind' => 'spend', 'bucket' => 'free', 'source' => 'agent_run']);
  71. ledgerRow(AgentAccount::user($bob), 5);
  72. $admin = creditAdmin();
  73. $rows = $this->getJson('/api/v3/admin/credit-accounts?filter[q]=alice', authHeader($admin))->assertOk()->json('data');
  74. expect($rows)->toHaveCount(1)
  75. ->and($rows[0])->toMatchArray([
  76. 'account_type' => 'user', 'account_id' => $alice, 'earned_balance' => 40, 'earned_total' => 50,
  77. 'spent_total' => 40, 'free_used_today' => 30,
  78. ])
  79. ->and($rows[0]['user']['id'])->toBe($alice);
  80. expect($this->getJson('/api/v3/admin/credit-accounts', authHeader($admin))->json('meta.total'))->toBe(2);
  81. });
  82. it('never treats a guest device id as the user with the same uuid', function () {
  83. $alice = makeStudio('alice-'.Str::random(5));
  84. ledgerRow(AgentAccount::guest($alice), -10, ['kind' => 'spend', 'bucket' => 'free', 'source' => 'agent_run']);
  85. $rows = $this->getJson('/api/v3/admin/credit-accounts?filter[account_type]=guest', authHeader(creditAdmin()))->json('data');
  86. expect($rows)->toHaveCount(1)->and($rows[0]['user'])->toBeNull();
  87. });
  88. it('rejects an unknown account type', function () {
  89. $this->getJson('/api/v3/admin/credit-accounts?filter[account_type]=robot', authHeader(creditAdmin()))->assertUnprocessable();
  90. });
  91. /* ------------------------------------------------------------------ 流水 */
  92. it('lists ledger entries of one account without exposing ids', function () {
  93. $alice = makeStudio('alice-'.Str::random(5));
  94. ledgerRow(AgentAccount::user($alice), 7);
  95. ledgerRow(AgentAccount::guest($alice), -10, ['kind' => 'spend', 'bucket' => 'free', 'source' => 'agent_run']);
  96. ledgerRow(AgentAccount::user(makeStudio('other-'.Str::random(5))), 3);
  97. $res = $this->getJson("/api/v3/admin/credit-ledger?filter[account_type]=user&filter[account_id]={$alice}", authHeader(creditAdmin()))
  98. ->assertOk();
  99. expect($res->json('data'))->toHaveCount(1)
  100. ->and($res->json('data.0'))->toMatchArray(['delta' => 7, 'kind' => 'earn', 'source' => 'reading', 'operator' => null])
  101. ->and($res->json('data.0'))->not->toHaveKey('id');
  102. });
  103. it('requires the account type together with the account id', function () {
  104. $this->getJson('/api/v3/admin/credit-ledger?filter[account_id]='.Str::uuid(), authHeader(creditAdmin()))
  105. ->assertUnprocessable()->assertJsonValidationErrors('filter.account_type');
  106. });
  107. it('keeps the ledger query count independent of the number of rows', function () {
  108. $admin = creditAdmin();
  109. $count = function () use ($admin) {
  110. DB::flushQueryLog();
  111. DB::enableQueryLog();
  112. $this->getJson('/api/v3/admin/credit-ledger', authHeader($admin))->assertOk();
  113. return count(DB::getQueryLog());
  114. };
  115. ledgerRow(AgentAccount::user(makeStudio('u-'.Str::random(5))), 1);
  116. $few = $count();
  117. foreach (range(1, 8) as $i) {
  118. ledgerRow(AgentAccount::user(makeStudio("u{$i}-".Str::random(5))), 1);
  119. }
  120. expect($count())->toBe($few);
  121. });
  122. /* ------------------------------------------------------------------ 手工加减 */
  123. it('grants credits by username and records the operator', function () {
  124. $username = 'alice-'.Str::random(5);
  125. $alice = makeStudio($username);
  126. $admin = creditAdmin();
  127. $res = $this->postJson('/api/v3/admin/credit-adjustments', ['user' => $username, 'delta' => 200, 'note' => '补发'], authHeader($admin))
  128. ->assertCreated();
  129. expect($res->json('data'))->toMatchArray(['account_id' => $alice, 'delta' => 200, 'kind' => 'adjust', 'source' => 'admin', 'note' => '补发'])
  130. ->and($res->json('data.operator.id'))->toBe($admin)
  131. ->and($res->json('meta'))->toBe(['created' => true, 'earned_balance' => 200]);
  132. expect(CreditLedgerEntry::where('account_id', $alice)->value('operator_uid'))->toBe($admin);
  133. });
  134. it('applies the same ref only once', function () {
  135. $alice = makeStudio('alice-'.Str::random(5));
  136. $body = ['user' => $alice, 'delta' => 50, 'note' => 'x', 'ref' => (string) Str::uuid()];
  137. $admin = authHeader(creditAdmin());
  138. $this->postJson('/api/v3/admin/credit-adjustments', $body, $admin)->assertCreated();
  139. $this->postJson('/api/v3/admin/credit-adjustments', $body, $admin)->assertOk()->assertJsonPath('meta.created', false);
  140. expect((int) CreditLedgerEntry::where('account_id', $alice)->sum('delta'))->toBe(50);
  141. });
  142. it('refuses a deduction that would make the balance negative', function () {
  143. $alice = makeStudio('alice-'.Str::random(5));
  144. ledgerRow(AgentAccount::user($alice), 30);
  145. $this->postJson('/api/v3/admin/credit-adjustments', ['user' => $alice, 'delta' => -31, 'note' => 'x'], authHeader(creditAdmin()))
  146. ->assertUnprocessable()->assertJsonValidationErrors('delta');
  147. $this->postJson('/api/v3/admin/credit-adjustments', ['user' => $alice, 'delta' => -30, 'note' => 'x'], authHeader(creditAdmin()))
  148. ->assertCreated()->assertJsonPath('meta.earned_balance', 0);
  149. });
  150. it('rejects an unknown user, a zero delta and a missing note', function () {
  151. $admin = authHeader(creditAdmin());
  152. $this->postJson('/api/v3/admin/credit-adjustments', ['user' => 'nobody-'.Str::random(8), 'delta' => 1, 'note' => 'x'], $admin)
  153. ->assertUnprocessable()->assertJsonValidationErrors('user');
  154. $this->postJson('/api/v3/admin/credit-adjustments', ['user' => 'x', 'delta' => 0], $admin)
  155. ->assertUnprocessable()->assertJsonValidationErrors(['delta', 'note']);
  156. });
  157. /* ------------------------------------------------------------------ 手工结算 */
  158. it('settles missing days, is idempotent and records the last run', function () {
  159. $alice = makeStudio('alice-'.Str::random(5));
  160. ReadingDaily::create(['user_uid' => $alice, 'day' => now('UTC')->subDays(2)->toDateString(), 'seconds' => 600, 'seconds_reported' => 600]);
  161. $admin = creditAdmin();
  162. $first = $this->postJson('/api/v3/admin/credit-settlements', [], authHeader($admin))->assertCreated()->json('data');
  163. $this->postJson('/api/v3/admin/credit-settlements', [], authHeader($admin))->assertCreated();
  164. expect($first)->toMatchArray(['mode' => 'missing', 'users' => 1, 'pairs' => 1, 'trigger' => 'admin'])
  165. ->and((int) CreditLedgerEntry::where('account_id', $alice)->sum('delta'))->toBe(10)
  166. ->and(RedisCache::get(CreditAdminService::LAST_SETTLEMENT_KEY)['trigger'])->toBe('admin');
  167. });
  168. it('re-settles one day on demand without double counting', function () {
  169. $alice = makeStudio('alice-'.Str::random(5));
  170. $day = now('UTC')->subDay()->toDateString();
  171. ReadingDaily::create(['user_uid' => $alice, 'day' => $day, 'seconds' => 300, 'seconds_reported' => 300]);
  172. $admin = authHeader(creditAdmin());
  173. $this->postJson('/api/v3/admin/credit-settlements', ['date' => $day], $admin)->assertCreated()
  174. ->assertJsonPath('data.mode', 'day')->assertJsonPath('data.users', 1);
  175. $this->postJson('/api/v3/admin/credit-settlements', ['date' => $day], $admin)->assertCreated();
  176. expect((int) CreditLedgerEntry::where('account_id', $alice)->sum('delta'))->toBe(5);
  177. });
  178. it('rejects a settlement date before credits went live or in the future', function (string $date) {
  179. $this->postJson('/api/v3/admin/credit-settlements', ['date' => $date], authHeader(creditAdmin()))
  180. ->assertUnprocessable()->assertJsonValidationErrors('date');
  181. })->with([
  182. 'before launch' => ['2020-01-01'],
  183. 'future' => [fn () => now('UTC')->addDay()->toDateString()],
  184. 'malformed' => ['yesterday'],
  185. ]);
  186. it('records the daily command as the last run too', function () {
  187. $this->artisan('credits:settle-activity')->assertSuccessful();
  188. expect(RedisCache::get(CreditAdminService::LAST_SETTLEMENT_KEY))->toMatchArray(['trigger' => 'cli', 'operator' => null]);
  189. });