ActivityRewardEligibilityTest.php 70 KB

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