ActivityRewardEligibilityTest.php 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Constants\HttpStatus;
  4. use App\Http\Controllers\admin\ActivityReward as AdminActivityReward;
  5. use App\Http\Controllers\admin\ActivityUser as AdminActivityUser;
  6. use App\Http\Controllers\admin\PaymentOrder as AdminPaymentOrder;
  7. use App\Http\Controllers\api\ActivityReward as ApiActivityReward;
  8. use App\Models\ActivityReward;
  9. use App\Services\ActivityQuotaService;
  10. use App\Services\ActivityEligibilityService;
  11. use App\Services\ActivityRewardService;
  12. use App\Services\BalanceLogService;
  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\DatabasePresenceVerifier;
  25. use PHPUnit\Framework\Attributes\DataProvider;
  26. use PHPUnit\Framework\TestCase;
  27. /** Runs real controllers and services against SQLite only; never boots application providers. */
  28. class ActivityRewardEligibilityTest extends TestCase
  29. {
  30. private Application $app;
  31. protected function setUp(): void
  32. {
  33. Facade::clearResolvedInstances();
  34. $this->app = new Application(dirname(__DIR__, 2));
  35. $this->app->instance('config', new Repository([
  36. 'app' => ['locale' => 'zh', 'url' => 'https://activity.example.test', 'timezone' => 'Asia/Shanghai'],
  37. ]));
  38. Facade::setFacadeApplication($this->app);
  39. $db = new Manager($this->app);
  40. $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  41. $db->setAsGlobal();
  42. $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. $validator = new Factory($translator, $this->app);
  48. $validator->setPresenceVerifier(new DatabasePresenceVerifier($db->getDatabaseManager()));
  49. $this->app->instance('validator', $validator);
  50. $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new \Tests\Support\JsonResponseFactory());
  51. Request::macro('validate', function (array $rules) {
  52. return app('validator')->make($this->all(), $rules)->validate();
  53. });
  54. $db->schema()->create('activity_rewards', function (Blueprint $t) {
  55. $t->id(); $t->string('title'); $t->string('sub_title');
  56. $t->integer('start_time'); $t->integer('end_time'); $t->integer('status')->default(1);
  57. $t->integer('type')->default(1); $t->string('lang')->default('zh');
  58. foreach (['detail_image', 'pc_image', 'detail_banner', 'pc_banner', 'content', 'params'] as $field) {
  59. $t->text($field)->nullable();
  60. }
  61. $t->timestamps();
  62. });
  63. (require dirname(__DIR__, 2) . '/database/migrations/2026_10_13_120000_add_activity_eligibility_fields.php')->up();
  64. $db->schema()->create('users', function (Blueprint $t) {
  65. $t->id(); $t->string('member_id')->unique(); $t->string('phone')->default('');
  66. $t->string('register_domain')->default(''); $t->integer('from')->default(1);
  67. $t->integer('level')->default(0); $t->integer('recharge_channel_group_id')->default(1);
  68. $t->string('language')->default('zh'); $t->timestamps();
  69. });
  70. $db->schema()->create('user_login', function (Blueprint $t) {
  71. $t->id(); $t->string('user_id'); $t->string('platform')->default('');
  72. $t->integer('status')->default(1); $t->timestamp('logout_time')->nullable(); $t->timestamps();
  73. });
  74. $db->schema()->create('balance_logs', function (Blueprint $t) {
  75. $t->id(); $t->string('member_id'); $t->integer('type')->default(1);
  76. $t->string('change_type'); $t->decimal('amount', 20, 2);
  77. $t->decimal('before_balance', 20, 2)->nullable(); $t->decimal('after_balance', 20, 2)->nullable();
  78. $t->integer('related_id')->nullable(); $t->integer('frozen_status')->nullable();
  79. $t->text('remark')->nullable(); $t->timestamps();
  80. });
  81. $db->schema()->create('wallet_bonus', function (Blueprint $t) {
  82. $t->id(); $t->string('member_id'); $t->integer('type')->default(1);
  83. $t->integer('activity_id'); $t->integer('related_id')->nullable();
  84. $t->decimal('amount', 20, 2); $t->decimal('need_flow', 20, 2);
  85. $t->decimal('remaind_flow', 20, 2); $t->integer('status'); $t->timestamps();
  86. });
  87. $db->schema()->create('activity_user', function (Blueprint $t) {
  88. $t->id(); $t->integer('activity_id'); $t->string('member_id');
  89. $t->string('title'); $t->string('sub_title'); $t->text('detail_image')->nullable();
  90. $t->integer('start_time'); $t->integer('end_time'); $t->integer('part_in_time');
  91. $t->integer('finish_time')->nullable(); $t->integer('status')->default(0);
  92. $t->decimal('gift_amount', 20, 2)->default(0); $t->decimal('betting_amount', 20, 2)->default(0);
  93. $t->decimal('effective_betting_amount', 20, 2)->default(0); $t->timestamps();
  94. });
  95. $db->schema()->create('payment_orders', function (Blueprint $t) {
  96. $t->id(); $t->string('member_id'); $t->integer('type'); $t->integer('status');
  97. $t->decimal('amount', 20, 2); $t->timestamps();
  98. });
  99. $db->schema()->create('recharges', function (Blueprint $t) {
  100. $t->id(); $t->string('member_id'); $t->integer('status');
  101. $t->decimal('amount', 20, 2)->default(0); $t->timestamps();
  102. });
  103. $db->schema()->create('wallets', function (Blueprint $t) {
  104. $t->id(); $t->string('member_id')->unique();
  105. $t->decimal('available_balance', 20, 2)->default(0);
  106. $t->decimal('frozen_balance', 20, 2)->default(0); $t->timestamps();
  107. });
  108. (require dirname(__DIR__, 2) . '/database/migrations/2026_10_14_120000_add_activity_reward_quotas.php')->up();
  109. (require dirname(__DIR__, 2) . '/database/migrations/2026_11_07_180000_allow_permanent_activities.php')->up();
  110. $this->request('/api/ActivityReward', []);
  111. }
  112. protected function tearDown(): void
  113. {
  114. DB::disconnect();
  115. Facade::clearResolvedInstances();
  116. parent::tearDown();
  117. }
  118. private function request(string $path, array $params, string $method = 'GET'): void
  119. {
  120. $this->app->instance('request', Request::create($path, $method, $params));
  121. }
  122. private function form(array $overrides = []): array
  123. {
  124. return $overrides + [
  125. 'title' => '资格测试活动', 'sub_title' => '参与资格',
  126. 'start_time' => '2000-01-01 00:00:00', 'end_time' => '2099-12-31 23:59:59',
  127. 'detail_image' => '/app.png', 'pc_image' => '/pc.png',
  128. 'detail_banner' => '/app-banner.png', 'pc_banner' => '/pc-banner.png',
  129. 'status' => 1, 'type' => 1, 'lang' => 'zh',
  130. ];
  131. }
  132. private function save(array $params): array
  133. {
  134. $this->request('/admin/ActivityReward/submit', $this->form($params), 'POST');
  135. return (new AdminActivityReward())->store()->getData(true);
  136. }
  137. private function activity(array $params = []): ActivityReward
  138. {
  139. $result = $this->save($params);
  140. $this->assertSame(0, $result['code'], $result['msg']);
  141. return ActivityReward::query()->latest('id')->first();
  142. }
  143. private function legacyActivity(array $params = []): ActivityReward
  144. {
  145. $data = $this->form($params);
  146. $data['start_time'] = strtotime($data['start_time']);
  147. $data['end_time'] = strtotime($data['end_time']);
  148. if (isset($data['params']) && is_array($data['params'])) $data['params'] = json_encode($data['params']);
  149. $id = DB::table('activity_rewards')->insertGetId($data);
  150. return ActivityReward::findOrFail($id);
  151. }
  152. private function member(string $id = '1001', string $registeredAt = '2026-10-01 12:34:56', string $phone = ''): void
  153. {
  154. DB::table('users')->insert([
  155. 'member_id' => $id, 'phone' => $phone, 'created_at' => $registeredAt, 'updated_at' => $registeredAt,
  156. ]);
  157. }
  158. private function login(string $id, string $platform, int $status = 1): void
  159. {
  160. DB::table('user_login')->insert([
  161. 'user_id' => $id, 'platform' => $platform, 'status' => $status,
  162. 'created_at' => '2026-10-01 12:34:56', 'updated_at' => '2026-10-01 12:34:56',
  163. ]);
  164. }
  165. private function deposit(string $id, string $amount, string $category = '充值', int $type = 1): void
  166. {
  167. DB::table('balance_logs')->insert([
  168. 'member_id' => $id, 'amount' => $amount, 'change_type' => $category, 'type' => $type,
  169. 'created_at' => '2026-09-01 10:00:00', 'updated_at' => '2026-09-01 10:00:00',
  170. ]);
  171. }
  172. private function eligibility(ActivityReward $activity, ?string $id): array
  173. {
  174. return ActivityEligibilityService::evaluate($activity, ActivityEligibilityService::memberContext($id));
  175. }
  176. private function list(array $params = []): array
  177. {
  178. $this->request('/api/ActivityReward', $params);
  179. if (isset($params['platform']) && is_string($params['platform'])) request()->headers->set('Platform', $params['platform']);
  180. $result = (new ApiActivityReward())->index()->getData(true);
  181. $this->assertSame(0, $result['code'], $result['msg']);
  182. return $result['data'];
  183. }
  184. private function adminList(array $params = []): array
  185. {
  186. $this->request('/admin/ActivityReward', $params + ['page' => 1, 'limit' => 10]);
  187. $result = (new AdminActivityReward())->index()->getData(true);
  188. $this->assertSame(0, $result['code'], $result['msg']);
  189. return $result['data'];
  190. }
  191. public function test_admin_activity_list_combines_filters_before_count_and_pagination(): void
  192. {
  193. $base = ['title' => '联合筛选活动', 'status' => 0, 'lang' => 'zh', 'type' => 1,
  194. 'publish_platforms' => ['PC'], 'show_ineligible' => false];
  195. $low = $this->activity(['sort' => 1, 'params' => ['marker' => 'original']] + $base);
  196. $middle = $this->activity(['sort' => 2, 'start_time' => '2090-01-01 00:00:00'] + $base);
  197. $high = $this->activity(['sort' => 3, 'end_time' => '2001-01-01 00:00:00'] + $base);
  198. foreach ([['publish_platforms' => ['H5']], ['status' => 1], ['lang' => 'en'],
  199. ['title' => '其他标题'], ['type' => 3], ['type' => 2]] as $override) {
  200. $this->activity($override + ['sort' => 99] + $base);
  201. }
  202. $filters = ['platform' => 'pc', 'status' => '0', 'lang' => 'zh', 'title' => '联合筛选', 'type' => '1', 'limit' => 2];
  203. $first = $this->adminList($filters);
  204. $this->assertSame(3, $first['total']);
  205. $this->assertSame([$high->id, $middle->id], array_column($first['data'], 'id'));
  206. $this->assertSame([0, 0], array_map('intval', array_column($first['data'], 'status')));
  207. $this->assertSame('2001-01-01', $first['data'][0]['end_time']);
  208. $this->assertSame('2090-01-01', $first['data'][1]['start_time']);
  209. $second = $this->adminList(['page' => 2] + $filters);
  210. $this->assertSame(3, $second['total']);
  211. $this->assertSame([$low->id], array_column($second['data'], 'id'));
  212. $this->assertSame(['marker' => 'original'], $second['data'][0]['params']);
  213. }
  214. public function test_admin_activity_platform_filters_include_unrestricted_and_football_rows(): void
  215. {
  216. $rows = [];
  217. foreach (['pc' => ['PC'], 'h5' => ['H5'], 'both' => ['PC', 'H5'], 'app' => ['APP'], 'empty' => []] as $key => $platforms) {
  218. $rows[$key] = $this->legacyActivity(['title' => $key, 'publish_platforms' => json_encode($platforms)]);
  219. }
  220. $rows['null'] = $this->legacyActivity(['title' => 'legacy null', 'publish_platforms' => null]);
  221. $rows['football'] = $this->legacyActivity(['title' => '任意足球标题', 'type' => 2, 'publish_platforms' => '["APP"]']);
  222. foreach (['pc' => ['pc', 'both', 'empty', 'null'], 'h5' => ['h5', 'both', 'empty', 'null']] as $platform => $keys) {
  223. $result = $this->adminList(['platform' => $platform]);
  224. $expected = array_map(static fn($key) => $rows[$key]->id, $keys);
  225. rsort($expected);
  226. $this->assertSame(4, $result['total']);
  227. $this->assertSame($expected, array_column($result['data'], 'id'));
  228. $this->assertNotContains($rows['app']->id, array_column($result['data'], 'id'));
  229. $this->assertNotContains($rows['football']->id, array_column($result['data'], 'id'));
  230. $this->assertSame(['APP'], $rows['football']->publish_platforms);
  231. }
  232. $this->assertSame(7, $this->adminList()['total']);
  233. }
  234. public function test_admin_activity_empty_filters_keep_ended_rows_after_synchronizing_status(): void
  235. {
  236. $expired = $this->legacyActivity(['title' => '已结束但仍上架', 'status' => 1, 'end_time' => '2001-01-01 00:00:00']);
  237. $future = $this->legacyActivity(['title' => '未开始但已上架', 'status' => 1, 'start_time' => '2090-01-01 00:00:00']);
  238. $down = $this->legacyActivity(['title' => '已手动下架', 'status' => 0]);
  239. $up = $this->adminList(['status' => 1]);
  240. $this->assertSame(1, $up['total']);
  241. $this->assertSame([$future->id], array_column($up['data'], 'id'));
  242. $this->assertSame([1], array_map('intval', array_column($up['data'], 'status')));
  243. $this->assertSame(0, (int)$expired->fresh()->status);
  244. foreach ([0, '0'] as $status) {
  245. $result = $this->adminList(['status' => $status]);
  246. $this->assertSame(2, $result['total']);
  247. $this->assertSame([$down->id, $expired->id], array_column($result['data'], 'id'));
  248. }
  249. foreach ([[], ['platform' => '', 'status' => '', 'lang' => ''], ['platform' => null, 'status' => null, 'lang' => null]] as $filters) {
  250. $this->assertSame(3, $this->adminList($filters)['total']);
  251. }
  252. }
  253. public function test_admin_activity_invalid_list_filters_return_validation_errors_without_writes(): void
  254. {
  255. $this->legacyActivity(['title' => '校验前活动', 'status' => 0]);
  256. $before = DB::table('activity_rewards')->orderBy('id')->get()->toArray();
  257. foreach ([['platform' => 'app'], ['platform' => 'PC'], ['platform' => []], ['status' => 2],
  258. ['status' => -1], ['status' => 'up'], ['status' => []], ['lang' => str_repeat('a', 11)],
  259. ['lang' => []], ['page' => 0], ['limit' => 0]] as $invalid) {
  260. $this->request('/admin/ActivityReward', $invalid + ['page' => 1, 'limit' => 10]);
  261. DB::connection()->enableQueryLog();
  262. DB::connection()->flushQueryLog();
  263. $result = (new AdminActivityReward())->index()->getData(true);
  264. $queries = DB::connection()->getQueryLog();
  265. DB::connection()->disableQueryLog();
  266. $this->assertSame(HttpStatus::CUSTOM_ERROR, $result['code'], json_encode($invalid));
  267. $this->assertSame([], $queries, 'Invalid filters must be rejected before querying or mutating activities.');
  268. }
  269. foreach ([['page' => 1], ['limit' => 10]] as $incomplete) {
  270. $this->request('/admin/ActivityReward', $incomplete);
  271. $this->assertSame(HttpStatus::CUSTOM_ERROR, (new AdminActivityReward())->index()->getData(true)['code']);
  272. }
  273. $this->assertEquals($before, DB::table('activity_rewards')->orderBy('id')->get()->toArray());
  274. }
  275. public function test_admin_platform_filter_compiles_mysql_json_queries_without_connecting_to_a_database(): void
  276. {
  277. $this->app['config']->set('database.connections.mysql_filter_preview', [
  278. 'driver' => 'mysql', 'host' => '127.0.0.1', 'database' => 'not_connected',
  279. 'username' => 'not_connected', 'password' => '', 'prefix' => 'bot_',
  280. ]);
  281. $original = DB::getDefaultConnection();
  282. DB::setDefaultConnection('mysql_filter_preview');
  283. try {
  284. $connection = DB::connection();
  285. // Laravel 11+ 的 MySQL 语法编译需要服务器版本;用只回答版本、拒绝执行 SQL 的替身,仍保证不连库
  286. $connection->setPdo(new class('sqlite::memory:') extends \PDO {
  287. public function getAttribute(int $attribute): mixed { return $attribute === \PDO::ATTR_SERVER_VERSION ? '8.0.36' : parent::getAttribute($attribute); }
  288. public function prepare(string $query, array $options = []): \PDOStatement|false { throw new \RuntimeException('This SQL preview must never connect to a database.'); }
  289. public function query(string $query, ?int $fetchMode = null, mixed ...$fetchModeArgs): \PDOStatement|false { throw new \RuntimeException('This SQL preview must never connect to a database.'); }
  290. public function exec(string $statement): int|false { throw new \RuntimeException('This SQL preview must never connect to a database.'); }
  291. });
  292. $this->request('/admin/ActivityReward', ['page' => 1, 'limit' => 10, 'platform' => 'h5', 'status' => '0', 'lang' => 'en']);
  293. $queries = $connection->pretend(function () {
  294. $result = (new AdminActivityReward())->index()->getData(true);
  295. $this->assertSame(0, $result['code'], $result['msg']);
  296. });
  297. $sql = strtolower(implode("\n", array_column($queries, 'query')));
  298. $this->assertStringContainsString('json_contains', $sql);
  299. $this->assertStringContainsString('json_length', $sql);
  300. $this->assertStringNotContainsString('json_each', $sql);
  301. // 到期状态 UPDATE 在前,平台和语言条件应检查统计及列表的 SELECT。
  302. $selects = array_filter($queries, fn ($query) => str_starts_with(strtolower($query['query']), 'select'));
  303. $this->assertCount(2, $selects);
  304. foreach ($selects as $query) {
  305. $this->assertContains('"H5"', $query['bindings']);
  306. $this->assertContains('en', $query['bindings']);
  307. }
  308. } finally {
  309. DB::disconnect('mysql_filter_preview');
  310. DB::setDefaultConnection($original);
  311. }
  312. }
  313. public function test_old_forms_and_old_database_rows_keep_unrestricted_defaults(): void
  314. {
  315. $activity = $this->activity();
  316. $this->assertSame([], $activity->publish_platforms);
  317. $this->assertSame([], $activity->register_platforms);
  318. $this->assertFalse((bool)$activity->register_time_limited);
  319. $this->assertFalse((bool)$activity->deposit_limited);
  320. $this->assertTrue((bool)$activity->show_ineligible);
  321. $this->assertNull($activity->reward_quota);
  322. $this->assertSame(0, (int)$activity->rewarded_count);
  323. $this->assertTrue((bool)$activity->quota_enabled);
  324. $this->assertSame(0, (int)$activity->sort);
  325. $this->assertFalse($this->eligibility($activity, null)['is_eligible']);
  326. $this->assertSame('请先登录', $this->eligibility($activity, null)['ineligible_reason']);
  327. $this->member();
  328. $this->assertTrue($this->eligibility($activity, '1001')['is_eligible']);
  329. $this->assertTrue(ActivityEligibilityService::isPublishedOn($activity, 'PC'));
  330. $this->assertTrue(ActivityEligibilityService::isPublishedOn($activity, 'H5'));
  331. $this->assertTrue(ActivityEligibilityService::isPublishedOn($activity, 'APP'));
  332. DB::table('activity_rewards')->insert([
  333. 'title' => '旧数据', 'sub_title' => '无新字段', 'start_time' => 1, 'end_time' => 4102444799,
  334. 'status' => 1, 'type' => 1, 'lang' => 'zh',
  335. ]);
  336. $legacy = ActivityReward::query()->latest('id')->first();
  337. $this->assertFalse((bool)$legacy->quota_enabled);
  338. $this->assertTrue($this->eligibility($legacy, '1001')['is_eligible']);
  339. $this->assertCount(2, $this->list());
  340. $this->assertNull($legacy->publish_platforms);
  341. $this->assertNull($legacy->register_platforms);
  342. $result = $this->save(['id' => $legacy->id, 'title' => '旧数据正常编辑']);
  343. $this->assertSame(0, $result['code'], $result['msg']);
  344. $legacy->refresh();
  345. $this->assertSame([], $legacy->publish_platforms);
  346. $this->assertSame([], $legacy->register_platforms);
  347. $this->assertTrue((bool)$legacy->show_ineligible);
  348. $this->assertFalse((bool)$legacy->quota_enabled);
  349. }
  350. public function test_admin_controller_persists_all_new_fields_and_preserves_false_flags_on_omitted_update(): void
  351. {
  352. $activity = $this->activity([
  353. 'publish_platforms' => ['PC', 'APP'], 'reward_quota' => 1234, 'sort' => 7,
  354. 'register_time_limited' => 1, 'register_start_time' => '2026-10-01 12:34:56',
  355. 'register_end_time' => '2026-10-02 12:34:56', 'register_platforms' => ['H5'],
  356. 'deposit_limited' => 1, 'deposit_min' => '0.01', 'deposit_max' => '999999999999.99',
  357. 'show_ineligible' => 0,
  358. ]);
  359. $this->assertSame(['PC', 'APP'], $activity->publish_platforms);
  360. $this->assertSame(['H5'], $activity->register_platforms);
  361. $this->assertSame(1234, (int)$activity->reward_quota);
  362. $this->assertSame(7, (int)$activity->sort);
  363. $this->assertFalse((bool)$activity->show_ineligible);
  364. $this->assertTrue((bool)$activity->deposit_limited);
  365. $this->assertSame(0, $this->save(['id' => $activity->id, 'title' => '编辑名称'])['code']);
  366. $activity->refresh();
  367. $this->assertSame(['PC', 'APP'], $activity->publish_platforms);
  368. $this->assertSame(['H5'], $activity->register_platforms);
  369. $this->assertFalse((bool)$activity->show_ineligible);
  370. $this->assertTrue((bool)$activity->register_time_limited);
  371. $this->assertTrue((bool)$activity->deposit_limited);
  372. $this->assertSame(1234, (int)$activity->reward_quota);
  373. $this->assertSame(0, $this->save([
  374. 'id' => $activity->id, 'register_time_limited' => 0, 'deposit_limited' => 0,
  375. ])['code']);
  376. $this->assertSame(0, $this->save(['id' => $activity->id, 'title' => '再次编辑名称'])['code']);
  377. $activity->refresh();
  378. $this->assertFalse((bool)$activity->register_time_limited);
  379. $this->assertFalse((bool)$activity->deposit_limited);
  380. $this->assertFalse((bool)$activity->show_ineligible);
  381. $this->assertNull($activity->register_start_time);
  382. $this->assertNull($activity->register_end_time);
  383. $this->assertNull($activity->deposit_min);
  384. $this->assertNull($activity->deposit_max);
  385. }
  386. public function test_reward_quota_accepts_inclusive_integer_limits_and_nullable_unlimited(): void
  387. {
  388. foreach ([0, 2147483647, null] as $quota) {
  389. $activity = $this->activity(['reward_quota' => $quota]);
  390. $this->assertSame($quota, $activity->reward_quota);
  391. $this->assertSame(0, (int)$activity->rewarded_count);
  392. }
  393. }
  394. public function test_invalid_ranges_amount_precision_and_platform_lists_are_rejected_without_writes(): void
  395. {
  396. foreach ([
  397. ['publish_platforms' => 'PC'], ['publish_platforms' => ['Android']], ['publish_platforms' => null],
  398. ['register_platforms' => null],
  399. ['register_platforms' => ['WEB']], ['register_platforms' => [['PC']]],
  400. ['reward_quota' => -1], ['reward_quota' => '1.001'], ['reward_quota' => '1e2'],
  401. ['reward_quota' => 2147483648], ['reward_quota' => []],
  402. ['budget' => '1.00'],
  403. ['sort' => -1], ['sort' => '1.5'], ['show_ineligible' => 2],
  404. ['register_time_limited' => 1],
  405. ['register_time_limited' => 1, 'register_start_time' => '2026-10-02', 'register_end_time' => '2026-10-01'],
  406. ['register_time_limited' => 1, 'register_start_time' => 'not-a-date', 'register_end_time' => '2026-10-01'],
  407. ['deposit_limited' => 1, 'deposit_min' => '100.01', 'deposit_max' => '100.00'],
  408. ['deposit_limited' => 1, 'deposit_min' => '-0.01'],
  409. ['deposit_limited' => 1, 'deposit_max' => '100.001'],
  410. ['deposit_limited' => 1, 'deposit_max' => '1000000000000.00'],
  411. ['deposit_limited' => 1, 'deposit_min' => '1.00'],
  412. ['deposit_limited' => 1, 'deposit_max' => '100.00'],
  413. ] as $invalid) {
  414. $result = $this->save($invalid);
  415. $this->assertNotSame(0, $result['code'], json_encode($invalid));
  416. $this->assertSame(0, DB::table('activity_rewards')->count(), json_encode($invalid));
  417. }
  418. }
  419. public function test_partial_update_validates_against_retained_bound_and_service_cannot_bypass_validation(): void
  420. {
  421. $activity = $this->activity(['deposit_limited' => 1, 'deposit_min' => '10.00', 'deposit_max' => '20.00']);
  422. $this->assertNotSame(0, $this->save(['id' => $activity->id, 'deposit_min' => '20.01'])['code']);
  423. $activity->refresh();
  424. $this->assertSame('10.00', (string)$activity->deposit_min);
  425. $this->assertSame('20.00', (string)$activity->deposit_max);
  426. try {
  427. ActivityRewardService::submit(['id' => $activity->id, 'deposit_max' => '-1.00']);
  428. $this->fail('Direct service writes must reject invalid eligibility configuration.');
  429. } catch (\Exception $e) {
  430. $this->assertNotSame('', $e->getMessage());
  431. }
  432. $activity->refresh();
  433. $this->assertSame('20.00', (string)$activity->deposit_max);
  434. }
  435. public function test_football_type_ignores_even_invalid_new_fields_and_resets_existing_limits(): void
  436. {
  437. $invalidFields = [
  438. 'publish_platforms' => ['H5'], 'reward_quota' => 'invalid', 'sort' => 37,
  439. 'register_time_limited' => 'invalid', 'register_start_time' => 'invalid',
  440. 'register_end_time' => 'invalid', 'register_platforms' => ['invalid'],
  441. 'deposit_limited' => 'invalid', 'deposit_min' => -1, 'deposit_max' => 'invalid',
  442. 'show_ineligible' => 'invalid',
  443. ];
  444. $football = $this->activity(['type' => 2] + $invalidFields);
  445. $this->assertSame(['H5'], $football->publish_platforms);
  446. $this->assertSame([], $football->register_platforms);
  447. $this->assertFalse((bool)$football->register_time_limited);
  448. $this->assertFalse((bool)$football->deposit_limited);
  449. $this->assertTrue((bool)$football->show_ineligible);
  450. $this->assertNull($football->reward_quota);
  451. $this->assertSame(37, (int)$football->sort);
  452. $this->assertTrue($this->eligibility($football, null)['is_eligible']);
  453. $this->assertFalse(ActivityEligibilityService::isPublishedOn($football, 'PC'));
  454. $this->assertTrue(ActivityEligibilityService::isPublishedOn($football, 'H5'));
  455. $restricted = $this->activity(['register_platforms' => ['APP'], 'deposit_limited' => 1, 'deposit_min' => 100, 'deposit_max' => 200]);
  456. $this->assertSame(0, $this->save(['id' => $restricted->id, 'type' => 2] + $invalidFields)['code']);
  457. $restricted->refresh();
  458. $this->assertSame([], $restricted->register_platforms);
  459. $this->assertFalse((bool)$restricted->deposit_limited);
  460. $this->assertTrue($this->eligibility($restricted, null)['is_eligible']);
  461. }
  462. public function test_registration_datetime_is_exact_and_both_boundaries_are_inclusive(): void
  463. {
  464. $activity = $this->activity([
  465. 'register_time_limited' => 1, 'register_start_time' => '2026-10-01 12:34:56',
  466. 'register_end_time' => '2026-10-01 12:34:57',
  467. ]);
  468. foreach ([['1001', '12:34:55', false], ['1002', '12:34:56', true],
  469. ['1003', '12:34:57', true], ['1004', '12:34:58', false]] as [$id, $time, $eligible]) {
  470. $this->member($id, '2026-10-01 ' . $time);
  471. $result = $this->eligibility($activity, $id);
  472. $this->assertSame($eligible, $result['is_eligible'], $time);
  473. $this->assertSame($eligible, $result['ineligible_reason'] === '');
  474. }
  475. }
  476. public function test_lifetime_deposit_uses_wallet_currency_ledger_categories_and_inclusive_cents(): void
  477. {
  478. $this->member();
  479. $this->deposit('1001', '150.00');
  480. $this->deposit('1001', '25.23', '三方充值');
  481. $this->deposit('1001', '26.00', '人工充值');
  482. $this->deposit('1001', '9999.00', '注册赠送');
  483. $this->deposit('1001', '8888.00', '优惠活动');
  484. $this->deposit('1001', '7777.00', '充值', 2);
  485. $this->deposit('1001', '-55.00', '投注');
  486. DB::table('payment_orders')->insert(['member_id' => '1001', 'type' => 1, 'status' => 2, 'amount' => 777]);
  487. DB::table('recharges')->insert(['member_id' => '1001', 'status' => 1, 'amount' => 222]);
  488. $activity = $this->activity(['deposit_limited' => 1, 'deposit_min' => '201.23', 'deposit_max' => '201.23']);
  489. $this->assertTrue($this->eligibility($activity, '1001')['is_eligible']);
  490. foreach ([['deposit_min' => '201.24', 'deposit_max' => '999999999999.99'],
  491. ['deposit_min' => '0.00', 'deposit_max' => '201.22']] as $limits) {
  492. $this->assertSame(0, $this->save(['id' => $activity->id] + $limits)['code']);
  493. $activity->refresh();
  494. $this->assertFalse($this->eligibility($activity, '1001')['is_eligible']);
  495. }
  496. }
  497. public function test_zero_deposit_is_supported_and_enabled_ranges_require_both_bounds(): void
  498. {
  499. $this->member();
  500. $activity = $this->activity(['deposit_limited' => 1, 'deposit_min' => '0.00', 'deposit_max' => '0.00']);
  501. $this->assertTrue($this->eligibility($activity, '1001')['is_eligible']);
  502. $this->assertNotSame(0, $this->save(['deposit_limited' => 1, 'deposit_min' => '1.00'])['code']);
  503. $this->assertNotSame(0, $this->save(['deposit_limited' => 1, 'deposit_max' => '0.00'])['code']);
  504. $this->assertSame(1, DB::table('activity_rewards')->count());
  505. }
  506. public function test_registration_platform_uses_first_successful_login_and_groups_ios_android_as_app(): void
  507. {
  508. $activity = $this->activity(['register_platforms' => ['APP']]);
  509. $this->member('1001');
  510. $this->login('1001', 'PC', 0);
  511. $this->login('1001', 'iOS');
  512. $this->login('1001', 'PC');
  513. $this->assertTrue($this->eligibility($activity, '1001')['is_eligible']);
  514. $this->member('1002');
  515. $this->login('1002', 'Android');
  516. $this->assertTrue($this->eligibility($activity, '1002')['is_eligible']);
  517. $this->member('1003');
  518. $this->login('1003', 'H5');
  519. $this->login('1003', 'Android');
  520. $this->assertFalse($this->eligibility($activity, '1003')['is_eligible']);
  521. $this->member('1004');
  522. DB::table('users')->where('member_id', '1004')->update(['register_domain' => 'com.example.app']);
  523. $this->assertFalse($this->eligibility($activity, '1004')['is_eligible']);
  524. $this->member('1005');
  525. $this->login('1005', '');
  526. $this->login('1005', 'Android');
  527. $this->assertFalse($this->eligibility($activity, '1005')['is_eligible']);
  528. $h5 = $this->activity(['register_platforms' => ['H5']]);
  529. $this->member('1006');
  530. $this->login('1006', 'WeChat');
  531. $this->assertTrue($this->eligibility($h5, '1006')['is_eligible']);
  532. }
  533. public function test_guest_and_member_display_choices_and_sort_order_are_enforced_by_controller(): void
  534. {
  535. $this->member();
  536. $this->deposit('1001', '100.00');
  537. $unrestricted = $this->activity(['sort' => 1]);
  538. $hidden = $this->activity(['sort' => 9, 'deposit_limited' => 1, 'deposit_min' => '100.01', 'deposit_max' => '200.00', 'show_ineligible' => 0]);
  539. $shown = $this->activity(['sort' => 7, 'deposit_limited' => 1, 'deposit_min' => '100.01', 'deposit_max' => '200.00', 'show_ineligible' => 1]);
  540. $eligible = $this->activity(['sort' => 7, 'deposit_limited' => 1, 'deposit_min' => '100.00', 'deposit_max' => '200.00', 'show_ineligible' => 0]);
  541. $this->activity(['type' => 2, 'sort' => 99]);
  542. $this->activity(['status' => 0]);
  543. $guest = $this->list();
  544. $this->assertSame([$shown->id, $unrestricted->id], array_column($guest, 'id'));
  545. $this->assertFalse($guest[0]['is_eligible']);
  546. $this->assertNotSame('', $guest[0]['ineligible_reason']);
  547. $this->assertFalse($guest[1]['is_eligible']);
  548. $this->assertSame('请先登录', $guest[1]['ineligible_reason']);
  549. $member = $this->list(['member_id' => '1001']);
  550. $this->assertSame([$eligible->id, $shown->id, $unrestricted->id], array_column($member, 'id'));
  551. $this->assertNotContains($hidden->id, array_column($member, 'id'));
  552. $this->assertTrue($member[0]['is_eligible']);
  553. $this->assertSame('', $member[0]['ineligible_reason']);
  554. $this->assertFalse($member[1]['is_eligible']);
  555. $this->assertFalse($member[0]['is_claimed']);
  556. }
  557. public function test_publication_platform_filter_is_independent_of_member_registration_platform(): void
  558. {
  559. $this->member();
  560. $this->login('1001', 'iOS');
  561. $pc = $this->activity(['publish_platforms' => ['PC'], 'register_platforms' => ['APP']]);
  562. $h5 = $this->activity(['publish_platforms' => ['H5']]);
  563. $app = $this->activity(['publish_platforms' => ['APP']]);
  564. $all = $this->activity();
  565. $this->assertTrue(ActivityEligibilityService::isPublishedOn($pc, 'PC'));
  566. $this->assertFalse(ActivityEligibilityService::isPublishedOn($pc, 'APP'));
  567. $this->assertTrue($this->eligibility($pc, '1001')['is_eligible']);
  568. foreach ([['PC', $pc], ['H5', $h5], ['APP', $app]] as [$platform, $specific]) {
  569. $rows = $this->list(['member_id' => '1001', 'platform' => $platform]);
  570. $this->assertSame([$all->id, $specific->id], array_column($rows, 'id'), $platform);
  571. }
  572. $this->assertSame([$all->id, $pc->id], array_column($this->list(['member_id' => '1001']), 'id'));
  573. $this->request('/api/ActivityReward', ['platform' => 'INVALID']);
  574. $this->assertNotSame(0, (new ApiActivityReward())->index()->getData(true)['code']);
  575. }
  576. public function test_participation_rejects_ineligible_even_when_shown_and_before_existing_phone_checks(): void
  577. {
  578. $this->member();
  579. $activity = $this->activity(['register_platforms' => ['APP'], 'show_ineligible' => 1]);
  580. $reason = $this->eligibility($activity, '1001')['ineligible_reason'];
  581. $this->request('/api/ActivityReward/participate', ['member_id' => '1001', 'activity_id' => $activity->id], 'POST');
  582. $result = (new ApiActivityReward())->participate()->getData(true);
  583. $this->assertNotSame(0, $result['code']);
  584. $this->assertSame($reason, $result['msg']);
  585. $this->assertNotSame(HttpStatus::NOT_BIND_PHONE, $result['code']);
  586. $this->assertSame(0, DB::table('activity_user')->count());
  587. $this->login('1001', 'Android');
  588. $this->request('/api/ActivityReward/participate', ['member_id' => '1001', 'activity_id' => $activity->id], 'POST');
  589. $this->assertSame(HttpStatus::NOT_BIND_PHONE, (new ApiActivityReward())->participate()->getData(true)['code']);
  590. }
  591. public function test_eligible_member_can_submit_activity_and_list_retains_claimed_state(): void
  592. {
  593. $this->member('1001', '2026-10-01 12:34:56', '15500001001');
  594. $this->login('1001', 'PC');
  595. $this->deposit('1001', '100.00');
  596. DB::table('payment_orders')->insert(['member_id' => '1001', 'type' => 1, 'status' => 2, 'amount' => '100.00']);
  597. $activity = $this->activity(['register_platforms' => ['PC'], 'deposit_limited' => 1, 'deposit_min' => '100.00', 'deposit_max' => '200.00', 'reward_quota' => 1]);
  598. $this->request('/api/ActivityReward/participate', ['member_id' => '1001', 'activity_id' => $activity->id], 'POST');
  599. $result = (new ApiActivityReward())->participate()->getData(true);
  600. $this->assertSame(0, $result['code'], $result['msg']);
  601. $this->assertSame(1, DB::table('activity_user')->count());
  602. $this->assertSame(0, (int)$activity->fresh()->rewarded_count);
  603. $this->assertSame(0, DB::table('activity_reward_recipients')->count());
  604. $rows = $this->list(['member_id' => '1001']);
  605. $this->assertTrue($rows[0]['is_eligible']);
  606. $this->assertTrue($rows[0]['is_claimed']);
  607. }
  608. public function test_automatic_recharge_and_old_member_rewards_check_eligibility_before_bonus_side_effects(): void
  609. {
  610. $this->member();
  611. $this->deposit('1001', '100.00');
  612. $this->activity([
  613. 'type' => 3, 'deposit_limited' => 1, 'deposit_min' => '100.01', 'deposit_max' => '200.00',
  614. 'params' => ['reward_ratio' => 5, 'min_recharge_amount' => 0, 'reward_turnover_ratio' => 1],
  615. ]);
  616. $this->activity([
  617. 'type' => 4, 'register_platforms' => ['APP'],
  618. 'params' => ['no_login_days' => 1, 'reward_rules' => [['start_level' => 0, 'end_level' => 5, 'bonus' => 10]]],
  619. ]);
  620. $this->assertFalse(BalanceLogService::calculateRechargeBonus('100.00', '1001', 123));
  621. $this->assertFalse(BalanceLogService::calculateUserReturnRechargeBonus('100.00', '1001', 1, 123));
  622. $this->assertSame(0, DB::table('wallet_bonus')->count());
  623. $this->assertSame(1, DB::table('balance_logs')->count());
  624. }
  625. /** Exercise the real addLog entry without relying on a caller-owned transaction. */
  626. private function automaticRewardFixtures(): array
  627. {
  628. $schema = DB::connection()->getSchemaBuilder();
  629. $schema->create('config', function (Blueprint $t) {
  630. $t->id(); $t->string('field'); $t->string('val'); $t->timestamps();
  631. });
  632. $schema->create('level', function (Blueprint $t) {
  633. $t->id(); $t->integer('level'); $t->decimal('recharge', 20, 2); $t->timestamps();
  634. });
  635. $schema->create('recharge_channel_group', function (Blueprint $t) {
  636. $t->id(); $t->text('activity_type'); $t->softDeletes(); $t->timestamps();
  637. });
  638. $schema->create('backflow', function (Blueprint $t) {
  639. $t->id(); $t->string('member_id'); $t->string('date');
  640. foreach (['recharge_amount', 'withdrawal_amount', 'backflow_ratio', 'amount'] as $field) {
  641. $t->decimal($field, 20, 2)->default(0);
  642. }
  643. $t->timestamps();
  644. });
  645. DB::table('config')->insert([
  646. ['field' => 'huishui_percentage', 'val' => '0'],
  647. ['field' => 'huishui_restriction', 'val' => '999999'],
  648. ['field' => 'recharge_rate', 'val' => '0'],
  649. ]);
  650. DB::table('level')->insert(['level' => 0, 'recharge' => '0']);
  651. DB::table('recharge_channel_group')->insert(['id' => 1, 'activity_type' => 'recharge,old_user']);
  652. DB::table('backflow')->insert(['member_id' => '1001', 'date' => date('Y-m')]);
  653. $this->member();
  654. DB::table('wallets')->insert(['member_id' => '1001', 'available_balance' => '100.00', 'frozen_balance' => '2.00']);
  655. foreach ([date('Y-m-d 00:00:00', strtotime('-14 days')), date('Y-m-d 00:00:00')] as $loggedAt) {
  656. DB::table('user_login')->insert([
  657. 'user_id' => '1001', 'status' => 1, 'platform' => 'PC',
  658. 'created_at' => $loggedAt, 'updated_at' => $loggedAt,
  659. ]);
  660. }
  661. return [
  662. $this->activity(['type' => 3, 'reward_quota' => 1,
  663. 'params' => ['reward_ratio' => 5, 'reward_turnover_ratio' => 1]]),
  664. $this->activity(['type' => 4, 'reward_quota' => 1,
  665. 'params' => ['no_login_days' => 7,
  666. 'reward_rules' => [['start_level' => 0, 'end_level' => 0, 'bonus' => '7.00', 'turnover_rate' => 1]]]]),
  667. ];
  668. }
  669. public static function automaticRewardWriteFailures(): array
  670. {
  671. return [
  672. 'USDT wallet save failure' => ['充值', 'wallet'],
  673. 'third-party wallet save failure' => ['三方充值', 'wallet'],
  674. 'recharge reward ledger failure' => ['充值', '即充即送'],
  675. 'return reward ledger failure after first award' => ['三方充值', '老用户回归'],
  676. ];
  677. }
  678. public function test_frontend_manual_deposit_approval_receives_configured_recharge_activities(): void
  679. {
  680. [$recharge, $return] = $this->automaticRewardFixtures();
  681. DB::connection()->getSchemaBuilder()->table('payment_orders', function (Blueprint $t) {
  682. $t->integer('state')->default(0); $t->text('remark')->nullable();
  683. });
  684. DB::table('payment_orders')->insert([
  685. 'id' => 900, 'member_id' => '1001', 'type' => 3, 'status' => 5, 'amount' => '100.00',
  686. ]);
  687. $this->request('/admin/paymentOrder/manualAudit', ['id' => 900, 'status' => 2], 'POST');
  688. $this->assertSame(0, (new AdminPaymentOrder())->manualAudit()->getData(true)['code']);
  689. // 活动赠送直接进入可用余额,不再走冻结金额
  690. $this->assertEquals('212.00', DB::table('wallets')->value('available_balance'));
  691. $this->assertEquals('2.00', DB::table('wallets')->value('frozen_balance'));
  692. $this->assertSame(1, (int)$recharge->fresh()->rewarded_count);
  693. $this->assertSame(1, (int)$return->fresh()->rewarded_count);
  694. $this->assertSame(2, DB::table('wallet_bonus')->where('related_id', 900)->count());
  695. $this->assertSame(0, DB::table('balance_logs')->where('type', 2)->count());
  696. $this->assertSame(2, DB::table('balance_logs')->where('type', 1)->where('related_id', 900)->whereIn('change_type', ['即充即送', '老用户回归'])->count());
  697. $this->assertSame('充值', DB::table('balance_logs')->where('type', 1)->value('change_type'));
  698. }
  699. #[DataProvider('automaticRewardWriteFailures')]
  700. public function test_automatic_reward_failure_rolls_back_recipients_count_bonus_ledger_and_wallet(string $category, string $failure): void
  701. {
  702. [$recharge, $return] = $this->automaticRewardFixtures();
  703. if ($failure === 'wallet') {
  704. DB::statement("CREATE TRIGGER fail_reward_wallet BEFORE UPDATE ON bot_wallets
  705. WHEN NEW.available_balance > OLD.available_balance
  706. BEGIN SELECT RAISE(ABORT, 'injected reward write failure'); END");
  707. } else {
  708. DB::statement("CREATE TRIGGER fail_reward_ledger BEFORE INSERT ON bot_balance_logs
  709. WHEN NEW.change_type = '$failure'
  710. BEGIN SELECT RAISE(ABORT, 'injected reward write failure'); END");
  711. }
  712. $this->assertSame(0, DB::transactionLevel());
  713. try {
  714. BalanceLogService::addLog('1001', '100.00', '0.00', '100.00', $category, 900, '');
  715. $this->fail('The injected database write failure must reach the caller.');
  716. } catch (\Illuminate\Database\QueryException $e) {
  717. $this->assertStringContainsString('injected reward write failure', $e->getMessage());
  718. }
  719. $this->assertSame(0, DB::transactionLevel());
  720. $this->assertSame(0, (int)$recharge->fresh()->rewarded_count);
  721. $this->assertSame(0, (int)$return->fresh()->rewarded_count);
  722. $this->assertSame(0, DB::table('activity_reward_recipients')->count());
  723. $this->assertSame(0, DB::table('wallet_bonus')->count());
  724. $this->assertSame(0, DB::table('balance_logs')->whereIn('change_type', ['即充即送', '老用户回归'])->count());
  725. $this->assertEquals('2.00', DB::table('wallets')->value('frozen_balance'));
  726. $this->assertEquals('100.00', DB::table('wallets')->value('available_balance'));
  727. // The completed principal deposit stays recorded when only rewards fail.
  728. $this->assertSame(1, DB::table('balance_logs')->where('change_type', $category)->count());
  729. }
  730. public function test_automatic_rewards_commit_one_recipient_per_activity_with_bonus_ledgers_and_wallet(): void
  731. {
  732. [$recharge, $return] = $this->automaticRewardFixtures();
  733. BalanceLogService::addLog('1001', '100.00', '0.00', '100.00', '充值', 900, '');
  734. $this->assertSame(0, DB::transactionLevel());
  735. $this->assertSame(1, (int)$recharge->fresh()->rewarded_count);
  736. $this->assertSame(1, (int)$return->fresh()->rewarded_count);
  737. $this->assertSame(2, DB::table('activity_reward_recipients')->where('member_id', '1001')->count());
  738. $this->assertEquals('2.00', DB::table('wallets')->value('frozen_balance'));
  739. $this->assertEquals('112.00', DB::table('wallets')->value('available_balance'));
  740. $this->assertSame(2, DB::table('wallet_bonus')->count());
  741. $this->assertEquals('12.00', DB::table('wallet_bonus')->sum('amount'));
  742. $this->assertEquals('12.00', DB::table('balance_logs')->where('type', 1)->whereIn('change_type', ['即充即送', '老用户回归'])->sum('amount'));
  743. $this->assertEquals('100.00', DB::table('balance_logs')->where('change_type', '即充即送')->value('before_balance'));
  744. $this->assertEquals('105.00', DB::table('balance_logs')->where('change_type', '老用户回归')->value('before_balance'));
  745. $this->assertSame(1, DB::table('balance_logs')->where('change_type', '充值')->count());
  746. }
  747. public function test_automatic_reward_transaction_respects_an_existing_caller_transaction(): void
  748. {
  749. [$recharge, $return] = $this->automaticRewardFixtures();
  750. DB::beginTransaction();
  751. BalanceLogService::addLog('1001', '100.00', '0.00', '100.00', '三方充值', 900, '');
  752. $this->assertSame(1, DB::transactionLevel());
  753. $this->assertEquals('112.00', DB::table('wallets')->value('available_balance'));
  754. DB::rollBack();
  755. $this->assertSame(0, (int)$recharge->fresh()->rewarded_count);
  756. $this->assertSame(0, (int)$return->fresh()->rewarded_count);
  757. $this->assertSame(0, DB::table('activity_reward_recipients')->count());
  758. $this->assertEquals('2.00', DB::table('wallets')->value('frozen_balance'));
  759. $this->assertEquals('100.00', DB::table('wallets')->value('available_balance'));
  760. $this->assertSame(0, DB::table('wallet_bonus')->count());
  761. $this->assertSame(0, DB::table('balance_logs')->count());
  762. }
  763. public function test_automatic_recharge_uses_already_posted_current_deposit_once(): void
  764. {
  765. $this->member();
  766. $this->deposit('1001', '100.00');
  767. $activity = $this->activity([
  768. 'type' => 3, 'deposit_limited' => 1, 'deposit_min' => '100.00', 'deposit_max' => '100.00',
  769. 'params' => ['reward_ratio' => 5, 'min_recharge_amount' => 0, 'reward_turnover_ratio' => 1],
  770. ]);
  771. $this->assertEquals('5.00', BalanceLogService::calculateRechargeBonus('100.00', '1001', 123));
  772. $this->assertSame(1, DB::table('wallet_bonus')->where('activity_id', $activity->id)->count());
  773. $this->assertEquals(5, DB::table('wallet_bonus')->value('amount'));
  774. $this->assertSame(1, DB::table('balance_logs')->count());
  775. }
  776. public function test_automatic_selection_skips_higher_sorted_ineligible_and_exhausted_activities(): void
  777. {
  778. $this->member();
  779. $this->login('1001', 'PC');
  780. $this->deposit('1001', '100.00');
  781. $rewardParams = ['reward_ratio' => 5, 'min_recharge_amount' => 0, 'reward_turnover_ratio' => 1];
  782. $lower = $this->activity([
  783. 'type' => 3, 'sort' => 1, 'reward_quota' => 2, 'register_platforms' => ['PC'], 'params' => $rewardParams,
  784. ]);
  785. $higher = $this->activity([
  786. 'type' => 3, 'sort' => 2, 'reward_quota' => 100, 'register_platforms' => ['APP'], 'params' => $rewardParams,
  787. ]);
  788. $this->assertSame($lower->id, ActivityRewardService::activeForMember(3, '1001')->id);
  789. $this->assertEquals('5.00', BalanceLogService::calculateRechargeBonus('100.00', '1001', 123));
  790. $lower->refresh();
  791. $higher->refresh();
  792. $this->assertSame(1, (int)$lower->rewarded_count);
  793. $this->assertSame(0, (int)$higher->rewarded_count);
  794. $this->assertSame(0, $this->save([
  795. 'id' => $higher->id, 'type' => 3, 'reward_quota' => 0, 'register_platforms' => ['PC'], 'params' => $rewardParams,
  796. ])['code']);
  797. $higher->refresh();
  798. $this->assertTrue($this->eligibility($higher, '1001')['is_eligible']);
  799. $this->assertSame($lower->id, ActivityRewardService::activeForMember(3, '1001')->id);
  800. $this->assertEquals('5.00', BalanceLogService::calculateRechargeBonus('100.00', '1001', 124));
  801. $lower->refresh();
  802. $higher->refresh();
  803. $this->assertSame(1, (int)$lower->rewarded_count);
  804. $this->assertSame(0, (int)$higher->rewarded_count);
  805. $this->assertSame(2, DB::table('wallet_bonus')->where('activity_id', $lower->id)->count());
  806. $this->assertSame(0, DB::table('wallet_bonus')->where('activity_id', $higher->id)->count());
  807. }
  808. public function test_ten_distinct_members_take_ten_slots_and_eleventh_is_denied_using_stale_model(): void
  809. {
  810. $activity = $this->activity(['reward_quota' => 10]);
  811. $grants = [];
  812. for ($member = 1; $member <= 10; $member++) {
  813. $id = (string)(1000 + $member);
  814. $this->member($id);
  815. $amount = $member % 2 ? '0.01' : '12345.67';
  816. $this->assertTrue(ActivityQuotaService::canAward($activity->fresh(), $id));
  817. $this->assertTrue(ActivityQuotaService::award($activity, $id, $amount, function () use (&$grants, $id) {
  818. $grants[] = $id;
  819. }));
  820. }
  821. $this->member('1011');
  822. $this->assertFalse(ActivityQuotaService::canAward($activity->fresh(), '1011'));
  823. $this->assertFalse(ActivityQuotaService::award($activity, '1011', '0.01', function () { $this->fail('Eleventh member must be denied.'); }));
  824. $this->assertSame(range(1001, 1010), array_map('intval', $grants));
  825. $this->assertSame(10, (int)$activity->fresh()->rewarded_count);
  826. $this->assertSame(10, DB::table('activity_reward_recipients')->where('activity_id', $activity->id)->count());
  827. }
  828. public function test_repeat_rewards_take_one_slot_and_same_member_counts_separately_in_each_activity(): void
  829. {
  830. $this->member();
  831. $first = $this->activity(['reward_quota' => 1]);
  832. $second = $this->activity(['reward_quota' => 1]);
  833. $grants = 0;
  834. foreach (['1.00', '2.50', '1000.00'] as $amount) {
  835. $this->assertTrue(ActivityQuotaService::award($first, '1001', $amount, function () use (&$grants) { $grants++; }));
  836. }
  837. $this->assertTrue(ActivityQuotaService::canAward($first->fresh(), '1001'));
  838. $this->assertFalse(ActivityQuotaService::canAward($first->fresh(), '1002'));
  839. $this->assertTrue(ActivityQuotaService::award($second, '1001', '0.01', function () use (&$grants) { $grants++; }));
  840. $this->assertSame(4, $grants);
  841. $this->assertSame(1, (int)$first->fresh()->rewarded_count);
  842. $this->assertSame(1, (int)$second->fresh()->rewarded_count);
  843. $this->assertSame(2, DB::table('activity_reward_recipients')->where('member_id', '1001')->count());
  844. }
  845. /** Checks SQL lock intent only; SQLite cannot reproduce MySQL repeatable-read snapshots. */
  846. public function test_award_locks_activity_then_recipient_for_current_read_but_precheck_does_not_lock(): void
  847. {
  848. $activity = $this->activity(['reward_quota' => 1]);
  849. $grammar = new class(DB::connection()) extends \Illuminate\Database\Query\Grammars\SQLiteGrammar {
  850. public array $reads = [];
  851. public function compileSelect(\Illuminate\Database\Query\Builder $query)
  852. {
  853. if (in_array($query->from, ['activity_rewards', 'activity_reward_recipients'], true)) {
  854. $this->reads[] = ['table' => $query->from, 'lock' => $query->lock];
  855. }
  856. return parent::compileSelect($query);
  857. }
  858. };
  859. DB::connection()->setQueryGrammar($grammar);
  860. $this->assertTrue(ActivityQuotaService::canAward($activity, '1001'));
  861. $this->assertSame([['table' => 'activity_reward_recipients', 'lock' => null]], $grammar->reads);
  862. $grammar->reads = [];
  863. $this->assertTrue(ActivityQuotaService::award($activity, '1001', '1.00', function () {}));
  864. $this->assertSame([
  865. ['table' => 'activity_rewards', 'lock' => true],
  866. ['table' => 'activity_reward_recipients', 'lock' => true],
  867. ], $grammar->reads);
  868. $grammar->reads = [];
  869. $this->assertTrue(ActivityQuotaService::award($activity, '1001', '2.00', function () {}));
  870. $this->assertSame([
  871. ['table' => 'activity_rewards', 'lock' => true],
  872. ['table' => 'activity_reward_recipients', 'lock' => true],
  873. ], $grammar->reads);
  874. $fresh = $activity->fresh();
  875. $this->assertSame(1, (int)$fresh->rewarded_count);
  876. $grammar->reads = [];
  877. $this->assertTrue(ActivityQuotaService::canAward($fresh, '1001'));
  878. $this->assertSame([['table' => 'activity_reward_recipients', 'lock' => null]], $grammar->reads);
  879. }
  880. public function test_quota_rejects_invalid_award_precision_amounts_and_empty_members_without_grant(): void
  881. {
  882. $activity = $this->activity(['reward_quota' => 1]);
  883. foreach (['1.009', '1e0', '-0.01', '0', '0.00', '1000000000000.00', 'not-an-amount'] as $amount) {
  884. $this->assertFalse(ActivityQuotaService::award($activity, '1001', $amount, function () use ($amount) {
  885. $this->fail('Invalid award must not invoke grant: ' . $amount);
  886. }), $amount);
  887. $this->assertSame(0, (int)$activity->fresh()->rewarded_count, $amount);
  888. $this->assertSame(0, DB::table('activity_reward_recipients')->count());
  889. }
  890. foreach ([null, ''] as $id) {
  891. $this->assertFalse(ActivityQuotaService::canAward($activity, $id));
  892. $this->assertFalse(ActivityQuotaService::award($activity, $id, '1.00', function () { $this->fail('Missing member must not take a slot.'); }));
  893. }
  894. }
  895. public function test_failed_grant_rolls_back_recipient_counter_wallet_and_bonus_ledger(): void
  896. {
  897. $this->member();
  898. DB::table('wallets')->insert(['member_id' => '1001', 'available_balance' => '50.00']);
  899. $activity = $this->activity(['reward_quota' => 1]);
  900. try {
  901. ActivityQuotaService::award($activity, '1001', '2.50', function () use ($activity) {
  902. DB::table('wallets')->where('member_id', '1001')->update(['available_balance' => '52.50']);
  903. $this->deposit('1001', '2.50', '优惠活动');
  904. DB::table('wallet_bonus')->insert([
  905. 'member_id' => '1001', 'activity_id' => $activity->id, 'amount' => '2.50',
  906. 'need_flow' => '2.50', 'remaind_flow' => '2.50', 'status' => 1,
  907. ]);
  908. throw new \RuntimeException('fixture grant failed');
  909. });
  910. $this->fail('Grant failures must propagate so callers can roll back the reward.');
  911. } catch (\RuntimeException $e) {
  912. $this->assertSame('fixture grant failed', $e->getMessage());
  913. }
  914. $this->assertSame(0, DB::table('balance_logs')->count());
  915. $this->assertSame(0, DB::table('wallet_bonus')->count());
  916. $this->assertSame(0, DB::table('activity_reward_recipients')->count());
  917. $this->assertSame(0, (int)$activity->fresh()->rewarded_count);
  918. $this->assertEquals('50.00', DB::table('wallets')->value('available_balance'));
  919. $this->assertTrue(ActivityQuotaService::canAward($activity->fresh(), '1001'));
  920. $this->assertTrue(ActivityQuotaService::award($activity, '1001', '10.00', function () {}));
  921. $this->assertSame(1, (int)$activity->fresh()->rewarded_count);
  922. }
  923. public function test_outer_rollback_releases_recipient_and_count_with_reward_writes(): void
  924. {
  925. $activity = $this->activity(['reward_quota' => 1]);
  926. DB::beginTransaction();
  927. $this->assertTrue(ActivityQuotaService::award($activity, '1001', '1.00', function () { $this->deposit('1001', '1.00', '优惠活动'); }));
  928. $this->assertSame(1, DB::transactionLevel());
  929. $this->assertSame(1, (int)$activity->fresh()->rewarded_count);
  930. $this->assertSame(1, DB::table('activity_reward_recipients')->count());
  931. DB::rollBack();
  932. $this->assertSame(0, (int)$activity->fresh()->rewarded_count);
  933. $this->assertSame(0, DB::table('activity_reward_recipients')->count());
  934. $this->assertSame(0, DB::table('balance_logs')->count());
  935. }
  936. public function test_zero_quota_blocks_new_members_unlimited_counts_members_and_football_bypasses_quota(): void
  937. {
  938. $zero = $this->activity(['reward_quota' => 0]);
  939. $this->assertFalse(ActivityQuotaService::canAward($zero, '1001'));
  940. $this->assertFalse(ActivityQuotaService::award($zero, '1001', '0.01', function () { $this->fail('Zero quota must block new recipients.'); }));
  941. $unlimited = $this->activity();
  942. foreach (['1001', '1002', '1001'] as $id) {
  943. $this->assertTrue(ActivityQuotaService::award($unlimited, $id, '100.50', function () {}));
  944. }
  945. $this->assertNull($unlimited->fresh()->reward_quota);
  946. $this->assertSame(2, (int)$unlimited->fresh()->rewarded_count);
  947. $football = $this->activity(['type' => 2, 'reward_quota' => 0]);
  948. $granted = false;
  949. $this->assertTrue(ActivityQuotaService::award($football, '1001', '1.00', function () use (&$granted) { $granted = true; }));
  950. $this->assertTrue($granted);
  951. $this->assertSame(0, (int)$football->fresh()->rewarded_count);
  952. $this->assertSame(0, DB::table('activity_reward_recipients')->where('activity_id', $football->id)->count());
  953. }
  954. public function test_lowering_quota_below_occupied_count_preserves_existing_recipient_and_rejects_new_member(): void
  955. {
  956. $activity = $this->activity(['reward_quota' => 2]);
  957. foreach (['1001', '1002'] as $id) {
  958. $this->assertTrue(ActivityQuotaService::award($activity, $id, '1.00', function () {}));
  959. }
  960. $this->assertSame(0, $this->save(['id' => $activity->id, 'reward_quota' => 0])['code']);
  961. $activity->refresh();
  962. $this->assertTrue(ActivityQuotaService::canAward($activity, '1001'));
  963. $this->assertFalse(ActivityQuotaService::canAward($activity, '1003'));
  964. $this->assertTrue(ActivityQuotaService::award($activity, '1001', '2.50', function () {}));
  965. $this->assertFalse(ActivityQuotaService::award($activity, '1003', '0.01', function () { $this->fail('Reduced quota must block new recipients.'); }));
  966. $this->assertSame(2, (int)$activity->fresh()->rewarded_count);
  967. $this->assertSame(2, DB::table('activity_reward_recipients')->count());
  968. }
  969. public function test_admin_edits_cannot_reset_readonly_recipient_count_or_use_legacy_money_budget(): void
  970. {
  971. $activity = $this->activity(['reward_quota' => 1]);
  972. $this->assertTrue(ActivityQuotaService::award($activity, '1001', '8.00', function () {}));
  973. $result = $this->save(['id' => $activity->id, 'rewarded_count' => 0, 'reward_quota' => 2,
  974. 'quota_enabled' => 0, 'budget_used' => '10.00']);
  975. $this->assertSame(0, $result['code'], $result['msg']);
  976. $this->assertSame(1, (int)$activity->fresh()->rewarded_count);
  977. $this->assertSame(2, (int)$activity->fresh()->reward_quota);
  978. $this->assertTrue((bool)$activity->fresh()->quota_enabled);
  979. $this->assertSame('0.00', (string)$activity->fresh()->budget_used);
  980. ActivityRewardService::submit(['id' => $activity->id, 'rewarded_count' => 0]);
  981. $this->assertSame(1, (int)$activity->fresh()->rewarded_count);
  982. $this->assertNotSame(0, $this->save(['id' => $activity->id, 'budget' => '10.00'])['code']);
  983. $this->assertSame(1, (int)$activity->fresh()->rewarded_count);
  984. // Mixed-mode APIs retain old fields, with the server-owned mode identifying the rules.
  985. $this->request('/admin/ActivityReward', ['page' => 1, 'limit' => 10]);
  986. $admin = (new AdminActivityReward())->index()->getData(true);
  987. $this->assertSame(0, $admin['code'], $admin['msg']);
  988. foreach ([$admin['data']['data'][0], $this->list(['member_id' => '1001'])[0]] as $row) {
  989. $this->assertNull($row['budget']);
  990. $this->assertSame('0.00', (string)$row['budget_used']);
  991. $this->assertTrue((bool)$row['quota_enabled']);
  992. $this->assertSame(2, (int)$row['reward_quota']);
  993. $this->assertSame(1, (int)$row['rewarded_count']);
  994. }
  995. }
  996. public function test_automatic_rewards_stop_for_new_members_at_quota_but_repeat_reward_keeps_one_slot(): void
  997. {
  998. foreach (['1001', '1002'] as $id) {
  999. $this->member($id);
  1000. $this->deposit($id, '100.00');
  1001. }
  1002. $params = ['reward_ratio' => 5, 'min_recharge_amount' => 0, 'reward_turnover_ratio' => 1];
  1003. $activity = $this->activity(['type' => 3, 'reward_quota' => 0, 'params' => $params]);
  1004. $this->assertFalse(BalanceLogService::calculateRechargeBonus('100.00', '1001', 123));
  1005. $this->assertSame(0, DB::table('wallet_bonus')->count());
  1006. $this->assertSame(0, (int)$activity->fresh()->rewarded_count);
  1007. $this->assertSame(0, $this->save(['id' => $activity->id, 'type' => 3, 'reward_quota' => 1, 'params' => $params])['code']);
  1008. $this->assertEquals('5.00', BalanceLogService::calculateRechargeBonus('100.00', '1001', 123));
  1009. $this->assertEquals('10.00', BalanceLogService::calculateRechargeBonus('200.00', '1001', 124));
  1010. $this->assertFalse(BalanceLogService::calculateRechargeBonus('100.00', '1002', 125));
  1011. $this->assertSame(2, DB::table('wallet_bonus')->count());
  1012. $this->assertSame(1, (int)$activity->fresh()->rewarded_count);
  1013. $this->assertSame(1, DB::table('activity_reward_recipients')->where('activity_id', $activity->id)->count());
  1014. }
  1015. public function test_manual_gift_rechecks_eligibility_and_quota_before_wallet_and_application_changes(): void
  1016. {
  1017. $this->member();
  1018. DB::table('wallets')->insert(['member_id' => '1001', 'available_balance' => '50.00']);
  1019. foreach ([['register_platforms' => ['APP']], ['reward_quota' => 0]] as $limits) {
  1020. $activity = $this->activity($limits);
  1021. $applicationId = DB::table('activity_user')->insertGetId([
  1022. 'member_id' => '1001', 'activity_id' => $activity->id, 'status' => 0,
  1023. 'title' => '待赠送', 'sub_title' => '资格检查', 'detail_image' => '/app.png',
  1024. 'start_time' => 1, 'end_time' => 4102444799, 'part_in_time' => time(),
  1025. ]);
  1026. $this->request('/admin/ActivityUser/gift', ['id' => $applicationId, 'amount' => '1.00', 'betting_amount' => 1], 'POST');
  1027. $result = (new AdminActivityUser())->gift()->getData(true);
  1028. $this->assertSame(HttpStatus::CUSTOM_ERROR, $result['code'], $result['msg']);
  1029. $this->assertSame(0, (int)DB::table('activity_user')->where('id', $applicationId)->value('status'));
  1030. $this->assertEquals('50.00', DB::table('wallets')->value('available_balance'));
  1031. $this->assertSame(0, DB::table('balance_logs')->count());
  1032. $activity->refresh();
  1033. $this->assertSame(0, (int)$activity->rewarded_count);
  1034. $this->assertSame(0, DB::table('activity_reward_recipients')->count());
  1035. }
  1036. }
  1037. public function test_legacy_activity_retains_money_budget_and_cannot_be_switched_to_quota_by_client(): void
  1038. {
  1039. $this->member();
  1040. $legacy = $this->legacyActivity(['budget' => '10.00']);
  1041. $this->assertFalse((bool)$legacy->quota_enabled);
  1042. $this->assertTrue(ActivityQuotaService::award($legacy, '1001', '6.00', function () {}));
  1043. $this->assertFalse(ActivityQuotaService::award($legacy, '1001', '5.00', function () { $this->fail('Old money budget must reject an award above the remaining amount.'); }));
  1044. $this->assertTrue(ActivityQuotaService::award($legacy, '1001', '4.00', function () {}));
  1045. $legacy->refresh();
  1046. $this->assertSame('10.00', (string)$legacy->budget_used);
  1047. $this->assertFalse(ActivityQuotaService::canAward($legacy, '1001'));
  1048. $this->assertSame(0, (int)$legacy->rewarded_count);
  1049. $this->assertSame(0, DB::table('activity_reward_recipients')->count());
  1050. $this->assertNotSame(0, $this->save(['id' => $legacy->id, 'reward_quota' => 10])['code']);
  1051. $result = $this->save(['id' => $legacy->id, 'quota_enabled' => 1,
  1052. 'budget' => '12.00', 'budget_used' => '0.00', 'rewarded_count' => 999]);
  1053. $this->assertSame(0, $result['code'], $result['msg']);
  1054. $legacy->refresh();
  1055. $this->assertFalse((bool)$legacy->quota_enabled);
  1056. $this->assertNull($legacy->reward_quota);
  1057. $this->assertSame('12.00', (string)$legacy->budget);
  1058. $this->assertSame('10.00', (string)$legacy->budget_used);
  1059. $this->assertSame(0, (int)$legacy->rewarded_count);
  1060. $new = $this->activity(['reward_quota' => 1, 'quota_enabled' => 0]);
  1061. $this->assertTrue((bool)$new->quota_enabled);
  1062. $this->assertTrue(ActivityQuotaService::award($new, '1001', '100.00', function () {}));
  1063. $this->assertSame(1, (int)$new->fresh()->rewarded_count);
  1064. $this->assertSame(1, DB::table('activity_reward_recipients')->count());
  1065. $rows = array_column($this->list(['member_id' => '1001']), null, 'id');
  1066. $this->assertFalse((bool)$rows[$legacy->id]['quota_enabled']);
  1067. $this->assertSame('12.00', (string)$rows[$legacy->id]['budget']);
  1068. $this->assertSame('10.00', (string)$rows[$legacy->id]['budget_used']);
  1069. $this->assertTrue((bool)$rows[$new->id]['quota_enabled']);
  1070. }
  1071. public function test_creation_mode_is_immutable_when_an_activity_type_changes(): void
  1072. {
  1073. $legacy = $this->legacyActivity(['type' => 2]);
  1074. $this->assertSame(0, $this->save(['id' => $legacy->id, 'type' => 1, 'quota_enabled' => 1])['code']);
  1075. $this->assertFalse((bool)$legacy->fresh()->quota_enabled);
  1076. $new = $this->activity(['type' => 2]);
  1077. $this->assertSame(0, $this->save(['id' => $new->id, 'type' => 1, 'reward_quota' => 1, 'quota_enabled' => 0])['code']);
  1078. $this->assertTrue((bool)$new->fresh()->quota_enabled);
  1079. $this->assertSame(1, (int)$new->fresh()->reward_quota);
  1080. }
  1081. public function test_manual_gift_failure_rolls_back_wallet_application_recipient_and_counter(): void
  1082. {
  1083. $this->member();
  1084. DB::table('wallets')->insert(['member_id' => '1001', 'available_balance' => '50.00']);
  1085. $activity = $this->activity(['reward_quota' => 1]);
  1086. $applicationId = DB::table('activity_user')->insertGetId([
  1087. 'member_id' => '1001', 'activity_id' => $activity->id, 'status' => 0,
  1088. 'title' => '待赠送', 'sub_title' => '资格检查', 'detail_image' => '/app.png',
  1089. 'start_time' => 1, 'end_time' => 4102444799, 'part_in_time' => time(),
  1090. ]);
  1091. DB::statement("CREATE TRIGGER fail_manual_gift_ledger BEFORE INSERT ON bot_balance_logs
  1092. WHEN NEW.change_type = '优惠活动'
  1093. BEGIN SELECT RAISE(ABORT, 'injected manual reward failure'); END");
  1094. $this->request('/admin/ActivityUser/gift', ['id' => $applicationId, 'amount' => '1.00', 'betting_amount' => 1], 'POST');
  1095. $result = (new AdminActivityUser())->gift()->getData(true);
  1096. $this->assertNotSame(0, $result['code']);
  1097. $this->assertStringContainsString('injected manual reward failure', $result['msg']);
  1098. $this->assertEquals('50.00', DB::table('wallets')->value('available_balance'));
  1099. $this->assertSame(0, (int)DB::table('activity_user')->value('status'));
  1100. $this->assertSame(0, (int)$activity->fresh()->rewarded_count);
  1101. $this->assertSame(0, DB::table('activity_reward_recipients')->count());
  1102. $this->assertSame(0, DB::table('balance_logs')->count());
  1103. }
  1104. public function test_migration_adds_optional_yuebao_activity_reference_and_rolls_back_cleanly(): void
  1105. {
  1106. $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_10_13_120000_add_activity_eligibility_fields.php';
  1107. $migration->down();
  1108. DB::connection()->getSchemaBuilder()->create('yuebao_item', function (Blueprint $t) {
  1109. $t->id(); $t->decimal('principal', 20, 2)->default(0);
  1110. });
  1111. $migration->up();
  1112. $schema = DB::connection()->getSchemaBuilder();
  1113. $this->assertTrue($schema->hasColumn('yuebao_item', 'activity_id'));
  1114. $this->assertTrue($schema->hasColumn('activity_rewards', 'budget_used'));
  1115. $this->assertTrue($schema->hasColumn('activity_rewards', 'quota_enabled'));
  1116. DB::table('yuebao_item')->insert(['principal' => '100.00']);
  1117. $this->assertNull(DB::table('yuebao_item')->value('activity_id'));
  1118. $migration->down();
  1119. $this->assertFalse($schema->hasColumn('yuebao_item', 'activity_id'));
  1120. $this->assertFalse($schema->hasColumn('activity_rewards', 'budget_used'));
  1121. $this->assertEquals(100, DB::table('yuebao_item')->value('principal'));
  1122. }
  1123. public function test_quota_migration_up_down_and_unique_recipient_constraint_preserve_old_activity_storage(): void
  1124. {
  1125. $activity = $this->activity(['reward_quota' => 1]);
  1126. $this->assertTrue(ActivityQuotaService::award($activity, '1001', '1.00', function () {}));
  1127. try {
  1128. DB::table('activity_reward_recipients')->insert([
  1129. 'activity_id' => $activity->id, 'member_id' => '1001', 'created_at' => '2026-10-14 12:00:00',
  1130. ]);
  1131. $this->fail('Recipient table must reject duplicate activity/member pairs.');
  1132. } catch (\Illuminate\Database\QueryException $e) {
  1133. $this->assertStringContainsString('UNIQUE', $e->getMessage());
  1134. }
  1135. $this->assertSame(1, DB::table('activity_reward_recipients')->count());
  1136. $schema = DB::connection()->getSchemaBuilder();
  1137. $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_10_14_120000_add_activity_reward_quotas.php';
  1138. $migration->down();
  1139. $this->assertFalse($schema->hasTable('activity_reward_recipients'));
  1140. $this->assertFalse($schema->hasColumn('activity_rewards', 'reward_quota'));
  1141. $this->assertFalse($schema->hasColumn('activity_rewards', 'rewarded_count'));
  1142. $this->assertFalse($schema->hasColumn('activity_rewards', 'quota_enabled'));
  1143. $this->assertTrue($schema->hasColumn('activity_rewards', 'budget'));
  1144. $this->assertTrue($schema->hasColumn('activity_rewards', 'budget_used'));
  1145. $this->assertSame(1, DB::table('activity_rewards')->count());
  1146. $migration->up();
  1147. $this->assertTrue($schema->hasTable('activity_reward_recipients'));
  1148. $this->assertNull(DB::table('activity_rewards')->value('reward_quota'));
  1149. $this->assertSame(0, (int)DB::table('activity_rewards')->value('rewarded_count'));
  1150. $this->assertFalse((bool)DB::table('activity_rewards')->value('quota_enabled'));
  1151. }
  1152. }