ShareAdminManagementTest.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. $this->assertArrayNotHasKey('activation_date', $settings);
  102. foreach (['current_policy', 'pending_policy'] as $key) {
  103. if ($settings[$key] !== null) $this->assertArrayNotHasKey('benefit_enabled', $settings[$key]);
  104. }
  105. }
  106. public function test_explicit_setup_and_initializer_gate_enablement(): void
  107. {
  108. $initial = $this->admin->settings();
  109. $this->assertArrayNotHasKey('activation_date', $initial);
  110. $this->assertNoCommissionSwitch($initial);
  111. $this->fails(fn () => $this->admin->saveSettings($this->config()), '初始化');
  112. $this->fails(fn () => $this->admin->saveSettings($this->config(['benefit_enabled' => 0])), '初始化');
  113. $this->assertSame(0, DB::table('share_settings')->count());
  114. $this->initialized();
  115. $incomplete = $this->config(); unset($incomplete['valid_member_min_effective_bet']);
  116. $this->fails(fn () => $this->admin->saveSettings($incomplete), 'required');
  117. $this->fails(fn () => $this->admin->saveSettings($this->config(['tier_one_rate' => 4])), '已移除');
  118. $this->fails(fn () => $this->admin->saveSettings($this->config(['share_domain' => 'https://pc.example/a'])), '源地址');
  119. $data = $this->admin->saveSettings($this->config());
  120. $this->assertArrayNotHasKey('activation_date', $data);
  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(0, (int) DB::table('share_policies')->where('id', $data['pending_policy']['id'])->value('benefit_enabled'));
  125. $this->assertSame(0, (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_without_retired_activation_state(): 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(0, (int) DB::table('share_policies')->where('id', $settings['pending_policy']['id'])->value('benefit_enabled'));
  149. $this->assertSame(0, (int) DB::table('share_policies')->where('id', $settings['current_policy']['id'])->value('benefit_enabled'));
  150. $this->admin->saveSettings($this->config());
  151. $this->assertArrayNotHasKey('activation_date', $this->admin->settings());
  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 ([null, '2099-01-01', 'invalid', []] as $value) $legacyInputs[] = ['activation_date' => $value];
  184. foreach ($legacyInputs as $legacyInput) {
  185. $request = Request::create('/admin/shareEarning/settings', 'POST', $this->config($legacyInput + ['enabled' => 0]));
  186. $request->user = (object) ['id' => 8, 'username' => 'admin'];
  187. $this->app->instance('request', $request);
  188. $body = (new ShareEarning())->saveSettings($this->admin)->getData(true);
  189. $this->assertSame(0, $body['code'], $body['msg']);
  190. $this->assertNoCommissionSwitch($body['data']);
  191. $this->assertSame(0, $body['data']['enabled']);
  192. $this->assertArrayNotHasKey('activation_date', $body['data']);
  193. $this->assertSame(0, (int) DB::table('share_settings')->value('benefit_enabled'));
  194. $this->assertSame(0, (int) DB::table('share_policies')->where('effective_date', '2026-10-25')->value('benefit_enabled'));
  195. }
  196. $this->assertSame(2, DB::table('share_policies')->count());
  197. $this->assertSame($past, (array) DB::table('share_policies')->where('id', $past['id'])->first());
  198. $this->assertArrayNotHasKey('benefit_enabled', ShareSetting::query()->firstOrFail()->toArray());
  199. Carbon::setTestNow(Carbon::parse('2026-10-24 23:59:59', 'Asia/Shanghai'));
  200. $this->assertSame($past['id'], $this->admin->settings()['current_policy']['id']);
  201. Carbon::setTestNow(Carbon::parse('2026-10-25 00:00:00', 'Asia/Shanghai'));
  202. $current = $this->admin->settings();
  203. $this->assertNoCommissionSwitch($current);
  204. $this->assertSame('2026-10-25', $current['current_policy']['effective_date']);
  205. $this->assertSame(0, (int) DB::table('share_policies')->where('id', $current['current_policy']['id'])->value('benefit_enabled'));
  206. $this->assertNull($current['pending_policy']);
  207. }
  208. public function test_existing_disabled_configuration_remains_unchanged_until_a_complete_save(): void
  209. {
  210. $id = DB::table('share_settings')->insertGetId(['benefit_enabled' => 0, 'share_domain' => 'https://legacy.example.test']);
  211. $before = (array) DB::table('share_settings')->where('id', $id)->first();
  212. $this->assertNoCommissionSwitch($this->admin->settings());
  213. $this->assertArrayNotHasKey('benefit_enabled', ShareSetting::query()->findOrFail($id)->toArray());
  214. $this->assertSame($before, (array) DB::table('share_settings')->where('id', $id)->first());
  215. $this->fails(fn () => $this->admin->saveSettings($this->config(['benefit_enabled' => 1])), '初始化');
  216. $this->assertSame($before, (array) DB::table('share_settings')->where('id', $id)->first());
  217. $this->initialized();
  218. $saved = $this->admin->saveSettings($this->config(['benefit_enabled' => 0]));
  219. $this->assertNoCommissionSwitch($saved);
  220. $this->assertSame(0, (int) DB::table('share_settings')->where('id', $id)->value('benefit_enabled'));
  221. $this->assertArrayNotHasKey('activation_date', $saved);
  222. $this->assertSame(0, (int) DB::table('share_policies')->where('id', $saved['current_policy']['id'])->value('benefit_enabled'));
  223. }
  224. public function test_retired_indirect_coefficient_is_rejected_even_when_null_without_saving(): void
  225. {
  226. $this->initialized();
  227. foreach ([null, 0, '30.0000'] as $value) {
  228. $this->fails(fn () => $this->admin->saveSettings($this->config(['indirect_bonus_rate' => $value])), '已移除');
  229. }
  230. $this->assertSame(0, DB::table('share_settings')->count());
  231. $this->assertSame(1, DB::table('share_policies')->count());
  232. $this->assertSame(0, DB::table('operation_audits')->count());
  233. $request = Request::create('/admin/shareEarning/settings', 'POST', $this->config(['indirect_bonus_rate' => '30']));
  234. $this->app->instance('request', $request);
  235. $body = (new ShareEarning())->saveSettings($this->admin)->getData(true);
  236. $this->assertSame(-3, $body['code']);
  237. $this->assertStringContainsString('已移除', $body['msg']);
  238. $this->assertSame(0, DB::table('share_settings')->count());
  239. }
  240. public function test_rule_edits_need_no_coefficient_and_preserve_archived_policy_values(): void
  241. {
  242. $this->initialized();
  243. DB::table('share_settings')->insert(['indirect_bonus_rate' => '25.0000']);
  244. DB::table('share_policies')->update(['indirect_bonus_rate' => '30.0000']);
  245. $archived = (array) DB::table('share_policies')->where('effective_date', '1970-01-01')->first();
  246. $settings = $this->admin->saveSettings($this->config());
  247. $this->assertArrayNotHasKey('indirect_bonus_rate', $settings);
  248. $this->assertArrayNotHasKey('indirect_bonus_rate', $settings['current_policy']);
  249. $this->assertArrayNotHasKey('indirect_bonus_rate', $settings['pending_policy']);
  250. $this->assertNull(DB::table('share_policies')->where('id', $settings['pending_policy']['id'])->value('indirect_bonus_rate'));
  251. $this->assertSame('25.0000', bcadd((string) DB::table('share_settings')->value('indirect_bonus_rate'), '0', 4));
  252. $model = ShareSetting::query()->firstOrFail();
  253. $this->assertArrayNotHasKey('indirect_bonus_rate', $model->getCasts());
  254. $this->assertArrayNotHasKey('indirect_bonus_rate', $model->toArray());
  255. $this->assertArrayNotHasKey('benefit_enabled', $model->toArray());
  256. $rules = $this->admin->saveRateRules('third:1', [['min_valid_members' => 0, 'min_performance' => 0, 'rate' => '10']]);
  257. $this->assertSame('10.0000', $rules['categories'][0]['pending_rules'][0]['rate']);
  258. $this->admin->saveSettings($this->config(['valid_member_min_effective_bet' => '250']));
  259. $this->admin->saveLevel(['level' => 2, 'name' => '二级', 'image' => '', 'incremental_commission' => '10']);
  260. $settings = $this->admin->settings();
  261. $this->assertSame('10.0000', $settings['pending_policy']['rules']['third:1'][0]['rate']);
  262. $this->assertSame('250.00', $settings['pending_policy']['valid_member_min_effective_bet']);
  263. $this->assertArrayNotHasKey('indirect_bonus_rate', $settings['pending_policy']);
  264. $this->assertNull(DB::table('share_policies')->where('id', $settings['pending_policy']['id'])->value('indirect_bonus_rate'));
  265. $this->assertSame($archived, (array) DB::table('share_policies')->where('id', $archived['id'])->first());
  266. Carbon::setTestNow(Carbon::parse('2026-10-25 01:00:00', 'Asia/Shanghai'));
  267. $this->assertSame('10.0000', $this->admin->rateRules('third:1')['categories'][0]['current_rules'][0]['rate']);
  268. $this->assertArrayNotHasKey('indirect_bonus_rate', $this->admin->settings()['current_policy']);
  269. }
  270. public function test_diagnostic_and_backfill_output_hide_archived_coefficient_without_writes(): void
  271. {
  272. $schema = DB::connection()->getSchemaBuilder();
  273. $schema->table('users', function (Blueprint $t) {
  274. $t->string('user_code')->default(''); $t->string('agent_user_code')->nullable(); $t->integer('from')->default(1);
  275. });
  276. $schema->create('config', function (Blueprint $t) {
  277. $t->id(); $t->string('field'); $t->string('val');
  278. });
  279. $schema->create('share_commission_records', function (Blueprint $t) {
  280. $t->id(); $t->date('stat_date'); $t->integer('status');
  281. });
  282. DB::table('config')->insert(['field' => 'recharge_rate', 'val' => '2.5000']);
  283. DB::table('share_settings')->insert(['benefit_enabled' => 1, 'indirect_bonus_rate' => '30', 'valid_member_min_effective_bet' => '100']);
  284. $before = (array) DB::table('share_settings')->first();
  285. $data = (new ShareCommissionDiagnostics())->inspect(null);
  286. $this->assertArrayNotHasKey('indirect_bonus_rate', $data);
  287. $this->assertArrayNotHasKey('benefit_enabled', $data);
  288. $this->assertEquals('100', $data['valid_member_min_effective_bet']);
  289. $command = new BackfillShareCommissions();
  290. $command->setLaravel($this->app);
  291. $tester = new CommandTester($command);
  292. $tester->execute(['--diagnose' => true, '--all' => true]);
  293. $this->assertSame(0, $tester->getStatusCode(), $tester->getDisplay());
  294. $this->assertStringNotContainsString('indirect_bonus_rate', $tester->getDisplay());
  295. $this->assertStringNotContainsString('benefit_enabled', $tester->getDisplay());
  296. $this->assertStringContainsString('valid_member_min_effective_bet: 100', $tester->getDisplay());
  297. $this->assertSame($before, (array) DB::table('share_settings')->first());
  298. $this->assertSame(0, DB::table('share_commission_records')->count());
  299. $this->assertSame(0, DB::table('balance_logs')->count());
  300. }
  301. public function test_deposit_precision_and_display_switch_do_not_silently_change_money_configuration(): void
  302. {
  303. $this->initialized();
  304. $this->fails(fn () => $this->admin->saveSettings($this->config(['valid_member_min_deposit' => '20.123'])), 'regex');
  305. $this->assertSame(0, DB::table('share_settings')->count());
  306. $this->assertSame(1, DB::table('share_policies')->count());
  307. $saved = $this->admin->saveSettings($this->config(['enabled' => 0, 'valid_member_min_deposit' => '20.12']));
  308. $this->assertSame(0, $saved['enabled']);
  309. $this->assertNoCommissionSwitch($saved);
  310. $this->assertSame(0, (int) DB::table('share_settings')->value('benefit_enabled'));
  311. $this->assertSame(0, (int) DB::table('share_policies')->where('id', $saved['pending_policy']['id'])->value('benefit_enabled'));
  312. $this->assertSame('20.12', $saved['pending_policy']['valid_member_min_deposit']);
  313. $this->assertSame('20.12', $saved['valid_member_min_deposit']);
  314. $this->assertSame('20.1200000000', bcadd((string)DB::table('share_policies')->where('effective_date', '2026-10-25')->value('valid_member_min_deposit'), '0', 10));
  315. }
  316. public function test_rules_are_ordered_by_threshold_and_invalid_ladders_are_rejected_without_pending_writes(): void
  317. {
  318. $this->admin->saveRateRules('third:1', [
  319. ['min_valid_members' => 2, 'min_performance' => '100', 'rate' => '0.30'],
  320. ['min_valid_members' => 1, 'min_performance' => '100', 'rate' => '0.20'],
  321. ['min_valid_members' => 0, 'min_performance' => '10', 'rate' => '0.10'],
  322. ]);
  323. $rules = $this->admin->rateRules('third:1')['categories'][0]['pending_rules'];
  324. $this->assertSame([0, 1, 2], array_column($rules, 'min_valid_members'));
  325. $this->assertSame(['10.00', '100.00', '100.00'], array_column($rules, 'min_performance'));
  326. $before = (array)DB::table('share_policies')->where('effective_date', '2026-10-25')->first();
  327. $this->fails(fn () => $this->admin->saveRateRules('third:1', [
  328. ['min_valid_members' => 1, 'min_performance' => '100.0', 'rate' => '0.20'],
  329. ['min_valid_members' => 1, 'min_performance' => '100.00', 'rate' => '0.30'],
  330. ]), '不可重复');
  331. $this->fails(fn () => $this->admin->saveRateRules('third:1', [
  332. ['min_valid_members' => 2, 'min_performance' => '100', 'rate' => '0.20'],
  333. ['min_valid_members' => 1, 'min_performance' => '200', 'rate' => '0.30'],
  334. ]), '人数门槛不可降低');
  335. $this->fails(fn () => $this->admin->saveRateRules('third:1', [
  336. ['min_valid_members' => 1, 'min_performance' => '100', 'rate' => '0.30'],
  337. ['min_valid_members' => 2, 'min_performance' => '200', 'rate' => '0.20'],
  338. ]), '返佣比例不可降低');
  339. $this->assertSame($before, (array)DB::table('share_policies')->where('effective_date', '2026-10-25')->first());
  340. $this->assertSame(1, DB::table('operation_audits')->count());
  341. }
  342. public function test_levels_sum_increments_and_never_downgrade_members(): void
  343. {
  344. DB::table('share_members')->insert(['user_id' => 7, 'level' => 1, 'bound_at' => '2026-10-24 00:00:00']);
  345. DB::table('share_accounts')->insert(['user_id' => 7, 'earned_amount' => 25]);
  346. $this->admin->saveLevel(['level' => 2, 'name' => '二级', 'image' => '', 'incremental_commission' => 10]);
  347. $this->admin->saveLevel(['level' => 3, 'name' => '三级', 'image' => '/three.png', 'incremental_commission' => 20]);
  348. $this->assertSame(2, (int)DB::table('share_members')->value('level'));
  349. $levels = $this->admin->levels()['data'];
  350. $this->assertSame('30.00', $levels[2]['cumulative_commission']);
  351. $this->admin->saveLevel(['id' => $levels[1]['id'], 'level' => 2, 'name' => '二级', 'image' => '', 'incremental_commission' => 100]);
  352. $this->assertSame(2, (int)DB::table('share_members')->value('level'));
  353. $this->fails(fn () => $this->admin->deleteLevel($levels[1]['id']), '已有会员');
  354. $this->admin->deleteLevel($levels[2]['id']);
  355. $this->assertCount(2, $this->admin->levels()['data']);
  356. }
  357. private function pending(string $earned = '10.019', string $amount = '10.01'): int
  358. {
  359. DB::table('users')->insert(['id' => 7, 'member_id' => 'M7', 'account' => 'member7', 'first_name' => '会员']);
  360. DB::table('wallets')->insert(['member_id' => 'M7', 'available_balance' => 20]);
  361. DB::table('share_accounts')->insert(['user_id' => 7, 'earned_amount' => $earned, 'paid_amount' => 0, 'reserved_amount' => $amount]);
  362. return DB::table('share_claims')->insertGetId(['user_id' => 7, 'request_id' => 'req-1', 'active_user_id' => 7,
  363. 'amount' => $amount, 'status' => 'pending', 'created_at' => '2026-10-24 12:00:00', 'updated_at' => '2026-10-24 12:00:00']);
  364. }
  365. public function test_approval_credits_member_wallet_once_and_retains_fractional_remainder(): void
  366. {
  367. $id = $this->pending();
  368. $approved = $this->claims->audit($id, 'approve', 8, '已核对');
  369. $this->assertSame('approved', $approved['status']);
  370. $this->assertSame('0.00', $approved['commission_account']['spendable_amount']);
  371. $this->assertSame('10.01', $approved['commission_account']['paid_amount']);
  372. $this->assertEquals('30.01', DB::table('wallets')->value('available_balance'));
  373. $this->assertEquals('0.0090000000', bcsub((string)DB::table('share_accounts')->value('earned_amount'), (string)DB::table('share_accounts')->value('paid_amount'), 10));
  374. $this->assertNull(DB::table('share_claims')->value('active_user_id'));
  375. $this->claims->audit($id, 'approve', 8, '重复');
  376. $this->assertSame(1, DB::table('balance_logs')->count());
  377. $this->assertSame(1, DB::table('operation_audits')->count());
  378. $this->assertSame('分享佣金领取', DB::table('balance_logs')->value('change_type'));
  379. $this->assertSame(8, (int)DB::table('operation_audits')->value('operator_id'));
  380. $this->fails(fn () => $this->claims->audit($id, 'reject', 8), '不可更改');
  381. }
  382. public function test_recomputed_insufficiency_blocks_approval_and_rejection_releases_full_reservation(): void
  383. {
  384. $id = $this->pending('5.00', '10.01');
  385. $this->assertFalse($this->claims->detail($id)['can_approve']);
  386. $this->fails(fn () => $this->claims->audit($id, 'approve', 8), '重新申请');
  387. $this->assertSame('pending', DB::table('share_claims')->value('status'));
  388. $this->assertEquals(20, DB::table('wallets')->value('available_balance'));
  389. $rejected = $this->claims->audit($id, 'reject', 8, '请重新申请');
  390. $this->assertSame('5.00', $rejected['commission_account']['spendable_amount']);
  391. $this->assertSame(0, DB::table('balance_logs')->count());
  392. $this->claims->audit($id, 'reject', 8);
  393. $this->assertSame(1, DB::table('operation_audits')->count());
  394. }
  395. public function test_audit_failure_rolls_back_wallet_log_account_and_claim(): void
  396. {
  397. $id = $this->pending();
  398. DB::statement("CREATE TRIGGER block_operation_audit BEFORE INSERT ON bot_operation_audits BEGIN SELECT RAISE(ABORT, 'audit offline'); END");
  399. try { $this->claims->audit($id, 'approve', 8); $this->fail('Expected audit write failure'); }
  400. catch (\Illuminate\Database\QueryException $e) { $this->assertStringContainsString('audit offline', $e->getMessage()); }
  401. $this->assertEquals(20, DB::table('wallets')->value('available_balance'));
  402. $this->assertSame('pending', DB::table('share_claims')->value('status'));
  403. $this->assertEquals(0, DB::table('share_accounts')->value('paid_amount'));
  404. $this->assertEquals('10.01', DB::table('share_accounts')->value('reserved_amount'));
  405. $this->assertSame(0, DB::table('balance_logs')->count());
  406. }
  407. public function test_admin_controller_envelopes_and_filtered_lists(): void
  408. {
  409. $id = $this->pending();
  410. $this->assertSame(0, (new ShareEarning())->settings($this->admin)->getData(true)['code']);
  411. $request = Request::create('/admin/shareEarning/claims/audit', 'POST', ['id' => $id, 'action' => 'approve']);
  412. $request->user = (object)['id' => 8, 'username' => 'admin'];
  413. $this->app->instance('request', $request);
  414. $body = (new SharingManagement())->auditClaim($this->claims)->getData(true);
  415. $this->assertSame(0, $body['code']); $this->assertSame('approved', $body['data']['status']);
  416. $list = $this->claims->list(['status' => 'approved', 'account' => 'member7', 'start_date' => '2026-10-24', 'end_date' => '2026-10-24']);
  417. $this->assertSame(1, $list['total']); $this->assertSame('10.01', $list['data'][0]['amount']);
  418. $this->assertSame(0, $this->claims->list(['status' => 'pending'])['total']);
  419. }
  420. public function test_database_errors_do_not_expose_sql_in_admin_responses(): void
  421. {
  422. $this->app->instance('log', new \Psr\Log\NullLogger());
  423. DB::statement('DROP TABLE bot_share_levels');
  424. $body = (new SharingManagement())->levels($this->admin)->getData(true);
  425. $this->assertSame(-3, $body['code']);
  426. $this->assertStringContainsString('暂不可用', $body['msg']);
  427. $this->assertStringNotContainsString('SQLSTATE', $body['msg']);
  428. $this->assertStringNotContainsString('share_levels', $body['msg']);
  429. }
  430. public function test_money_configuration_cannot_lose_subcent_values_during_frontend_roundtrip(): void
  431. {
  432. $this->initialized();
  433. $this->fails(fn () => $this->admin->saveSettings($this->config(['valid_member_min_effective_bet'=>'0.001'])), 'regex');
  434. $this->fails(fn () => $this->admin->saveRateRules('third:2', [['min_valid_members'=>0,'min_performance'=>'0.001','rate'=>'0.1']]), 'regex');
  435. $this->fails(fn () => $this->admin->saveLevel(['level'=>2,'name'=>'二级','image'=>'','incremental_commission'=>'0.001']), 'regex');
  436. $this->assertSame(1, DB::table('share_policies')->count());
  437. $this->assertSame(1, DB::table('share_levels')->count());
  438. }
  439. }