ActivityRewardEligibilityTest.php 70 KB

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