Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat(billing): customize plan features and monthly-equivalent pricing
Timothy Yinbf7d4c4be2f7
diff --git a/apps/cloud/app/assets/cloud.css b/apps/cloud/app/assets/cloud.cssindex 1a92fab9..ad09d55b 100644--- a/apps/cloud/app/assets/cloud.css+++ b/apps/cloud/app/assets/cloud.css@@ -2120,6 +2120,9 @@ a.cf-domain-address:hover {gap: 10px;flex-wrap: wrap;}+.cf-plan-card-heading.has-recommendation {+ justify-content: flex-start;+}.cf-plan-card-heading h2 {font-size: 19px;}@@ -2158,11 +2161,16 @@ a.cf-domain-address:hover {gap: 12px;font-size: 12px;}-.cf-plan-features li span {+.cf-plan-features li > span {+ min-width: 0;+ overflow-wrap: anywhere;color: var(--muted-foreground);}.cf-plan-features strong {- white-space: nowrap;+ min-width: 0;+ max-width: 60%;+ overflow-wrap: anywhere;+ text-align: right;font-weight: 550;}.cf-rule-details {diff --git a/apps/cloud/app/components/CloudPlanFeatureValue.vue b/apps/cloud/app/components/CloudPlanFeatureValue.vuenew file mode 100644index 00000000..9e428925--- /dev/null+++ b/apps/cloud/app/components/CloudPlanFeatureValue.vue@@ -0,0 +1,27 @@+<script setup lang="ts">+defineProps<{ feature: { type: string; value?: string | number } }>()+const { t, locale } = useI18n()+</script>+<template>+ <UIcon+ v-if="['supported', 'unsupported', 'dash'].includes(feature.type)"+ :name="+ {+ supported: 'i-lucide-check',+ unsupported: 'i-lucide-x',+ dash: 'i-lucide-minus',+ }[feature.type]+ "+ :aria-label="+ feature.type === 'dash'+ ? '—'+ : t('cloud.billing.' + (feature.type === 'supported' ? 'yes' : 'no'))+ "+ role="img"+ />+ <span v-else>{{+ feature.type === 'number'+ ? new Intl.NumberFormat(locale).format(Number(feature.value))+ : feature.value+ }}</span>+</template>diff --git a/apps/cloud/app/components/CloudPricing.vue b/apps/cloud/app/components/CloudPricing.vueindex 6f99d581..25155b0a 100644--- a/apps/cloud/app/components/CloudPricing.vue+++ b/apps/cloud/app/components/CloudPricing.vue@@ -22,7 +22,7 @@ const requestedPurchase = computed(() =>const { t, locale } = useI18n(),links = useCloudLinks(),interval = ref<1 | 3>(- requestedPurchase.value && route.query.interval === '3' ? 3 : 1,+ requestedPurchase.value && route.query.interval === '1' ? 1 : 3,)const billingPeriod = computed({get: () => String(interval.value),@@ -54,19 +54,43 @@ const comparisonColumns = computed(() => [row.values[plan.id],})),])-const comparisonRows = computed(() =>- [...BILLING_LIMITS, 'conditions'].map((key) => ({- label: t('cloud.billing.' + key),- values: Object.fromEntries(- (data.value?.plans ?? []).map((plan: any) => [- plan.id,- key === 'conditions'- ? String(plan.policy.rules.length || '—')- : allowance(key, plan.policy.limits[key], locale.value),- ]),+const comparisonRows = computed(() => {+ const plans = data.value?.plans ?? []+ const labels = [+ ...new Set<string>(+ plans.flatMap((plan: any) =>+ (plan.policy.features ?? []).map((f: any) => f.label),+ ),),- })),-)+ ]+ return [...BILLING_LIMITS, 'conditions']+ .map((key) => ({+ key,+ label: t('cloud.billing.' + key),+ values: Object.fromEntries(+ (data.value?.plans ?? []).map((plan: any) => [+ plan.id,+ key === 'conditions'+ ? String(plan.policy.rules.length || '—')+ : allowance(key, plan.policy.limits[key], locale.value),+ ]),+ ),+ }))+ .concat(+ labels.map((label) => ({+ key: 'feature:' + label,+ label,+ values: Object.fromEntries(+ plans.map((plan: any) => [+ plan.id,+ plan.policy.features?.find((f: any) => f.label === label) ?? {+ type: 'dash',+ },+ ]),+ ),+ })),+ )+})if (billing) await billing.readyconst currentPlan = computed(() => billing?.data.value?.plan.id)const originalAmount = (plan: any) =>@@ -339,7 +363,15 @@ async function checkout(plan: any) {}).format(discountBps(plan) / 100)}}%</span>- <div class="cf-plan-card-heading">+ <div+ class="cf-plan-card-heading"+ :class="{+ 'has-recommendation':+ embedded &&+ plan.featured &&+ !(portal && plan.id === currentPlan),+ }"+ ><h2>{{ plan.name }}</h2><CfBadge v-if="portal && plan.id === currentPlan">{{$t('cloud.billing.current')@@ -353,19 +385,27 @@ async function checkout(plan: any) {</p><p class="cf-plan-original-price"><del v-if="discountBps(plan) > 0 && originalAmount(plan) > 0">{{- price(originalAmount(plan), plan.currency, locale)+ price(+ originalAmount(plan) === null+ ? null+ : originalAmount(plan) / interval,+ plan.currency,+ locale,+ )}}</del></p><div class="cf-plan-price"><strong>{{amount(plan) === 0? $t('cloud.billing.free')- : price(amount(plan), plan.currency, locale)+ : price(+ amount(plan) === null ? null : amount(plan) / interval,+ plan.currency,+ locale,+ )}}</strong><span v-if="amount(plan) !== null && amount(plan) > 0"- >/{{- $t('cloud.billing.' + (interval === 1 ? 'month' : 'quarter'))- }}</span+ >/{{ $t('cloud.billing.month') }}</span></div><p class="cf-price-caption">@@ -373,10 +413,9 @@ async function checkout(plan: any) {amount(plan) === null? $t('cloud.billing.notPriced'): interval === 3 && amount(plan) > 0- ? '≈ ' +- price(amount(plan)! / 3, plan.currency, locale) ++ ? price(amount(plan), plan.currency, locale) +' / ' +- $t('cloud.billing.month')+ $t('cloud.billing.quarter'): $t(amount(plan) === 0? 'cloud.billing.noCharge'@@ -491,9 +530,32 @@ async function checkout(plan: any) {:key="key"><span>{{ $t('cloud.billing.' + key) }}</span- ><strong>{{- allowance(key, plan.policy.limits[key], locale)- }}</strong>+ ><strong+ ><UIcon+ v-if="key === 'byos'"+ :name="+ plan.policy.limits[key]+ ? 'i-lucide-check'+ : 'i-lucide-minus'+ "+ :aria-label="+ $t(+ 'cloud.billing.' ++ (plan.policy.limits[key] ? 'yes' : 'no'),+ )+ "+ role="img"+ /><template v-else>{{+ allowance(key, plan.policy.limits[key], locale)+ }}</template></strong+ >+ </li>+ <li+ v-for="(feature, index) in plan.policy.features ?? []"+ :key="'feature:' + index"+ >+ <span>{{ feature.label }}</span+ ><strong><CloudPlanFeatureValue :feature="feature" /></strong></li></ul><details@@ -512,7 +574,12 @@ async function checkout(plan: any) {:key="key">{{ $t('cloud.billing.' + key) }}:- {{ allowance(String(key), Number(value), locale) }}+ <CloudPlanFeatureValue+ v-if="key === 'byos'"+ :feature="{ type: value ? 'supported' : 'dash' }"+ /><template v-else>{{+ allowance(String(key), Number(value), locale)+ }}</template></li></ul></div>@@ -536,8 +603,26 @@ async function checkout(plan: any) {:data="comparisonRows":columns="comparisonColumns":caption="$t('cloud.billing.compare')"- /></section- ></template>+ ><template+ v-for="plan in data.plans"+ :key="plan.id"+ #[`plan:${plan.id}-cell`]="{ row }"+ >+ <CloudPlanFeatureValue+ v-if="row.original.key.startsWith('feature:')"+ :feature="row.original.values[plan.id]"+ />+ <CloudPlanFeatureValue+ v-else-if="row.original.key === 'byos'"+ :feature="{+ type: plan.policy.limits.byos ? 'supported' : 'dash',+ }"+ />+ <template v-else>{{ row.original.values[plan.id] }}</template>+ </template></CfTable+ >+ </section></template+ ><div class="cf-pricing-footer"><CloudSupportLink /><NuxtLink:to="links.redeem"diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.tsindex f2433a23..731c4854 100644--- a/packages/platform/src/dodo-payments.ts+++ b/packages/platform/src/dodo-payments.ts@@ -94,7 +94,7 @@ export async function syncDodoProducts(if (effectivePrice < 1) fail('payment_price_invalid', 400)const body = {name: snapshot.product.name,- description: snapshot.product.description.slice(0, 1000),+ description: snapshot.product.description,tax_category: 'saas' as const,price: {type: 'recurring_price' as const,diff --git a/packages/platform/src/entitlements.ts b/packages/platform/src/entitlements.tsindex 5777e237..1f806ad0 100644--- a/packages/platform/src/entitlements.ts+++ b/packages/platform/src/entitlements.ts@@ -34,7 +34,13 @@ type Condition =op: 'eq' | 'gte' | 'lte'value: string | number | boolean}+export type PlanFeature = {+ label: string+ type: 'supported' | 'unsupported' | 'dash' | 'number' | 'text'+ value?: string | number+}export interface PlanPolicy {+ features?: PlanFeature[]limits: Limitsrules: { when: Condition; limits: Partial<Limits> }[]}@@ -46,9 +52,41 @@ export function validatePolicy(value: unknown): PlanPolicy {!plain(value.limits) ||!Array.isArray(value.rules) ||value.rules.length > 32 ||- Object.keys(value).some((k) => !['limits', 'rules'].includes(k))+ Object.keys(value).some((k) => !['limits', 'rules', 'features'].includes(k)))throw new Error('Invalid policy')+ if (value.features !== undefined) {+ if (!Array.isArray(value.features) || value.features.length > 32)+ throw new Error('Invalid plan features')+ const labels = new Set<string>()+ for (const feature of value.features) {+ if (+ !plain(feature) ||+ Object.keys(feature).some(+ (k) => !['label', 'type', 'value'].includes(k),+ ) ||+ typeof feature.label !== 'string' ||+ !feature.label.trim() ||+ feature.label.length > 100 ||+ typeof feature.type !== 'string' ||+ !['supported', 'unsupported', 'dash', 'number', 'text'].includes(+ String(feature.type),+ ) ||+ (feature.type === 'number' &&+ (typeof feature.value !== 'number' ||+ !Number.isFinite(feature.value) ||+ Math.abs(feature.value) > Number.MAX_SAFE_INTEGER)) ||+ (feature.type === 'text' &&+ (typeof feature.value !== 'string' || feature.value.length > 200)) ||+ (!['number', 'text'].includes(String(feature.type)) &&+ feature.value !== undefined)+ )+ throw new Error('Invalid plan feature')+ if (labels.has(feature.label.trim()))+ throw new Error('Duplicate plan feature')+ labels.add(feature.label.trim())+ }+ }function limits(v: unknown, complete: boolean) {if (!plain(v) ||@@ -113,7 +151,13 @@ export function validatePolicy(value: unknown): PlanPolicy {if (Number((rule.limits as Record<string, unknown>).byos ?? 0) > 1)throw new Error('Invalid BYOS entitlement')}- return structuredClone(value) as unknown as PlanPolicy+ const policy = structuredClone(value) as unknown as PlanPolicy+ if (policy.features)+ policy.features = policy.features.map((f) => ({+ ...f,+ label: f.label.trim(),+ }))+ return policy}export function evaluatePolicy(policy: PlanPolicy,diff --git a/packages/platform/src/payment-product-sync.ts b/packages/platform/src/payment-product-sync.tsindex 0ae66004..69a0ec2a 100644--- a/packages/platform/src/payment-product-sync.ts+++ b/packages/platform/src/payment-product-sync.ts@@ -33,17 +33,48 @@ function condition(c: any): string {export function paymentProductSnapshot(plan: any, interval: number) {const policy = validatePolicy(JSON.parse(plan.policy_json)),price = interval === 1 ? plan.monthly_price : plan.quarterly_price- const description = [- plan.description || plan.name,- '',- ...LIMIT_KEYS.map((k) => `${names[k]}: ${allowance(k, policy.limits[k])}`),+ // Dodo product descriptions support Markdown. Escape admin-authored text so it+ // remains content, and truncate at whole list items within the API limit.+ const markdown = (value: string) =>+ value+ .replace(/[\r\n]+/g, ' ')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/([\\`*_{}[\]()#+.!|~-])/g, '\\$1')+ const items = [+ ...LIMIT_KEYS.map(+ (k) => `- **${names[k]}:** ${allowance(k, policy.limits[k])}`,+ ),+ ...(policy.features ?? []).map(+ (f) =>+ `- **${markdown(f.label)}:** ${markdown(f.type === 'supported' ? 'Included' : f.type === 'unsupported' ? 'Not included' : f.type === 'dash' ? '—' : String(f.value))}`,+ ),...policy.rules.map((r) =>- `When ${condition(r.when)}: ${Object.entries(r.limits)- .map(([k, v]) => `${names[k]} ${allowance(k, Number(v))}`)+ `- When ${markdown(condition(r.when))}: ${Object.entries(r.limits)+ .map(([k, v]) => `${names[k]}: ${allowance(k, Number(v))}`).join('; ')}`,),- ].join('\n')+ ]+ let introduction = ''+ for (const char of String(plan.description || plan.name)) {+ const escaped = markdown(char)+ if (introduction.length + escaped.length > 500) break+ introduction += escaped+ }+ let description = introduction + '\n\n'+ for (let i = 0; i < items.length; i++) {+ const suffix =+ i < items.length - 1 ? '\n\nSee the platform for full plan details.' : ''+ if (description.length + items[i]!.length + 1 + suffix.length > 1000) {+ description += '\nSee the platform for full plan details.'+ break+ }+ description += items[i] + '\n'+ }+ description = description.trim()+return {planId: plan.id,interval,diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.tsindex b7f79702..f2e0da51 100644--- a/tests/dodo-payments.test.ts+++ b/tests/dodo-payments.test.ts@@ -658,7 +658,10 @@ test('wrong amounts cannot grant access and authoritative refunds revoke only thconst f = await fixture()try {await syncDodoProducts(f.db, root, f.transport)- assert.match([...f.products.values()][0].description, /Platform storage:/)+ assert.match(+ [...f.products.values()][0].description,+ /Platform storage:\*\*/,+ )const checkout = await createPaymentCheckout(f.db,root,diff --git a/tests/plan-features.test.ts b/tests/plan-features.test.tsnew file mode 100644index 00000000..1365fee2--- /dev/null+++ b/tests/plan-features.test.ts@@ -0,0 +1,90 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import {+ FREE_LIMITS,+ validatePolicy,+ evaluatePolicy,+} from '../packages/platform/src/entitlements.ts'+import { paymentProductSnapshot } from '../packages/platform/src/payment-product-sync.ts'+const features = [+ { label: 'Upcoming collaboration', type: 'supported' },+ { label: 'Team exports', type: 'unsupported' },+ { label: 'Availability', type: 'dash' },+ { label: 'Team members', type: 'number', value: 5 },+ { label: 'Support', type: 'text', value: 'Email & chat' },+]+const policy = () => ({+ limits: { ...FREE_LIMITS },+ rules: [],+ features: structuredClone(features),+})+test('display features round trip without changing resource allowances; reject malformed values', () => {+ const validated = validatePolicy(policy())+ assert.deepEqual(validated.features, features)+ assert.deepEqual(+ evaluatePolicy(validated, {+ storageMode: 'platform',+ workspaceAgeDays: 1,+ emailVerified: true,+ }),+ FREE_LIMITS,+ )+ for (const bad of [+ { label: '', type: 'text', value: 'x' },+ { label: 'x', type: 'html', value: '<b>x</b>' },+ { label: 'x', type: 'number', value: '5' },+ { label: 'x', type: 'number', value: Infinity },+ { label: 'x', type: 'text', value: 'x'.repeat(201) },+ { label: 'x', type: 'supported', value: true },+ ]) {+ assert.throws(() => validatePolicy({ ...policy(), features: [bad] }))+ }+ assert.throws(() =>+ validatePolicy({ ...policy(), features: Array(33).fill(features[0]) }),+ )+ assert.throws(() =>+ validatePolicy({ ...policy(), features: [features[0], features[0]] }),+ )+ assert.doesNotThrow(() => validatePolicy({ limits: FREE_LIMITS, rules: [] }))+})+test('Dodo descriptions use escaped Markdown paragraphs and whole list items within the API limit', () => {+ const plan = {+ id: 'pro',+ name: 'Pro',+ description: 'Photo **hosting** <script>',+ monthly_price: 1200,+ quarterly_price: 3000,+ currency: 'USD',+ policy_json: JSON.stringify(policy()),+ }+ const description = paymentProductSnapshot(plan, 3).product.description+ assert.match(+ description,+ /Photo \\\*\\\*hosting\\\*\\\* <script>\n\n- \*\*Custom S3 storage:\*\* Not included/,+ )+ assert.match(description, /- \*\*Upcoming collaboration:\*\* Included/)+ assert.match(description, /- \*\*Support:\*\* Email & chat/)+ const long = paymentProductSnapshot(+ {+ ...plan,+ description: '&'.repeat(500),+ policy_json: JSON.stringify({+ ...policy(),+ features: Array.from({ length: 32 }, (_, i) => ({+ label: 'Feature ' + i,+ type: 'text',+ value: 'x'.repeat(200),+ })),+ }),+ },+ 1,+ ).product.description+ assert.ok(long.length <= 1000)+ assert.ok(long.endsWith('See the platform for full plan details.'))+ assert.ok(+ long+ .split('\n')+ .filter((l) => l.startsWith('- **Feature'))+ .every((l) => l.endsWith('x'.repeat(200))),+ )+})