ActivityRewardEligibilityTest.php 69 KB

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