From c93d015a2226c914774c2925f875c392eeebd882 Mon Sep 17 00:00:00 2001 From: roble Date: Sun, 15 Nov 2026 19:48:27 +0000 Subject: [PATCH 01/10] fix: a new price row whose key starts with a price's id doesn't keep that price Co-Authored-By: Claude Opus 5.5 --- .../Resources/Products/Pages/EditProduct.php | 5 ++++- tests/Feature/ProductAdminGuardsTest.php | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/Filament/Resources/Products/Pages/EditProduct.php b/src/Filament/Resources/Products/Pages/EditProduct.php index 7f0851b..e8df071 100644 --- a/src/Filament/Resources/Products/Pages/EditProduct.php +++ b/src/Filament/Resources/Products/Pages/EditProduct.php @@ -59,7 +59,10 @@ protected function handleRecordUpdate(Model $record, array $data): Model */ protected function beforeSave(): void { - $kept = collect($this->data['prices'] ?? [])->keys()->map(fn ($key) => (int) str_replace('record-', '', (string) $key)); + // Saved rows are keyed `record-`; a new row's UUID key may start with digits too. + $kept = collect($this->data['prices'] ?? [])->keys() + ->map(fn ($key) => preg_match('/^record-(\d+)$/', (string) $key, $match) ? (int) $match[1] : null) + ->filter(); $removed = $this->getRecord()->prices() ->whereNotNull('provider_price_id') diff --git a/tests/Feature/ProductAdminGuardsTest.php b/tests/Feature/ProductAdminGuardsTest.php index 17d4d24..5497ea3 100644 --- a/tests/Feature/ProductAdminGuardsTest.php +++ b/tests/Feature/ProductAdminGuardsTest.php @@ -78,6 +78,23 @@ public function test_removing_a_price_pushed_after_the_form_opened_keeps_it(): v $this->assertModelExists($price); } + /** A new row's key is a UUID, and one starting with the price's id is not that price. */ + public function test_a_new_row_whose_key_starts_with_the_price_id_does_not_keep_it(): void + { + $product = Product::factory()->create(['provider_product_id' => null]); + $price = Price::factory()->create(['product_id' => $product->id, 'provider_price_id' => null]); + + $page = Livewire::test(EditProduct::class, ['record' => $product->getKey()]); + $row = $page->get('data.prices')["record-{$price->id}"]; + + $price->forceFill(['provider' => 'stripe', 'provider_price_id' => 'price_pushed'])->save(); + + $page->set('data.prices', ["{$price->id}abcdef-0000-4000-8000-000000000000" => $row])->call('save'); + + $this->assertModelExists($price); + $this->assertSame(1, $product->prices()->count()); + } + public function test_a_gateway_managed_price_keeps_its_amount(): void { $product = Product::factory()->create([ From 5dbe0db9018e239f2bf5c8bfa32dba5177716a0e Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 16 Nov 2026 08:58:58 +0000 Subject: [PATCH 02/10] chore: alias dev as 3.6.x-dev, past the v3.5.0 release Co-Authored-By: Claude Opus 5.5 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index b830dcd..3cb616a 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ ] }, "branch-alias": { - "dev-dev": "3.5.x-dev" + "dev-dev": "3.6.x-dev" } }, "autoload": { From 8e4f7822a81ce9386c4ad984472b0092f7cd82dd Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 16 Nov 2026 11:37:49 +0000 Subject: [PATCH 03/10] chore: alias dev as 3.x-dev, so it never falls behind a minor release Co-Authored-By: Claude Opus 5.5 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 3cb616a..ff2814d 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ ] }, "branch-alias": { - "dev-dev": "3.6.x-dev" + "dev-dev": "3.x-dev" } }, "autoload": { From 0e820c009669959cc2c44309917381e4935b05d2 Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 16 Nov 2026 12:29:52 +0000 Subject: [PATCH 04/10] feat: the demo seeder declares its accounts (#[DemoAccount]) The installer and modules:seed name the featured ones; a test checks the seeder creates every account it declares. Co-Authored-By: Claude Opus 5.5 --- database/seeders/ShowcaseBillingDatabaseSeeder.php | 2 ++ tests/Feature/ShowcaseStaffTest.php | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/database/seeders/ShowcaseBillingDatabaseSeeder.php b/database/seeders/ShowcaseBillingDatabaseSeeder.php index f96a56f..5d4afbc 100644 --- a/database/seeders/ShowcaseBillingDatabaseSeeder.php +++ b/database/seeders/ShowcaseBillingDatabaseSeeder.php @@ -7,6 +7,7 @@ use Modules\Billing\Models\Product; use Modules\Billing\Services\CatalogPush; use Modules\Billing\Services\PaymentGatewayManager; +use Saucebase\Core\Attributes\DemoAccount; use Spatie\Permission\Models\Role; /** @@ -16,6 +17,7 @@ * created locally and pushed to the provider when its keys are present, which * is what makes the demo site's checkout work. */ +#[DemoAccount('billing@saucebase.dev', 'staff: the billing admin')] class ShowcaseBillingDatabaseSeeder extends Seeder { public function run(): void diff --git a/tests/Feature/ShowcaseStaffTest.php b/tests/Feature/ShowcaseStaffTest.php index 79334e0..839b332 100644 --- a/tests/Feature/ShowcaseStaffTest.php +++ b/tests/Feature/ShowcaseStaffTest.php @@ -7,6 +7,7 @@ use Illuminate\Support\Facades\Hash; use Modules\Billing\Database\Seeders\DatabaseSeeder; use Modules\Billing\Database\Seeders\ShowcaseBillingDatabaseSeeder; +use Saucebase\Core\Testing\AssertsDemoAccounts; use Tests\TestCase; /** @@ -15,6 +16,7 @@ */ class ShowcaseStaffTest extends TestCase { + use AssertsDemoAccounts; use RefreshDatabase; public function test_the_demo_adds_a_staff_account_for_this_module_only(): void @@ -35,4 +37,10 @@ public function test_demo_accounts_use_the_configured_demo_password(): void $this->assertTrue(Hash::check('not-the-old-default', User::where('email', 'billing@saucebase.dev')->value('password'))); } + + /** The accounts the seeder declares (#[DemoAccount]) are the ones it creates. */ + public function test_every_declared_demo_account_is_created(): void + { + $this->assertDemoAccountsSeeded(ShowcaseBillingDatabaseSeeder::class); + } } From 7904f350cfed00b19dd4f229fb078200c55e1d29 Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 16 Nov 2026 19:34:56 +0000 Subject: [PATCH 05/10] refactor: rename billWorkspaces to billTenants for clarity in BillingOwnerTest --- tests/Feature/BillingOwnerTest.php | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/tests/Feature/BillingOwnerTest.php b/tests/Feature/BillingOwnerTest.php index 57ec42e..6d8ceae 100644 --- a/tests/Feature/BillingOwnerTest.php +++ b/tests/Feature/BillingOwnerTest.php @@ -80,7 +80,7 @@ protected function setUp(): void } /** Resolves on every call, from the database: a removed member is out on their next request. */ - private function billWorkspaces(): void + private function billTenants(): void { app(BillingOwners::class)->resolveUsing(function (User $user): ?TestWorkspace { $workspace = TestWorkspace::find($this->workspace->id); @@ -161,7 +161,7 @@ public function test_without_a_resolver_the_user_is_the_owner(): void public function test_a_managers_checkout_bills_the_workspace_with_the_buyers_details(): void { - $this->billWorkspaces(); + $this->billTenants(); $price = Price::factory()->create(); $this->actingAs($this->manager)->post(route('billing.checkout.create'), ['price_id' => $price->id]) @@ -174,7 +174,7 @@ public function test_a_managers_checkout_bills_the_workspace_with_the_buyers_det public function test_members_get_the_workspaces_plan(): void { - $this->billWorkspaces(); + $this->billTenants(); $this->subscribeWorkspace(); $owner = app(BillingOwners::class)->for($this->member); @@ -190,7 +190,7 @@ public function test_members_get_the_workspaces_plan(): void public function test_a_member_who_cannot_manage_billing_changes_nothing(): void { - $this->billWorkspaces(); + $this->billTenants(); $this->subscribeWorkspace(); $session = $this->pendingSession(); @@ -209,7 +209,7 @@ public function test_a_member_who_cannot_manage_billing_changes_nothing(): void public function test_the_billing_panel_shows_for_a_manager(): void { - $this->billWorkspaces(); + $this->billTenants(); $this->subscribeWorkspace(); $this->actingAs($this->manager); @@ -220,7 +220,7 @@ public function test_the_billing_panel_shows_for_a_manager(): void public function test_a_removed_member_loses_the_plan_on_their_next_request(): void { - $this->billWorkspaces(); + $this->billTenants(); $this->subscribeWorkspace(); $this->assertTrue(app(BillingOwners::class)->for($this->member)?->canUseFeature('exports') ?? false); @@ -244,7 +244,7 @@ public function test_a_resolver_answering_with_something_that_is_not_an_owner_is public function test_a_guest_still_starts_a_checkout_and_is_sent_to_register(): void { - $this->billWorkspaces(); + $this->billTenants(); $price = Price::factory()->create(); $response = $this->post(route('billing.checkout.create'), ['price_id' => $price->id]); @@ -258,14 +258,14 @@ public function test_a_checkout_bound_to_one_workspace_is_refused_while_acting_f { $other = TestWorkspace::create(['name' => 'Other', 'billing_email' => 'b@other.test', 'members' => [(string) $this->manager->id => 'manager']]); $session = $this->pendingSession($other->billingCustomer()->create(['provider' => 'stripe'])->id); - $this->billWorkspaces(); + $this->billTenants(); $this->actingAs($this->manager)->post(route('billing.checkout.retry', $session))->assertForbidden(); } public function test_the_return_fulfils_only_the_managed_owners_checkout(): void { - $this->billWorkspaces(); + $this->billTenants(); $service = $this->mock(WebhookHandler::class); $service->shouldNotReceive('fulfillCheckoutIfNeeded'); @@ -278,7 +278,7 @@ public function test_the_return_fulfils_only_the_managed_owners_checkout(): void public function test_the_owner_sees_the_customer_it_just_got(): void { - $this->billWorkspaces(); + $this->billTenants(); $workspace = app(BillingOwners::class)->managedBy($this->manager); $this->assertNull($workspace->billingAccount()); @@ -289,7 +289,7 @@ public function test_the_owner_sees_the_customer_it_just_got(): void public function test_a_second_managers_checkout_keeps_the_billing_contact(): void { - $this->billWorkspaces(); + $this->billTenants(); $customer = $this->workspace->billingCustomer()->create(['provider' => 'stripe', 'provider_customer_id' => 'cus_ws', 'name' => 'Acme Ltd', 'email' => 'billing@acme.test']); $second = $this->createUser(); $this->workspace->update(['members' => [...$this->workspace->members, (string) $second->id => 'manager']]); From 598d737a0af6dd83c257a3fa1045986021d3f1f0 Mon Sep 17 00:00:00 2001 From: roble Date: Wed, 18 Nov 2026 11:52:53 +0000 Subject: [PATCH 06/10] test: the user menu names the Free plan when the app has one The fallback test assumed no Free plan. An app that seeds one (the Uptime template) names it for every user, as planName() intends. Co-Authored-By: Claude Opus 5.5 --- tests/e2e/tests/sidebar/user-menu.spec.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/e2e/tests/sidebar/user-menu.spec.ts b/tests/e2e/tests/sidebar/user-menu.spec.ts index 5e1e360..94631ae 100644 --- a/tests/e2e/tests/sidebar/user-menu.spec.ts +++ b/tests/e2e/tests/sidebar/user-menu.spec.ts @@ -16,16 +16,23 @@ test.describe.parallel('Sidebar user menu', () => { await expect(page.getByTestId('user-menu-plan')).toHaveText('Pro'); }); - test('falls back to the email when there is no plan to name', async ({ + // A user with nothing bought is on the app's Free plan, if it has one (a template may + // ship one); with none, there is no plan to name and the menu falls back to the email. + test('names the Free plan, or the email when there is none', async ({ page, + laravel, loginAs, credentials, }) => { + const [free] = await laravel.select( + "SELECT name FROM products WHERE kind = 'free' AND deleted_at IS NULL", + ); + await loginAs(credentials.user); await page.goto('/dashboard'); await expect(page.getByTestId('user-menu-plan')).toHaveText( - credentials.user.email, + (free?.name as string | undefined) ?? credentials.user.email, ); }); }); From 28103a828d31d15d14a5589c1c21c78af5d6791f Mon Sep 17 00:00:00 2001 From: roble Date: Thu, 19 Nov 2026 09:21:49 +0000 Subject: [PATCH 07/10] fix: the React checkout shows its validation errors An invalid email or too-long coupon came back with no message on React; Vue shows them through core's InputField, which React doesn't have. The errors now render under their fields with the same ids and test ids (email-error, checkout-email-error), aria-invalid and aria-describedby. Co-Authored-By: Claude Opus 5.5 --- resources/js/react/pages/Checkout.tsx | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/resources/js/react/pages/Checkout.tsx b/resources/js/react/pages/Checkout.tsx index 0a8b0cd..bc3f28a 100644 --- a/resources/js/react/pages/Checkout.tsx +++ b/resources/js/react/pages/Checkout.tsx @@ -1,5 +1,5 @@ import { Button } from '@/components/ui/button'; -import { Field, FieldLabel } from '@/components/ui/field'; +import { Field, FieldError, FieldLabel } from '@/components/ui/field'; import { Input } from '@/components/ui/input'; import { useForm, usePage } from '@inertiajs/react'; import type { CheckoutSession } from '@modules/billing/resources/js/types'; @@ -29,7 +29,8 @@ export default function Checkout({ const price = session.price; const product = price.product; - const { data, setData, post, processing } = useForm({ + // Errors under their fields, with the ids and test ids Vue's InputField gives them. + const { data, setData, post, processing, errors } = useForm({ email: user?.email ?? '', coupon: '', }); @@ -130,6 +131,10 @@ export default function Checkout({ id="coupon" name="coupon" data-testid="checkout-coupon" + aria-invalid={errors.coupon ? true : undefined} + aria-describedby={ + errors.coupon ? 'coupon-error' : undefined + } type="text" placeholder={t('Enter your code')} value={data.coupon} @@ -137,6 +142,12 @@ export default function Checkout({ setData('coupon', event.target.value) } /> + + {errors.coupon} + )} @@ -214,6 +225,10 @@ export default function Checkout({ id="email" name="email" data-testid="checkout-email" + aria-invalid={errors.email ? true : undefined} + aria-describedby={ + errors.email ? 'email-error' : undefined + } type="email" placeholder={t('Enter your email')} autoComplete="email" @@ -223,6 +238,12 @@ export default function Checkout({ setData('email', event.target.value) } /> + + {errors.email} +

From cba6bb80a2348e567d760f119be8f4f258c3585c Mon Sep 17 00:00:00 2001 From: roble Date: Thu, 19 Nov 2026 21:34:00 +0000 Subject: [PATCH 08/10] fix: the first payment is matched by its invoice, late invoices keep the period, React pricing renders its interval on first paint Co-Authored-By: Claude Opus 5.5 --- .../saucebase-billing-development/SKILL.md | 6 +- resources/js/lib/intervals.test.ts | 16 +++++ resources/js/lib/intervals.ts | 10 +++ .../js/react/components/ProductSection.tsx | 20 ++---- src/Actions/CompleteCheckout.php | 3 +- src/Data/Webhook/CheckoutSessionData.php | 2 + src/Data/Webhook/InvoicePaymentData.php | 1 + src/Services/Gateways/StripeEventMapper.php | 2 + src/Services/WebhookHandler.php | 18 ++--- tests/Feature/WebhookHandlerTest.php | 66 ++++++++++++++++++- tests/Unit/StripeEventMapperTest.php | 10 +++ 11 files changed, 122 insertions(+), 32 deletions(-) diff --git a/resources/boost/skills/saucebase-billing-development/SKILL.md b/resources/boost/skills/saucebase-billing-development/SKILL.md index a4945ae..216d69f 100644 --- a/resources/boost/skills/saucebase-billing-development/SKILL.md +++ b/resources/boost/skills/saucebase-billing-development/SKILL.md @@ -90,7 +90,7 @@ On return, the provider sends the buyer to `settings.billing?checkout_session={o - `SubscriptionTrialWillEnd` → mirrors trial dates and fires `TrialEnding` - `PaymentMethodAttached` / `PaymentMethodDetached` → keeps cards added or removed in the provider's portal in step, and clears a subscription pointing at a removed one. Attaching never makes a card the default - `CustomerUpdated` → the default card follows `invoice_settings.default_payment_method`, cleared when the provider clears it - - `InvoicePaid` → creates/updates Invoice, syncs subscription period dates + - `InvoicePaid` → creates/updates Invoice, syncs subscription period dates through `applyIfCurrent()` (a late invoice for an earlier period is skipped, and a Cancelled row is left alone; it does not stamp `last_event_at`) ### Subscription Lifecycle @@ -164,7 +164,7 @@ The **data contract is provider-neutral**: incoming webhooks, `retrieveSubscript It is **not** a drop-in for any provider yet: optional operations (portal, plan change) have no capability flags, payment identity across checkout/payment/refund is Stripe-shaped (an invoice ID stands in when there is no payment intent), and running two providers at once is sc-788. `NeutralGatewayTest` is the proof of the contract — a fake provider that speaks only the module's data. ### Payment Correlation -Payments are matched by provider identity, never by time. `createPaymentFromWebhook()` looks for an existing row by `provider_payment_id` (so a failed invoice that later succeeds updates the same record), then for the subscription's checkout-created payment that has no intent yet. An invoice whose subscription does not exist locally throws, and the retry lands after `CheckoutCompleted` has created it. +Payments are matched by provider identity, never by time. Checkout records a subscription's first payment under its invoice (`CheckoutSessionData::providerInvoiceId`, Stripe's session `invoice`), as the payment intent is not known yet. `createPaymentFromWebhook()` looks for an existing row by `provider_payment_id` (so a failed invoice that later succeeds updates the same record), then by the event's `providerInvoiceId`, and replaces checkout's stand-in with the intent. A gateway that names no invoice gets a second row for the first payment. An invoice whose subscription does not exist locally throws, and the retry lands after `CheckoutCompleted` has created it. ## ENV Variables @@ -264,7 +264,7 @@ purpose allows it by pattern, e.g. - `Product::description` is rich-editor HTML, also imported from the provider, rendered with `v-html` on the pricing and checkout pages. It is cast with core's `SanitizedHtml` (`Str::sanitizeHtml()` on read, stored as written), so every read is safe markup (sc-1131) - `CheckoutSession` uses `uuid` as the route key (not `id`) — always resolve via UUID in URLs - Every `provider_*_id` is namespaced by a `provider` column (the gateway driver slug). Look rows up with both, never by the provider ID alone; uniqueness is `(provider, provider_x_id)` -- `subscriptions.last_event_at` is when the last applied provider event happened. `SubscriptionUpdated`/`Deleted` skip events older than it, so a late delivery cannot roll state back +- `subscriptions.last_event_at` is when the last applied provider event happened. `SubscriptionUpdated`/`Deleted`, `TrialWillEnd` and `InvoicePaid`'s period sync skip events older than it, so a late delivery cannot roll state back - Webhook signature verification happens inside `StripeGateway::verifyAndParseWebhook()` before deduplication — a bad signature throws `InvalidWebhookSignatureException`, which `WebhookController` answers with an empty 400. Any other exception is an empty 500 so Stripe retries; do not catch and acknowledge (see *Errors*) - Stripe API versions from 2025-03-31 keep `current_period_start/end` on the subscription **item**, not the subscription. `StripeEventMapper::subscription()` checks both; nothing else reads periods from Stripe - Webhook tests build deliveries with `Tests\Support\StripeWebhook::make()`, which runs Stripe-shaped fixtures through the real mapper — mapper + service integration, not Stripe end to end. It defaults a completed checkout to `payment_status: paid`, as Stripe always sends one diff --git a/resources/js/lib/intervals.test.ts b/resources/js/lib/intervals.test.ts index 99d5456..b1fa5e6 100644 --- a/resources/js/lib/intervals.test.ts +++ b/resources/js/lib/intervals.test.ts @@ -4,6 +4,7 @@ import { getIntervalLabel, matchesInterval, normalizeInterval, + pickInterval, } from './intervals'; describe('intervals', () => { @@ -37,3 +38,18 @@ describe('intervals', () => { expect(getIntervalLabel('quarter')).toBe('quarter'); }); }); + +describe('pickInterval', () => { + it('keeps the current interval while it is offered', () => { + expect(pickInterval(['month', 'year'], 'year')).toBe('year'); + }); + + /** Decided while rendering, so the server's first paint selects a toggle that has cards. */ + it('falls back to the first offered interval', () => { + expect(pickInterval(['year', 'one_time'], 'month')).toBe('year'); + }); + + it('keeps the current one when nothing is offered', () => { + expect(pickInterval([], 'month')).toBe('month'); + }); +}); diff --git a/resources/js/lib/intervals.ts b/resources/js/lib/intervals.ts index a7978fa..e43a0a8 100644 --- a/resources/js/lib/intervals.ts +++ b/resources/js/lib/intervals.ts @@ -32,3 +32,13 @@ export function matchesInterval( export function getIntervalLabel(interval: string): string { return INTERVAL_CONFIG[interval]?.label || interval; } + +/** + * The toggle's interval: the current one while it is offered, else the first offered. + * Decided while rendering (not in an effect), so the server's first paint agrees. + */ +export function pickInterval(available: string[], current: string): string { + return available.length === 0 || available.includes(current) + ? current + : available[0]; +} diff --git a/resources/js/react/components/ProductSection.tsx b/resources/js/react/components/ProductSection.tsx index 82142cf..f0a4a9e 100644 --- a/resources/js/react/components/ProductSection.tsx +++ b/resources/js/react/components/ProductSection.tsx @@ -1,5 +1,5 @@ import { useT } from '@saucebase/react/i18n'; -import { useEffect, useMemo, useState, type ReactNode } from 'react'; +import { useMemo, useState, type ReactNode } from 'react'; import type { PlanAction, @@ -10,6 +10,7 @@ import { getIntervalLabel, matchesInterval, normalizeInterval, + pickInterval, } from '../../lib/intervals'; import ProductCard from './ProductCard'; @@ -60,17 +61,10 @@ export default function ProductSection({ ); }, [products]); - const [billingInterval, setBillingInterval] = useState('month'); - - // Set default to first available interval when products change - useEffect(() => { - if ( - availableIntervals.length > 0 && - !availableIntervals.includes(billingInterval) - ) { - setBillingInterval(availableIntervals[0]); - } - }, [availableIntervals, billingInterval]); + const [chosenInterval, setChosenInterval] = useState('month'); + // Derived while rendering, so the server's first paint selects an offered interval; + // an effect only ran in the browser, after a paint of the wrong (empty) toggle. + const billingInterval = pickInterval(availableIntervals, chosenInterval); const filteredProducts = useMemo( () => @@ -113,7 +107,7 @@ export default function ProductSection({ {availableIntervals.map((interval) => (