feature plus ux rearrangements
This commit is contained in:
@@ -1,36 +1,19 @@
|
||||
<script lang="ts">
|
||||
let { items }: { items: { title: string; content: any }[] } = $props();
|
||||
let openIndex = $state<number | null>(null);
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
// Styled wrapper — group AccordionItem children inside.
|
||||
let { children, defaultOpen = false }: { children: Snippet; defaultOpen?: boolean } = $props();
|
||||
</script>
|
||||
|
||||
<div class="accordion">
|
||||
{#each items as item, i}
|
||||
<div class="accordion-item" class:open={openIndex === i}>
|
||||
<button class="accordion-trigger" onclick={() => openIndex = openIndex === i ? null : i}>
|
||||
<span>{item.title}</span>
|
||||
<span class="accordion-arrow">{openIndex === i ? '▾' : '▸'}</span>
|
||||
</button>
|
||||
{#if openIndex === i}
|
||||
<div class="accordion-body">
|
||||
{@render item.content()}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
<div class="accordion" class:default-open={defaultOpen}>
|
||||
{@render children()}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.accordion { border: 1px solid #e5e7eb; border-radius: 8px; overflow: hidden; }
|
||||
.accordion-item { border-bottom: 1px solid #f3f4f6; }
|
||||
.accordion-item:last-child { border-bottom: none; }
|
||||
.accordion-trigger {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
width: 100%; padding: 0.7rem 1rem;
|
||||
background: #fafafa; border: none;
|
||||
font-size: 0.9rem; font-weight: 500; color: #374151;
|
||||
cursor: pointer; text-align: left;
|
||||
.accordion {
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: #fff;
|
||||
}
|
||||
.accordion-trigger:hover { background: #f3f4f6; }
|
||||
.accordion-arrow { font-size: 0.8rem; color: #9ca3af; }
|
||||
.accordion-body { padding: 1rem; }
|
||||
</style>
|
||||
</style>
|
||||
@@ -0,0 +1,36 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
let { title, open = $bindable(false), children }: { title: string; open?: boolean; children: Snippet } = $props();
|
||||
</script>
|
||||
|
||||
<div class="accordion-item" class:open>
|
||||
<button
|
||||
class="accordion-trigger"
|
||||
onclick={() => (open = !open)}
|
||||
aria-expanded={open}
|
||||
>
|
||||
<span>{title}</span>
|
||||
<span class="accordion-arrow">{open ? '▾' : '▸'}</span>
|
||||
</button>
|
||||
{#if open}
|
||||
<div class="accordion-body">
|
||||
{@render children()}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.accordion-item { border-bottom: 1px solid #f3f4f6; }
|
||||
.accordion-item:last-child { border-bottom: none; }
|
||||
.accordion-trigger {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
width: 100%; padding: 0.7rem 1rem;
|
||||
background: #fafafa; border: none;
|
||||
font-size: 0.95rem; font-weight: 600; color: #374151;
|
||||
cursor: pointer; text-align: left;
|
||||
}
|
||||
.accordion-trigger:hover { background: #f3f4f6; }
|
||||
.accordion-arrow { font-size: 0.8rem; color: #9ca3af; }
|
||||
.accordion-body { padding: 1rem; }
|
||||
</style>
|
||||
@@ -4,14 +4,16 @@
|
||||
title,
|
||||
accent,
|
||||
scrollX = false,
|
||||
children
|
||||
}: { cols?: 1 | 2 | 3 | 4 | 5 | 6; title?: string; accent?: string; scrollX?: boolean; children?: any } = $props();
|
||||
children,
|
||||
class: className,
|
||||
selected = false
|
||||
}: { cols?: 1 | 2 | 3 | 4 | 5 | 6; title?: string; accent?: string; scrollX?: boolean; children?: any; class?: string; selected?: boolean } = $props();
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="card"
|
||||
data-cols={cols}
|
||||
style="--card-cols: {cols}; {accent ? `--card-accent: ${accent}` : ''}"
|
||||
class="card {className || ''} {selected ? 'selected' : ''}"
|
||||
class:has-accent={!!accent}
|
||||
class:scroll-x={scrollX}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
<script lang="ts">
|
||||
import { notices, type NoticeType } from '$lib/stores/notices.svelte';
|
||||
|
||||
function icon(type: NoticeType) {
|
||||
switch (type) {
|
||||
case 'success': return '✅';
|
||||
case 'warning': return '⚠️';
|
||||
case 'error': return '❌';
|
||||
default: return 'ℹ️';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if notices.list.length > 0}
|
||||
<div class="notice-container" role="region" aria-label="Notifications">
|
||||
{#each notices.list as notice (notice.id)}
|
||||
<div class="notice notice-{notice.type}">
|
||||
<div class="notice-content">
|
||||
<div class="notice-icon">{icon(notice.type)}</div>
|
||||
<div class="notice-text">
|
||||
<h4>{notice.title}</h4>
|
||||
{#if notice.message}
|
||||
<p>{notice.message}</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{#if notice.action}
|
||||
<a href={notice.action.href} class="notice-action">{notice.action.label}</a>
|
||||
{/if}
|
||||
{#if notice.dismissible}
|
||||
<button class="notice-dismiss" onclick={() => notices.remove(notice.id)} aria-label="Dismiss">✕</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.notice-container {
|
||||
position: fixed;
|
||||
top: 5rem;
|
||||
right: 1.5rem;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
max-width: 380px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.notice {
|
||||
background: white;
|
||||
border-radius: 10px;
|
||||
padding: 1rem 1.25rem;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
border-left: 4px solid #6366f1;
|
||||
animation: slidein 0.25s ease;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.notice-success { border-left-color: #059669; }
|
||||
.notice-warning { border-left-color: #d97706; }
|
||||
.notice-error { border-left-color: #dc2626; }
|
||||
.notice-content {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.6rem;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.notice-icon {
|
||||
font-size: 1.1rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.notice-text h4 {
|
||||
margin: 0 0 0.25rem;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
color: #111827;
|
||||
}
|
||||
.notice-text p {
|
||||
margin: 0;
|
||||
font-size: 0.8rem;
|
||||
color: #6b7280;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.notice-action {
|
||||
font-size: 0.8rem;
|
||||
color: #4338ca;
|
||||
font-weight: 500;
|
||||
text-decoration: none;
|
||||
flex-shrink: 0;
|
||||
align-self: center;
|
||||
}
|
||||
.notice-action:hover { text-decoration: underline; }
|
||||
.notice-dismiss {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 1rem;
|
||||
color: #9ca3af;
|
||||
cursor: pointer;
|
||||
padding: 0.2rem;
|
||||
line-height: 1;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.notice-dismiss:hover { color: #374151; }
|
||||
@keyframes slidein {
|
||||
from { opacity: 0; transform: translateX(20px); }
|
||||
to { opacity: 1; transform: translateX(0); }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,152 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { Button, CardGrid, Card } from '$lib/components';
|
||||
|
||||
interface Tier {
|
||||
id: 'trial' | 'monthly' | 'yearly';
|
||||
name: string;
|
||||
price: string;
|
||||
period: string;
|
||||
desc: string;
|
||||
cta: string;
|
||||
featured?: boolean;
|
||||
}
|
||||
|
||||
const tiers: Tier[] = [
|
||||
{
|
||||
id: 'trial',
|
||||
name: 'Trial',
|
||||
price: 'Free',
|
||||
period: 'for a set period',
|
||||
desc: 'Try FamChore free for a period (e.g. 3 months) with a code.',
|
||||
cta: 'Start trial'
|
||||
},
|
||||
{
|
||||
id: 'monthly',
|
||||
name: 'Monthly',
|
||||
price: '£3',
|
||||
period: '/month',
|
||||
desc: 'Full access for one family. Cancel anytime.',
|
||||
cta: 'Choose monthly',
|
||||
featured: true
|
||||
},
|
||||
{
|
||||
id: 'yearly',
|
||||
name: 'Yearly',
|
||||
price: '£30',
|
||||
period: '/year',
|
||||
desc: 'Two months free vs monthly. Best value for committed families.',
|
||||
cta: 'Choose yearly'
|
||||
}
|
||||
];
|
||||
|
||||
let { action, hideTrial = false, selected = '', error = '', onsubmit }: {
|
||||
action: string;
|
||||
hideTrial?: boolean;
|
||||
selected?: string;
|
||||
error?: string;
|
||||
onsubmit?: any;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<CardGrid>
|
||||
{#each tiers.filter((t) => !(hideTrial && t.id === 'trial')) as tier}
|
||||
<Card title={tier.name} accent={tier.featured ? '#6366f1' : undefined} selected={selected === tier.id}>
|
||||
<p class="price">
|
||||
<span class="amount">{tier.price}</span>
|
||||
<span class="period">{tier.period}</span>
|
||||
</p>
|
||||
<p class="hint">{tier.desc}</p>
|
||||
|
||||
{#if tier.id === 'trial'}
|
||||
<form
|
||||
method="POST"
|
||||
action={action}
|
||||
use:enhance={onsubmit ?? undefined}
|
||||
>
|
||||
<input type="hidden" name="plan" value="trial" />
|
||||
<label class="field-label" for="trial-code">Trial code</label>
|
||||
<input
|
||||
id="trial-code"
|
||||
name="code"
|
||||
placeholder="e.g. FAM3MONTHS"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<Button type="submit" size="md" variant="secondary">Start trial</Button>
|
||||
</form>
|
||||
{:else}
|
||||
<form
|
||||
method="POST"
|
||||
action={action}
|
||||
use:enhance={onsubmit ?? undefined}
|
||||
>
|
||||
<input type="hidden" name="plan" value={tier.id} />
|
||||
<Button type="submit" size="md" variant={tier.featured ? 'primary' : 'secondary'}>
|
||||
{tier.cta}
|
||||
</Button>
|
||||
</form>
|
||||
{/if}
|
||||
|
||||
{#if error}
|
||||
<p class="error">{error}</p>
|
||||
{/if}
|
||||
</Card>
|
||||
{/each}
|
||||
</CardGrid>
|
||||
|
||||
<style>
|
||||
.hint {
|
||||
font-size: 0.85rem;
|
||||
color: #9ca3af;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.price {
|
||||
margin: 0 0 0.5rem;
|
||||
}
|
||||
.amount {
|
||||
font-size: 2rem;
|
||||
font-weight: 700;
|
||||
color: #1f2937;
|
||||
}
|
||||
.period {
|
||||
color: #9ca3af;
|
||||
font-size: 0.9rem;
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
.field-label {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
color: #6b7280;
|
||||
}
|
||||
input {
|
||||
padding: 0.55rem 0.75rem;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 8px;
|
||||
font-size: 0.9rem;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
input:focus {
|
||||
outline: 2px solid #6366f1;
|
||||
outline-offset: -1px;
|
||||
}
|
||||
form :global(.btn) {
|
||||
width: 100%;
|
||||
}
|
||||
.error {
|
||||
color: #dc2626;
|
||||
background: #fef2f2;
|
||||
padding: 0.5rem;
|
||||
border-radius: 6px;
|
||||
font-size: 0.85rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
:global(.selected) {
|
||||
border: 2px solid #6366f1;
|
||||
}
|
||||
</style>
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
let collapsed = $state(false);
|
||||
|
||||
let famSlug = $derived(page.params.fam);
|
||||
let famSlug = $derived(page.data.famSlug ?? page.params.fam);
|
||||
let memberName = $derived(session?.memberName || page.params.username || '');
|
||||
|
||||
function toggle() {
|
||||
|
||||
@@ -6,5 +6,8 @@ export { default as Card } from './Card.svelte';
|
||||
export { default as CardGrid } from './CardGrid.svelte';
|
||||
export { default as Button } from './Button.svelte';
|
||||
export { default as Accordion } from './Accordion.svelte';
|
||||
export { default as AccordionItem } from './AccordionItem.svelte';
|
||||
export { default as Chat } from './Chat.svelte';
|
||||
export { default as AuthShell } from './AuthShell.svelte';
|
||||
export { default as NoticeDialog } from './NoticeDialog.svelte';
|
||||
export { default as PricingPlans } from './PricingPlans.svelte';
|
||||
|
||||
@@ -32,3 +32,19 @@ export function formatHumanDate(dateStr: string | undefined): string {
|
||||
const sameYear = d.getFullYear() === new Date().getFullYear();
|
||||
return `${weekday} ${d.getDate()} ${mon}${sameYear ? '' : ' ' + String(d.getFullYear()).slice(2)}`;
|
||||
}
|
||||
|
||||
// Add months to a date (UTC), handling month overflow correctly.
|
||||
export function addMonthsUTC(date: Date, months: number): Date {
|
||||
const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + months, date.getUTCDate()));
|
||||
return d;
|
||||
}
|
||||
|
||||
// Short human date: "5 Aug" / "5 Aug 26"
|
||||
export function formatShortDate(dateStr: string | Date | undefined): string {
|
||||
if (!dateStr) return '';
|
||||
const d = dateStr instanceof Date ? dateStr : new Date(dateStr);
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
const mon = d.toLocaleDateString('en-GB', { month: 'short' });
|
||||
const sameYear = d.getFullYear() === new Date().getFullYear();
|
||||
return `${d.getDate()} ${mon}${sameYear ? '' : ' ' + String(d.getFullYear()).slice(2)}`;
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// App-wide notices — Svelte 5 rune store (.svelte.ts). Rendered globally by
|
||||
// <NoticeDialog /> in the root layout.
|
||||
export type NoticeType = 'info' | 'success' | 'warning' | 'error';
|
||||
|
||||
export interface Notice {
|
||||
id: string;
|
||||
type: NoticeType;
|
||||
title: string;
|
||||
message?: string;
|
||||
action?: { label: string; href: string };
|
||||
dismissible: boolean;
|
||||
}
|
||||
|
||||
let idCounter = 0;
|
||||
|
||||
class NoticeStore {
|
||||
list = $state<Notice[]>([]);
|
||||
|
||||
add(notice: Omit<Notice, 'id'>): string {
|
||||
const id = `notice-${Date.now()}-${idCounter++}`;
|
||||
this.list.push({ ...notice, id });
|
||||
return id;
|
||||
}
|
||||
|
||||
remove(id: string) {
|
||||
this.list = this.list.filter((n) => n.id !== id);
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.list = [];
|
||||
}
|
||||
|
||||
success(title: string, message?: string, action?: Notice['action']) {
|
||||
return this.add({ type: 'success', title, message, action, dismissible: true });
|
||||
}
|
||||
info(title: string, message?: string, action?: Notice['action']) {
|
||||
return this.add({ type: 'info', title, message, action, dismissible: true });
|
||||
}
|
||||
warning(title: string, message?: string, action?: Notice['action']) {
|
||||
return this.add({ type: 'warning', title, message, action, dismissible: true });
|
||||
}
|
||||
error(title: string, message?: string, action?: Notice['action']) {
|
||||
return this.add({ type: 'error', title, message, action, dismissible: true });
|
||||
}
|
||||
}
|
||||
|
||||
export const notices = new NoticeStore();
|
||||
|
||||
// Fire-and-forget helper — auto-dismisses after `duration` ms.
|
||||
export function addAutoDismissNotice(notice: Omit<Notice, 'id'>, duration = 5000): string {
|
||||
const id = notices.add({ ...notice, dismissible: true });
|
||||
setTimeout(() => notices.remove(id), duration);
|
||||
return id;
|
||||
}
|
||||
@@ -41,7 +41,6 @@ export interface Fam {
|
||||
name: string;
|
||||
slug: string;
|
||||
stripeCustomerId?: string;
|
||||
featureFlags: Record<string, boolean>;
|
||||
payday?: number;
|
||||
paydayTime?: string;
|
||||
timezone?: string;
|
||||
|
||||
Reference in New Issue
Block a user