AgentApiRegressionTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Http\Controllers\admin\Agent as AdminAgent;
  4. use App\Http\Controllers\AgentApiController;
  5. use App\Http\Middleware\AgentAuthMiddleware;
  6. use App\Models\Agent\Agent;
  7. use App\Models\Agent\AgentBalanceLog;
  8. use App\Models\Agent\AgentLoginLog;
  9. use App\Models\Agent\AgentRebateRecord;
  10. use App\Models\Agent\AgentToken;
  11. use App\Models\Agent\AgentWithdrawAccount;
  12. use App\Models\Agent\AgentWithdrawal;
  13. use App\Services\Agent\AgentCommissionService;
  14. use App\Services\Agent\AgentMemberService;
  15. use App\Services\Agent\AgentProfitCommissionAssignmentService;
  16. use App\Services\Agent\AgentReportService;
  17. use App\Services\Agent\AgentService;
  18. use App\Services\Agent\AgentWalletService;
  19. use App\Services\Agent\AgentWithdrawalService;
  20. use App\Services\PaymentOrderService;
  21. use Carbon\Carbon;
  22. use Illuminate\Config\Repository;
  23. use Illuminate\Contracts\Debug\ExceptionHandler;
  24. use Illuminate\Database\Capsule\Manager;
  25. use Illuminate\Database\QueryException;
  26. use Illuminate\Database\Schema\Blueprint;
  27. use Illuminate\Events\Dispatcher;
  28. use Illuminate\Foundation\Application;
  29. use Illuminate\Hashing\BcryptHasher;
  30. use Illuminate\Http\JsonResponse;
  31. use Illuminate\Http\Request;
  32. use Illuminate\Support\Facades\DB;
  33. use Illuminate\Support\Facades\Facade;
  34. use Illuminate\Support\Facades\Schema;
  35. use Illuminate\Translation\ArrayLoader;
  36. use Illuminate\Translation\Translator;
  37. use Illuminate\Validation\Factory;
  38. use PHPUnit\Framework\TestCase;
  39. use Tests\Support\AgentTestEnvironment;
  40. class AgentApiRegressionTest extends TestCase
  41. {
  42. use AgentTestEnvironment;
  43. public function test_admin_password_reset_revokes_old_login(): void
  44. {
  45. $agent = $this->agent(); $token = $this->token($agent);
  46. $this->agents->update($agent, ['password' => 'new-password']);
  47. $this->assertSame(0, AgentToken::query()->where('agent_id', $agent->id)->count());
  48. $request = Request::create('/agent/profile');
  49. $request->headers->set('Authorization', 'Bearer ' . $token);
  50. $response = (new AgentAuthMiddleware())->handle($request, fn () => new JsonResponse(['code' => 0]));
  51. $this->assertSame(101011, $response->getData(true)['code']);
  52. }
  53. public function test_disable_then_enable_does_not_restore_old_login(): void
  54. {
  55. $agent = $this->agent(); $this->token($agent);
  56. $this->agents->update($agent, ['status' => 0]);
  57. $this->agents->update($agent, ['status' => 1]);
  58. $this->assertSame(0, AgentToken::query()->count());
  59. }
  60. public function test_non_sensitive_edit_preserves_login(): void
  61. {
  62. $agent = $this->agent(); $this->token($agent);
  63. $this->agents->update($agent, ['real_name' => 'new name']);
  64. $this->assertSame(1, AgentToken::query()->count());
  65. }
  66. public function test_finance_counts_include_only_successful_in_range_provider_orders(): void
  67. {
  68. $agent = $this->agent();
  69. DB::table('users')->insert(['member_id' => 'm1', 'username' => 'member', 'agent_id' => $agent->id,
  70. 'created_at' => '2026-01-01 00:00:00']);
  71. $base = ['member_id' => 'm1', 'amount' => 10, 'created_at' => now()];
  72. DB::table('recharges')->insert($base + ['status' => 1]);
  73. DB::table('withdraws')->insert($base + ['status' => 1]);
  74. foreach ([PaymentOrderService::TYPE_PAY, PaymentOrderService::TYPE_PAYOUT, PaymentOrderService::TYPE_SELF_PAYOUT] as $type) {
  75. DB::table('payment_orders')->insert($base + ['type' => $type, 'status' => PaymentOrderService::STATUS_SUCCESS]);
  76. }
  77. DB::table('payment_orders')->insert($base + ['type' => PaymentOrderService::TYPE_PAY, 'status' => -99]);
  78. DB::table('payment_orders')->insert(array_merge($base, ['type' => PaymentOrderService::TYPE_PAY,
  79. 'status' => PaymentOrderService::STATUS_SUCCESS, 'created_at' => '2026-08-01 00:00:00']));
  80. DB::table('payment_orders')->insert(array_merge($base, ['type' => PaymentOrderService::TYPE_PAY,
  81. 'status' => PaymentOrderService::STATUS_SUCCESS, 'member_id' => 'unrelated']));
  82. $result = (new AgentMemberService(new AgentReportService()))->finance($agent, []);
  83. $member = $result['list'][0];
  84. $this->assertSame(2, $member->recharge_count);
  85. $this->assertSame(3, $member->withdraw_count);
  86. $this->assertSame('20.0000', $member->recharge_amount);
  87. $this->assertSame('30.0000', $member->withdraw_amount);
  88. }
  89. public function test_login_logs_filter_login_time_not_record_creation_time(): void
  90. {
  91. $agent = $this->agent();
  92. AgentLoginLog::query()->create(['agent_id' => $agent->id, 'username' => $agent->username,
  93. 'login_at' => '2026-09-06 23:59:59', 'created_at' => '2026-09-07 00:00:01']);
  94. $controller = new AdminAgent();
  95. $request = Request::create('/admin/agent/login-logs', 'GET', ['start_date' => '2026-09-06', 'end_date' => '2026-09-06']);
  96. $this->assertSame(1, $controller->loginLogs($request)->getData(true)['data']['total']);
  97. }
  98. public function test_admin_balance_logs_include_signed_debits_for_the_selected_agent(): void
  99. {
  100. $agent = $this->agent(Agent::TYPE_EQUITY);
  101. $other = $this->agent();
  102. $wallets = new AgentWalletService();
  103. foreach ([$agent, $other] as $owner) {
  104. $wallets->adjust($owner->id, '100', 'credit', '初始额度', 'credit-' . $owner->id, 'admin', 1);
  105. $wallets->adjust($owner->id, '25.1250', 'debit', '人工扣款', 'debit-' . $owner->id, 'admin', 1);
  106. }
  107. $controller = new AdminAgent();
  108. $query = ['agent_id' => $agent->id];
  109. $all = $controller->balanceLogs(Request::create('/admin/agent/balance-logs', 'GET', $query))->getData(true);
  110. $this->assertSame(0, $all['code']);
  111. $this->assertSame(['debit', 'credit'], array_column($all['data']['list'], 'type'));
  112. $this->assertContains(['value' => 'debit', 'label' => '人工扣款'], $all['data']['types']);
  113. $filtered = $controller->balanceLogs(Request::create('/admin/agent/balance-logs', 'GET', $query + ['type' => 'debit']))->getData(true)['data'];
  114. $this->assertSame(1, $filtered['total']);
  115. $row = $filtered['list'][0];
  116. $this->assertSame(['人工扣款', '-25.1250', '100.0000', '74.8750'], [$row['type_text'], $row['amount'], $row['before_balance'], $row['after_balance']]);
  117. $this->assertArrayNotHasKey('idempotency_key', $row);
  118. }
  119. public function test_admin_withdrawal_list_includes_the_current_agent_type_and_label(): void
  120. {
  121. $joint = $this->agent();
  122. $equity = $this->agent(Agent::TYPE_EQUITY);
  123. foreach ([$joint, $equity] as $agent) {
  124. $account = $this->fundedAccount($agent);
  125. (new AgentWithdrawalService())->request($agent, $account->id, '10', 'withdraw-old', 'type-list');
  126. }
  127. $response = (new AdminAgent())->withdrawals(Request::create('/admin/agent/withdrawals'))->getData(true);
  128. $this->assertSame(0, $response['code']);
  129. $agents = array_column($response['data']['list'], 'agent', 'agent_id');
  130. $this->assertSame([1, '合营'], [$agents[$joint->id]['type'], $agents[$joint->id]['type_text']]);
  131. $this->assertSame([2, '入股'], [$agents[$equity->id]['type'], $agents[$equity->id]['type_text']]);
  132. }
  133. private function fundedAccount(Agent $agent): AgentWithdrawAccount
  134. {
  135. $this->paymentChannels(); // 提现按总后台通道组合校验(组合 1 含 usdt)
  136. Agent::query()->whereKey($agent->id)->update(['balance' => 100, 'realtime_balance' => 100]);
  137. return AgentWithdrawAccount::query()->create(['agent_id' => $agent->id, 'type' => 'usdt', 'network' => 'TRC20',
  138. 'account' => 'TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE', 'status' => 1]);
  139. }
  140. public function test_withdrawal_uses_current_password_not_stale_request_model(): void
  141. {
  142. $agent = $this->agent(); $account = $this->fundedAccount($agent);
  143. $this->agents->update($agent, ['withdraw_password' => 'withdraw-new']);
  144. $this->expectException(\InvalidArgumentException::class);
  145. $this->expectExceptionMessage('提现密码错误');
  146. (new AgentWithdrawalService())->request($agent, $account->id, '10', 'withdraw-old', 'stale');
  147. }
  148. public function test_disabled_agent_cannot_submit_with_stale_request_model(): void
  149. {
  150. $agent = $this->agent(); $account = $this->fundedAccount($agent);
  151. $this->agents->update($agent, ['status' => 0]);
  152. $this->expectException(\RuntimeException::class);
  153. $this->expectExceptionMessage('代理账号已禁用');
  154. (new AgentWithdrawalService())->request($agent, $account->id, '10', 'withdraw-old', 'disabled');
  155. }
  156. public function test_withdrawal_retry_and_rejection_move_funds_once(): void
  157. {
  158. $agent = $this->agent(); $account = $this->fundedAccount($agent);
  159. $service = new AgentWithdrawalService();
  160. $one = $service->request($agent, $account->id, '10', 'withdraw-old', 'retry');
  161. $two = $service->request($agent, $account->id, '10', 'withdraw-old', 'retry');
  162. $this->assertSame($one->id, $two->id);
  163. $this->assertSame('90.0000', $agent->fresh()->balance);
  164. $this->assertSame('10.0000', $agent->fresh()->frozen_balance);
  165. $service->audit($one->id, 'reject', 1);
  166. $this->assertSame('100.0000', $agent->fresh()->balance);
  167. $this->assertSame('0.0000', $agent->fresh()->frozen_balance);
  168. $this->assertSame(1, AgentWithdrawal::query()->count());
  169. $this->assertSame(2, AgentBalanceLog::query()->count());
  170. }
  171. public function test_member_finance_does_not_include_other_agent_members(): void
  172. {
  173. $agent = $this->agent(); $other = $this->agent();
  174. foreach ([$agent, $agent, $other] as $i => $owner) {
  175. DB::table('users')->insert(['member_id' => 'm' . $i, 'username' => 'member' . $i,
  176. 'agent_id' => $owner->id, 'created_at' => now()]);
  177. }
  178. $service = new AgentMemberService(new AgentReportService());
  179. $this->assertSame(2, $service->finance($agent, [])['total']);
  180. $this->assertSame(0, $service->finance($agent, ['agent_id' => $other->id])['total']);
  181. $this->assertSame(1, $service->finance($other, [])['total']);
  182. }
  183. public function test_business_errors_keep_existing_response_contract(): void
  184. {
  185. $controller = new class extends AgentApiController {
  186. public function trigger() {
  187. return $this->execute(fn () => throw new \RuntimeException('代理余额不足'));
  188. }
  189. };
  190. $data = $controller->trigger()->getData(true);
  191. $this->assertSame(['code', 'timestamp', 'msg', 'data'], array_keys($data));
  192. $this->assertSame(-3, $data['code']);
  193. $this->assertSame('代理余额不足', $data['msg']);
  194. }
  195. public function test_settlement_command_rejects_invalid_and_unfinished_dates(): void
  196. {
  197. $handler = $this->createMock(ExceptionHandler::class);
  198. $handler->expects($this->exactly(3))->method('report');
  199. $this->app->instance(ExceptionHandler::class, $handler);
  200. $reports = $this->createMock(AgentReportService::class);
  201. $reports->expects($this->never())->method('refreshDaily');
  202. $this->app->instance(AgentReportService::class, $reports);
  203. $commissions = $this->createMock(AgentCommissionService::class);
  204. $commissions->expects($this->never())->method('settle');
  205. $this->app->instance(AgentCommissionService::class, $commissions);
  206. foreach (['2026-02-30', '2026-09-07', '2026-09-08'] as $date) {
  207. $command = new \App\Console\Commands\AgentDailySettle();
  208. $command->setLaravel($this->app);
  209. $tester = new \Symfony\Component\Console\Tester\CommandTester($command);
  210. $this->assertSame(1, $tester->execute(['date' => $date]));
  211. }
  212. }
  213. public function test_sql_errors_are_logged_but_not_returned_to_frontend(): void
  214. {
  215. $handler = $this->createMock(ExceptionHandler::class);
  216. $handler->expects($this->once())->method('report');
  217. $this->app->instance(ExceptionHandler::class, $handler);
  218. $controller = new class extends AgentApiController {
  219. public function trigger() {
  220. return $this->execute(fn () => throw new QueryException('select sensitive_table', ['secret'], new \PDOException('internal database error')));
  221. }
  222. };
  223. $data = $controller->trigger()->getData(true);
  224. $this->assertSame(-3, $data['code']);
  225. $this->assertSame('系统处理失败,请稍后重试', $data['msg']);
  226. $this->assertSame([], $data['data']);
  227. }
  228. }