metatrondelivery/app/routes/webhooks.app_subscriptions.update.tsx
metatroncubeswdev d150509978
Some checks failed
CI / Lint, Unit & Integration Tests (push) Has been cancelled
feat(phase-8): Billing API with server-side feature gating
Add real Shopify Billing API integration: Free/Starter/Growth/Pro plans
(app/lib/billing-plans.ts, priced per PRODUCT_STRATEGY.md §6) wired into
shopify.server.ts's billing config, a merchant-facing plan page
(app/routes/app.billing.tsx) using billing.request/billing.cancel, and
webhooks.app_subscriptions.update.tsx as the durable sync path for
Shop.tier (fires even when a merchant cancels from Shopify's own billing
page, not just from this app).

Gate the features actually built so far in both loader and action (never
just hidden in the UI, so a direct POST can't bypass a tier limit):
delivery zones/rates require Growth+, the dispatch dashboard requires
Starter+, and location count is capped per tier (Free=1, Starter=3,
Growth/Pro=unlimited). Split pure tier logic (app/lib/billing-plans.ts)
from DB-backed reads/writes (app/services/billing.server.ts) so the
client-rendered UpsellState component can import the Tier type without
pulling server code into the client bundle — same split as currency.ts.

Covered by tests/unit/billing-plans.test.ts (pure tier ranking/mapping)
and tests/integration/billing.test.ts (tier persistence and location-limit
enforcement against live Postgres).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 09:29:42 -04:00

22 lines
1.0 KiB
TypeScript

import type { ActionFunctionArgs } from "@remix-run/node";
import { authenticate } from "../shopify.server";
import { setShopTier, tierFromPlanName } from "../services/billing.server";
// Fires whenever an AppSubscription's status changes (created, activated,
// cancelled, expired, frozen for non-payment, declined) — the durable,
// authoritative way to keep Shop.tier in sync, since it fires even when the
// merchant cancels from Shopify's own billing page rather than /app/billing.
export const action = async ({ request }: ActionFunctionArgs) => {
const { shop, topic, payload } = await authenticate.webhook(request);
const subscription = (payload as { app_subscription?: { name?: string; status?: string } })
.app_subscription;
const tier = subscription?.status === "ACTIVE" ? tierFromPlanName(subscription.name) : "free";
await setShopTier(shop, tier);
console.log(`[billing] ${topic} for ${shop}: ${subscription?.name ?? "none"} (${subscription?.status}) -> tier=${tier}`);
return new Response();
};