ActivityRewardEligibilityTest.php 67 KB

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