This commit is contained in:
Meghdad committed 2026-08-24 19:44:24 +03:30
commit 8d5446f466
232 files changed
+25416

No files matched your search

+96
View File
@@ -0,0 +1,96 @@
<?php
use App\Models\BazaarPurchase;
use App\Models\BazaarSubscription;
use App\Models\MobileApp;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
beforeEach(function () {
Http::preventStrayRequests();
});
it('validates and records a Bazaar purchase', function () {
$app = MobileApp::factory()->create(['package_name' => 'ir.example.billing']);
Http::fake([
'pardakht.cafebazaar.ir/devapi/v2/api/validate/*' => Http::response([
'consumptionState' => 1,
'purchaseState' => 0,
'kind' => 'androidpublisher#inappPurchase',
'developerPayload' => 'user-42',
'purchaseTime' => 1787551200000,
]),
]);
$this->withHeaders(appApiHeaders($app))
->postJson('/api/v1/apps/ir.example.billing/bazaar/billing/purchases/validate', [
'product_id' => 'coins_100',
'purchase_token' => 'purchase-token',
])
->assertSuccessful()
->assertJsonPath('data.purchaseState', 0);
$purchase = BazaarPurchase::firstOrFail();
expect($purchase->product_id)->toBe('coins_100')
->and($purchase->status)->toBe('purchased')
->and($purchase->is_consumed)->toBeFalse();
Http::assertSent(fn (Request $request): bool => $request->hasHeader('CAFEBAZAAR-PISHKHAN-API-SECRET', $app->bazaar_api_secret));
});
it('records subscription activity and protects cancellation', function () {
$app = MobileApp::factory()->create(['package_name' => 'ir.example.subscription']);
Http::fake([
'pardakht.cafebazaar.ir/devapi/v2/api/applications/*/subscriptions/*/purchases/*' => Http::response([
'kind' => 'androidpublisher#subscriptionPurchase',
'initiationTimestampMsec' => now()->subDay()->getTimestampMs(),
'validUntilTimestampMsec' => now()->addMonth()->getTimestampMs(),
'autoRenewing' => true,
'linkedSubscriptionToken' => 'linked-token',
]),
]);
$payload = ['subscription_id' => 'monthly', 'purchase_token' => 'subscription-token'];
$this->withHeaders(appApiHeaders($app))
->postJson('/api/v1/apps/ir.example.subscription/bazaar/billing/subscriptions/validate', $payload)
->assertSuccessful();
$subscription = BazaarSubscription::firstOrFail();
expect($subscription->status)->toBe('active')
->and($subscription->auto_renewing)->toBeTrue();
$this->withHeaders(appApiHeaders($app))
->postJson('/api/v1/apps/ir.example.subscription/bazaar/billing/subscriptions/cancel', $payload)
->assertForbidden();
});
it('requires the management key for refunds', function () {
$app = MobileApp::factory()->create(['package_name' => 'ir.example.refund']);
$this->withHeaders(appApiHeaders($app))
->postJson('/api/v1/apps/ir.example.refund/bazaar/billing/purchases/refund', ['purchase_token' => 'token'])
->assertForbidden()
->assertJsonPath('error.code', 'invalid_management_key');
});
it('verifies Bazaar purchase signatures on the server', function () {
$privateKey = openssl_pkey_new(['private_key_bits' => 2048]);
openssl_pkey_export($privateKey, $privateKeyPem);
$publicKey = openssl_pkey_get_details($privateKey)['key'];
$originalJson = '{"orderId":"12999763169054705758.1371079406387615"}';
openssl_sign($originalJson, $signature, $privateKeyPem, OPENSSL_ALGO_SHA1);
$app = MobileApp::factory()->create([
'package_name' => 'ir.example.signature',
'bazaar_billing_public_key' => $publicKey,
]);
$this->withHeaders(appApiHeaders($app))
->postJson('/api/v1/apps/ir.example.signature/bazaar/billing/signatures/verify', [
'original_json' => $originalJson,
'signature' => base64_encode($signature),
])
->assertSuccessful()
->assertJsonPath('data.valid', true);
});
+49
View File
@@ -0,0 +1,49 @@
<?php
use App\Models\MobileApp;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
beforeEach(function () {
Http::preventStrayRequests();
});
it('builds a state-bound Bazaar authorization URL', function () {
$app = MobileApp::factory()->create([
'package_name' => 'ir.example.login',
'bazaar_login_client_id' => 'client-id',
'bazaar_login_client_secret' => 'client-secret',
'bazaar_login_redirect_url' => 'https://api.example.test/callback',
]);
$this->withHeaders(appApiHeaders($app))
->getJson('/api/v1/apps/ir.example.login/bazaar/login/authorization-url?state=csrf-state')
->assertSuccessful()
->assertJsonPath('data.state', 'csrf-state')
->assertJsonPath('data.authorization_url', fn (string $url): bool => str_contains($url, 'client_id=client-id') && str_contains($url, 'state=csrf-state'));
});
it('exchanges Bazaar authorization codes without logging secrets', function () {
$app = MobileApp::factory()->create([
'package_name' => 'ir.example.oauth',
'bazaar_login_client_id' => 'client-id',
'bazaar_login_client_secret' => 'client-secret',
'bazaar_login_redirect_url' => 'https://api.example.test/callback',
]);
Http::fake([
'account.cafebazaar.ir/api/v0/tokens' => Http::response([
'access_token' => 'access-token',
'token_type' => 'Bearer',
'expires_in' => 3600,
'refresh_token' => 'refresh-token',
]),
]);
$this->withHeaders(appApiHeaders($app))
->postJson('/api/v1/apps/ir.example.oauth/bazaar/login/exchange', ['code' => 'authorization-code'])
->assertSuccessful()
->assertJsonPath('data.access_token', 'access-token');
Http::assertSent(fn (Request $request): bool => $request['client_id'] === 'client-id' && $request['client_secret'] === 'client-secret');
expect($app->bazaarApiRequests()->firstOrFail()->response_body['access_token'])->toBe('[REDACTED]');
});
+58
View File
@@ -0,0 +1,58 @@
<?php
use App\Models\BazaarRelease;
use App\Models\MobileApp;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
beforeEach(function () {
Http::preventStrayRequests();
});
it('creates and commits a managed Bazaar release', function () {
$app = MobileApp::factory()->create(['package_name' => 'ir.example.publish']);
Http::fake([
'api.pishkhan.cafebazaar.ir/v1/apps/releases/' => Http::response([
'type' => 'success',
'message' => 'New Release successfully created.',
'release' => ['packages' => []],
], 201),
'api.pishkhan.cafebazaar.ir/v1/apps/releases/commit/' => Http::response([
'type' => 'success',
'message' => 'Release successfully committed.',
'release' => ['id' => 159, 'committed' => true],
]),
]);
$headers = appApiHeaders($app, true);
$this->withHeaders($headers)
->postJson('/api/v1/apps/ir.example.publish/bazaar/releases')
->assertCreated();
$this->withHeaders($headers)
->postJson('/api/v1/apps/ir.example.publish/bazaar/releases/commit', [
'changelog_fa' => 'نسخه جدید',
'changelog_en' => 'New release',
'developer_note' => 'Automated release',
'staged_rollout_percentage' => 10,
'auto_publish' => true,
])
->assertSuccessful();
$release = BazaarRelease::firstOrFail();
expect($release->status)->toBe('committed')
->and($release->bazaar_release_id)->toBe(159)
->and($release->staged_rollout_percentage)->toBe(10)
->and($release->auto_publish)->toBeTrue();
Http::assertSent(fn (Request $request): bool => $request->hasHeader('CAFEBAZAAR-PISHKHAN-API-SECRET', $app->bazaar_api_secret));
});
it('rejects publishing without the management key', function () {
$app = MobileApp::factory()->create(['package_name' => 'ir.example.protected']);
$this->withHeaders(appApiHeaders($app))
->postJson('/api/v1/apps/ir.example.protected/bazaar/releases')
->assertForbidden();
});
+54
View File
@@ -0,0 +1,54 @@
<?php
use App\Models\BazaarReview;
use App\Models\MobileApp;
use Illuminate\Support\Facades\Http;
beforeEach(function () {
Http::preventStrayRequests();
});
it('synchronizes filtered Bazaar reviews', function () {
$app = MobileApp::factory()->create(['package_name' => 'ir.example.reviews']);
Http::fake([
'sandoghche.cafebazaar.ir/api/v0/reviews/*' => Http::response([
'next' => null,
'previous' => null,
'results' => [[
'id' => 122280901,
'user_account_id' => 'user-id',
'sdk_version' => 33,
'likes' => 4,
'dislikes' => 0,
'app_version_code' => 30200,
'publish_date' => '2025-01-05T10:12:45+03:30',
'is_edited' => false,
'text' => 'Great app',
'rate' => 5,
'developer_reply' => null,
]],
]),
]);
$this->withHeaders(appApiHeaders($app))
->getJson('/api/v1/apps/ir.example.reviews/bazaar/reviews?rate_min=4&is_replied=false')
->assertSuccessful()
->assertJsonPath('data.results.0.id', 122280901);
$review = BazaarReview::firstOrFail();
expect($review->rate)->toBe(5)->and($review->text)->toBe('Great app');
});
it('replies to a review with management authorization', function () {
$app = MobileApp::factory()->create(['package_name' => 'ir.example.reply']);
BazaarReview::factory()->for($app)->create(['bazaar_review_id' => 42]);
Http::fake([
'sandoghche.cafebazaar.ir/api/v0/reviews/42/' => Http::response(['text' => 'Thank you', 'email' => 'support@example.test'], 201),
]);
$this->withHeaders(appApiHeaders($app, true))
->postJson('/api/v1/apps/ir.example.reply/bazaar/reviews/42/reply', ['text' => 'Thank you', 'email' => 'support@example.test'])
->assertCreated();
expect(BazaarReview::firstOrFail()->developer_reply_text)->toBe('Thank you');
});
+7
View File
@@ -0,0 +1,7 @@
<?php
test('the application returns a successful response', function () {
$response = $this->get('/');
$response->assertStatus(200);
});
@@ -0,0 +1,56 @@
<?php
use App\Models\BazaarApiRequest;
use App\Models\BazaarPurchase;
use App\Models\BazaarRelease;
use App\Models\BazaarReview;
use App\Models\BazaarSubscription;
use App\Models\MobileApp;
use App\Models\User;
use Database\Seeders\LocalDevelopmentSeeder;
use Illuminate\Support\Facades\Hash;
it('seeds a complete relationship graph without duplicating data', function () {
$this->seed(LocalDevelopmentSeeder::class);
$countsAfterFirstRun = [
MobileApp::class => MobileApp::query()->count(),
BazaarPurchase::class => BazaarPurchase::query()->count(),
BazaarSubscription::class => BazaarSubscription::query()->count(),
BazaarRelease::class => BazaarRelease::query()->count(),
BazaarReview::class => BazaarReview::query()->count(),
BazaarApiRequest::class => BazaarApiRequest::query()->count(),
];
$this->seed(LocalDevelopmentSeeder::class);
$countsAfterSecondRun = [
MobileApp::class => MobileApp::query()->count(),
BazaarPurchase::class => BazaarPurchase::query()->count(),
BazaarSubscription::class => BazaarSubscription::query()->count(),
BazaarRelease::class => BazaarRelease::query()->count(),
BazaarReview::class => BazaarReview::query()->count(),
BazaarApiRequest::class => BazaarApiRequest::query()->count(),
];
$owner = User::query()->where('email', 'admin@example.test')->firstOrFail();
$cafeApp = MobileApp::query()->where('package_name', 'ir.local.cafe')->firstOrFail();
expect($countsAfterSecondRun)->toBe($countsAfterFirstRun)
->and($countsAfterSecondRun)->toBe([
MobileApp::class => 2,
BazaarPurchase::class => 11,
BazaarSubscription::class => 8,
BazaarRelease::class => 4,
BazaarReview::class => 16,
BazaarApiRequest::class => 21,
])
->and(User::query()->where('email', 'admin@example.test')->count())->toBe(1)
->and(Hash::check('password', $owner->password))->toBeTrue()
->and($owner->mobileApps()->count())->toBe(2)
->and($cafeApp->bazaarPurchases()->count())->toBe(8)
->and($cafeApp->bazaarSubscriptions()->count())->toBe(6)
->and($cafeApp->bazaarReleases()->count())->toBe(3)
->and($cafeApp->bazaarReviews()->count())->toBe(12)
->and($cafeApp->bazaarApiRequests()->count())->toBe(16);
});
+82
View File
@@ -0,0 +1,82 @@
<?php
use App\Models\BazaarApiRequest;
use App\Models\BazaarPurchase;
use App\Models\BazaarRelease;
use App\Models\BazaarReview;
use App\Models\BazaarSubscription;
use App\Models\MobileApp;
use App\Models\User;
it('returns only public configuration for the selected app', function () {
$app = MobileApp::factory()->create([
'package_name' => 'ir.example.coffee',
'configuration' => ['api_base' => 'https://example.test'],
'feature_flags' => ['new_home' => true],
'bazaar_login_client_secret' => 'must-not-leak',
]);
$this->withHeaders(appApiHeaders($app))
->getJson('/api/v1/apps/ir.example.coffee')
->assertSuccessful()
->assertJsonPath('data.package_name', 'ir.example.coffee')
->assertJsonPath('data.configuration.api_base', 'https://example.test')
->assertJsonPath('data.feature_flags.new_home', true)
->assertJsonMissing(['bazaar_login_client_secret' => 'must-not-leak']);
});
it('rejects invalid app keys and disabled apps', function () {
$app = MobileApp::factory()->create(['package_name' => 'ir.example.disabled', 'is_active' => false]);
$this->withHeaders(['X-App-Key' => $app->client_key])
->getJson('/api/v1/apps/ir.example.disabled')
->assertForbidden()
->assertJsonPath('error.code', 'app_disabled');
$activeApp = MobileApp::factory()->create(['package_name' => 'ir.example.active']);
$this->withHeaders(['X-App-Key' => 'wrong'])
->getJson('/api/v1/apps/ir.example.active')
->assertUnauthorized()
->assertJsonPath('error.code', 'invalid_app_key');
});
it('allows panel users to access only attached app tenants', function () {
$user = User::factory()->create();
$allowedApp = MobileApp::factory()->create();
$otherApp = MobileApp::factory()->create();
$user->mobileApps()->attach($allowedApp, ['role' => 'owner']);
expect($user->canAccessTenant($allowedApp))->toBeTrue()
->and($user->canAccessTenant($otherApp))->toBeFalse();
});
it('renders the tenant dashboard for an attached panel user', function () {
$user = User::factory()->create();
$app = MobileApp::factory()->create(['package_name' => 'ir.example.panel']);
$user->mobileApps()->attach($app, ['role' => 'owner']);
$this->actingAs($user)
->get('/admin/apps/ir.example.panel')
->assertSuccessful();
$this->get('/admin/apps/ir.example.panel/profile')
->assertSuccessful();
});
it('renders every tenant-scoped Bazaar monitoring resource', function () {
$user = User::factory()->create();
$app = MobileApp::factory()->create(['package_name' => 'ir.example.monitored']);
$user->mobileApps()->attach($app, ['role' => 'owner']);
BazaarPurchase::factory()->for($app)->create();
BazaarSubscription::factory()->for($app)->create();
BazaarRelease::factory()->for($app)->create();
BazaarReview::factory()->for($app)->create();
BazaarApiRequest::factory()->for($app)->create();
$this->actingAs($user);
foreach (['bazaar-purchases', 'bazaar-subscriptions', 'bazaar-releases', 'bazaar-reviews', 'bazaar-api-requests'] as $resource) {
$this->get("/admin/apps/ir.example.monitored/{$resource}")->assertSuccessful();
}
});
+124
View File
@@ -0,0 +1,124 @@
<?php
use App\Filament\Pages\Tenancy\EditMobileAppProfile;
use App\Jobs\SyncCafeBazaarApp;
use App\Models\BazaarPurchase;
use App\Models\BazaarReview;
use App\Models\BazaarSubscription;
use App\Models\MobileApp;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Http;
use Livewire\Livewire;
beforeEach(function () {
Http::preventStrayRequests();
});
it('reconciles known Bazaar data and records synchronization health', function () {
$app = MobileApp::factory()->create([
'package_name' => 'ir.example.sync',
]);
$purchase = BazaarPurchase::factory()->for($app)->create([
'product_id' => 'coins',
'purchase_token' => 'purchase-token',
'validated_at' => now(),
]);
$subscription = BazaarSubscription::factory()->for($app)->create([
'subscription_id' => 'monthly',
'purchase_token' => 'subscription-token',
'validated_at' => now(),
]);
Http::fake([
'pardakht.cafebazaar.ir/devapi/v2/api/validate/*' => Http::response([
'consumptionState' => 1,
'purchaseState' => 1,
'purchaseTime' => now()->subWeek()->getTimestampMs(),
]),
'pardakht.cafebazaar.ir/devapi/v2/api/applications/*/subscriptions/*/purchases/*' => Http::response([
'initiationTimestampMsec' => now()->subMonth()->getTimestampMs(),
'validUntilTimestampMsec' => now()->subMinute()->getTimestampMs(),
'autoRenewing' => false,
]),
'api.pishkhan.cafebazaar.ir/v1/apps/releases/last-*' => Http::response([], 404),
'sandoghche.cafebazaar.ir/api/v0/reviews/*' => Http::response([
'next' => null,
'results' => [[
'id' => 9001,
'user_account_id' => 'reviewer',
'rate' => 4,
'text' => 'Useful',
'app_version_code' => 7,
'is_edited' => false,
'publish_date' => now()->toIso8601String(),
'developer_reply' => null,
]],
]),
]);
$this->artisan('bazaar:sync', ['--app' => $app->package_name, '--now' => true, '--force' => true])
->assertSuccessful();
expect($purchase->refresh()->status)->toBe('refunded')
->and($subscription->refresh()->status)->toBe('expired')
->and(BazaarReview::query()->whereBelongsTo($app)->where('bazaar_review_id', 9001)->exists())->toBeTrue()
->and($app->refresh()->bazaar_sync_status)->toBe('succeeded')
->and($app->bazaar_last_synced_at)->not->toBeNull()
->and($app->bazaar_sync_summary['purchases_checked'])->toBe(1)
->and($app->bazaar_sync_summary['subscriptions_checked'])->toBe(1)
->and($app->bazaar_sync_summary['reviews_imported'])->toBe(1)
->and($app->bazaar_sync_summary['release_states_checked'])->toBe(3);
});
it('queues only apps whose synchronization is due', function () {
Bus::fake();
$dueApp = MobileApp::factory()->create(['bazaar_last_synced_at' => now()->subHour()]);
$freshApp = MobileApp::factory()->create(['bazaar_last_synced_at' => now()]);
MobileApp::factory()->create(['bazaar_sync_enabled' => false]);
$this->artisan('bazaar:sync')->assertSuccessful();
Bus::assertDispatched(SyncCafeBazaarApp::class, fn (SyncCafeBazaarApp $job): bool => $job->mobileAppId === $dueApp->id);
Bus::assertNotDispatched(SyncCafeBazaarApp::class, fn (SyncCafeBazaarApp $job): bool => $job->mobileAppId === $freshApp->id);
});
it('marks a synchronization partial when Bazaar rejects an operation', function () {
$app = MobileApp::factory()->create(['bazaar_comments_secret' => null]);
BazaarSubscription::factory()->for($app)->create(['validated_at' => now()->subHour()]);
Http::fake([
'pardakht.cafebazaar.ir/devapi/v2/api/applications/*/subscriptions/*/purchases/*' => Http::response(['error' => 'invalid_token'], 400),
'api.pishkhan.cafebazaar.ir/v1/apps/releases/last-*' => Http::response([], 404),
]);
$this->artisan('bazaar:sync', ['--app' => $app->package_name, '--now' => true, '--force' => true])
->assertSuccessful();
expect($app->refresh()->bazaar_sync_status)->toBe('partial')
->and($app->bazaar_sync_error)->toContain('1 Bazaar operation')
->and($app->bazaar_sync_summary['failures'][0]['operation'])->toBe('subscription');
});
it('shows synchronization controls on the tenant settings page', function () {
Bus::fake();
$user = User::factory()->create();
$app = MobileApp::factory()->create(['bazaar_sync_status' => 'succeeded']);
$app->users()->attach($user, ['role' => 'owner']);
$this->actingAs($user);
Filament::setCurrentPanel(Filament::getPanel('admin'));
Filament::setTenant($app);
Filament::bootCurrentPanel();
Livewire::test(EditMobileAppProfile::class)
->assertSuccessful()
->assertSee('Cafe Bazaar synchronization')
->assertActionVisible('syncBazaar')
->callAction('syncBazaar')
->assertNotified('Cafe Bazaar synchronization queued');
Bus::assertDispatched(SyncCafeBazaarApp::class, fn (SyncCafeBazaarApp $job): bool => $job->mobileAppId === $app->id && $job->force);
});