ShareAdminManagementTest.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Console\Commands\BackfillShareCommissions;
  4. use App\Http\Controllers\admin\ShareEarning;
  5. use App\Http\Controllers\admin\SharingManagement;
  6. use App\Models\BalanceLog;
  7. use App\Models\ShareSetting;
  8. use App\Services\BalanceLogService;
  9. use App\Services\ShareCommissionDiagnostics;
  10. use App\Services\Sharing\ShareAdminService;
  11. use App\Services\Sharing\ShareClaimAuditService;
  12. use Carbon\Carbon;
  13. use Illuminate\Config\Repository;
  14. use Illuminate\Database\Capsule\Manager;
  15. use Illuminate\Database\Schema\Blueprint;
  16. use Illuminate\Foundation\Application;
  17. use Illuminate\Http\JsonResponse;
  18. use Illuminate\Http\Request;
  19. use Illuminate\Support\Facades\DB;
  20. use Illuminate\Support\Facades\Facade;
  21. use Illuminate\Translation\ArrayLoader;
  22. use Illuminate\Translation\Translator;
  23. use Illuminate\Validation\Factory;
  24. use Illuminate\Validation\ValidationException;
  25. use PHPUnit\Framework\TestCase;
  26. use Symfony\Component\Console\Tester\CommandTester;
  27. /** Only an isolated, prefixed SQLite database; never boots project providers or reads .env. */
  28. class ShareAdminManagementTest extends TestCase
  29. {
  30. private Application $app;
  31. private ShareAdminService $admin;
  32. private ShareClaimAuditService $claims;
  33. protected function setUp(): void
  34. {
  35. Facade::clearResolvedInstances();
  36. Carbon::setTestNow(Carbon::parse('2026-10-24 18:00:00', 'Asia/Shanghai'));
  37. $this->app = new Application(dirname(__DIR__, 2));
  38. $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai']]));
  39. Facade::setFacadeApplication($this->app);
  40. $db = new Manager($this->app);
  41. $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  42. $db->setAsGlobal(); $db->bootEloquent();
  43. $this->app->instance('db', $db->getDatabaseManager());
  44. $this->app->bind('db.schema', fn () => $db->schema());
  45. $translator = new Translator(new ArrayLoader(), 'zh');
  46. $this->app->instance('translator', $translator);
  47. $this->app->instance('validator', new Factory($translator, $this->app));
  48. $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new class {
  49. public function json($data, $status = 200, $headers = [], $options = 0) { return new JsonResponse($data, $status, $headers, $options); }
  50. });
  51. Request::macro('validate', function (array $rules) { return app('validator')->make($this->all(), $rules)->validate(); });
  52. $db->schema()->create('share_settings', function (Blueprint $t) {
  53. $t->id(); $t->integer('enabled')->default(0); $t->integer('benefit_enabled')->default(0);
  54. $t->string('share_domain')->default(''); $t->decimal('valid_member_min_deposit', 20, 2)->default(20);
  55. $t->decimal('non_seller_threshold', 24, 10)->default(200); $t->decimal('tier_one_rate', 8, 4)->default(4);
  56. $t->decimal('tier_two_rate', 8, 4)->default(6); $t->integer('operator_id')->nullable(); $t->string('operator_name')->default(''); $t->timestamps();
  57. });
  58. $db->schema()->create('users', function (Blueprint $t) {
  59. $t->id(); $t->string('member_id')->unique(); $t->string('account'); $t->string('first_name'); $t->timestamps();
  60. });
  61. $db->schema()->create('wallets', function (Blueprint $t) {
  62. $t->id(); $t->string('member_id')->unique(); $t->decimal('available_balance', 24, 10)->default(0); $t->timestamps();
  63. });
  64. $db->schema()->create('balance_logs', function (Blueprint $t) {
  65. $t->id(); $t->string('member_id'); $t->string('change_type'); $t->integer('type')->default(1);
  66. foreach (['amount', 'before_balance', 'after_balance'] as $field) $t->decimal($field, 24, 10);
  67. $t->integer('related_id')->nullable(); $t->text('remark')->nullable(); $t->timestamps();
  68. });
  69. $db->schema()->create('operation_audits', function (Blueprint $t) {
  70. $t->id(); $t->string('resource_type'); $t->integer('resource_id')->nullable(); $t->string('action');
  71. $t->json('changes'); $t->integer('operator_id')->nullable(); $t->string('operator_name'); $t->timestamp('created_at')->useCurrent();
  72. });
  73. (require dirname(__DIR__, 2) . '/database/migrations/2026_10_24_120000_create_member_sharing_system.php')->up();
  74. $request = Request::create('/admin/shareEarning/settings', 'GET');
  75. $request->user = (object)['id' => 8, 'username' => 'admin'];
  76. $this->app->instance('request', $request);
  77. $this->admin = new ShareAdminService(); $this->claims = new ShareClaimAuditService();
  78. }
  79. protected function tearDown(): void
  80. {
  81. BalanceLogService::$MODEL = BalanceLog::class;
  82. Carbon::setTestNow(); DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown();
  83. }
  84. private function config(array $extra = []): array
  85. {
  86. return array_replace(['enabled' => 1, 'share_domain' => 'https://PC.example.com/',
  87. 'valid_member_min_deposit' => '20.00', 'valid_member_min_effective_bet' => '100.00'], $extra);
  88. }
  89. private function initialized(): void
  90. {
  91. DB::table('share_system_state')->insert(['key' => 'initialized_at', 'value' => '2026-10-24 18:00:00']);
  92. }
  93. private function fails(callable $callback, string $contains): void
  94. {
  95. try { $callback(); $this->fail('Expected validation rejection'); }
  96. catch (ValidationException $e) { $this->assertStringContainsString($contains, $e->validator->errors()->first()); }
  97. }
  98. private function assertNoCommissionSwitch(array $settings): void
  99. {
  100. $this->assertArrayNotHasKey('benefit_enabled', $settings);
  101. foreach (['current_policy', 'pending_policy'] as $key) {
  102. if ($settings[$key] !== null) $this->assertArrayNotHasKey('benefit_enabled', $settings[$key]);
  103. }
  104. }
  105. public function test_explicit_setup_and_initializer_gate_enablement(): void
  106. {
  107. $initial = $this->admin->settings();
  108. $this->assertNull($initial['activation_date']);
  109. $this->assertNoCommissionSwitch($initial);
  110. $this->fails(fn () => $this->admin->saveSettings($this->config()), '初始化');
  111. $this->fails(fn () => $this->admin->saveSettings($this->config(['benefit_enabled' => 0])), '初始化');
  112. $this->assertSame(0, DB::table('share_settings')->count());
  113. $this->initialized();
  114. $incomplete = $this->config(); unset($incomplete['valid_member_min_effective_bet']);
  115. $this->fails(fn () => $this->admin->saveSettings($incomplete), 'required');
  116. $this->fails(fn () => $this->admin->saveSettings($this->config(['tier_one_rate' => 4])), '已移除');
  117. $this->fails(fn () => $this->admin->saveSettings($this->config(['activation_date' => '2020-01-01'])), '不可指定');
  118. $this->fails(fn () => $this->admin->saveSettings($this->config(['share_domain' => 'https://pc.example/a'])), '源地址');
  119. $data = $this->admin->saveSettings($this->config());
  120. $this->assertSame('2026-10-25', $data['activation_date']);
  121. $this->assertSame('https://pc.example.com', $data['share_domain']);
  122. $this->assertNoCommissionSwitch($data);
  123. $this->assertSame(0, (int) DB::table('share_policies')->where('id', $data['current_policy']['id'])->value('benefit_enabled'));
  124. $this->assertSame(1, (int) DB::table('share_policies')->where('id', $data['pending_policy']['id'])->value('benefit_enabled'));
  125. $this->assertSame(1, (int) DB::table('share_settings')->value('benefit_enabled'));
  126. $this->assertArrayNotHasKey('tier_one_rate', $data);
  127. $this->assertArrayNotHasKey('indirect_bonus_rate', $data);
  128. $this->assertArrayNotHasKey('indirect_bonus_rate', $data['current_policy']);
  129. $this->assertArrayNotHasKey('indirect_bonus_rate', $data['pending_policy']);
  130. $this->assertSame(12, count($data['pending_policy']['rules']['third:1']));
  131. }
  132. public function test_pending_policy_edits_preserve_past_policy_and_activation_date(): void
  133. {
  134. $this->initialized();
  135. $first = $this->admin->saveSettings($this->config());
  136. $pendingId = $first['pending_policy']['id'];
  137. $this->admin->saveRateRules('third:1', [['min_valid_members' => 1, 'min_performance' => '1000000', 'rate' => '0.25']]);
  138. $again = $this->admin->saveSettings($this->config(['valid_member_min_effective_bet' => '250']));
  139. $this->assertSame($pendingId, $again['pending_policy']['id']);
  140. $this->assertSame('0.2500', $again['pending_policy']['rules']['third:1'][0]['rate']);
  141. Carbon::setTestNow(Carbon::parse('2026-10-25 01:00:00', 'Asia/Shanghai'));
  142. $before = (array)DB::table('share_policies')->where('id', $pendingId)->first();
  143. $this->admin->saveSettings($this->config(['benefit_enabled' => 0]));
  144. $this->admin->saveRateRules('third:2', [['min_valid_members' => 0, 'min_performance' => 10, 'rate' => '0.50']]);
  145. $this->assertSame($before, (array)DB::table('share_policies')->where('id', $pendingId)->first());
  146. $settings = $this->admin->settings();
  147. $this->assertNoCommissionSwitch($settings);
  148. $this->assertSame(1, (int) DB::table('share_policies')->where('id', $settings['pending_policy']['id'])->value('benefit_enabled'));
  149. $this->assertSame(1, (int) DB::table('share_policies')->where('id', $settings['current_policy']['id'])->value('benefit_enabled'));
  150. $this->admin->saveSettings($this->config());
  151. $this->assertSame('2026-10-25', $this->admin->settings()['activation_date']);
  152. $this->assertSame(3, DB::table('share_policies')->count());
  153. }
  154. public function test_both_member_thresholds_are_required_and_invalid_values_cannot_create_configuration(): void
  155. {
  156. $this->initialized();
  157. foreach (['valid_member_min_deposit', 'valid_member_min_effective_bet'] as $field) {
  158. foreach ([null, ''] as $value) {
  159. $input = $this->config([$field => $value, 'benefit_enabled' => 0]);
  160. try { $this->admin->saveSettings($input); $this->fail('Expected a required member threshold'); }
  161. catch (ValidationException $e) {
  162. $this->assertArrayHasKey('Required', $e->validator->failed()[$field]);
  163. $this->assertArrayNotHasKey('RequiredIf', $e->validator->failed()[$field]);
  164. }
  165. }
  166. $input = $this->config(['benefit_enabled' => 0]); unset($input[$field]);
  167. try { $this->admin->saveSettings($input); $this->fail('Expected a missing member threshold rejection'); }
  168. catch (ValidationException $e) { $this->assertArrayHasKey('Required', $e->validator->failed()[$field]); }
  169. foreach ([-1, 'invalid', '20.001'] as $value) {
  170. $this->fails(fn () => $this->admin->saveSettings($this->config([$field => $value, 'benefit_enabled' => 0])), 'regex');
  171. }
  172. }
  173. $this->assertSame(0, DB::table('share_settings')->count());
  174. $this->assertSame(1, DB::table('share_policies')->count());
  175. $this->assertSame(0, DB::table('operation_audits')->count());
  176. }
  177. public function test_legacy_switch_input_is_ignored_and_cannot_disable_complete_configuration(): void
  178. {
  179. $this->initialized();
  180. $past = (array) DB::table('share_policies')->where('effective_date', '1970-01-01')->first();
  181. $legacyInputs = [[]];
  182. foreach ([0, 1, '0', '1', null, 'obsolete', []] as $value) $legacyInputs[] = ['benefit_enabled' => $value];
  183. foreach ($legacyInputs as $legacyInput) {
  184. $request = Request::create('/admin/shareEarning/settings', 'POST', $this->config($legacyInput + ['enabled' => 0]));
  185. $request->user = (object) ['id' => 8, 'username' => 'admin'];
  186. $this->app->instance('request', $request);
  187. $body = (new ShareEarning())->saveSettings($this->admin)->getData(true);
  188. $this->assertSame(0, $body['code'], $body['msg']);
  189. $this->assertNoCommissionSwitch($body['data']);
  190. $this->assertSame(0, $body['data']['enabled']);
  191. $this->assertSame('2026-10-25', $body['data']['activation_date']);
  192. $this->assertSame(1, (int) DB::table('share_settings')->value('benefit_enabled'));
  193. $this->assertSame(1, (int) DB::table('share_policies')->where('effective_date', '2026-10-25')->value('benefit_enabled'));
  194. }
  195. $this->assertSame(2, DB::table('share_policies')->count());
  196. $this->assertSame($past, (array) DB::table('share_policies')->where('id', $past['id'])->first());
  197. $this->assertArrayNotHasKey('benefit_enabled', ShareSetting::query()->firstOrFail()->toArray());
  198. Carbon::setTestNow(Carbon::parse('2026-10-24 23:59:59', 'Asia/Shanghai'));
  199. $this->assertSame($past['id'], $this->admin->settings()['current_policy']['id']);
  200. Carbon::setTestNow(Carbon::parse('2026-10-25 00:00:00', 'Asia/Shanghai'));
  201. $current = $this->admin->settings();
  202. $this->assertNoCommissionSwitch($current);
  203. $this->assertSame('2026-10-25', $current['current_policy']['effective_date']);
  204. $this->assertSame(1, (int) DB::table('share_policies')->where('id', $current['current_policy']['id'])->value('benefit_enabled'));
  205. $this->assertNull($current['pending_policy']);
  206. }
  207. public function test_existing_disabled_configuration_remains_unchanged_until_a_complete_save(): void
  208. {
  209. $id = DB::table('share_settings')->insertGetId(['benefit_enabled' => 0, 'share_domain' => 'https://legacy.example.test']);
  210. $before = (array) DB::table('share_settings')->where('id', $id)->first();
  211. $this->assertNoCommissionSwitch($this->admin->settings());
  212. $this->assertArrayNotHasKey('benefit_enabled', ShareSetting::query()->findOrFail($id)->toArray());
  213. $this->assertSame($before, (array) DB::table('share_settings')->where('id', $id)->first());
  214. $this->fails(fn () => $this->admin->saveSettings($this->config(['benefit_enabled' => 1])), '初始化');
  215. $this->assertSame($before, (array) DB::table('share_settings')->where('id', $id)->first());
  216. $this->initialized();
  217. $saved = $this->admin->saveSettings($this->config(['benefit_enabled' => 0]));
  218. $this->assertNoCommissionSwitch($saved);
  219. $this->assertSame(1, (int) DB::table('share_settings')->where('id', $id)->value('benefit_enabled'));
  220. $this->assertSame('2026-10-25', $saved['activation_date']);
  221. $this->assertSame(0, (int) DB::table('share_policies')->where('id', $saved['current_policy']['id'])->value('benefit_enabled'));
  222. }
  223. public function test_retired_indirect_coefficient_is_rejected_even_when_null_without_saving(): void
  224. {
  225. $this->initialized();
  226. foreach ([null, 0, '30.0000'] as $value) {
  227. $this->fails(fn () => $this->admin->saveSettings($this->config(['indirect_bonus_rate' => $value])), '已移除');
  228. }
  229. $this->assertSame(0, DB::table('share_settings')->count());
  230. $this->assertSame(1, DB::table('share_policies')->count());
  231. $this->assertSame(0, DB::table('operation_audits')->count());
  232. $request = Request::create('/admin/shareEarning/settings', 'POST', $this->config(['indirect_bonus_rate' => '30']));
  233. $this->app->instance('request', $request);
  234. $body = (new ShareEarning())->saveSettings($this->admin)->getData(true);
  235. $this->assertSame(-3, $body['code']);
  236. $this->assertStringContainsString('已移除', $body['msg']);
  237. $this->assertSame(0, DB::table('share_settings')->count());
  238. }
  239. public function test_rule_edits_need_no_coefficient_and_preserve_archived_policy_values(): void
  240. {
  241. $this->initialized();
  242. DB::table('share_settings')->insert(['indirect_bonus_rate' => '25.0000']);
  243. DB::table('share_policies')->update(['indirect_bonus_rate' => '30.0000']);
  244. $archived = (array) DB::table('share_policies')->where('effective_date', '1970-01-01')->first();
  245. $settings = $this->admin->saveSettings($this->config());
  246. $this->assertArrayNotHasKey('indirect_bonus_rate', $settings);
  247. $this->assertArrayNotHasKey('indirect_bonus_rate', $settings['current_policy']);
  248. $this->assertArrayNotHasKey('indirect_bonus_rate', $settings['pending_policy']);
  249. $this->assertNull(DB::table('share_policies')->where('id', $settings['pending_policy']['id'])->value('indirect_bonus_rate'));
  250. $this->assertSame('25.0000', bcadd((string) DB::table('share_settings')->value('indirect_bonus_rate'), '0', 4));
  251. $model = ShareSetting::query()->firstOrFail();
  252. $this->assertArrayNotHasKey('indirect_bonus_rate', $model->getCasts());
  253. $this->assertArrayNotHasKey('indirect_bonus_rate', $model->toArray());
  254. $this->assertArrayNotHasKey('benefit_enabled', $model->toArray());
  255. $rules = $this->admin->saveRateRules('third:1', [['min_valid_members' => 0, 'min_performance' => 0, 'rate' => '10']]);
  256. $this->assertSame('10.0000', $rules['categories'][0]['pending_rules'][0]['rate']);
  257. $this->admin->saveSettings($this->config(['valid_member_min_effective_bet' => '250']));
  258. $this->admin->saveLevel(['level' => 2, 'name' => '二级', 'image' => '', 'incremental_commission' => '10']);
  259. $settings = $this->admin->settings();
  260. $this->assertSame('10.0000', $settings['pending_policy']['rules']['third:1'][0]['rate']);
  261. $this->assertSame('250.00', $settings['pending_policy']['valid_member_min_effective_bet']);
  262. $this->assertArrayNotHasKey('indirect_bonus_rate', $settings['pending_policy']);
  263. $this->assertNull(DB::table('share_policies')->where('id', $settings['pending_policy']['id'])->value('indirect_bonus_rate'));
  264. $this->assertSame($archived, (array) DB::table('share_policies')->where('id', $archived['id'])->first());
  265. Carbon::setTestNow(Carbon::parse('2026-10-25 01:00:00', 'Asia/Shanghai'));
  266. $this->assertSame('10.0000', $this->admin->rateRules('third:1')['categories'][0]['current_rules'][0]['rate']);
  267. $this->assertArrayNotHasKey('indirect_bonus_rate', $this->admin->settings()['current_policy']);
  268. }
  269. public function test_diagnostic_and_backfill_output_hide_archived_coefficient_without_writes(): void
  270. {
  271. $schema = DB::connection()->getSchemaBuilder();
  272. $schema->table('users', function (Blueprint $t) {
  273. $t->string('user_code')->default(''); $t->string('agent_user_code')->nullable(); $t->integer('from')->default(1);
  274. });
  275. $schema->create('config', function (Blueprint $t) {
  276. $t->id(); $t->string('field'); $t->string('val');
  277. });
  278. $schema->create('share_commission_records', function (Blueprint $t) {
  279. $t->id(); $t->date('stat_date'); $t->integer('status');
  280. });
  281. DB::table('config')->insert(['field' => 'recharge_rate', 'val' => '2.5000']);
  282. DB::table('share_settings')->insert(['benefit_enabled' => 1, 'indirect_bonus_rate' => '30', 'valid_member_min_effective_bet' => '100']);
  283. $before = (array) DB::table('share_settings')->first();
  284. $data = (new ShareCommissionDiagnostics())->inspect(null);
  285. $this->assertArrayNotHasKey('indirect_bonus_rate', $data);
  286. $this->assertArrayNotHasKey('benefit_enabled', $data);
  287. $this->assertEquals('100', $data['valid_member_min_effective_bet']);
  288. $command = new BackfillShareCommissions();
  289. $command->setLaravel($this->app);
  290. $tester = new CommandTester($command);
  291. $tester->execute(['--diagnose' => true, '--all' => true]);
  292. $this->assertSame(0, $tester->getStatusCode(), $tester->getDisplay());
  293. $this->assertStringNotContainsString('indirect_bonus_rate', $tester->getDisplay());
  294. $this->assertStringNotContainsString('benefit_enabled', $tester->getDisplay());
  295. $this->assertStringContainsString('valid_member_min_effective_bet: 100', $tester->getDisplay());
  296. $this->assertSame($before, (array) DB::table('share_settings')->first());
  297. $this->assertSame(0, DB::table('share_commission_records')->count());
  298. $this->assertSame(0, DB::table('balance_logs')->count());
  299. }
  300. public function test_deposit_precision_and_display_switch_do_not_silently_change_money_configuration(): void
  301. {
  302. $this->initialized();
  303. $this->fails(fn () => $this->admin->saveSettings($this->config(['valid_member_min_deposit' => '20.123'])), 'regex');
  304. $this->assertSame(0, DB::table('share_settings')->count());
  305. $this->assertSame(1, DB::table('share_policies')->count());
  306. $saved = $this->admin->saveSettings($this->config(['enabled' => 0, 'valid_member_min_deposit' => '20.12']));
  307. $this->assertSame(0, $saved['enabled']);
  308. $this->assertNoCommissionSwitch($saved);
  309. $this->assertSame(1, (int) DB::table('share_settings')->value('benefit_enabled'));
  310. $this->assertSame(1, (int) DB::table('share_policies')->where('id', $saved['pending_policy']['id'])->value('benefit_enabled'));
  311. $this->assertSame('20.12', $saved['pending_policy']['valid_member_min_deposit']);
  312. $this->assertSame('20.12', $saved['valid_member_min_deposit']);
  313. $this->assertSame('20.1200000000', bcadd((string)DB::table('share_policies')->where('effective_date', '2026-10-25')->value('valid_member_min_deposit'), '0', 10));
  314. }
  315. public function test_rules_are_ordered_by_threshold_and_invalid_ladders_are_rejected_without_pending_writes(): void
  316. {
  317. $this->admin->saveRateRules('third:1', [
  318. ['min_valid_members' => 2, 'min_performance' => '100', 'rate' => '0.30'],
  319. ['min_valid_members' => 1, 'min_performance' => '100', 'rate' => '0.20'],
  320. ['min_valid_members' => 0, 'min_performance' => '10', 'rate' => '0.10'],
  321. ]);
  322. $rules = $this->admin->rateRules('third:1')['categories'][0]['pending_rules'];
  323. $this->assertSame([0, 1, 2], array_column($rules, 'min_valid_members'));
  324. $this->assertSame(['10.00', '100.00', '100.00'], array_column($rules, 'min_performance'));
  325. $before = (array)DB::table('share_policies')->where('effective_date', '2026-10-25')->first();
  326. $this->fails(fn () => $this->admin->saveRateRules('third:1', [
  327. ['min_valid_members' => 1, 'min_performance' => '100.0', 'rate' => '0.20'],
  328. ['min_valid_members' => 1, 'min_performance' => '100.00', 'rate' => '0.30'],
  329. ]), '不可重复');
  330. $this->fails(fn () => $this->admin->saveRateRules('third:1', [
  331. ['min_valid_members' => 2, 'min_performance' => '100', 'rate' => '0.20'],
  332. ['min_valid_members' => 1, 'min_performance' => '200', 'rate' => '0.30'],
  333. ]), '人数门槛不可降低');
  334. $this->fails(fn () => $this->admin->saveRateRules('third:1', [
  335. ['min_valid_members' => 1, 'min_performance' => '100', 'rate' => '0.30'],
  336. ['min_valid_members' => 2, 'min_performance' => '200', 'rate' => '0.20'],
  337. ]), '返佣比例不可降低');
  338. $this->assertSame($before, (array)DB::table('share_policies')->where('effective_date', '2026-10-25')->first());
  339. $this->assertSame(1, DB::table('operation_audits')->count());
  340. }
  341. public function test_levels_sum_increments_and_never_downgrade_members(): void
  342. {
  343. DB::table('share_members')->insert(['user_id' => 7, 'level' => 1, 'bound_at' => '2026-10-24 00:00:00']);
  344. DB::table('share_accounts')->insert(['user_id' => 7, 'earned_amount' => 25]);
  345. $this->admin->saveLevel(['level' => 2, 'name' => '二级', 'image' => '', 'incremental_commission' => 10]);
  346. $this->admin->saveLevel(['level' => 3, 'name' => '三级', 'image' => '/three.png', 'incremental_commission' => 20]);
  347. $this->assertSame(2, (int)DB::table('share_members')->value('level'));
  348. $levels = $this->admin->levels()['data'];
  349. $this->assertSame('30.00', $levels[2]['cumulative_commission']);
  350. $this->admin->saveLevel(['id' => $levels[1]['id'], 'level' => 2, 'name' => '二级', 'image' => '', 'incremental_commission' => 100]);
  351. $this->assertSame(2, (int)DB::table('share_members')->value('level'));
  352. $this->fails(fn () => $this->admin->deleteLevel($levels[1]['id']), '已有会员');
  353. $this->admin->deleteLevel($levels[2]['id']);
  354. $this->assertCount(2, $this->admin->levels()['data']);
  355. }
  356. private function pending(string $earned = '10.019', string $amount = '10.01'): int
  357. {
  358. DB::table('users')->insert(['id' => 7, 'member_id' => 'M7', 'account' => 'member7', 'first_name' => '会员']);
  359. DB::table('wallets')->insert(['member_id' => 'M7', 'available_balance' => 20]);
  360. DB::table('share_accounts')->insert(['user_id' => 7, 'earned_amount' => $earned, 'paid_amount' => 0, 'reserved_amount' => $amount]);
  361. return DB::table('share_claims')->insertGetId(['user_id' => 7, 'request_id' => 'req-1', 'active_user_id' => 7,
  362. 'amount' => $amount, 'status' => 'pending', 'created_at' => '2026-10-24 12:00:00', 'updated_at' => '2026-10-24 12:00:00']);
  363. }
  364. public function test_approval_credits_member_wallet_once_and_retains_fractional_remainder(): void
  365. {
  366. $id = $this->pending();
  367. $approved = $this->claims->audit($id, 'approve', 8, '已核对');
  368. $this->assertSame('approved', $approved['status']);
  369. $this->assertSame('0.00', $approved['commission_account']['spendable_amount']);
  370. $this->assertSame('10.01', $approved['commission_account']['paid_amount']);
  371. $this->assertEquals('30.01', DB::table('wallets')->value('available_balance'));
  372. $this->assertEquals('0.0090000000', bcsub((string)DB::table('share_accounts')->value('earned_amount'), (string)DB::table('share_accounts')->value('paid_amount'), 10));
  373. $this->assertNull(DB::table('share_claims')->value('active_user_id'));
  374. $this->claims->audit($id, 'approve', 8, '重复');
  375. $this->assertSame(1, DB::table('balance_logs')->count());
  376. $this->assertSame(1, DB::table('operation_audits')->count());
  377. $this->assertSame('分享佣金领取', DB::table('balance_logs')->value('change_type'));
  378. $this->assertSame(8, (int)DB::table('operation_audits')->value('operator_id'));
  379. $this->fails(fn () => $this->claims->audit($id, 'reject', 8), '不可更改');
  380. }
  381. public function test_recomputed_insufficiency_blocks_approval_and_rejection_releases_full_reservation(): void
  382. {
  383. $id = $this->pending('5.00', '10.01');
  384. $this->assertFalse($this->claims->detail($id)['can_approve']);
  385. $this->fails(fn () => $this->claims->audit($id, 'approve', 8), '重新申请');
  386. $this->assertSame('pending', DB::table('share_claims')->value('status'));
  387. $this->assertEquals(20, DB::table('wallets')->value('available_balance'));
  388. $rejected = $this->claims->audit($id, 'reject', 8, '请重新申请');
  389. $this->assertSame('5.00', $rejected['commission_account']['spendable_amount']);
  390. $this->assertSame(0, DB::table('balance_logs')->count());
  391. $this->claims->audit($id, 'reject', 8);
  392. $this->assertSame(1, DB::table('operation_audits')->count());
  393. }
  394. public function test_audit_failure_rolls_back_wallet_log_account_and_claim(): void
  395. {
  396. $id = $this->pending();
  397. DB::statement("CREATE TRIGGER block_operation_audit BEFORE INSERT ON bot_operation_audits BEGIN SELECT RAISE(ABORT, 'audit offline'); END");
  398. try { $this->claims->audit($id, 'approve', 8); $this->fail('Expected audit write failure'); }
  399. catch (\Illuminate\Database\QueryException $e) { $this->assertStringContainsString('audit offline', $e->getMessage()); }
  400. $this->assertEquals(20, DB::table('wallets')->value('available_balance'));
  401. $this->assertSame('pending', DB::table('share_claims')->value('status'));
  402. $this->assertEquals(0, DB::table('share_accounts')->value('paid_amount'));
  403. $this->assertEquals('10.01', DB::table('share_accounts')->value('reserved_amount'));
  404. $this->assertSame(0, DB::table('balance_logs')->count());
  405. }
  406. public function test_admin_controller_envelopes_and_filtered_lists(): void
  407. {
  408. $id = $this->pending();
  409. $this->assertSame(0, (new ShareEarning())->settings($this->admin)->getData(true)['code']);
  410. $request = Request::create('/admin/shareEarning/claims/audit', 'POST', ['id' => $id, 'action' => 'approve']);
  411. $request->user = (object)['id' => 8, 'username' => 'admin'];
  412. $this->app->instance('request', $request);
  413. $body = (new SharingManagement())->auditClaim($this->claims)->getData(true);
  414. $this->assertSame(0, $body['code']); $this->assertSame('approved', $body['data']['status']);
  415. $list = $this->claims->list(['status' => 'approved', 'account' => 'member7', 'start_date' => '2026-10-24', 'end_date' => '2026-10-24']);
  416. $this->assertSame(1, $list['total']); $this->assertSame('10.01', $list['data'][0]['amount']);
  417. $this->assertSame(0, $this->claims->list(['status' => 'pending'])['total']);
  418. }
  419. public function test_database_errors_do_not_expose_sql_in_admin_responses(): void
  420. {
  421. $this->app->instance('log', new \Psr\Log\NullLogger());
  422. DB::statement('DROP TABLE bot_share_levels');
  423. $body = (new SharingManagement())->levels($this->admin)->getData(true);
  424. $this->assertSame(-3, $body['code']);
  425. $this->assertStringContainsString('暂不可用', $body['msg']);
  426. $this->assertStringNotContainsString('SQLSTATE', $body['msg']);
  427. $this->assertStringNotContainsString('share_levels', $body['msg']);
  428. }
  429. public function test_money_configuration_cannot_lose_subcent_values_during_frontend_roundtrip(): void
  430. {
  431. $this->initialized();
  432. $this->fails(fn () => $this->admin->saveSettings($this->config(['valid_member_min_effective_bet'=>'0.001'])), 'regex');
  433. $this->fails(fn () => $this->admin->saveRateRules('third:2', [['min_valid_members'=>0,'min_performance'=>'0.001','rate'=>'0.1']]), 'regex');
  434. $this->fails(fn () => $this->admin->saveLevel(['level'=>2,'name'=>'二级','image'=>'','incremental_commission'=>'0.001']), 'regex');
  435. $this->assertSame(1, DB::table('share_policies')->count());
  436. $this->assertSame(1, DB::table('share_levels')->count());
  437. }
  438. }