| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070 |
- <?php
- namespace Tests\Integration;
- use App\Constants\HttpStatus;
- use App\Http\Controllers\admin\ActivityReward as AdminActivityReward;
- use App\Http\Controllers\admin\ActivityUser as AdminActivityUser;
- use App\Http\Controllers\api\ActivityReward as ApiActivityReward;
- use App\Models\ActivityReward;
- use App\Services\ActivityQuotaService;
- use App\Services\ActivityEligibilityService;
- use App\Services\ActivityRewardService;
- use App\Services\BalanceLogService;
- use Illuminate\Config\Repository;
- use Illuminate\Database\Capsule\Manager;
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Foundation\Application;
- use Illuminate\Http\JsonResponse;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Facade;
- use Illuminate\Translation\ArrayLoader;
- use Illuminate\Translation\Translator;
- use Illuminate\Validation\Factory;
- use Illuminate\Validation\DatabasePresenceVerifier;
- use PHPUnit\Framework\TestCase;
- /** Runs real controllers and services against SQLite only; never boots application providers. */
- class ActivityRewardEligibilityTest extends TestCase
- {
- private Application $app;
- protected function setUp(): void
- {
- Facade::clearResolvedInstances();
- $this->app = new Application(dirname(__DIR__, 2));
- $this->app->instance('config', new Repository([
- 'app' => ['locale' => 'zh', 'url' => 'https://activity.example.test', 'timezone' => 'Asia/Shanghai'],
- ]));
- Facade::setFacadeApplication($this->app);
- $db = new Manager($this->app);
- $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
- $db->setAsGlobal();
- $db->bootEloquent();
- $this->app->instance('db', $db->getDatabaseManager());
- $this->app->bind('db.schema', fn () => $db->schema());
- $translator = new Translator(new ArrayLoader(), 'zh');
- $this->app->instance('translator', $translator);
- $validator = new Factory($translator, $this->app);
- $validator->setPresenceVerifier(new DatabasePresenceVerifier($db->getDatabaseManager()));
- $this->app->instance('validator', $validator);
- $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new class {
- public function json($data, $status = 200, $headers = [], $options = 0) {
- return new JsonResponse($data, $status, $headers, $options);
- }
- });
- Request::macro('validate', function (array $rules) {
- return app('validator')->make($this->all(), $rules)->validate();
- });
- $db->schema()->create('activity_rewards', function (Blueprint $t) {
- $t->id(); $t->string('title'); $t->string('sub_title');
- $t->integer('start_time'); $t->integer('end_time'); $t->integer('status')->default(1);
- $t->integer('type')->default(1); $t->string('lang')->default('zh');
- foreach (['detail_image', 'pc_image', 'detail_banner', 'pc_banner', 'content', 'params'] as $field) {
- $t->text($field)->nullable();
- }
- $t->timestamps();
- });
- (require dirname(__DIR__, 2) . '/database/migrations/2026_10_13_120000_add_activity_eligibility_fields.php')->up();
- $db->schema()->create('users', function (Blueprint $t) {
- $t->id(); $t->string('member_id')->unique(); $t->string('phone')->default('');
- $t->string('register_domain')->default(''); $t->integer('from')->default(1);
- $t->integer('level')->default(0); $t->integer('recharge_channel_group_id')->default(1);
- $t->string('language')->default('zh'); $t->timestamps();
- });
- $db->schema()->create('user_login', function (Blueprint $t) {
- $t->id(); $t->string('user_id'); $t->string('platform')->default('');
- $t->integer('status')->default(1); $t->timestamp('logout_time')->nullable(); $t->timestamps();
- });
- $db->schema()->create('balance_logs', function (Blueprint $t) {
- $t->id(); $t->string('member_id'); $t->integer('type')->default(1);
- $t->string('change_type'); $t->decimal('amount', 20, 2);
- $t->decimal('before_balance', 20, 2)->nullable(); $t->decimal('after_balance', 20, 2)->nullable();
- $t->integer('related_id')->nullable(); $t->integer('frozen_status')->nullable();
- $t->text('remark')->nullable(); $t->timestamps();
- });
- $db->schema()->create('wallet_bonus', function (Blueprint $t) {
- $t->id(); $t->string('member_id'); $t->integer('type')->default(1);
- $t->integer('activity_id'); $t->integer('related_id')->nullable();
- $t->decimal('amount', 20, 2); $t->decimal('need_flow', 20, 2);
- $t->decimal('remaind_flow', 20, 2); $t->integer('status'); $t->timestamps();
- });
- $db->schema()->create('activity_user', function (Blueprint $t) {
- $t->id(); $t->integer('activity_id'); $t->string('member_id');
- $t->string('title'); $t->string('sub_title'); $t->text('detail_image')->nullable();
- $t->integer('start_time'); $t->integer('end_time'); $t->integer('part_in_time');
- $t->integer('finish_time')->nullable(); $t->integer('status')->default(0);
- $t->decimal('gift_amount', 20, 2)->default(0); $t->decimal('betting_amount', 20, 2)->default(0);
- $t->decimal('effective_betting_amount', 20, 2)->default(0); $t->timestamps();
- });
- $db->schema()->create('payment_orders', function (Blueprint $t) {
- $t->id(); $t->string('member_id'); $t->integer('type'); $t->integer('status');
- $t->decimal('amount', 20, 2); $t->timestamps();
- });
- $db->schema()->create('recharges', function (Blueprint $t) {
- $t->id(); $t->string('member_id'); $t->integer('status');
- $t->decimal('amount', 20, 2)->default(0); $t->timestamps();
- });
- $db->schema()->create('wallets', function (Blueprint $t) {
- $t->id(); $t->string('member_id')->unique();
- $t->decimal('available_balance', 20, 2)->default(0);
- $t->decimal('frozen_balance', 20, 2)->default(0); $t->timestamps();
- });
- (require dirname(__DIR__, 2) . '/database/migrations/2026_10_14_120000_add_activity_reward_quotas.php')->up();
- $this->request('/api/ActivityReward', []);
- }
- protected function tearDown(): void
- {
- DB::disconnect();
- Facade::clearResolvedInstances();
- parent::tearDown();
- }
- private function request(string $path, array $params, string $method = 'GET'): void
- {
- $this->app->instance('request', Request::create($path, $method, $params));
- }
- private function form(array $overrides = []): array
- {
- return $overrides + [
- 'title' => '资格测试活动', 'sub_title' => '参与资格',
- 'start_time' => '2000-01-01 00:00:00', 'end_time' => '2099-12-31 23:59:59',
- 'detail_image' => '/app.png', 'pc_image' => '/pc.png',
- 'detail_banner' => '/app-banner.png', 'pc_banner' => '/pc-banner.png',
- 'status' => 1, 'type' => 1, 'lang' => 'zh',
- ];
- }
- private function save(array $params): array
- {
- $this->request('/admin/ActivityReward/submit', $this->form($params), 'POST');
- return (new AdminActivityReward())->store()->getData(true);
- }
- private function activity(array $params = []): ActivityReward
- {
- $result = $this->save($params);
- $this->assertSame(0, $result['code'], $result['msg']);
- return ActivityReward::query()->latest('id')->first();
- }
- private function legacyActivity(array $params = []): ActivityReward
- {
- $data = $this->form($params);
- $data['start_time'] = strtotime($data['start_time']);
- $data['end_time'] = strtotime($data['end_time']);
- if (isset($data['params']) && is_array($data['params'])) $data['params'] = json_encode($data['params']);
- $id = DB::table('activity_rewards')->insertGetId($data);
- return ActivityReward::findOrFail($id);
- }
- private function member(string $id = '1001', string $registeredAt = '2026-10-01 12:34:56', string $phone = ''): void
- {
- DB::table('users')->insert([
- 'member_id' => $id, 'phone' => $phone, 'created_at' => $registeredAt, 'updated_at' => $registeredAt,
- ]);
- }
- private function login(string $id, string $platform, int $status = 1): void
- {
- DB::table('user_login')->insert([
- 'user_id' => $id, 'platform' => $platform, 'status' => $status,
- 'created_at' => '2026-10-01 12:34:56', 'updated_at' => '2026-10-01 12:34:56',
- ]);
- }
- private function deposit(string $id, string $amount, string $category = '充值', int $type = 1): void
- {
- DB::table('balance_logs')->insert([
- 'member_id' => $id, 'amount' => $amount, 'change_type' => $category, 'type' => $type,
- 'created_at' => '2026-09-01 10:00:00', 'updated_at' => '2026-09-01 10:00:00',
- ]);
- }
- private function eligibility(ActivityReward $activity, ?string $id): array
- {
- return ActivityEligibilityService::evaluate($activity, ActivityEligibilityService::memberContext($id));
- }
- private function list(array $params = []): array
- {
- $this->request('/api/ActivityReward', $params);
- $result = (new ApiActivityReward())->index()->getData(true);
- $this->assertSame(0, $result['code'], $result['msg']);
- return $result['data'];
- }
- public function test_old_forms_and_old_database_rows_keep_unrestricted_defaults(): void
- {
- $activity = $this->activity();
- $this->assertSame([], $activity->publish_platforms);
- $this->assertSame([], $activity->register_platforms);
- $this->assertFalse((bool)$activity->register_time_limited);
- $this->assertFalse((bool)$activity->deposit_limited);
- $this->assertTrue((bool)$activity->show_ineligible);
- $this->assertNull($activity->reward_quota);
- $this->assertSame(0, (int)$activity->rewarded_count);
- $this->assertTrue((bool)$activity->quota_enabled);
- $this->assertSame(0, (int)$activity->sort);
- $this->assertFalse($this->eligibility($activity, null)['is_eligible']);
- $this->assertSame('请先登录', $this->eligibility($activity, null)['ineligible_reason']);
- $this->member();
- $this->assertTrue($this->eligibility($activity, '1001')['is_eligible']);
- $this->assertTrue(ActivityEligibilityService::isPublishedOn($activity, 'PC'));
- $this->assertTrue(ActivityEligibilityService::isPublishedOn($activity, 'H5'));
- $this->assertTrue(ActivityEligibilityService::isPublishedOn($activity, 'APP'));
- DB::table('activity_rewards')->insert([
- 'title' => '旧数据', 'sub_title' => '无新字段', 'start_time' => 1, 'end_time' => 4102444799,
- 'status' => 1, 'type' => 1, 'lang' => 'zh',
- ]);
- $legacy = ActivityReward::query()->latest('id')->first();
- $this->assertFalse((bool)$legacy->quota_enabled);
- $this->assertTrue($this->eligibility($legacy, '1001')['is_eligible']);
- $this->assertCount(2, $this->list());
- $this->assertNull($legacy->publish_platforms);
- $this->assertNull($legacy->register_platforms);
- $result = $this->save(['id' => $legacy->id, 'title' => '旧数据正常编辑']);
- $this->assertSame(0, $result['code'], $result['msg']);
- $legacy->refresh();
- $this->assertSame([], $legacy->publish_platforms);
- $this->assertSame([], $legacy->register_platforms);
- $this->assertTrue((bool)$legacy->show_ineligible);
- $this->assertFalse((bool)$legacy->quota_enabled);
- }
- public function test_admin_controller_persists_all_new_fields_and_preserves_false_flags_on_omitted_update(): void
- {
- $activity = $this->activity([
- 'publish_platforms' => ['PC', 'APP'], 'reward_quota' => 1234, 'sort' => 7,
- 'register_time_limited' => 1, 'register_start_time' => '2026-10-01 12:34:56',
- 'register_end_time' => '2026-10-02 12:34:56', 'register_platforms' => ['H5'],
- 'deposit_limited' => 1, 'deposit_min' => '0.01', 'deposit_max' => '999999999999.99',
- 'show_ineligible' => 0,
- ]);
- $this->assertSame(['PC', 'APP'], $activity->publish_platforms);
- $this->assertSame(['H5'], $activity->register_platforms);
- $this->assertSame(1234, (int)$activity->reward_quota);
- $this->assertSame(7, (int)$activity->sort);
- $this->assertFalse((bool)$activity->show_ineligible);
- $this->assertTrue((bool)$activity->deposit_limited);
- $this->assertSame(0, $this->save(['id' => $activity->id, 'title' => '编辑名称'])['code']);
- $activity->refresh();
- $this->assertSame(['PC', 'APP'], $activity->publish_platforms);
- $this->assertSame(['H5'], $activity->register_platforms);
- $this->assertFalse((bool)$activity->show_ineligible);
- $this->assertTrue((bool)$activity->register_time_limited);
- $this->assertTrue((bool)$activity->deposit_limited);
- $this->assertSame(1234, (int)$activity->reward_quota);
- $this->assertSame(0, $this->save([
- 'id' => $activity->id, 'register_time_limited' => 0, 'deposit_limited' => 0,
- ])['code']);
- $this->assertSame(0, $this->save(['id' => $activity->id, 'title' => '再次编辑名称'])['code']);
- $activity->refresh();
- $this->assertFalse((bool)$activity->register_time_limited);
- $this->assertFalse((bool)$activity->deposit_limited);
- $this->assertFalse((bool)$activity->show_ineligible);
- $this->assertNull($activity->register_start_time);
- $this->assertNull($activity->register_end_time);
- $this->assertNull($activity->deposit_min);
- $this->assertNull($activity->deposit_max);
- }
- public function test_reward_quota_accepts_inclusive_integer_limits_and_nullable_unlimited(): void
- {
- foreach ([0, 2147483647, null] as $quota) {
- $activity = $this->activity(['reward_quota' => $quota]);
- $this->assertSame($quota, $activity->reward_quota);
- $this->assertSame(0, (int)$activity->rewarded_count);
- }
- }
- public function test_invalid_ranges_amount_precision_and_platform_lists_are_rejected_without_writes(): void
- {
- foreach ([
- ['publish_platforms' => 'PC'], ['publish_platforms' => ['Android']], ['publish_platforms' => null],
- ['register_platforms' => null],
- ['register_platforms' => ['WEB']], ['register_platforms' => [['PC']]],
- ['reward_quota' => -1], ['reward_quota' => '1.001'], ['reward_quota' => '1e2'],
- ['reward_quota' => 2147483648], ['reward_quota' => []],
- ['budget' => '1.00'],
- ['sort' => -1], ['sort' => '1.5'], ['show_ineligible' => 2],
- ['register_time_limited' => 1],
- ['register_time_limited' => 1, 'register_start_time' => '2026-10-02', 'register_end_time' => '2026-10-01'],
- ['register_time_limited' => 1, 'register_start_time' => 'not-a-date', 'register_end_time' => '2026-10-01'],
- ['deposit_limited' => 1, 'deposit_min' => '100.01', 'deposit_max' => '100.00'],
- ['deposit_limited' => 1, 'deposit_min' => '-0.01'],
- ['deposit_limited' => 1, 'deposit_max' => '100.001'],
- ['deposit_limited' => 1, 'deposit_max' => '1000000000000.00'],
- ['deposit_limited' => 1, 'deposit_min' => '1.00'],
- ['deposit_limited' => 1, 'deposit_max' => '100.00'],
- ] as $invalid) {
- $result = $this->save($invalid);
- $this->assertNotSame(0, $result['code'], json_encode($invalid));
- $this->assertSame(0, DB::table('activity_rewards')->count(), json_encode($invalid));
- }
- }
- public function test_partial_update_validates_against_retained_bound_and_service_cannot_bypass_validation(): void
- {
- $activity = $this->activity(['deposit_limited' => 1, 'deposit_min' => '10.00', 'deposit_max' => '20.00']);
- $this->assertNotSame(0, $this->save(['id' => $activity->id, 'deposit_min' => '20.01'])['code']);
- $activity->refresh();
- $this->assertSame('10.00', (string)$activity->deposit_min);
- $this->assertSame('20.00', (string)$activity->deposit_max);
- try {
- ActivityRewardService::submit(['id' => $activity->id, 'deposit_max' => '-1.00']);
- $this->fail('Direct service writes must reject invalid eligibility configuration.');
- } catch (\Exception $e) {
- $this->assertNotSame('', $e->getMessage());
- }
- $activity->refresh();
- $this->assertSame('20.00', (string)$activity->deposit_max);
- }
- public function test_football_type_ignores_even_invalid_new_fields_and_resets_existing_limits(): void
- {
- $invalidFields = [
- 'publish_platforms' => 'invalid', 'reward_quota' => 'invalid', 'sort' => -1,
- 'register_time_limited' => 'invalid', 'register_start_time' => 'invalid',
- 'register_end_time' => 'invalid', 'register_platforms' => ['invalid'],
- 'deposit_limited' => 'invalid', 'deposit_min' => -1, 'deposit_max' => 'invalid',
- 'show_ineligible' => 'invalid',
- ];
- $football = $this->activity(['type' => 2] + $invalidFields);
- $this->assertSame([], $football->publish_platforms);
- $this->assertSame([], $football->register_platforms);
- $this->assertFalse((bool)$football->register_time_limited);
- $this->assertFalse((bool)$football->deposit_limited);
- $this->assertTrue((bool)$football->show_ineligible);
- $this->assertNull($football->reward_quota);
- $this->assertSame(0, (int)$football->sort);
- $this->assertTrue($this->eligibility($football, null)['is_eligible']);
- $this->assertTrue(ActivityEligibilityService::isPublishedOn($football, 'PC'));
- $restricted = $this->activity(['register_platforms' => ['APP'], 'deposit_limited' => 1, 'deposit_min' => 100, 'deposit_max' => 200]);
- $this->assertSame(0, $this->save(['id' => $restricted->id, 'type' => 2] + $invalidFields)['code']);
- $restricted->refresh();
- $this->assertSame([], $restricted->register_platforms);
- $this->assertFalse((bool)$restricted->deposit_limited);
- $this->assertTrue($this->eligibility($restricted, null)['is_eligible']);
- }
- public function test_registration_datetime_is_exact_and_both_boundaries_are_inclusive(): void
- {
- $activity = $this->activity([
- 'register_time_limited' => 1, 'register_start_time' => '2026-10-01 12:34:56',
- 'register_end_time' => '2026-10-01 12:34:57',
- ]);
- foreach ([['1001', '12:34:55', false], ['1002', '12:34:56', true],
- ['1003', '12:34:57', true], ['1004', '12:34:58', false]] as [$id, $time, $eligible]) {
- $this->member($id, '2026-10-01 ' . $time);
- $result = $this->eligibility($activity, $id);
- $this->assertSame($eligible, $result['is_eligible'], $time);
- $this->assertSame($eligible, $result['ineligible_reason'] === '');
- }
- }
- public function test_lifetime_deposit_uses_wallet_currency_ledger_categories_and_inclusive_cents(): void
- {
- $this->member();
- $this->deposit('1001', '150.00');
- $this->deposit('1001', '25.23', '三方充值');
- $this->deposit('1001', '26.00', '人工充值');
- $this->deposit('1001', '9999.00', '注册赠送');
- $this->deposit('1001', '8888.00', '优惠活动');
- $this->deposit('1001', '7777.00', '充值', 2);
- $this->deposit('1001', '-55.00', '投注');
- DB::table('payment_orders')->insert(['member_id' => '1001', 'type' => 1, 'status' => 2, 'amount' => 777]);
- DB::table('recharges')->insert(['member_id' => '1001', 'status' => 1, 'amount' => 222]);
- $activity = $this->activity(['deposit_limited' => 1, 'deposit_min' => '201.23', 'deposit_max' => '201.23']);
- $this->assertTrue($this->eligibility($activity, '1001')['is_eligible']);
- foreach ([['deposit_min' => '201.24', 'deposit_max' => '999999999999.99'],
- ['deposit_min' => '0.00', 'deposit_max' => '201.22']] as $limits) {
- $this->assertSame(0, $this->save(['id' => $activity->id] + $limits)['code']);
- $activity->refresh();
- $this->assertFalse($this->eligibility($activity, '1001')['is_eligible']);
- }
- }
- public function test_zero_deposit_is_supported_and_enabled_ranges_require_both_bounds(): void
- {
- $this->member();
- $activity = $this->activity(['deposit_limited' => 1, 'deposit_min' => '0.00', 'deposit_max' => '0.00']);
- $this->assertTrue($this->eligibility($activity, '1001')['is_eligible']);
- $this->assertNotSame(0, $this->save(['deposit_limited' => 1, 'deposit_min' => '1.00'])['code']);
- $this->assertNotSame(0, $this->save(['deposit_limited' => 1, 'deposit_max' => '0.00'])['code']);
- $this->assertSame(1, DB::table('activity_rewards')->count());
- }
- public function test_registration_platform_uses_first_successful_login_and_groups_ios_android_as_app(): void
- {
- $activity = $this->activity(['register_platforms' => ['APP']]);
- $this->member('1001');
- $this->login('1001', 'PC', 0);
- $this->login('1001', 'iOS');
- $this->login('1001', 'PC');
- $this->assertTrue($this->eligibility($activity, '1001')['is_eligible']);
- $this->member('1002');
- $this->login('1002', 'Android');
- $this->assertTrue($this->eligibility($activity, '1002')['is_eligible']);
- $this->member('1003');
- $this->login('1003', 'H5');
- $this->login('1003', 'Android');
- $this->assertFalse($this->eligibility($activity, '1003')['is_eligible']);
- $this->member('1004');
- DB::table('users')->where('member_id', '1004')->update(['register_domain' => 'com.example.app']);
- $this->assertFalse($this->eligibility($activity, '1004')['is_eligible']);
- $this->member('1005');
- $this->login('1005', '');
- $this->login('1005', 'Android');
- $this->assertFalse($this->eligibility($activity, '1005')['is_eligible']);
- $h5 = $this->activity(['register_platforms' => ['H5']]);
- $this->member('1006');
- $this->login('1006', 'WeChat');
- $this->assertTrue($this->eligibility($h5, '1006')['is_eligible']);
- }
- public function test_guest_and_member_display_choices_and_sort_order_are_enforced_by_controller(): void
- {
- $this->member();
- $this->deposit('1001', '100.00');
- $unrestricted = $this->activity(['sort' => 1]);
- $hidden = $this->activity(['sort' => 9, 'deposit_limited' => 1, 'deposit_min' => '100.01', 'deposit_max' => '200.00', 'show_ineligible' => 0]);
- $shown = $this->activity(['sort' => 7, 'deposit_limited' => 1, 'deposit_min' => '100.01', 'deposit_max' => '200.00', 'show_ineligible' => 1]);
- $eligible = $this->activity(['sort' => 7, 'deposit_limited' => 1, 'deposit_min' => '100.00', 'deposit_max' => '200.00', 'show_ineligible' => 0]);
- $this->activity(['type' => 2, 'sort' => 99]);
- $this->activity(['status' => 0]);
- $guest = $this->list();
- $this->assertSame([$shown->id, $unrestricted->id], array_column($guest, 'id'));
- $this->assertFalse($guest[0]['is_eligible']);
- $this->assertNotSame('', $guest[0]['ineligible_reason']);
- $this->assertFalse($guest[1]['is_eligible']);
- $this->assertSame('请先登录', $guest[1]['ineligible_reason']);
- $member = $this->list(['member_id' => '1001']);
- $this->assertSame([$eligible->id, $shown->id, $unrestricted->id], array_column($member, 'id'));
- $this->assertNotContains($hidden->id, array_column($member, 'id'));
- $this->assertTrue($member[0]['is_eligible']);
- $this->assertSame('', $member[0]['ineligible_reason']);
- $this->assertFalse($member[1]['is_eligible']);
- $this->assertFalse($member[0]['is_claimed']);
- }
- public function test_publication_platform_filter_is_independent_of_member_registration_platform(): void
- {
- $this->member();
- $this->login('1001', 'iOS');
- $pc = $this->activity(['publish_platforms' => ['PC'], 'register_platforms' => ['APP']]);
- $h5 = $this->activity(['publish_platforms' => ['H5']]);
- $app = $this->activity(['publish_platforms' => ['APP']]);
- $all = $this->activity();
- $this->assertTrue(ActivityEligibilityService::isPublishedOn($pc, 'PC'));
- $this->assertFalse(ActivityEligibilityService::isPublishedOn($pc, 'APP'));
- $this->assertTrue($this->eligibility($pc, '1001')['is_eligible']);
- foreach ([['PC', $pc], ['H5', $h5], ['APP', $app]] as [$platform, $specific]) {
- $rows = $this->list(['member_id' => '1001', 'platform' => $platform]);
- $this->assertSame([$all->id, $specific->id], array_column($rows, 'id'), $platform);
- }
- $this->assertSame([$all->id], array_column($this->list(['member_id' => '1001']), 'id'));
- $this->request('/api/ActivityReward', ['platform' => 'INVALID']);
- $this->assertNotSame(0, (new ApiActivityReward())->index()->getData(true)['code']);
- }
- public function test_participation_rejects_ineligible_even_when_shown_and_before_existing_phone_checks(): void
- {
- $this->member();
- $activity = $this->activity(['register_platforms' => ['APP'], 'show_ineligible' => 1]);
- $reason = $this->eligibility($activity, '1001')['ineligible_reason'];
- $this->request('/api/ActivityReward/participate', ['member_id' => '1001', 'activity_id' => $activity->id], 'POST');
- $result = (new ApiActivityReward())->participate()->getData(true);
- $this->assertNotSame(0, $result['code']);
- $this->assertSame($reason, $result['msg']);
- $this->assertNotSame(HttpStatus::NOT_BIND_PHONE, $result['code']);
- $this->assertSame(0, DB::table('activity_user')->count());
- $this->login('1001', 'Android');
- $this->request('/api/ActivityReward/participate', ['member_id' => '1001', 'activity_id' => $activity->id], 'POST');
- $this->assertSame(HttpStatus::NOT_BIND_PHONE, (new ApiActivityReward())->participate()->getData(true)['code']);
- }
- public function test_eligible_member_can_submit_activity_and_list_retains_claimed_state(): void
- {
- $this->member('1001', '2026-10-01 12:34:56', '15500001001');
- $this->login('1001', 'PC');
- $this->deposit('1001', '100.00');
- DB::table('payment_orders')->insert(['member_id' => '1001', 'type' => 1, 'status' => 2, 'amount' => '100.00']);
- $activity = $this->activity(['register_platforms' => ['PC'], 'deposit_limited' => 1, 'deposit_min' => '100.00', 'deposit_max' => '200.00', 'reward_quota' => 1]);
- $this->request('/api/ActivityReward/participate', ['member_id' => '1001', 'activity_id' => $activity->id], 'POST');
- $result = (new ApiActivityReward())->participate()->getData(true);
- $this->assertSame(0, $result['code'], $result['msg']);
- $this->assertSame(1, DB::table('activity_user')->count());
- $this->assertSame(0, (int)$activity->fresh()->rewarded_count);
- $this->assertSame(0, DB::table('activity_reward_recipients')->count());
- $rows = $this->list(['member_id' => '1001']);
- $this->assertTrue($rows[0]['is_eligible']);
- $this->assertTrue($rows[0]['is_claimed']);
- }
- public function test_automatic_recharge_and_old_member_rewards_check_eligibility_before_bonus_side_effects(): void
- {
- $this->member();
- $this->deposit('1001', '100.00');
- $this->activity([
- 'type' => 3, 'deposit_limited' => 1, 'deposit_min' => '100.01', 'deposit_max' => '200.00',
- 'params' => ['reward_ratio' => 5, 'min_recharge_amount' => 0, 'reward_turnover_ratio' => 1],
- ]);
- $this->activity([
- 'type' => 4, 'register_platforms' => ['APP'],
- 'params' => ['no_login_days' => 1, 'reward_rules' => [['start_level' => 0, 'end_level' => 5, 'bonus' => 10]]],
- ]);
- $this->assertFalse(BalanceLogService::calculateRechargeBonus('100.00', '1001', 123));
- $this->assertFalse(BalanceLogService::calculateUserReturnRechargeBonus('100.00', '1001', 1, 123));
- $this->assertSame(0, DB::table('wallet_bonus')->count());
- $this->assertSame(1, DB::table('balance_logs')->count());
- }
- /** Exercise the real addLog entry without relying on a caller-owned transaction. */
- private function automaticRewardFixtures(): array
- {
- $schema = DB::connection()->getSchemaBuilder();
- $schema->create('config', function (Blueprint $t) {
- $t->id(); $t->string('field'); $t->string('val'); $t->timestamps();
- });
- $schema->create('level', function (Blueprint $t) {
- $t->id(); $t->integer('level'); $t->decimal('recharge', 20, 2); $t->timestamps();
- });
- $schema->create('recharge_channel_group', function (Blueprint $t) {
- $t->id(); $t->text('activity_type'); $t->softDeletes(); $t->timestamps();
- });
- $schema->create('backflow', function (Blueprint $t) {
- $t->id(); $t->string('member_id'); $t->string('date');
- foreach (['recharge_amount', 'withdrawal_amount', 'backflow_ratio', 'amount'] as $field) {
- $t->decimal($field, 20, 2)->default(0);
- }
- $t->timestamps();
- });
- DB::table('config')->insert([
- ['field' => 'huishui_percentage', 'val' => '0'],
- ['field' => 'huishui_restriction', 'val' => '999999'],
- ['field' => 'recharge_rate', 'val' => '0'],
- ]);
- DB::table('level')->insert(['level' => 0, 'recharge' => '0']);
- DB::table('recharge_channel_group')->insert(['id' => 1, 'activity_type' => 'recharge,old_user']);
- DB::table('backflow')->insert(['member_id' => '1001', 'date' => date('Y-m')]);
- $this->member();
- DB::table('wallets')->insert(['member_id' => '1001', 'available_balance' => '100.00', 'frozen_balance' => '2.00']);
- foreach ([date('Y-m-d 00:00:00', strtotime('-14 days')), date('Y-m-d 00:00:00')] as $loggedAt) {
- DB::table('user_login')->insert([
- 'user_id' => '1001', 'status' => 1, 'platform' => 'PC',
- 'created_at' => $loggedAt, 'updated_at' => $loggedAt,
- ]);
- }
- return [
- $this->activity(['type' => 3, 'reward_quota' => 1,
- 'params' => ['reward_ratio' => 5, 'reward_turnover_ratio' => 1]]),
- $this->activity(['type' => 4, 'reward_quota' => 1,
- 'params' => ['no_login_days' => 7,
- 'reward_rules' => [['start_level' => 0, 'end_level' => 0, 'bonus' => '7.00', 'turnover_rate' => 1]]]]),
- ];
- }
- public static function automaticRewardWriteFailures(): array
- {
- return [
- 'USDT wallet save failure' => ['充值', 'wallet'],
- 'third-party wallet save failure' => ['三方充值', 'wallet'],
- 'recharge reward ledger failure' => ['充值', '即充即送'],
- 'return reward ledger failure after first award' => ['三方充值', '老用户回归'],
- ];
- }
- /** @dataProvider automaticRewardWriteFailures */
- public function test_automatic_reward_failure_rolls_back_recipients_count_bonus_ledger_and_wallet(string $category, string $failure): void
- {
- [$recharge, $return] = $this->automaticRewardFixtures();
- if ($failure === 'wallet') {
- DB::statement("CREATE TRIGGER fail_reward_wallet BEFORE UPDATE ON bot_wallets
- WHEN NEW.frozen_balance > OLD.frozen_balance
- BEGIN SELECT RAISE(ABORT, 'injected reward write failure'); END");
- } else {
- DB::statement("CREATE TRIGGER fail_reward_ledger BEFORE INSERT ON bot_balance_logs
- WHEN NEW.change_type = '$failure'
- BEGIN SELECT RAISE(ABORT, 'injected reward write failure'); END");
- }
- $this->assertSame(0, DB::transactionLevel());
- try {
- BalanceLogService::addLog('1001', '100.00', '0.00', '100.00', $category, 900, '');
- $this->fail('The injected database write failure must reach the caller.');
- } catch (\Illuminate\Database\QueryException $e) {
- $this->assertStringContainsString('injected reward write failure', $e->getMessage());
- }
- $this->assertSame(0, DB::transactionLevel());
- $this->assertSame(0, (int)$recharge->fresh()->rewarded_count);
- $this->assertSame(0, (int)$return->fresh()->rewarded_count);
- $this->assertSame(0, DB::table('activity_reward_recipients')->count());
- $this->assertSame(0, DB::table('wallet_bonus')->count());
- $this->assertSame(0, DB::table('balance_logs')->where('type', 2)->count());
- $this->assertEquals('2.00', DB::table('wallets')->value('frozen_balance'));
- $this->assertEquals('100.00', DB::table('wallets')->value('available_balance'));
- // The completed principal deposit stays recorded when only rewards fail.
- $this->assertSame(1, DB::table('balance_logs')->where('change_type', $category)->count());
- }
- public function test_automatic_rewards_commit_one_recipient_per_activity_with_bonus_ledgers_and_wallet(): void
- {
- [$recharge, $return] = $this->automaticRewardFixtures();
- BalanceLogService::addLog('1001', '100.00', '0.00', '100.00', '充值', 900, '');
- $this->assertSame(0, DB::transactionLevel());
- $this->assertSame(1, (int)$recharge->fresh()->rewarded_count);
- $this->assertSame(1, (int)$return->fresh()->rewarded_count);
- $this->assertSame(2, DB::table('activity_reward_recipients')->where('member_id', '1001')->count());
- $this->assertEquals('14.00', DB::table('wallets')->value('frozen_balance'));
- $this->assertEquals('100.00', DB::table('wallets')->value('available_balance'));
- $this->assertSame(2, DB::table('wallet_bonus')->count());
- $this->assertEquals('12.00', DB::table('wallet_bonus')->sum('amount'));
- $this->assertEquals('12.00', DB::table('balance_logs')->where('type', 2)->sum('amount'));
- $this->assertEquals('2.00', DB::table('balance_logs')->where('change_type', '即充即送')->value('before_balance'));
- $this->assertEquals('7.00', DB::table('balance_logs')->where('change_type', '老用户回归')->value('before_balance'));
- $this->assertSame(1, DB::table('balance_logs')->where('change_type', '充值')->count());
- }
- public function test_automatic_reward_transaction_respects_an_existing_caller_transaction(): void
- {
- [$recharge, $return] = $this->automaticRewardFixtures();
- DB::beginTransaction();
- BalanceLogService::addLog('1001', '100.00', '0.00', '100.00', '三方充值', 900, '');
- $this->assertSame(1, DB::transactionLevel());
- $this->assertEquals('14.00', DB::table('wallets')->value('frozen_balance'));
- DB::rollBack();
- $this->assertSame(0, (int)$recharge->fresh()->rewarded_count);
- $this->assertSame(0, (int)$return->fresh()->rewarded_count);
- $this->assertSame(0, DB::table('activity_reward_recipients')->count());
- $this->assertEquals('2.00', DB::table('wallets')->value('frozen_balance'));
- $this->assertEquals('100.00', DB::table('wallets')->value('available_balance'));
- $this->assertSame(0, DB::table('wallet_bonus')->count());
- $this->assertSame(0, DB::table('balance_logs')->count());
- }
- public function test_automatic_recharge_uses_already_posted_current_deposit_once(): void
- {
- $this->member();
- $this->deposit('1001', '100.00');
- $activity = $this->activity([
- 'type' => 3, 'deposit_limited' => 1, 'deposit_min' => '100.00', 'deposit_max' => '100.00',
- 'params' => ['reward_ratio' => 5, 'min_recharge_amount' => 0, 'reward_turnover_ratio' => 1],
- ]);
- $this->assertEquals('5.00', BalanceLogService::calculateRechargeBonus('100.00', '1001', 123));
- $this->assertSame(1, DB::table('wallet_bonus')->where('activity_id', $activity->id)->count());
- $this->assertEquals(5, DB::table('wallet_bonus')->value('amount'));
- $this->assertSame(1, DB::table('balance_logs')->count());
- }
- public function test_automatic_selection_skips_higher_sorted_ineligible_and_exhausted_activities(): void
- {
- $this->member();
- $this->login('1001', 'PC');
- $this->deposit('1001', '100.00');
- $rewardParams = ['reward_ratio' => 5, 'min_recharge_amount' => 0, 'reward_turnover_ratio' => 1];
- $lower = $this->activity([
- 'type' => 3, 'sort' => 1, 'reward_quota' => 2, 'register_platforms' => ['PC'], 'params' => $rewardParams,
- ]);
- $higher = $this->activity([
- 'type' => 3, 'sort' => 2, 'reward_quota' => 100, 'register_platforms' => ['APP'], 'params' => $rewardParams,
- ]);
- $this->assertSame($lower->id, ActivityRewardService::activeForMember(3, '1001')->id);
- $this->assertEquals('5.00', BalanceLogService::calculateRechargeBonus('100.00', '1001', 123));
- $lower->refresh();
- $higher->refresh();
- $this->assertSame(1, (int)$lower->rewarded_count);
- $this->assertSame(0, (int)$higher->rewarded_count);
- $this->assertSame(0, $this->save([
- 'id' => $higher->id, 'type' => 3, 'reward_quota' => 0, 'register_platforms' => ['PC'], 'params' => $rewardParams,
- ])['code']);
- $higher->refresh();
- $this->assertTrue($this->eligibility($higher, '1001')['is_eligible']);
- $this->assertSame($lower->id, ActivityRewardService::activeForMember(3, '1001')->id);
- $this->assertEquals('5.00', BalanceLogService::calculateRechargeBonus('100.00', '1001', 124));
- $lower->refresh();
- $higher->refresh();
- $this->assertSame(1, (int)$lower->rewarded_count);
- $this->assertSame(0, (int)$higher->rewarded_count);
- $this->assertSame(2, DB::table('wallet_bonus')->where('activity_id', $lower->id)->count());
- $this->assertSame(0, DB::table('wallet_bonus')->where('activity_id', $higher->id)->count());
- }
- public function test_ten_distinct_members_take_ten_slots_and_eleventh_is_denied_using_stale_model(): void
- {
- $activity = $this->activity(['reward_quota' => 10]);
- $grants = [];
- for ($member = 1; $member <= 10; $member++) {
- $id = (string)(1000 + $member);
- $this->member($id);
- $amount = $member % 2 ? '0.01' : '12345.67';
- $this->assertTrue(ActivityQuotaService::canAward($activity->fresh(), $id));
- $this->assertTrue(ActivityQuotaService::award($activity, $id, $amount, function () use (&$grants, $id) {
- $grants[] = $id;
- }));
- }
- $this->member('1011');
- $this->assertFalse(ActivityQuotaService::canAward($activity->fresh(), '1011'));
- $this->assertFalse(ActivityQuotaService::award($activity, '1011', '0.01', function () { $this->fail('Eleventh member must be denied.'); }));
- $this->assertSame(range(1001, 1010), array_map('intval', $grants));
- $this->assertSame(10, (int)$activity->fresh()->rewarded_count);
- $this->assertSame(10, DB::table('activity_reward_recipients')->where('activity_id', $activity->id)->count());
- }
- public function test_repeat_rewards_take_one_slot_and_same_member_counts_separately_in_each_activity(): void
- {
- $this->member();
- $first = $this->activity(['reward_quota' => 1]);
- $second = $this->activity(['reward_quota' => 1]);
- $grants = 0;
- foreach (['1.00', '2.50', '1000.00'] as $amount) {
- $this->assertTrue(ActivityQuotaService::award($first, '1001', $amount, function () use (&$grants) { $grants++; }));
- }
- $this->assertTrue(ActivityQuotaService::canAward($first->fresh(), '1001'));
- $this->assertFalse(ActivityQuotaService::canAward($first->fresh(), '1002'));
- $this->assertTrue(ActivityQuotaService::award($second, '1001', '0.01', function () use (&$grants) { $grants++; }));
- $this->assertSame(4, $grants);
- $this->assertSame(1, (int)$first->fresh()->rewarded_count);
- $this->assertSame(1, (int)$second->fresh()->rewarded_count);
- $this->assertSame(2, DB::table('activity_reward_recipients')->where('member_id', '1001')->count());
- }
- /** Checks SQL lock intent only; SQLite cannot reproduce MySQL repeatable-read snapshots. */
- public function test_award_locks_activity_then_recipient_for_current_read_but_precheck_does_not_lock(): void
- {
- $activity = $this->activity(['reward_quota' => 1]);
- $grammar = new class extends \Illuminate\Database\Query\Grammars\SQLiteGrammar {
- public array $reads = [];
- public function compileSelect(\Illuminate\Database\Query\Builder $query)
- {
- if (in_array($query->from, ['activity_rewards', 'activity_reward_recipients'], true)) {
- $this->reads[] = ['table' => $query->from, 'lock' => $query->lock];
- }
- return parent::compileSelect($query);
- }
- };
- $grammar->setTablePrefix(DB::connection()->getTablePrefix());
- DB::connection()->setQueryGrammar($grammar);
- $this->assertTrue(ActivityQuotaService::canAward($activity, '1001'));
- $this->assertSame([['table' => 'activity_reward_recipients', 'lock' => null]], $grammar->reads);
- $grammar->reads = [];
- $this->assertTrue(ActivityQuotaService::award($activity, '1001', '1.00', function () {}));
- $this->assertSame([
- ['table' => 'activity_rewards', 'lock' => true],
- ['table' => 'activity_reward_recipients', 'lock' => true],
- ], $grammar->reads);
- $grammar->reads = [];
- $this->assertTrue(ActivityQuotaService::award($activity, '1001', '2.00', function () {}));
- $this->assertSame([
- ['table' => 'activity_rewards', 'lock' => true],
- ['table' => 'activity_reward_recipients', 'lock' => true],
- ], $grammar->reads);
- $fresh = $activity->fresh();
- $this->assertSame(1, (int)$fresh->rewarded_count);
- $grammar->reads = [];
- $this->assertTrue(ActivityQuotaService::canAward($fresh, '1001'));
- $this->assertSame([['table' => 'activity_reward_recipients', 'lock' => null]], $grammar->reads);
- }
- public function test_quota_rejects_invalid_award_precision_amounts_and_empty_members_without_grant(): void
- {
- $activity = $this->activity(['reward_quota' => 1]);
- foreach (['1.009', '1e0', '-0.01', '0', '0.00', '1000000000000.00', 'not-an-amount'] as $amount) {
- $this->assertFalse(ActivityQuotaService::award($activity, '1001', $amount, function () use ($amount) {
- $this->fail('Invalid award must not invoke grant: ' . $amount);
- }), $amount);
- $this->assertSame(0, (int)$activity->fresh()->rewarded_count, $amount);
- $this->assertSame(0, DB::table('activity_reward_recipients')->count());
- }
- foreach ([null, ''] as $id) {
- $this->assertFalse(ActivityQuotaService::canAward($activity, $id));
- $this->assertFalse(ActivityQuotaService::award($activity, $id, '1.00', function () { $this->fail('Missing member must not take a slot.'); }));
- }
- }
- public function test_failed_grant_rolls_back_recipient_counter_wallet_and_bonus_ledger(): void
- {
- $this->member();
- DB::table('wallets')->insert(['member_id' => '1001', 'available_balance' => '50.00']);
- $activity = $this->activity(['reward_quota' => 1]);
- try {
- ActivityQuotaService::award($activity, '1001', '2.50', function () use ($activity) {
- DB::table('wallets')->where('member_id', '1001')->update(['available_balance' => '52.50']);
- $this->deposit('1001', '2.50', '优惠活动');
- DB::table('wallet_bonus')->insert([
- 'member_id' => '1001', 'activity_id' => $activity->id, 'amount' => '2.50',
- 'need_flow' => '2.50', 'remaind_flow' => '2.50', 'status' => 1,
- ]);
- throw new \RuntimeException('fixture grant failed');
- });
- $this->fail('Grant failures must propagate so callers can roll back the reward.');
- } catch (\RuntimeException $e) {
- $this->assertSame('fixture grant failed', $e->getMessage());
- }
- $this->assertSame(0, DB::table('balance_logs')->count());
- $this->assertSame(0, DB::table('wallet_bonus')->count());
- $this->assertSame(0, DB::table('activity_reward_recipients')->count());
- $this->assertSame(0, (int)$activity->fresh()->rewarded_count);
- $this->assertEquals('50.00', DB::table('wallets')->value('available_balance'));
- $this->assertTrue(ActivityQuotaService::canAward($activity->fresh(), '1001'));
- $this->assertTrue(ActivityQuotaService::award($activity, '1001', '10.00', function () {}));
- $this->assertSame(1, (int)$activity->fresh()->rewarded_count);
- }
- public function test_outer_rollback_releases_recipient_and_count_with_reward_writes(): void
- {
- $activity = $this->activity(['reward_quota' => 1]);
- DB::beginTransaction();
- $this->assertTrue(ActivityQuotaService::award($activity, '1001', '1.00', function () { $this->deposit('1001', '1.00', '优惠活动'); }));
- $this->assertSame(1, DB::transactionLevel());
- $this->assertSame(1, (int)$activity->fresh()->rewarded_count);
- $this->assertSame(1, DB::table('activity_reward_recipients')->count());
- DB::rollBack();
- $this->assertSame(0, (int)$activity->fresh()->rewarded_count);
- $this->assertSame(0, DB::table('activity_reward_recipients')->count());
- $this->assertSame(0, DB::table('balance_logs')->count());
- }
- public function test_zero_quota_blocks_new_members_unlimited_counts_members_and_football_bypasses_quota(): void
- {
- $zero = $this->activity(['reward_quota' => 0]);
- $this->assertFalse(ActivityQuotaService::canAward($zero, '1001'));
- $this->assertFalse(ActivityQuotaService::award($zero, '1001', '0.01', function () { $this->fail('Zero quota must block new recipients.'); }));
- $unlimited = $this->activity();
- foreach (['1001', '1002', '1001'] as $id) {
- $this->assertTrue(ActivityQuotaService::award($unlimited, $id, '100.50', function () {}));
- }
- $this->assertNull($unlimited->fresh()->reward_quota);
- $this->assertSame(2, (int)$unlimited->fresh()->rewarded_count);
- $football = $this->activity(['type' => 2, 'reward_quota' => 0]);
- $granted = false;
- $this->assertTrue(ActivityQuotaService::award($football, '1001', '1.00', function () use (&$granted) { $granted = true; }));
- $this->assertTrue($granted);
- $this->assertSame(0, (int)$football->fresh()->rewarded_count);
- $this->assertSame(0, DB::table('activity_reward_recipients')->where('activity_id', $football->id)->count());
- }
- public function test_lowering_quota_below_occupied_count_preserves_existing_recipient_and_rejects_new_member(): void
- {
- $activity = $this->activity(['reward_quota' => 2]);
- foreach (['1001', '1002'] as $id) {
- $this->assertTrue(ActivityQuotaService::award($activity, $id, '1.00', function () {}));
- }
- $this->assertSame(0, $this->save(['id' => $activity->id, 'reward_quota' => 0])['code']);
- $activity->refresh();
- $this->assertTrue(ActivityQuotaService::canAward($activity, '1001'));
- $this->assertFalse(ActivityQuotaService::canAward($activity, '1003'));
- $this->assertTrue(ActivityQuotaService::award($activity, '1001', '2.50', function () {}));
- $this->assertFalse(ActivityQuotaService::award($activity, '1003', '0.01', function () { $this->fail('Reduced quota must block new recipients.'); }));
- $this->assertSame(2, (int)$activity->fresh()->rewarded_count);
- $this->assertSame(2, DB::table('activity_reward_recipients')->count());
- }
- public function test_admin_edits_cannot_reset_readonly_recipient_count_or_use_legacy_money_budget(): void
- {
- $activity = $this->activity(['reward_quota' => 1]);
- $this->assertTrue(ActivityQuotaService::award($activity, '1001', '8.00', function () {}));
- $result = $this->save(['id' => $activity->id, 'rewarded_count' => 0, 'reward_quota' => 2,
- 'quota_enabled' => 0, 'budget_used' => '10.00']);
- $this->assertSame(0, $result['code'], $result['msg']);
- $this->assertSame(1, (int)$activity->fresh()->rewarded_count);
- $this->assertSame(2, (int)$activity->fresh()->reward_quota);
- $this->assertTrue((bool)$activity->fresh()->quota_enabled);
- $this->assertSame('0.00', (string)$activity->fresh()->budget_used);
- ActivityRewardService::submit(['id' => $activity->id, 'rewarded_count' => 0]);
- $this->assertSame(1, (int)$activity->fresh()->rewarded_count);
- $this->assertNotSame(0, $this->save(['id' => $activity->id, 'budget' => '10.00'])['code']);
- $this->assertSame(1, (int)$activity->fresh()->rewarded_count);
- // Mixed-mode APIs retain old fields, with the server-owned mode identifying the rules.
- $this->request('/admin/ActivityReward', ['page' => 1, 'limit' => 10]);
- $admin = (new AdminActivityReward())->index()->getData(true);
- $this->assertSame(0, $admin['code'], $admin['msg']);
- foreach ([$admin['data']['data'][0], $this->list(['member_id' => '1001'])[0]] as $row) {
- $this->assertNull($row['budget']);
- $this->assertSame('0.00', (string)$row['budget_used']);
- $this->assertTrue((bool)$row['quota_enabled']);
- $this->assertSame(2, (int)$row['reward_quota']);
- $this->assertSame(1, (int)$row['rewarded_count']);
- }
- }
- public function test_automatic_rewards_stop_for_new_members_at_quota_but_repeat_reward_keeps_one_slot(): void
- {
- foreach (['1001', '1002'] as $id) {
- $this->member($id);
- $this->deposit($id, '100.00');
- }
- $params = ['reward_ratio' => 5, 'min_recharge_amount' => 0, 'reward_turnover_ratio' => 1];
- $activity = $this->activity(['type' => 3, 'reward_quota' => 0, 'params' => $params]);
- $this->assertFalse(BalanceLogService::calculateRechargeBonus('100.00', '1001', 123));
- $this->assertSame(0, DB::table('wallet_bonus')->count());
- $this->assertSame(0, (int)$activity->fresh()->rewarded_count);
- $this->assertSame(0, $this->save(['id' => $activity->id, 'type' => 3, 'reward_quota' => 1, 'params' => $params])['code']);
- $this->assertEquals('5.00', BalanceLogService::calculateRechargeBonus('100.00', '1001', 123));
- $this->assertEquals('10.00', BalanceLogService::calculateRechargeBonus('200.00', '1001', 124));
- $this->assertFalse(BalanceLogService::calculateRechargeBonus('100.00', '1002', 125));
- $this->assertSame(2, DB::table('wallet_bonus')->count());
- $this->assertSame(1, (int)$activity->fresh()->rewarded_count);
- $this->assertSame(1, DB::table('activity_reward_recipients')->where('activity_id', $activity->id)->count());
- }
- public function test_manual_gift_rechecks_eligibility_and_quota_before_wallet_and_application_changes(): void
- {
- $this->member();
- DB::table('wallets')->insert(['member_id' => '1001', 'available_balance' => '50.00']);
- foreach ([['register_platforms' => ['APP']], ['reward_quota' => 0]] as $limits) {
- $activity = $this->activity($limits);
- $applicationId = DB::table('activity_user')->insertGetId([
- 'member_id' => '1001', 'activity_id' => $activity->id, 'status' => 0,
- 'title' => '待赠送', 'sub_title' => '资格检查', 'detail_image' => '/app.png',
- 'start_time' => 1, 'end_time' => 4102444799, 'part_in_time' => time(),
- ]);
- $this->request('/admin/ActivityUser/gift', ['id' => $applicationId, 'amount' => '1.00', 'betting_amount' => 1], 'POST');
- $result = (new AdminActivityUser())->gift()->getData(true);
- $this->assertSame(HttpStatus::CUSTOM_ERROR, $result['code'], $result['msg']);
- $this->assertSame(0, (int)DB::table('activity_user')->where('id', $applicationId)->value('status'));
- $this->assertEquals('50.00', DB::table('wallets')->value('available_balance'));
- $this->assertSame(0, DB::table('balance_logs')->count());
- $activity->refresh();
- $this->assertSame(0, (int)$activity->rewarded_count);
- $this->assertSame(0, DB::table('activity_reward_recipients')->count());
- }
- }
- public function test_legacy_activity_retains_money_budget_and_cannot_be_switched_to_quota_by_client(): void
- {
- $this->member();
- $legacy = $this->legacyActivity(['budget' => '10.00']);
- $this->assertFalse((bool)$legacy->quota_enabled);
- $this->assertTrue(ActivityQuotaService::award($legacy, '1001', '6.00', function () {}));
- $this->assertFalse(ActivityQuotaService::award($legacy, '1001', '5.00', function () { $this->fail('Old money budget must reject an award above the remaining amount.'); }));
- $this->assertTrue(ActivityQuotaService::award($legacy, '1001', '4.00', function () {}));
- $legacy->refresh();
- $this->assertSame('10.00', (string)$legacy->budget_used);
- $this->assertFalse(ActivityQuotaService::canAward($legacy, '1001'));
- $this->assertSame(0, (int)$legacy->rewarded_count);
- $this->assertSame(0, DB::table('activity_reward_recipients')->count());
- $this->assertNotSame(0, $this->save(['id' => $legacy->id, 'reward_quota' => 10])['code']);
- $result = $this->save(['id' => $legacy->id, 'quota_enabled' => 1,
- 'budget' => '12.00', 'budget_used' => '0.00', 'rewarded_count' => 999]);
- $this->assertSame(0, $result['code'], $result['msg']);
- $legacy->refresh();
- $this->assertFalse((bool)$legacy->quota_enabled);
- $this->assertNull($legacy->reward_quota);
- $this->assertSame('12.00', (string)$legacy->budget);
- $this->assertSame('10.00', (string)$legacy->budget_used);
- $this->assertSame(0, (int)$legacy->rewarded_count);
- $new = $this->activity(['reward_quota' => 1, 'quota_enabled' => 0]);
- $this->assertTrue((bool)$new->quota_enabled);
- $this->assertTrue(ActivityQuotaService::award($new, '1001', '100.00', function () {}));
- $this->assertSame(1, (int)$new->fresh()->rewarded_count);
- $this->assertSame(1, DB::table('activity_reward_recipients')->count());
- $rows = array_column($this->list(['member_id' => '1001']), null, 'id');
- $this->assertFalse((bool)$rows[$legacy->id]['quota_enabled']);
- $this->assertSame('12.00', (string)$rows[$legacy->id]['budget']);
- $this->assertSame('10.00', (string)$rows[$legacy->id]['budget_used']);
- $this->assertTrue((bool)$rows[$new->id]['quota_enabled']);
- }
- public function test_creation_mode_is_immutable_when_an_activity_type_changes(): void
- {
- $legacy = $this->legacyActivity(['type' => 2]);
- $this->assertSame(0, $this->save(['id' => $legacy->id, 'type' => 1, 'quota_enabled' => 1])['code']);
- $this->assertFalse((bool)$legacy->fresh()->quota_enabled);
- $new = $this->activity(['type' => 2]);
- $this->assertSame(0, $this->save(['id' => $new->id, 'type' => 1, 'reward_quota' => 1, 'quota_enabled' => 0])['code']);
- $this->assertTrue((bool)$new->fresh()->quota_enabled);
- $this->assertSame(1, (int)$new->fresh()->reward_quota);
- }
- public function test_manual_gift_failure_rolls_back_wallet_application_recipient_and_counter(): void
- {
- $this->member();
- DB::table('wallets')->insert(['member_id' => '1001', 'available_balance' => '50.00']);
- $activity = $this->activity(['reward_quota' => 1]);
- $applicationId = DB::table('activity_user')->insertGetId([
- 'member_id' => '1001', 'activity_id' => $activity->id, 'status' => 0,
- 'title' => '待赠送', 'sub_title' => '资格检查', 'detail_image' => '/app.png',
- 'start_time' => 1, 'end_time' => 4102444799, 'part_in_time' => time(),
- ]);
- DB::statement("CREATE TRIGGER fail_manual_gift_ledger BEFORE INSERT ON bot_balance_logs
- WHEN NEW.change_type = '优惠活动'
- BEGIN SELECT RAISE(ABORT, 'injected manual reward failure'); END");
- $this->request('/admin/ActivityUser/gift', ['id' => $applicationId, 'amount' => '1.00', 'betting_amount' => 1], 'POST');
- $result = (new AdminActivityUser())->gift()->getData(true);
- $this->assertNotSame(0, $result['code']);
- $this->assertStringContainsString('injected manual reward failure', $result['msg']);
- $this->assertEquals('50.00', DB::table('wallets')->value('available_balance'));
- $this->assertSame(0, (int)DB::table('activity_user')->value('status'));
- $this->assertSame(0, (int)$activity->fresh()->rewarded_count);
- $this->assertSame(0, DB::table('activity_reward_recipients')->count());
- $this->assertSame(0, DB::table('balance_logs')->count());
- }
- public function test_migration_adds_optional_yuebao_activity_reference_and_rolls_back_cleanly(): void
- {
- $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_10_13_120000_add_activity_eligibility_fields.php';
- $migration->down();
- DB::connection()->getSchemaBuilder()->create('yuebao_item', function (Blueprint $t) {
- $t->id(); $t->decimal('principal', 20, 2)->default(0);
- });
- $migration->up();
- $schema = DB::connection()->getSchemaBuilder();
- $this->assertTrue($schema->hasColumn('yuebao_item', 'activity_id'));
- $this->assertTrue($schema->hasColumn('activity_rewards', 'budget_used'));
- $this->assertTrue($schema->hasColumn('activity_rewards', 'quota_enabled'));
- DB::table('yuebao_item')->insert(['principal' => '100.00']);
- $this->assertNull(DB::table('yuebao_item')->value('activity_id'));
- $migration->down();
- $this->assertFalse($schema->hasColumn('yuebao_item', 'activity_id'));
- $this->assertFalse($schema->hasColumn('activity_rewards', 'budget_used'));
- $this->assertEquals(100, DB::table('yuebao_item')->value('principal'));
- }
- public function test_quota_migration_up_down_and_unique_recipient_constraint_preserve_old_activity_storage(): void
- {
- $activity = $this->activity(['reward_quota' => 1]);
- $this->assertTrue(ActivityQuotaService::award($activity, '1001', '1.00', function () {}));
- try {
- DB::table('activity_reward_recipients')->insert([
- 'activity_id' => $activity->id, 'member_id' => '1001', 'created_at' => '2026-10-14 12:00:00',
- ]);
- $this->fail('Recipient table must reject duplicate activity/member pairs.');
- } catch (\Illuminate\Database\QueryException $e) {
- $this->assertStringContainsString('UNIQUE', $e->getMessage());
- }
- $this->assertSame(1, DB::table('activity_reward_recipients')->count());
- $schema = DB::connection()->getSchemaBuilder();
- $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_10_14_120000_add_activity_reward_quotas.php';
- $migration->down();
- $this->assertFalse($schema->hasTable('activity_reward_recipients'));
- $this->assertFalse($schema->hasColumn('activity_rewards', 'reward_quota'));
- $this->assertFalse($schema->hasColumn('activity_rewards', 'rewarded_count'));
- $this->assertFalse($schema->hasColumn('activity_rewards', 'quota_enabled'));
- $this->assertTrue($schema->hasColumn('activity_rewards', 'budget'));
- $this->assertTrue($schema->hasColumn('activity_rewards', 'budget_used'));
- $this->assertSame(1, DB::table('activity_rewards')->count());
- $migration->up();
- $this->assertTrue($schema->hasTable('activity_reward_recipients'));
- $this->assertNull(DB::table('activity_rewards')->value('reward_quota'));
- $this->assertSame(0, (int)DB::table('activity_rewards')->value('rewarded_count'));
- $this->assertFalse((bool)DB::table('activity_rewards')->value('quota_enabled'));
- }
- }
|