Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

Track first-month offers in PostHog (#369)

Paulo Castellano1e0235c13bc8
diff --git a/.ai/rules/index.md b/.ai/rules/index.md
index 09b33beb2..fdfdcdd24 100644
--- a/.ai/rules/index.md
+++ b/.ai/rules/index.md
@@ -6,6 +6,7 @@ Before planning or editing, find the row whose globs match the file's path and r
| --- | --- |
| app/Http/Controllers/Auth/GoogleBusinessController.php | .ai/rules/auth.md |
| app/Enums/GoogleBusiness/**, app/Jobs/PublishToSocialPlatform.php, app/Jobs/ReconcileGoogleBusinessPost.php, app/Console/Commands/ReconcileGoogleBusinessPosts.php, app/Services/Social/GoogleBusinessPublisher.php, app/Support/PostPlatformMetaRules.php, app/Services/Social/GoogleBusinessAnalytics.php | .ai/rules/google-business.md |
+| app/Listeners/StripeEventListener.php, app/Jobs/PostHog/TrackBilling.php, app/Jobs/PostHog/SyncAccountUsage.php | .ai/rules/jobs-post-hog.md |
| app/Jobs/ReconcileGoogleBusinessPost.php, app/Console/Commands/RecoverStuckPosts.php | .ai/rules/jobs.md |
| app/Jobs/PostHog/**, app/Models/PostPlatform.php, database/migrations/** | .ai/rules/migrations.md |
| app/Jobs/PostHog/** | .ai/rules/post-hog.md |
diff --git a/.ai/rules/jobs-post-hog.md b/.ai/rules/jobs-post-hog.md
new file mode 100644
index 000000000..09016fad4
--- /dev/null
+++ b/.ai/rules/jobs-post-hog.md
@@ -0,0 +1,11 @@
+---
+paths:
+ - 'app/Listeners/StripeEventListener.php'
+ - 'app/Jobs/PostHog/TrackBilling.php'
+ - 'app/Jobs/PostHog/SyncAccountUsage.php'
+---
+
+# Jobs Post Hog
+
+## Sync PostHog billing state after Cashier
+Listen to Cashier's WebhookHandled event so local subscription state is persisted before PostHog jobs are dispatched. Account group properties are the current snapshot: subscription_status is canceled as soon as an ends_at exists (including grace period), while has_active_subscription remains true until access ends. Keep first_month_offer_ends_at event-derived and set it only on subscription creation so renewals cannot extend it.
diff --git a/app/Actions/Billing/StartSubscriptionCheckout.php b/app/Actions/Billing/StartSubscriptionCheckout.php
index 14f835548..71386bb8d 100644
--- a/app/Actions/Billing/StartSubscriptionCheckout.php
+++ b/app/Actions/Billing/StartSubscriptionCheckout.php
@@ -32,10 +32,11 @@ class StartSubscriptionCheckout
'name' => $account->stripeName(),
]);
- $subscription = $account->newSubscription(Account::SUBSCRIPTION_NAME, $priceId)
- ->withMetadata($this->subscriptionMetadata($account));
+ $monthlyPlan = $this->monthlyPlan($plan, $priceId);
+ $subscription = $account->newSubscription(Account::SUBSCRIPTION_NAME, $priceId);
- ConfigureSubscriptionCheckout::apply($subscription, $account, $this->monthlyPlan($plan, $priceId));
+ ConfigureSubscriptionCheckout::apply($subscription, $account, $monthlyPlan);
+ $subscription->withMetadata($this->subscriptionMetadata($account, $subscription->couponId));
$session = $subscription->checkout([
'success_url' => route('app.billing.processing').'?session_id={CHECKOUT_SESSION_ID}',
@@ -48,7 +49,7 @@ class StartSubscriptionCheckout
/**
* @return array<string, string>
*/
- private function subscriptionMetadata(Account $account): array
+ private function subscriptionMetadata(Account $account, ?string $firstMonthCouponId): array
{
$owner = $account->owner;
@@ -67,6 +68,7 @@ class StartSubscriptionCheckout
'persona' => $owner?->persona?->value,
'goals' => implode(',', $owner?->goals ?? []),
'referral_source' => $owner?->referral_source?->value,
+ ConfigureSubscriptionCheckout::FIRST_MONTH_COUPON_METADATA_KEY => $firstMonthCouponId,
], filled(...));
return array_map(
diff --git a/app/Jobs/PostHog/SyncAccountUsage.php b/app/Jobs/PostHog/SyncAccountUsage.php
index d6dfdc8e7..15583900a 100644
--- a/app/Jobs/PostHog/SyncAccountUsage.php
+++ b/app/Jobs/PostHog/SyncAccountUsage.php
@@ -47,6 +47,7 @@ class SyncAccountUsage implements ShouldQueue
'name' => $account->name,
'plan' => $account->plan?->name,
'plan_slug' => $account->plan?->slug->value,
+ 'subscription_status' => $account->subscriptionStatus(),
'has_active_subscription' => $account->hasActiveSubscription(),
'is_on_trial' => $account->isOnTrial(),
'workspaces_count' => $usage['workspaceCount'],
diff --git a/app/Jobs/PostHog/TrackBilling.php b/app/Jobs/PostHog/TrackBilling.php
index 2542268fb..85e144aff 100644
--- a/app/Jobs/PostHog/TrackBilling.php
+++ b/app/Jobs/PostHog/TrackBilling.php
@@ -7,6 +7,7 @@ namespace App\Jobs\PostHog;
use App\Enums\PostHog\BillingEvent;
use App\Models\Account;
use App\Services\PostHogService;
+use App\Support\StripeSubscriptionConversion;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
@@ -56,6 +57,26 @@ class TrackBilling implements ShouldQueue
$account,
);
+ $postHog->groupIdentify('account', (string) $account->id, [
+ 'subscription_status' => $account->subscriptionStatus(),
+ 'has_active_subscription' => $account->hasActiveSubscription(),
+ ...$this->firstMonthOfferProperties(),
+ ]);
+
SyncUser::dispatch((string) $account->owner_id);
}
+
+ /**
+ * @return array<string, mixed>
+ */
+ private function firstMonthOfferProperties(): array
+ {
+ if ($this->event !== BillingEvent::Created) {
+ return [];
+ }
+
+ return [
+ 'first_month_offer_ends_at' => StripeSubscriptionConversion::firstMonthOfferEndsAt($this->payload),
+ ];
+ }
}
diff --git a/app/Jobs/PostHog/TrackCheckoutCompleted.php b/app/Jobs/PostHog/TrackCheckoutCompleted.php
index 4f577d18c..f3c30ae1f 100644
--- a/app/Jobs/PostHog/TrackCheckoutCompleted.php
+++ b/app/Jobs/PostHog/TrackCheckoutCompleted.php
@@ -20,6 +20,6 @@ class TrackCheckoutCompleted extends AbstractTrackStripeSubscriptionEvent
*/
protected function properties(Account $account): array
{
- return StripeSubscriptionConversion::propertiesFor($account, $this->payload);
+ return StripeSubscriptionConversion::checkoutPropertiesFor($account, $this->payload);
}
}
diff --git a/app/Listeners/StripeEventListener.php b/app/Listeners/StripeEventListener.php
index 5c0af45da..efcb5187c 100644
--- a/app/Listeners/StripeEventListener.php
+++ b/app/Listeners/StripeEventListener.php
@@ -15,11 +15,11 @@ use App\Services\PostHogService;
use App\Support\Billing\SubscriptionPlanSync;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
-use Laravel\Cashier\Events\WebhookReceived;
+use Laravel\Cashier\Events\WebhookHandled;
class StripeEventListener
{
- public function handle(WebhookReceived $event): void
+ public function handle(WebhookHandled $event): void
{
try {
if ($this->alreadyProcessed(data_get($event->payload, 'id'))) {
@@ -207,10 +207,9 @@ class StripeEventListener
/**
* Fires on the trial's first successful charge, using Stripe's own
- * `previous_attributes` rather than trusting local DB state — Cashier's
- * WebhookController dispatches WebhookReceived before it updates the
- * local subscription row, so relying on our own `stripe_status` here
- * would be fragile if that internal ordering ever changes.
+ * `previous_attributes` rather than trusting local DB state. This also
+ * covers a `past_due` recovery without mistaking a later billing-cycle
+ * recovery for the trial conversion.
*
* @param array<string, mixed> $payload
*/
diff --git a/app/Models/Account.php b/app/Models/Account.php
index 46090bd53..9b9e83894 100644
--- a/app/Models/Account.php
+++ b/app/Models/Account.php
@@ -75,6 +75,17 @@ class Account extends Model
return $this->subscribed(self::SUBSCRIPTION_NAME);
}
+ public function subscriptionStatus(): string
+ {
+ $subscription = $this->subscription(self::SUBSCRIPTION_NAME);
+
+ if (! $subscription) {
+ return 'none';
+ }
+
+ return $subscription->canceled() ? 'canceled' : $subscription->stripe_status;
+ }
+
public function hasAppAccess(): bool
{
if (config('trypost.self_hosted')) {
diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php
index 040f423b7..142e15cb2 100644
--- a/app/Providers/AppServiceProvider.php
+++ b/app/Providers/AppServiceProvider.php
@@ -48,7 +48,7 @@ use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
use Laravel\Cashier\Cashier;
-use Laravel\Cashier\Events\WebhookReceived;
+use Laravel\Cashier\Events\WebhookHandled;
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\CacheEvent;
use Laravel\Socialite\Facades\Socialite;
@@ -171,7 +171,7 @@ class AppServiceProvider extends ServiceProvider
protected function configureStripeWebhooks(): void
{
- Event::listen(WebhookReceived::class, StripeEventListener::class);
+ Event::listen(WebhookHandled::class, StripeEventListener::class);
}
protected function configureSocialite(): void
diff --git a/app/Support/Billing/ConfigureSubscriptionCheckout.php b/app/Support/Billing/ConfigureSubscriptionCheckout.php
index d810341ea..da97a4b24 100644
--- a/app/Support/Billing/ConfigureSubscriptionCheckout.php
+++ b/app/Support/Billing/ConfigureSubscriptionCheckout.php
@@ -12,6 +12,8 @@ use Stripe\Subscription as StripeSubscription;
final class ConfigureSubscriptionCheckout
{
+ public const FIRST_MONTH_COUPON_METADATA_KEY = 'trypost_first_month_coupon_id';
+
/**
* Stripe Checkout rejects subscription trials shorter than 48 hours.
*/
diff --git a/app/Support/StripeSubscriptionConversion.php b/app/Support/StripeSubscriptionConversion.php
index 30cdf73fd..a824dee9e 100644
--- a/app/Support/StripeSubscriptionConversion.php
+++ b/app/Support/StripeSubscriptionConversion.php
@@ -5,6 +5,8 @@ declare(strict_types=1);
namespace App\Support;
use App\Models\Account;
+use App\Support\Billing\ConfigureSubscriptionCheckout;
+use Illuminate\Support\Carbon;
final class StripeSubscriptionConversion
{
@@ -52,4 +54,58 @@ final class StripeSubscriptionConversion
return $properties;
}
+
+ /**
+ * @param array<string, mixed> $payload
+ * @return array<string, mixed>
+ */
+ public static function checkoutPropertiesFor(Account $account, array $payload): array
+ {
+ $properties = self::propertiesFor($account, $payload);
+ $firstMonthCouponId = self::firstMonthCouponId($payload);
+
+ $properties['is_first_month_offer'] = $firstMonthCouponId !== null;
+
+ if ($firstMonthCouponId === null) {
+ return $properties;
+ }
+
+ $properties['first_month_coupon_id'] = $firstMonthCouponId;
+ $firstMonthOfferEndsAt = self::firstMonthOfferEndsAt($payload);
+
+ if ($firstMonthOfferEndsAt !== null) {
+ $properties['first_month_offer_ends_at'] = $firstMonthOfferEndsAt;
+ }
+
+ return $properties;
+ }
+
+ /**
+ * @param array<string, mixed> $payload
+ */
+ public static function firstMonthOfferEndsAt(array $payload): ?string
+ {
+ if (self::firstMonthCouponId($payload) === null) {
+ return null;
+ }
+
+ $currentPeriodEnd = data_get($payload, 'data.object.items.data.0.current_period_end');
+
+ return is_int($currentPeriodEnd)
+ ? Carbon::createFromTimestamp($currentPeriodEnd)->toIso8601String()
+ : null;
+ }
+
+ /**
+ * @param array<string, mixed> $payload
+ */
+ private static function firstMonthCouponId(array $payload): ?string
+ {
+ $couponId = data_get(
+ $payload,
+ 'data.object.metadata.'.ConfigureSubscriptionCheckout::FIRST_MONTH_COUPON_METADATA_KEY,
+ );
+
+ return is_string($couponId) && $couponId !== '' ? $couponId : null;
+ }
}
diff --git a/tests/Feature/Jobs/PostHog/SyncAccountUsageTest.php b/tests/Feature/Jobs/PostHog/SyncAccountUsageTest.php
index e17dca94a..ee5ad6778 100644
--- a/tests/Feature/Jobs/PostHog/SyncAccountUsageTest.php
+++ b/tests/Feature/Jobs/PostHog/SyncAccountUsageTest.php
@@ -17,6 +17,7 @@ use Illuminate\Support\Str;
beforeEach(function () {
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);
+ config(['trypost.self_hosted' => false]);
$this->account = Account::factory()->create([
'plan_id' => Plan::query()->where('slug', 'workspace')->first()?->id,
@@ -65,12 +66,33 @@ test('handle group-identifies the account with usage metrics', function () {
$props = $job->payload['properties'];
return $job->payload['groupKey'] === (string) $this->account->id
+ && $props['subscription_status'] === 'none'
+ && $props['has_active_subscription'] === false
&& $props['workspaces_count'] === 1
&& $props['social_accounts_count'] === 2
&& $props['posts_count'] === 3;
});
});
+test('handle sends the active subscription state from the account', function () {
+ $this->account->subscriptions()->create([
+ 'type' => Account::SUBSCRIPTION_NAME,
+ 'stripe_id' => 'sub_test',
+ 'stripe_status' => 'active',
+ 'stripe_price' => 'price_test',
+ ]);
+ Queue::fake();
+
+ (new SyncAccountUsage((string) $this->account->id))->handle(app(PostHogService::class));
+
+ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {
+ return $job->method === 'groupIdentify'
+ && $job->payload['groupType'] === 'account'
+ && $job->payload['properties']['subscription_status'] === 'active'
+ && $job->payload['properties']['has_active_subscription'] === true;
+ });
+});
+
test('handle group-identifies the workspace when workspaceId is provided', function () {
$workspace = Workspace::factory()->create([
'account_id' => $this->account->id,
diff --git a/tests/Feature/Jobs/PostHog/TrackBillingTest.php b/tests/Feature/Jobs/PostHog/TrackBillingTest.php
index 0cd4612fa..0d7df5e50 100644
--- a/tests/Feature/Jobs/PostHog/TrackBillingTest.php
+++ b/tests/Feature/Jobs/PostHog/TrackBillingTest.php
@@ -17,12 +17,19 @@ use Illuminate\Support\Facades\Queue;
beforeEach(function () {
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);
+ config(['trypost.self_hosted' => false]);
$this->account = Account::factory()->create([
'plan_id' => Plan::query()->where('slug', 'workspace')->first()?->id,
]);
$this->user = User::factory()->create(['account_id' => $this->account->id]);
$this->account->update(['owner_id' => $this->user->id]);
+ $this->account->subscriptions()->create([
+ 'type' => Account::SUBSCRIPTION_NAME,
+ 'stripe_id' => 'sub_test',
+ 'stripe_status' => 'active',
+ 'stripe_price' => 'price_test',
+ ]);
$this->payload = [
'type' => 'customer.subscription.updated',
@@ -52,6 +59,81 @@ test('handle captures event on the owner profile with account group attached', f
});
});
+test('handle updates the account group with the current subscription state', function () {
+ Queue::fake();
+
+ (new TrackBilling((string) $this->account->id, BillingEvent::Updated, $this->payload))
+ ->handle(app(PostHogService::class));
+
+ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {
+ return $job->method === 'groupIdentify'
+ && $job->payload['groupType'] === 'account'
+ && $job->payload['groupKey'] === (string) $this->account->id
+ && $job->payload['properties']['subscription_status'] === 'active'
+ && $job->payload['properties']['has_active_subscription'] === true
+ && ! array_key_exists('first_month_offer_ends_at', $job->payload['properties']);
+ });
+});
+
+test('subscription creation sets the first month offer end on the account group', function () {
+ $periodEndsAt = now()->addMonth()->startOfSecond();
+ $this->payload['data']['object']['metadata'] = [
+ 'trypost_first_month_coupon_id' => 'WORKSPACES_88USD',
+ ];
+ $this->payload['data']['object']['items']['data'][0]['current_period_end'] = $periodEndsAt->timestamp;
+ Queue::fake();
+
+ (new TrackBilling((string) $this->account->id, BillingEvent::Created, $this->payload))
+ ->handle(app(PostHogService::class));
+
+ Queue::assertPushed(SendEvent::class, function (SendEvent $job) use ($periodEndsAt): bool {
+ return $job->method === 'groupIdentify'
+ && $job->payload['properties']['first_month_offer_ends_at'] === $periodEndsAt->toIso8601String();
+ });
+});
+
+test('subscription creation clears a previous first month offer when the new subscription has none', function () {
+ Queue::fake();
+
+ (new TrackBilling((string) $this->account->id, BillingEvent::Created, $this->payload))
+ ->handle(app(PostHogService::class));
+
+ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {
+ return $job->method === 'groupIdentify'
+ && array_key_exists('first_month_offer_ends_at', $job->payload['properties'])
+ && $job->payload['properties']['first_month_offer_ends_at'] === null;
+ });
+});
+
+test('subscription cancellation updates the account group after Cashier marks it ended', function () {
+ $this->account->subscription()->markAsCanceled();
+ $this->payload['data']['object']['status'] = 'canceled';
+ Queue::fake();
+
+ (new TrackBilling((string) $this->account->id, BillingEvent::Cancelled, $this->payload))
+ ->handle(app(PostHogService::class));
+
+ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {
+ return $job->method === 'groupIdentify'
+ && $job->payload['properties']['subscription_status'] === 'canceled'
+ && $job->payload['properties']['has_active_subscription'] === false;
+ });
+});
+
+test('scheduled cancellation is canceled while access remains active during the grace period', function () {
+ $this->account->subscription()->update(['ends_at' => now()->addWeek()]);
+ Queue::fake();
+
+ (new TrackBilling((string) $this->account->id, BillingEvent::Updated, $this->payload))
+ ->handle(app(PostHogService::class));
+
+ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {
+ return $job->method === 'groupIdentify'
+ && $job->payload['properties']['subscription_status'] === 'canceled'
+ && $job->payload['properties']['has_active_subscription'] === true;
+ });
+});
+
test('handle does not forward persona — it is already an identified person property', function () {
$this->user->update(['persona' => Persona::Agency->value]);
Queue::fake();
@@ -72,7 +154,8 @@ test('handle forwards previousPlan as a property when supplied', function () {
->handle(app(PostHogService::class));
Queue::assertPushed(SendEvent::class, function ($job) {
- return $job->payload['properties']['previous_plan'] === 'Starter';
+ return $job->method === 'capture'
+ && $job->payload['properties']['previous_plan'] === 'Starter';
});
});
@@ -142,9 +225,8 @@ test('handle logs locally but still does not push a PostHog network call in the
Queue::fake();
Bus::fake([SyncUser::class]);
- Log::shouldReceive('info')->once()->withArgs(
- fn ($message) => $message === 'PostHogService: capture',
- );
+ Log::shouldReceive('info')->once()->withArgs(fn ($message) => $message === 'PostHogService: capture');
+ Log::shouldReceive('info')->once()->withArgs(fn ($message) => $message === 'PostHogService: groupIdentify');
(new TrackBilling((string) $this->account->id, BillingEvent::Created, $this->payload))
->handle(app(PostHogService::class));
diff --git a/tests/Feature/Jobs/PostHog/TrackCheckoutCompletedTest.php b/tests/Feature/Jobs/PostHog/TrackCheckoutCompletedTest.php
index 4fa036fbc..b9664e21a 100644
--- a/tests/Feature/Jobs/PostHog/TrackCheckoutCompletedTest.php
+++ b/tests/Feature/Jobs/PostHog/TrackCheckoutCompletedTest.php
@@ -2,6 +2,7 @@
declare(strict_types=1);
+use App\Enums\Plan\Slug;
use App\Enums\PostHog\CheckoutEvent;
use App\Enums\User\Persona;
use App\Jobs\PostHog\SendEvent;
@@ -14,11 +15,12 @@ use Illuminate\Support\Facades\Queue;
beforeEach(function () {
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);
+ config(['cashier.first_month_coupon_ids.workspaces' => 'WORKSPACES_88USD']);
- $this->plan = Plan::where('slug', 'workspace')->firstOrFail();
+ $this->plan = Plan::where('slug', Slug::Workspaces)->firstOrFail();
$this->plan->update([
- 'stripe_monthly_price_id' => 'price_workspace_monthly',
- 'stripe_yearly_price_id' => 'price_workspace_yearly',
+ 'stripe_monthly_price_id' => 'price_workspaces_monthly',
+ 'stripe_yearly_price_id' => 'price_workspaces_yearly',
]);
$this->account = Account::factory()->create(['plan_id' => $this->plan->id]);
@@ -32,8 +34,8 @@ beforeEach(function () {
'customer' => 'cus_test123',
'items' => ['data' => [[
'price' => [
- 'id' => 'price_workspace_monthly',
- 'unit_amount' => 2900,
+ 'id' => 'price_workspaces_monthly',
+ 'unit_amount' => 9900,
'currency' => 'usd',
],
]]],
@@ -60,14 +62,53 @@ test('handle captures checkout.completed with plan, interval and conversion data
&& $job->payload['properties']['$groups']['account'] === (string) $this->account->id
&& $job->payload['properties']['plan_name'] === $this->plan->name
&& $job->payload['properties']['interval'] === 'monthly'
- && $job->payload['properties']['conversion_value'] === 29.0
+ && $job->payload['properties']['conversion_value'] === 99.0
&& $job->payload['properties']['conversion_currency'] === 'USD'
- && $job->payload['properties']['conversion_transaction_id'] === 'sub_test123';
+ && $job->payload['properties']['conversion_transaction_id'] === 'sub_test123'
+ && $job->payload['properties']['is_first_month_offer'] === false;
+ });
+});
+
+test('handle marks checkout.completed when the subscription uses the configured first month coupon', function () {
+ $periodEndsAt = now()->addMonth()->startOfSecond();
+ $this->payload['data']['object']['metadata'] = [
+ 'trypost_first_month_coupon_id' => 'WORKSPACES_88USD',
+ ];
+ $this->payload['data']['object']['items']['data'][0]['current_period_end'] = $periodEndsAt->timestamp;
+ Queue::fake();
+
+ (new TrackCheckoutCompleted((string) $this->account->id, $this->payload))
+ ->handle(app(PostHogService::class));
+
+ Queue::assertPushed(SendEvent::class, function (SendEvent $job) use ($periodEndsAt): bool {
+ $properties = $job->payload['properties'];
+
+ return $properties['is_first_month_offer'] === true
+ && $properties['first_month_coupon_id'] === 'WORKSPACES_88USD'
+ && $properties['first_month_offer_ends_at'] === $periodEndsAt->toIso8601String();
+ });
+});
+
+test('handle uses the checkout marker even when the coupon configuration changes before the job runs', function () {
+ $this->payload['data']['object']['metadata'] = [
+ 'trypost_first_month_coupon_id' => 'WORKSPACES_88USD',
+ ];
+ config(['cashier.first_month_coupon_ids.workspaces' => null]);
+ Queue::fake();
+
+ (new TrackCheckoutCompleted((string) $this->account->id, $this->payload))
+ ->handle(app(PostHogService::class));
+
+ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {
+ $properties = $job->payload['properties'];
+
+ return $properties['is_first_month_offer'] === true
+ && $properties['first_month_coupon_id'] === 'WORKSPACES_88USD';
});
});
test('handle resolves the yearly interval from the price id', function () {
- $this->payload['data']['object']['items']['data'][0]['price']['id'] = 'price_workspace_yearly';
+ $this->payload['data']['object']['items']['data'][0]['price']['id'] = 'price_workspaces_yearly';
Queue::fake();
(new TrackCheckoutCompleted((string) $this->account->id, $this->payload))
diff --git a/tests/Feature/Listeners/StripeEventListenerTest.php b/tests/Feature/Listeners/StripeEventListenerTest.php
index 839ee3a11..9849d263a 100644
--- a/tests/Feature/Listeners/StripeEventListenerTest.php
+++ b/tests/Feature/Listeners/StripeEventListenerTest.php
@@ -13,7 +13,7 @@ use App\Models\Account;
use App\Models\Plan;
use App\Models\User;
use Illuminate\Support\Facades\Bus;
-use Laravel\Cashier\Events\WebhookReceived;
+use Laravel\Cashier\Events\WebhookHandled;
beforeEach(function () {
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);
@@ -52,7 +52,7 @@ beforeEach(function () {
// ========================================
test('subscription created handles event without error', function () {
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => ['customer' => 'cus_test123', 'id' => 'sub_123']],
]));
@@ -63,7 +63,7 @@ test('subscription created handles event without error', function () {
test('subscription created clears the generic trial_ends_at on the account', function () {
$this->account->update(['trial_ends_at' => now()->addDays(3)]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -81,7 +81,7 @@ test('subscription created clears the generic trial_ends_at on the account', fun
// ========================================
test('subscription updated handles event without error', function () {
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => ['object' => ['customer' => 'cus_test123', 'id' => 'sub_123']],
]));
@@ -94,7 +94,7 @@ test('subscription updated handles event without error', function () {
// ========================================
test('subscription deleted handles event without error', function () {
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.deleted',
'data' => ['object' => ['customer' => 'cus_test123', 'id' => 'sub_123']],
]));
@@ -109,7 +109,7 @@ test('subscription deleted handles event without error', function () {
test('ignores event without customer id', function () {
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => []],
]));
@@ -120,7 +120,7 @@ test('ignores event without customer id', function () {
test('ignores event for unknown customer', function () {
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => ['customer' => 'cus_nonexistent']],
]));
@@ -131,7 +131,7 @@ test('ignores event for unknown customer', function () {
test('ignores event with empty payload', function () {
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([]));
+ $this->listener->handle(new WebhookHandled([]));
Bus::assertNotDispatched(TrackBilling::class);
});
@@ -139,7 +139,7 @@ test('ignores event with empty payload', function () {
test('ignores event with null type', function () {
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => null,
'data' => ['object' => ['customer' => 'cus_test123']],
]));
@@ -152,7 +152,7 @@ test('ignores event with null type', function () {
// ========================================
test('handles malformed payload gracefully', function () {
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'data' => 'not_an_array',
]));
@@ -166,7 +166,7 @@ test('handles malformed payload gracefully', function () {
test('subscription created dispatches TrackBilling with subscription.created event', function () {
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => ['customer' => 'cus_test123', 'id' => 'sub_123', 'status' => 'trialing']],
]));
@@ -181,7 +181,7 @@ test('subscription created dispatches TrackBilling with subscription.created eve
test('subscription updated dispatches TrackBilling with subscription.updated event', function () {
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => ['object' => ['customer' => 'cus_test123', 'status' => 'active']],
]));
@@ -197,7 +197,7 @@ test('subscription deleted dispatches TrackBilling with subscription.cancelled e
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.deleted',
'data' => ['object' => ['customer' => 'cus_test123', 'status' => 'canceled']],
]));
@@ -211,7 +211,7 @@ test('subscription deleted dispatches TrackBilling with subscription.cancelled e
test('unknown event types do not dispatch TrackBilling', function () {
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'invoice.payment_succeeded',
'data' => ['object' => ['customer' => 'cus_test123']],
]));
@@ -223,7 +223,7 @@ test('TrackBilling is not dispatched when PostHog is disabled', function () {
config(['services.posthog.enabled' => false]);
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => ['customer' => 'cus_test123', 'id' => 'sub_123']],
]));
@@ -236,7 +236,7 @@ test('TrackBilling is not dispatched when PostHog is disabled in production', fu
config(['services.posthog.enabled' => false, 'services.posthog.api_key' => null]);
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => ['customer' => 'cus_test123', 'id' => 'sub_123']],
]));
@@ -249,7 +249,7 @@ test('TrackBilling is dispatched in the local environment even when PostHog is d
config(['services.posthog.enabled' => false, 'services.posthog.api_key' => null]);
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => ['customer' => 'cus_test123', 'id' => 'sub_123']],
]));
@@ -261,7 +261,7 @@ test('TrackBilling is not dispatched when api key is missing', function () {
config(['services.posthog.api_key' => null]);
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => ['customer' => 'cus_test123', 'id' => 'sub_123']],
]));
@@ -276,7 +276,7 @@ test('TrackBilling is not dispatched when api key is missing', function () {
test('subscription created syncs the plan from the price id on first activation', function () {
$this->account->update(['plan_id' => null]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -291,7 +291,7 @@ test('subscription created syncs the plan from the price id on first activation'
test('subscription created does not sync a plan while payment is incomplete', function () {
$this->account->update(['plan_id' => null]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -306,7 +306,7 @@ test('subscription created does not sync a plan while payment is incomplete', fu
test('subscription created syncs the workspaces plan while trialing', function () {
$this->account->update(['plan_id' => null]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -321,7 +321,7 @@ test('subscription created syncs the workspaces plan while trialing', function (
test('subscription updated maps the plan by its monthly price id', function () {
$this->account->update(['plan_id' => null]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -336,7 +336,7 @@ test('subscription updated maps the plan by its monthly price id', function () {
test('subscription updated maps the plan by its yearly price id too', function () {
$this->account->update(['plan_id' => null]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -351,7 +351,7 @@ test('subscription updated maps the plan by its yearly price id too', function (
test('subscription updated does not sync a richer plan while past due', function () {
$this->account->update(['plan_id' => $this->socials->id]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -366,7 +366,7 @@ test('subscription updated does not sync a richer plan while past due', function
test('subscription updated does not clear workspaces while past due', function () {
$this->account->update(['plan_id' => $this->workspaces->id]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -381,7 +381,7 @@ test('subscription updated does not clear workspaces while past due', function (
test('subscription updated overwrites socials with workspaces when active', function () {
$this->account->update(['plan_id' => $this->socials->id]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -396,7 +396,7 @@ test('subscription updated overwrites socials with workspaces when active', func
test('subscription updated overwrites workspaces with socials when active', function () {
$this->account->update(['plan_id' => $this->workspaces->id]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -411,7 +411,7 @@ test('subscription updated overwrites workspaces with socials when active', func
test('subscription updated clears the plan when payment is unpaid canceled or expired', function (string $status) {
$this->account->update(['plan_id' => $this->workspaces->id]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -430,7 +430,7 @@ test('subscription updated clears the plan when payment is unpaid canceled or ex
test('subscription updated leaves plan_id alone when the price already matches', function () {
$this->account->update(['plan_id' => $this->plan->id]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -445,7 +445,7 @@ test('subscription updated leaves plan_id alone when the price already matches',
test('subscription updated ignores unknown price ids without erroring', function () {
$this->account->update(['plan_id' => $this->plan->id]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -459,7 +459,7 @@ test('subscription updated ignores unknown price ids without erroring', function
test('subscription deleted clears the account plan_id', function () {
$this->account->update(['plan_id' => $this->plan->id]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.deleted',
'data' => ['object' => ['customer' => 'cus_test123', 'status' => 'canceled']],
]));
@@ -472,7 +472,7 @@ test('subscription deleted is idempotent when plan_id is already null', function
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.deleted',
'data' => ['object' => ['customer' => 'cus_test123']],
]));
@@ -493,7 +493,7 @@ test('subscription updated forwards the previous plan name to TrackBilling', fun
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -512,7 +512,7 @@ test('subscription deleted forwards the previous plan name to TrackBilling', fun
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.deleted',
'data' => ['object' => ['customer' => 'cus_test123']],
]));
@@ -528,7 +528,7 @@ test('subscription created forwards a null previous plan when account had none',
Bus::fake([TrackBilling::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -549,19 +549,21 @@ test('subscription created forwards a null previous plan when account had none',
test('subscription created dispatches TrackCheckoutCompleted when status is active', function () {
Bus::fake([TrackCheckoutCompleted::class, TrackTrialStarted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => [
'customer' => 'cus_test123',
'id' => 'sub_123',
'status' => 'active',
- 'items' => ['data' => [['price' => ['id' => 'price_workspace_monthly']]]],
+ 'metadata' => ['trypost_first_month_coupon_id' => 'WORKSPACES_88USD'],
+ 'items' => ['data' => [['price' => ['id' => 'price_workspaces_monthly']]]],
]],
]));
Bus::assertDispatched(
TrackCheckoutCompleted::class,
- fn ($job) => $job->accountId === (string) $this->account->id,
+ fn ($job) => $job->accountId === (string) $this->account->id
+ && data_get($job->payload, 'data.object.metadata.trypost_first_month_coupon_id') === 'WORKSPACES_88USD',
);
Bus::assertNotDispatched(TrackTrialStarted::class);
});
@@ -569,7 +571,7 @@ test('subscription created dispatches TrackCheckoutCompleted when status is acti
test('subscription created dispatches TrackTrialStarted when status is trialing', function () {
Bus::fake([TrackCheckoutCompleted::class, TrackTrialStarted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -590,7 +592,7 @@ test('subscription created dispatches TrackTrialStarted when status is trialing'
test('subscription created dispatches neither job for a status we do not track', function () {
Bus::fake([TrackCheckoutCompleted::class, TrackTrialStarted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -607,7 +609,7 @@ test('subscription created dispatches neither job for a status we do not track',
test('subscription updated and deleted do not dispatch TrackCheckoutCompleted or TrackTrialStarted', function (string $type) {
Bus::fake([TrackCheckoutCompleted::class, TrackTrialStarted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => $type,
'data' => ['object' => ['customer' => 'cus_test123', 'id' => 'sub_123', 'status' => 'active']],
]));
@@ -623,7 +625,7 @@ test('TrackCheckoutCompleted is not dispatched when PostHog is disabled', functi
config(['services.posthog.enabled' => false]);
Bus::fake([TrackCheckoutCompleted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -641,7 +643,7 @@ test('TrackCheckoutCompleted and TrackTrialStarted are not dispatched when PostH
config(['services.posthog.enabled' => false, 'services.posthog.api_key' => null]);
Bus::fake([TrackCheckoutCompleted::class, TrackTrialStarted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -660,7 +662,7 @@ test('TrackCheckoutCompleted is dispatched in the local environment even when Po
config(['services.posthog.enabled' => false, 'services.posthog.api_key' => null]);
Bus::fake([TrackCheckoutCompleted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.created',
'data' => ['object' => [
'customer' => 'cus_test123',
@@ -680,7 +682,7 @@ test('TrackCheckoutCompleted is dispatched in the local environment even when Po
test('subscription updated dispatches TrackTrialConverted when trialing transitions to active', function () {
Bus::fake([TrackTrialConverted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => [
'object' => [
@@ -703,7 +705,7 @@ test('subscription updated dispatches TrackTrialConverted when a trial recovers
Bus::fake([TrackTrialConverted::class]);
$trialEnd = now()->subDay()->timestamp;
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => [
'object' => [
@@ -729,7 +731,7 @@ test('subscription updated dispatches TrackTrialConverted when a trial recovers
test('subscription updated does not dispatch TrackTrialConverted for a past_due recovery on a subscription that never had a trial', function () {
Bus::fake([TrackTrialConverted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => [
'object' => ['customer' => 'cus_test123', 'id' => 'sub_123', 'status' => 'active'],
@@ -749,7 +751,7 @@ test('subscription updated does not dispatch TrackTrialConverted for a later, un
$trialEnd = now()->subMonths(6)->timestamp;
$currentPeriodStart = now()->subDays(3)->timestamp;
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => [
'object' => [
@@ -772,7 +774,7 @@ test('subscription updated does not dispatch TrackTrialConverted for a later, un
test('subscription updated does not dispatch TrackTrialConverted when the new status is not active', function () {
Bus::fake([TrackTrialConverted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => [
'object' => ['customer' => 'cus_test123', 'id' => 'sub_123', 'status' => 'past_due'],
@@ -787,7 +789,7 @@ test('TrackTrialConverted is not dispatched when PostHog is disabled', function
config(['services.posthog.enabled' => false]);
Bus::fake([TrackTrialConverted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => [
'object' => ['customer' => 'cus_test123', 'id' => 'sub_123', 'status' => 'active'],
@@ -803,7 +805,7 @@ test('TrackTrialConverted is not dispatched when PostHog is disabled in producti
config(['services.posthog.enabled' => false, 'services.posthog.api_key' => null]);
Bus::fake([TrackTrialConverted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => [
'object' => ['customer' => 'cus_test123', 'id' => 'sub_123', 'status' => 'active'],
@@ -819,7 +821,7 @@ test('TrackTrialConverted is dispatched in the local environment even when PostH
config(['services.posthog.enabled' => false, 'services.posthog.api_key' => null]);
Bus::fake([TrackTrialConverted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => [
'object' => ['customer' => 'cus_test123', 'id' => 'sub_123', 'status' => 'active'],
@@ -846,8 +848,8 @@ test('redelivering the same stripe event id only processes it once', function ()
],
];
- $this->listener->handle(new WebhookReceived($payload));
- $this->listener->handle(new WebhookReceived($payload));
+ $this->listener->handle(new WebhookHandled($payload));
+ $this->listener->handle(new WebhookHandled($payload));
Bus::assertDispatchedTimes(TrackTrialConverted::class, 1);
});
@@ -855,7 +857,7 @@ test('redelivering the same stripe event id only processes it once', function ()
test('two different stripe event ids are both processed', function () {
Bus::fake([TrackTrialConverted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'id' => 'evt_test_first',
'type' => 'customer.subscription.updated',
'data' => [
@@ -863,7 +865,7 @@ test('two different stripe event ids are both processed', function () {
'previous_attributes' => ['status' => 'trialing'],
],
]));
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'id' => 'evt_test_second',
'type' => 'customer.subscription.updated',
'data' => [
@@ -878,7 +880,7 @@ test('two different stripe event ids are both processed', function () {
test('an event without an id is still processed (no idempotency key available)', function () {
Bus::fake([TrackTrialConverted::class]);
- $this->listener->handle(new WebhookReceived([
+ $this->listener->handle(new WebhookHandled([
'type' => 'customer.subscription.updated',
'data' => [
'object' => ['customer' => 'cus_test123', 'id' => 'sub_123', 'status' => 'active'],
diff --git a/tests/Unit/Actions/Billing/StartSubscriptionCheckoutTest.php b/tests/Unit/Actions/Billing/StartSubscriptionCheckoutTest.php
index bb1f3403f..e16d26e1d 100644
--- a/tests/Unit/Actions/Billing/StartSubscriptionCheckoutTest.php
+++ b/tests/Unit/Actions/Billing/StartSubscriptionCheckoutTest.php
@@ -187,8 +187,20 @@ test('redirect applies the plan first-month coupon on a monthly price', function
$account->refresh();
$builder = Mockery::mock(SubscriptionBuilder::class);
- $builder->shouldReceive('withMetadata')->once()->andReturnSelf();
- $builder->shouldReceive('withCoupon')->once()->with('SOCIALS_18USD')->andReturnSelf();
+ $builder->shouldReceive('withCoupon')
+ ->once()
+ ->with('SOCIALS_18USD')
+ ->ordered()
+ ->andReturnUsing(function () use ($builder): SubscriptionBuilder {
+ $builder->couponId = 'SOCIALS_18USD';
+
+ return $builder;
+ });
+ $builder->shouldReceive('withMetadata')
+ ->once()
+ ->with(['trypost_first_month_coupon_id' => 'SOCIALS_18USD'])
+ ->ordered()
+ ->andReturnSelf();
$builder->shouldReceive('trialDays')->never();
$builder->shouldReceive('checkout')
->once()
@@ -227,7 +239,7 @@ test('redirect skips the first-month coupon on a yearly price', function () {
$account->refresh();
$builder = Mockery::mock(SubscriptionBuilder::class);
- $builder->shouldReceive('withMetadata')->once()->andReturnSelf();
+ $builder->shouldReceive('withMetadata')->once()->with([])->andReturnSelf();
$builder->shouldReceive('withCoupon')->never();
$builder->shouldReceive('trialDays')->once()->with(8)->andReturnSelf();
$builder->shouldReceive('checkout')
diff --git a/tests/Unit/Models/AccountTest.php b/tests/Unit/Models/AccountTest.php
index 313e76102..a91c98191 100644
--- a/tests/Unit/Models/AccountTest.php
+++ b/tests/Unit/Models/AccountTest.php
@@ -22,6 +22,50 @@ test('isPastDue returns false without a subscription', function () {
expect($account->isPastDue())->toBeFalse();
});
+test('subscriptionStatus returns none without a subscription', function () {
+ $account = Account::factory()->create(['trial_ends_at' => null]);
+
+ expect($account->subscriptionStatus())->toBe('none');
+});
+
+test('subscriptionStatus returns the current Stripe status', function () {
+ $account = Account::factory()->create(['trial_ends_at' => null]);
+ $account->subscriptions()->create([
+ 'type' => Account::SUBSCRIPTION_NAME,
+ 'stripe_id' => 'sub_test_'.fake()->uuid(),
+ 'stripe_status' => 'past_due',
+ 'stripe_price' => 'price_123',
+ ]);
+
+ expect($account->subscriptionStatus())->toBe('past_due');
+});
+
+test('subscriptionStatus returns canceled during the grace period', function () {
+ $account = Account::factory()->create(['trial_ends_at' => null]);
+ $account->subscriptions()->create([
+ 'type' => Account::SUBSCRIPTION_NAME,
+ 'stripe_id' => 'sub_test_'.fake()->uuid(),
+ 'stripe_status' => 'active',
+ 'stripe_price' => 'price_123',
+ 'ends_at' => now()->addDay(),
+ ]);
+
+ expect($account->subscriptionStatus())->toBe('canceled');
+});
+
+test('subscriptionStatus returns canceled after the subscription has ended', function () {
+ $account = Account::factory()->create(['trial_ends_at' => null]);
+ $account->subscriptions()->create([
+ 'type' => Account::SUBSCRIPTION_NAME,
+ 'stripe_id' => 'sub_test_'.fake()->uuid(),
+ 'stripe_status' => 'active',
+ 'stripe_price' => 'price_123',
+ 'ends_at' => now(),
+ ]);
+
+ expect($account->subscriptionStatus())->toBe('canceled');
+});
+
test('isPastDue returns true for a past_due subscription', function () {
config(['trypost.self_hosted' => false]);
diff --git a/tests/Unit/Support/Billing/ConfigureSubscriptionCheckoutTest.php b/tests/Unit/Support/Billing/ConfigureSubscriptionCheckoutTest.php
index 3514f3e20..c466e00aa 100644
--- a/tests/Unit/Support/Billing/ConfigureSubscriptionCheckoutTest.php
+++ b/tests/Unit/Support/Billing/ConfigureSubscriptionCheckoutTest.php
@@ -216,9 +216,9 @@ test('does not throw when coupon and promo are both set but a prior canceled sub
->and(trialExpiresAt($subscription))->toBeNull();
});
-test('empty coupon with card required does not throw and still applies trial', function () {
+test('missing coupon with card required does not throw and still applies trial', function (?string $couponId) {
config([
- 'cashier.first_month_coupon_ids.socials' => '',
+ 'cashier.first_month_coupon_ids.socials' => $couponId,
'cashier.allow_promotion_codes' => false,
]);
Workspace::factory()->create(['account_id' => $this->account->id]);
@@ -231,7 +231,10 @@ test('empty coupon with card required does not throw and still applies trial', f
expect($subscription->couponId)->toBeNull()
->and(trialExpiresAt($subscription)?->toDateTimeString())->toBe('2026-08-15 12:00:00');
-});
+})->with([
+ 'environment variable is unset' => null,
+ 'environment variable is empty' => '',
+]);
test('skips the coupon and allows promotion codes when a card is not required', function () {
config([