feature plus ux rearrangements
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
import { pbAdmin } from '$lib/server/pocketbase';
|
||||
|
||||
// How a family has access. 'none' = signed up with no code/sub yet (gated).
|
||||
export type PaymentMode = 'none' | 'code' | 'sub' | 'canceled';
|
||||
|
||||
export interface FamAccess {
|
||||
disabled: boolean;
|
||||
mode: PaymentMode;
|
||||
reason: '' | 'no_access' | 'canceled' | 'subscription_inactive' | 'code_disabled' | 'code_expired';
|
||||
}
|
||||
|
||||
// UTC timestamp `months` months after `iso`. Used for the code's global expiry
|
||||
// (from the code's createdAt) and the duration clock (from entry date).
|
||||
export function addMonthsUTC(iso: string | Date, months: number): number {
|
||||
const d = new Date(iso);
|
||||
d.setUTCMonth(d.getUTCMonth() + months);
|
||||
return d.getTime();
|
||||
}
|
||||
|
||||
// A code is usable iff it exists, is not globally disabled, is not past its own
|
||||
// createdAt+expiry window (expiry 0 = never), and the duration clock from the
|
||||
// fam's entry date hasn't run out (duration 0 = continuous).
|
||||
export function codeIsValid(code: any, enteredAt?: string): boolean {
|
||||
if (!code) return false;
|
||||
if (code.active === false) return false;
|
||||
const now = Date.now();
|
||||
const expiryMonths = Number(code.expiry) || 0;
|
||||
if (expiryMonths > 0 && now >= addMonthsUTC(code.createdAt, expiryMonths)) return false;
|
||||
const durationMonths = Number(code.duration) || 0;
|
||||
if (durationMonths > 0 && enteredAt) {
|
||||
if (now >= addMonthsUTC(enteredAt, durationMonths)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Deterministic decision from a fam + its linked code (no I/O). `active` on the
|
||||
// fam is the single source of truth for "usable right now".
|
||||
export function computeFamAccess(fam: any, code: any): FamAccess {
|
||||
const mode: PaymentMode = fam.paymentMode || 'none';
|
||||
switch (mode) {
|
||||
case 'code': {
|
||||
if (code?.active === false) return { disabled: true, mode, reason: 'code_disabled' };
|
||||
return codeIsValid(code, fam.accessCodeEnteredAt)
|
||||
? { disabled: false, mode, reason: '' }
|
||||
: { disabled: true, mode, reason: 'code_expired' };
|
||||
}
|
||||
case 'sub':
|
||||
return fam.active === false
|
||||
? { disabled: true, mode, reason: 'subscription_inactive' }
|
||||
: { disabled: false, mode, reason: '' };
|
||||
case 'canceled':
|
||||
return { disabled: true, mode, reason: 'canceled' };
|
||||
case 'none':
|
||||
default:
|
||||
return { disabled: true, mode, reason: 'no_access' };
|
||||
}
|
||||
}
|
||||
|
||||
// Read the fam + linked code and persist `active` if it drifted. Called on every
|
||||
// [fam] layout load (both roles) and wherever access state must be re-evaluated.
|
||||
export async function ensureFamAccess(famId: string): Promise<{ fam: any; access: FamAccess }> {
|
||||
const fam = await pbAdmin.getOne('fams', famId);
|
||||
if (!fam) return { fam: null, access: { disabled: true, mode: 'none', reason: 'no_access' } };
|
||||
let code: any = null;
|
||||
if (fam.accessCodeId) {
|
||||
try {
|
||||
code = await pbAdmin.getOne('accesscodes', fam.accessCodeId);
|
||||
} catch {
|
||||
code = null;
|
||||
}
|
||||
}
|
||||
const access = computeFamAccess(fam, code);
|
||||
if (fam.active !== !access.disabled) {
|
||||
await pbAdmin.update('fams', famId, { active: !access.disabled });
|
||||
}
|
||||
return { fam: { ...fam, active: !access.disabled }, access };
|
||||
}
|
||||
|
||||
// Apply an access code value to a fam. Automatic (no approval) — validates
|
||||
// against the accesscodes collection and sets paymentMode='code' on success.
|
||||
export async function applyAccessCode(famId: string, value: string) {
|
||||
const val = String(value || '').trim();
|
||||
if (!val) return { error: 'Enter an access code' };
|
||||
const list = await pbAdmin.getList('accesscodes', `value = '${val}'`);
|
||||
const code = list?.[0];
|
||||
if (!code) return { error: 'That access code is not recognised' };
|
||||
if (code.active === false) return { error: 'That access code is disabled' };
|
||||
const now = new Date().toISOString();
|
||||
const valid = codeIsValid(code, now);
|
||||
await pbAdmin.update('fams', famId, {
|
||||
paymentMode: 'code',
|
||||
accessCodeId: code.id,
|
||||
accessCodeEnteredAt: now,
|
||||
active: valid
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
active: valid,
|
||||
code: { name: code.name, value: code.value, duration: code.duration, expiry: code.expiry }
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import { clearLegacyCookies } from '$lib/server/session';
|
||||
import type { RequestEvent } from '@sveltejs/kit';
|
||||
import { pbAdmin } from '$lib/server/pocketbase';
|
||||
|
||||
@@ -17,7 +18,7 @@ export function requireAuth(event: RequestEvent) {
|
||||
export function clearSession(event: RequestEvent) {
|
||||
event.cookies.delete('session', { path: '/' });
|
||||
event.cookies.delete('pb_token', { path: '/' });
|
||||
event.cookies.delete('device_token', { path: '/' });
|
||||
clearLegacyCookies(event.cookies);
|
||||
}
|
||||
|
||||
// Resolve the fam slug + admin display name used for the post-login redirect.
|
||||
|
||||
@@ -154,6 +154,122 @@ async function ensureOtp(ids: Record<string, string>): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
// Platform access codes — the codes that enable access to the platform. They're
|
||||
// global (not fam-scoped) and managed via the platform admin page (superuser
|
||||
// only), so all rules are null like `otp`. A code grants a family a subscription
|
||||
// for `duration` months (0 = continuous); `expiry` is months-after-createdAt
|
||||
// (0 = never expires); `active` is a failsafe toggle. Entered at create-family
|
||||
// and in admin settings.
|
||||
async function ensureAccessCodes(): Promise<void> {
|
||||
if (await getCollection("accesscodes")) {
|
||||
await ensureAccessCodeFields();
|
||||
await seedAccessCodes();
|
||||
return;
|
||||
}
|
||||
await createCollection({
|
||||
name: "accesscodes",
|
||||
type: "base",
|
||||
listRule: null,
|
||||
viewRule: null,
|
||||
createRule: null,
|
||||
updateRule: null,
|
||||
deleteRule: null,
|
||||
fields: [
|
||||
{ name: "value", type: "text", required: true, unique: true },
|
||||
{ name: "name", type: "text", required: true },
|
||||
{ name: "duration", type: "number", required: false },
|
||||
{ name: "expiry", type: "number", required: false },
|
||||
{ name: "active", type: "bool", required: false },
|
||||
// When set (>0) this code is a TRIAL code: maps to Stripe
|
||||
// trial_period_days at checkout instead of platform access.
|
||||
{ name: "trialDays", type: "number", required: false },
|
||||
{ name: "createdAt", type: "date", required: false },
|
||||
],
|
||||
});
|
||||
await seedAccessCodes();
|
||||
}
|
||||
|
||||
// Idempotent field-add for installs where accesscodes predates a field.
|
||||
async function ensureAccessCodeFields(): Promise<void> {
|
||||
const col = await getCollection("accesscodes");
|
||||
if (!col) return;
|
||||
const has = (n: string) => col.fields.some((f: any) => f.name === n);
|
||||
if (!has("trialDays")) {
|
||||
await updateCollection(col.id, {
|
||||
...col,
|
||||
fields: [...col.fields, { name: "trialDays", type: "number", required: false }],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Idempotent seeds — developer code + an example trial code.
|
||||
async function seedAccessCodes(): Promise<void> {
|
||||
const t = await auth();
|
||||
const seeds = [
|
||||
{ value: "dev123", name: "developer", duration: 0, expiry: 0, active: true, trialDays: null },
|
||||
{ value: "FAM3MONTHS", name: "3-month trial", duration: null, expiry: null, active: true, trialDays: 90 },
|
||||
];
|
||||
for (const seed of seeds) {
|
||||
const res = await fetch(
|
||||
`${PB_ENDPOINT}/api/collections/accesscodes/records?filter=value='${seed.value}'`,
|
||||
{ headers: { Authorization: `Bearer ${t}` } },
|
||||
);
|
||||
const data = await res.json();
|
||||
if (data?.items?.length) continue;
|
||||
const created = await fetch(`${PB_ENDPOINT}/api/collections/accesscodes/records`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${t}` },
|
||||
body: JSON.stringify({ ...seed, createdAt: new Date().toISOString() }),
|
||||
});
|
||||
const c = await created.json();
|
||||
if (!created.ok) throw new Error(`Seed accesscode failed: ${JSON.stringify(c)}`);
|
||||
console.log(` ✓ Seeded access code: ${seed.name} (${seed.value})`);
|
||||
}
|
||||
}
|
||||
|
||||
// Platform settings — a single global record holding the platform feature
|
||||
// flags (replaces the per-fam fams.featureFlags). Publicly readable (empty
|
||||
// list/view rules) so every client can deduce flags on app load; writes stay
|
||||
// superuser-only (null rules), so like otp/accesscodes this lives in
|
||||
// migrate.ts rather than SCHEMA_PLAN.
|
||||
async function ensurePlatform(): Promise<void> {
|
||||
if (!(await getCollection("platform"))) {
|
||||
await createCollection({
|
||||
name: "platform",
|
||||
type: "base",
|
||||
listRule: "",
|
||||
viewRule: "",
|
||||
createRule: null,
|
||||
updateRule: null,
|
||||
deleteRule: null,
|
||||
fields: [
|
||||
{ name: "label", type: "text", required: true },
|
||||
{ name: "flags", type: "json", required: false },
|
||||
],
|
||||
});
|
||||
}
|
||||
await seedPlatform();
|
||||
}
|
||||
|
||||
// Idempotent seed — create the singleton 'global' settings record if missing.
|
||||
async function seedPlatform(): Promise<void> {
|
||||
const t = await auth();
|
||||
const res = await fetch(
|
||||
`${PB_ENDPOINT}/api/collections/platform/records?filter=label='global'`,
|
||||
{ headers: { Authorization: `Bearer ${t}` } },
|
||||
);
|
||||
const data = await res.json();
|
||||
if (data?.items?.length) return;
|
||||
const created = await fetch(`${PB_ENDPOINT}/api/collections/platform/records`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${t}` },
|
||||
body: JSON.stringify({ label: "global", flags: { debug: false } }),
|
||||
});
|
||||
const c = await created.json();
|
||||
if (!created.ok) throw new Error(`Seed platform failed: ${JSON.stringify(c)}`);
|
||||
console.log(" ✓ Seeded platform settings (global)");
|
||||
}
|
||||
|
||||
// Bootstrap the full schema on a fresh/wiped PocketBase. Idempotent — skips if
|
||||
// `fams` already exists (data is disposable; there is no incremental migration
|
||||
// history).
|
||||
@@ -177,8 +293,38 @@ async function ensureSchema(): Promise<void> {
|
||||
console.log("[migrate] Schema bootstrapped.");
|
||||
}
|
||||
|
||||
// Add the access-gating fields to `fams` on installs where it already exists
|
||||
// (fresh installs get them via SCHEMA_PLAN). Idempotent — only adds missing
|
||||
// fields.
|
||||
async function ensureFamFields(): Promise<void> {
|
||||
const famsCol = await getCollection("fams");
|
||||
if (!famsCol) return;
|
||||
const has = (n: string) => famsCol.fields.some((f: any) => f.name === n);
|
||||
const needed: any[] = [];
|
||||
if (!has("active")) {
|
||||
needed.push({ name: "active", type: "bool", required: false });
|
||||
}
|
||||
if (!has("paymentMode")) {
|
||||
needed.push({ name: "paymentMode", type: "select", required: false, values: ["none", "code", "sub", "canceled"], maxSelect: 1 });
|
||||
}
|
||||
if (!has("accessCodeId")) {
|
||||
needed.push({ name: "accessCodeId", type: "text", required: false });
|
||||
}
|
||||
if (!has("accessCodeEnteredAt")) {
|
||||
needed.push({ name: "accessCodeEnteredAt", type: "date", required: false });
|
||||
}
|
||||
if (needed.length) {
|
||||
await updateCollection(famsCol.id, { ...famsCol, fields: [...famsCol.fields, ...needed] });
|
||||
}
|
||||
}
|
||||
|
||||
export async function migrate(): Promise<void> {
|
||||
console.log("[migrate] Checking PB collection schemas...");
|
||||
await ensureSchema();
|
||||
// Runs even when the schema already exists (unlike ensureSchema's early
|
||||
// return) so new platform collections/fields/seed land on existing installs.
|
||||
await ensureFamFields();
|
||||
await ensureAccessCodes();
|
||||
await ensurePlatform();
|
||||
console.log("[migrate] Done");
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { pbAdmin } from '$lib/server/pocketbase';
|
||||
|
||||
// Platform-level feature flags, stored on the singleton `platform` record
|
||||
// (label='global'). Replaces the deprecated per-fam fams.featureFlags.
|
||||
export type PlatformFlags = Record<string, boolean>;
|
||||
|
||||
let cache: { flags: PlatformFlags; at: number } | null = null;
|
||||
const TTL_MS = 10_000;
|
||||
|
||||
async function findGlobal(): Promise<any | null> {
|
||||
const recs = (await pbAdmin.getList('platform', `label = 'global'`)) as any[];
|
||||
return recs[0] || null;
|
||||
}
|
||||
|
||||
// Public read used by loads. Cached briefly so per-request layout loads don't
|
||||
// hammer PB; flag changes propagate within the TTL.
|
||||
export async function getPlatformFlags(): Promise<PlatformFlags> {
|
||||
if (cache && Date.now() - cache.at < TTL_MS) return cache.flags;
|
||||
try {
|
||||
const rec = await findGlobal();
|
||||
cache = { flags: rec?.flags || {}, at: Date.now() };
|
||||
} catch {
|
||||
if (!cache) cache = { flags: {}, at: Date.now() };
|
||||
}
|
||||
return cache.flags;
|
||||
}
|
||||
|
||||
// Superuser write (platform admin dashboard / server-side only).
|
||||
export async function setPlatformFlag(key: string, value: boolean): Promise<PlatformFlags> {
|
||||
const rec = await findGlobal();
|
||||
if (!rec) throw new Error('platform settings record missing');
|
||||
const flags: PlatformFlags = { ...(rec.flags || {}), [key]: value };
|
||||
await pbAdmin.update('platform', rec.id, { flags });
|
||||
cache = { flags, at: Date.now() };
|
||||
return flags;
|
||||
}
|
||||
@@ -21,4 +21,12 @@ export function setSessionCookie(cookies: Cookies, token: string) {
|
||||
|
||||
export function clearSessionCookie(cookies: Cookies) {
|
||||
cookies.delete(SESSION_COOKIE, { path: '/' });
|
||||
}
|
||||
|
||||
// Legacy pre-PB-auth child cookie. No longer issued anywhere; these deletes
|
||||
// exist only to scrub it from browsers that still carry one.
|
||||
const LEGACY_DEVICE_COOKIE = 'device_token';
|
||||
|
||||
export function clearLegacyCookies(cookies: Cookies) {
|
||||
cookies.delete(LEGACY_DEVICE_COOKIE, { path: '/' });
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { pbAdmin } from '$lib/server/pocketbase';
|
||||
import type Stripe from 'stripe';
|
||||
|
||||
// Shared Stripe event handling. Both the real webhook (/account/webhook) and
|
||||
// the dev-only simulator (/account/webhook/simulate) route through here so the
|
||||
// DB effects are identical.
|
||||
// Shared Stripe event handling. The real webhook (/api/webhooks/stripe) routes
|
||||
// through here so the DB effects are identical.
|
||||
export async function handleStripeEvent(event: Stripe.Event): Promise<void> {
|
||||
switch (event.type) {
|
||||
case 'checkout.session.completed': {
|
||||
@@ -12,19 +11,28 @@ export async function handleStripeEvent(event: Stripe.Event): Promise<void> {
|
||||
if (famId && session.customer) {
|
||||
await pbAdmin.update('fams', famId, {
|
||||
stripeCustomerId: String(session.customer),
|
||||
active: true
|
||||
active: true,
|
||||
paymentMode: 'sub'
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'customer.subscription.created':
|
||||
case 'customer.subscription.updated':
|
||||
case 'customer.subscription.deleted':
|
||||
case 'customer.subscription.paused': {
|
||||
const sub = event.data.object as Stripe.Subscription;
|
||||
await setActiveFromSubscription(sub);
|
||||
break;
|
||||
}
|
||||
case 'customer.subscription.deleted': {
|
||||
const sub = event.data.object as Stripe.Subscription;
|
||||
const fams = await pbAdmin.getList('fams', `stripeCustomerId = '${sub.customer}'`);
|
||||
const fam = fams[0];
|
||||
if (fam) {
|
||||
await pbAdmin.update('fams', fam.id, { active: false, paymentMode: 'canceled' });
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,5 +45,5 @@ async function setActiveFromSubscription(sub: Stripe.Subscription) {
|
||||
// Active only while the sub is trialing/active (not past_due/canceled/paused).
|
||||
const active =
|
||||
sub.status === 'trialing' || sub.status === 'active' || sub.status === 'past_due';
|
||||
await pbAdmin.update('fams', fam.id, { active });
|
||||
await pbAdmin.update('fams', fam.id, { active, paymentMode: 'sub' });
|
||||
}
|
||||
@@ -28,17 +28,18 @@ export const PLAN_IDS: Record<'trial' | 'monthly' | 'yearly', string> = {
|
||||
yearly: String(STRIPE_PRICE_YEARLY) || 'price_dummy_yearly'
|
||||
};
|
||||
|
||||
// Trial codes (app-side). In practice these should live in a PB collection;
|
||||
// for the dummy flow a static map is enough. Maps code -> trial days.
|
||||
export const TRIAL_CODES: Record<string, number> = {
|
||||
FAM3MONTHS: 90,
|
||||
FAMTRIAL: 30
|
||||
};
|
||||
|
||||
export function resolveTrialDays(code?: string): number | null {
|
||||
// Trial codes live in PB (`accesscodes` with trialDays > 0, active) so the
|
||||
// platform admin can manage them. A matching active code maps to Stripe
|
||||
// trial_period_days at checkout; anything else is not a trial code.
|
||||
export async function resolveTrialDays(code?: string): Promise<number | null> {
|
||||
if (!code) return null;
|
||||
const days = TRIAL_CODES[code.trim().toUpperCase()];
|
||||
return typeof days === 'number' ? days : null;
|
||||
const { pbAdmin } = await import('$lib/server/pocketbase');
|
||||
const recs = (await pbAdmin.getList(
|
||||
'accesscodes',
|
||||
`value = '${code.trim().toUpperCase()}' && active = true`
|
||||
)) as any[];
|
||||
const days = Number(recs?.[0]?.trialDays) || 0;
|
||||
return days > 0 ? days : null;
|
||||
}
|
||||
|
||||
export function verifyStripeEvent(rawBody: string, signature: string): Stripe.Event {
|
||||
@@ -68,7 +69,7 @@ export async function createCheckoutSession(opts: {
|
||||
mode: 'subscription',
|
||||
metadata: { famId: opts.famId, plan: opts.plan },
|
||||
success_url: `${opts.origin}/account?checkout=success`,
|
||||
cancel_url: `${opts.origin}/subscriptions?checkout=cancelled`
|
||||
cancel_url: `${opts.origin}/pricing?checkout=cancelled`
|
||||
};
|
||||
|
||||
// Attach customer if we already have a Stripe customer id for this fam.
|
||||
@@ -93,10 +94,10 @@ export async function createCheckoutSession(opts: {
|
||||
}
|
||||
|
||||
// Stripe Billing portal session for managing/cancelling the subscription.
|
||||
export async function createBillingPortalSession(customerId: string, origin: string) {
|
||||
export async function createBillingPortalSession(customerId: string, origin: string, famSlug = '') {
|
||||
return stripe.billingPortal.sessions.create({
|
||||
customer: customerId,
|
||||
return_url: `${origin}/account`
|
||||
return_url: `${origin}/${famSlug}?checkout=return`
|
||||
});
|
||||
}
|
||||
|
||||
@@ -108,6 +109,7 @@ export async function createEmbeddedCheckoutSession(opts: {
|
||||
plan: PlanId | 'price' | 'trial';
|
||||
priceId?: string;
|
||||
famId: string;
|
||||
famSlug: string;
|
||||
email?: string | null;
|
||||
customerId?: string | null;
|
||||
trialDays?: number | null;
|
||||
@@ -124,7 +126,7 @@ export async function createEmbeddedCheckoutSession(opts: {
|
||||
mode: 'subscription',
|
||||
ui_mode: 'embedded_page',
|
||||
metadata: { famId: opts.famId, plan: opts.plan },
|
||||
return_url: `${opts.origin}/account?checkout=return`
|
||||
return_url: `${opts.origin}/${opts.famSlug}?checkout=return`
|
||||
};
|
||||
|
||||
if (opts.customerId) {
|
||||
|
||||
Reference in New Issue
Block a user