ActivityRewardEligibilityTest.php 69 KB

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