feat(admin): implement pricing overrides for plans and update pricing logic

This commit is contained in:
Jose Selesan
2026-06-10 11:22:57 -03:00
parent dc8a10a612
commit ef926c63a2
10 changed files with 389 additions and 48 deletions

View File

@@ -1,3 +1,6 @@
# deps # deps
node_modules/ node_modules/
prisma.config.prod.ts prisma.config.prod.ts
# build output
dist/

View File

@@ -4,7 +4,7 @@ export const planSeeds = [
name: 'Basic', name: 'Basic',
price: '49.00', price: '49.00',
rules: { rules: {
version: 'v1', version: 'v2',
limits: { limits: {
maxCourts: 2, maxCourts: 2,
maxBookingsPerDay: 80, maxBookingsPerDay: 80,
@@ -22,6 +22,11 @@ export const planSeeds = [
advancedReports: false, advancedReports: false,
whatsappReminders: false, whatsappReminders: false,
}, },
pricing: {
overrides: {
AR: { amount: 14999, currency: 'ARS' },
},
},
}, },
}, },
{ {
@@ -29,7 +34,7 @@ export const planSeeds = [
name: 'Advanced', name: 'Advanced',
price: '99.00', price: '99.00',
rules: { rules: {
version: 'v1', version: 'v2',
limits: { limits: {
maxCourts: 5, maxCourts: 5,
maxBookingsPerDay: 220, maxBookingsPerDay: 220,
@@ -47,6 +52,11 @@ export const planSeeds = [
advancedReports: true, advancedReports: true,
whatsappReminders: true, whatsappReminders: true,
}, },
pricing: {
overrides: {
AR: { amount: 29999, currency: 'ARS' },
},
},
}, },
}, },
{ {
@@ -54,7 +64,7 @@ export const planSeeds = [
name: 'Enterprise', name: 'Enterprise',
price: '199.00', price: '199.00',
rules: { rules: {
version: 'v1', version: 'v2',
limits: { limits: {
maxCourts: 20, maxCourts: 20,
maxBookingsPerDay: 2000, maxBookingsPerDay: 2000,
@@ -72,6 +82,11 @@ export const planSeeds = [
advancedReports: true, advancedReports: true,
whatsappReminders: true, whatsappReminders: true,
}, },
pricing: {
overrides: {
AR: { amount: 59999, currency: 'ARS' },
},
},
}, },
}, },
] as const; ] as const;

View File

@@ -1,4 +1,6 @@
import { fetchGeoInfo } from '@/lib/geoip';
import { db } from '@/lib/prisma'; import { db } from '@/lib/prisma';
import { resolvePlanPrice } from '@/modules/plan/services/plan-pricing.service';
import { parsePlanRules } from '@/modules/plan/services/plan-rules.service'; import { parsePlanRules } from '@/modules/plan/services/plan-rules.service';
import type { AppContext } from '@/types/hono'; import type { AppContext } from '@/types/hono';
@@ -9,13 +11,26 @@ export async function listPlansHandler(c: AppContext) {
}, },
}); });
const countryParam = c.req.query('country');
let countryCode: string | undefined;
if (countryParam) {
countryCode = countryParam;
} else {
const ip = c.req.header('x-forwarded-for')?.split(',')[0]?.trim() || '127.0.0.1';
const geo = await fetchGeoInfo(ip);
countryCode = geo?.countryCode || undefined;
}
return c.json( return c.json(
plans.map((plan) => { plans.map((plan) => {
const rules = parsePlanRules(plan.rules); const rules = parsePlanRules(plan.rules);
const resolved = resolvePlanPrice(Number(plan.price), rules, countryCode);
return { return {
code: plan.code, code: plan.code,
name: plan.name, name: plan.name,
price: Number(plan.price), price: resolved.amount,
currency: resolved.currency,
features: rules.features, features: rules.features,
limits: rules.limits, limits: rules.limits,
}; };

View File

@@ -0,0 +1,25 @@
import type { PlanRules } from '@repo/api-contract';
export type PlanPrice = {
amount: number;
currency: string;
};
export function resolvePlanPrice(
defaultPrice: number,
rules: PlanRules,
countryCode?: string
): PlanPrice {
if (!countryCode) {
return { amount: defaultPrice, currency: 'USD' };
}
if (rules.version === 'v2' && rules.pricing?.overrides) {
const override = rules.pricing.overrides[countryCode];
if (override) {
return { amount: override.amount, currency: override.currency };
}
}
return { amount: defaultPrice, currency: 'USD' };
}

View File

@@ -0,0 +1,87 @@
import { expect, test } from 'bun:test';
import type { PlanRules } from '@repo/api-contract';
const DEFAULT_PRICE = 29.99;
function makeV1Rules(): PlanRules {
return {
version: 'v1',
limits: { maxCourts: 3, maxBookingsPerDay: 50 },
policies: { allowOverbooking: false },
features: {
onlinePayments: false,
publicBookingPage: false,
advancedReports: false,
whatsappReminders: false,
},
};
}
function makeV2Rules(overrides?: Record<string, { amount: number; currency: string }>): PlanRules {
return {
version: 'v2',
limits: { maxCourts: 5, maxBookingsPerDay: 100 },
policies: { allowOverbooking: false },
features: {
onlinePayments: true,
publicBookingPage: true,
advancedReports: true,
whatsappReminders: true,
},
...(overrides ? { pricing: { overrides } } : {}),
};
}
const { resolvePlanPrice } = await import('@/modules/plan/services/plan-pricing.service');
test('returns default price in USD when no country code is provided', () => {
const result = resolvePlanPrice(
DEFAULT_PRICE,
makeV2Rules({ AR: { amount: 14999, currency: 'ARS' } })
);
expect(result).toEqual({ amount: DEFAULT_PRICE, currency: 'USD' });
});
test('returns overridden price for matching country code', () => {
const rules = makeV2Rules({ AR: { amount: 14999, currency: 'ARS' } });
const result = resolvePlanPrice(DEFAULT_PRICE, rules, 'AR');
expect(result).toEqual({ amount: 14999, currency: 'ARS' });
});
test('returns default price for country without override', () => {
const rules = makeV2Rules({ AR: { amount: 14999, currency: 'ARS' } });
const result = resolvePlanPrice(DEFAULT_PRICE, rules, 'CL');
expect(result).toEqual({ amount: DEFAULT_PRICE, currency: 'USD' });
});
test('returns default price for v1 rules (no pricing config)', () => {
const result = resolvePlanPrice(DEFAULT_PRICE, makeV1Rules(), 'AR');
expect(result).toEqual({ amount: DEFAULT_PRICE, currency: 'USD' });
});
test('returns default price for v2 rules with empty overrides', () => {
const rules = makeV2Rules({});
const result = resolvePlanPrice(DEFAULT_PRICE, rules, 'AR');
expect(result).toEqual({ amount: DEFAULT_PRICE, currency: 'USD' });
});
test('returns default price when v2 rules has no pricing section', () => {
const rules = makeV2Rules();
const result = resolvePlanPrice(DEFAULT_PRICE, rules, 'AR');
expect(result).toEqual({ amount: DEFAULT_PRICE, currency: 'USD' });
});
test('selects correct override among multiple countries', () => {
const rules = makeV2Rules({
AR: { amount: 24999, currency: 'ARS' },
BR: { amount: 59.99, currency: 'USD' },
});
expect(resolvePlanPrice(DEFAULT_PRICE, rules, 'AR')).toEqual({ amount: 24999, currency: 'ARS' });
expect(resolvePlanPrice(DEFAULT_PRICE, rules, 'BR')).toEqual({ amount: 59.99, currency: 'USD' });
expect(resolvePlanPrice(DEFAULT_PRICE, rules, 'US')).toEqual({
amount: DEFAULT_PRICE,
currency: 'USD',
});
});

View File

@@ -9,11 +9,18 @@ import {
} from '@/components/ui/dialog'; } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { AdminLayout } from '@/features/admin/admin-layout'; import { AdminLayout } from '@/features/admin/admin-layout';
import { ApiClientError, apiClient } from '@/lib/api-client'; import { ApiClientError, apiClient } from '@/lib/api-client';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useLocation } from '@tanstack/react-router'; import { useLocation } from '@tanstack/react-router';
import { BarChart3, Pencil, Plus, RefreshCw, Trash2 } from 'lucide-react'; import { BarChart3, Pencil, Plus, RefreshCw, Trash2, X } from 'lucide-react';
import { useState } from 'react'; import { useState } from 'react';
type Plan = { type Plan = {
@@ -25,6 +32,61 @@ type Plan = {
complexCount: number; complexCount: number;
}; };
type PriceOverride = {
country: string;
amount: string;
currency: string;
};
function initOverrides(rules: unknown): PriceOverride[] {
const r = rules as Record<string, unknown> | null | undefined;
const pricing = r?.pricing as Record<string, unknown> | undefined;
const overrides = pricing?.overrides as
| Record<string, { amount: number; currency: string }>
| undefined;
if (!overrides) return [];
return Object.entries(overrides).map(([country, data]) => ({
country,
amount: String(data.amount),
currency: data.currency,
}));
}
function buildRulesData(
mode: 'create' | 'edit',
existingRules: unknown,
priceOverrides: PriceOverride[]
): unknown {
const base =
mode === 'edit' && typeof existingRules === 'object' && existingRules !== null
? { ...(existingRules as Record<string, unknown>) }
: {};
const validOverrides = priceOverrides.filter((o) => o.country.trim());
if (validOverrides.length > 0) {
const overrides: Record<string, { amount: number; currency: string }> = {};
for (const o of validOverrides) {
overrides[o.country.trim().toUpperCase()] = {
amount: Number.parseFloat(o.amount),
currency: o.currency,
};
}
return {
...base,
version: 'v2',
pricing: { overrides },
};
}
if (mode === 'edit') {
const { pricing: _, ...clean } = base;
return Object.keys(clean).length > 0 ? clean : {};
}
return {};
}
function PlanFormDialog({ function PlanFormDialog({
mode, mode,
plan, plan,
@@ -38,6 +100,9 @@ function PlanFormDialog({
const [code, setCode] = useState(plan?.code ?? ''); const [code, setCode] = useState(plan?.code ?? '');
const [name, setName] = useState(plan?.name ?? ''); const [name, setName] = useState(plan?.name ?? '');
const [price, setPrice] = useState(String(plan?.price ?? '')); const [price, setPrice] = useState(String(plan?.price ?? ''));
const [priceOverrides, setPriceOverrides] = useState<PriceOverride[]>(() =>
mode === 'edit' && plan ? initOverrides(plan.rules) : []
);
const createMutation = useMutation({ const createMutation = useMutation({
mutationFn: (data: { code: string; name: string; price: number; rules: object }) => mutationFn: (data: { code: string; name: string; price: number; rules: object }) =>
@@ -49,7 +114,7 @@ function PlanFormDialog({
}); });
const updateMutation = useMutation({ const updateMutation = useMutation({
mutationFn: (data: { name?: string; price?: number }) => mutationFn: (data: { name?: string; price?: number; rules?: unknown }) =>
apiClient.admin.updatePlan(plan!.code, data), apiClient.admin.updatePlan(plan!.code, data),
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['admin-plans'] }); queryClient.invalidateQueries({ queryKey: ['admin-plans'] });
@@ -62,22 +127,36 @@ function PlanFormDialog({
const handleSubmit = (e: React.FormEvent) => { const handleSubmit = (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
const rules = buildRulesData(mode, plan?.rules, priceOverrides);
if (mode === 'create') { if (mode === 'create') {
createMutation.mutate({ createMutation.mutate({
code, code,
name, name,
price: Number.parseFloat(price), price: Number.parseFloat(price),
rules: {}, rules: rules as object,
}); });
} else { } else {
updateMutation.mutate({ updateMutation.mutate({
name, name,
price: Number.parseFloat(price), price: Number.parseFloat(price),
rules,
}); });
} }
}; };
const addOverride = () => {
setPriceOverrides((prev) => [...prev, { country: '', amount: '', currency: 'ARS' }]);
};
const removeOverride = (index: number) => {
setPriceOverrides((prev) => prev.filter((_, i) => i !== index));
};
const updateOverride = (index: number, field: keyof PriceOverride, value: string) => {
setPriceOverrides((prev) => prev.map((o, i) => (i === index ? { ...o, [field]: value } : o)));
};
return ( return (
<Dialog open onOpenChange={(open) => !open && onClose()}> <Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="rounded-2xl sm:max-w-md"> <DialogContent className="rounded-2xl sm:max-w-md">
@@ -118,7 +197,9 @@ function PlanFormDialog({
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="price">Precio</Label> <Label htmlFor="price">
Precio USD <span className="text-xs text-muted-foreground">(fallback global)</span>
</Label>
<Input <Input
id="price" id="price"
type="number" type="number"
@@ -131,6 +212,72 @@ function PlanFormDialog({
/> />
</div> </div>
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label>Precios por país</Label>
<Button
type="button"
variant="outline"
size="sm"
className="rounded-xl"
onClick={addOverride}
>
<Plus className="mr-1 size-3" />
Agregar
</Button>
</div>
{priceOverrides.map((override, index) => (
<div key={index} className="flex items-end gap-2">
<div className="flex-1 space-y-1">
<Label className="text-xs">País</Label>
<Input
value={override.country}
onChange={(e) => updateOverride(index, 'country', e.target.value)}
placeholder="AR"
maxLength={2}
className="uppercase"
/>
</div>
<div className="flex-1 space-y-1">
<Label className="text-xs">Monto</Label>
<Input
type="number"
step="0.01"
min="0"
value={override.amount}
onChange={(e) => updateOverride(index, 'amount', e.target.value)}
placeholder="14999"
/>
</div>
<div className="w-24 space-y-1">
<Label className="text-xs">Moneda</Label>
<Select
value={override.currency}
onValueChange={(v) => updateOverride(index, 'currency', v)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="USD">USD</SelectItem>
<SelectItem value="ARS">ARS</SelectItem>
</SelectContent>
</Select>
</div>
<Button
type="button"
variant="ghost"
size="icon"
className="size-9 shrink-0 rounded-lg text-destructive hover:bg-destructive/10"
onClick={() => removeOverride(index)}
>
<X className="size-3.5" />
</Button>
</div>
))}
</div>
{error && ( {error && (
<p className="text-sm text-destructive"> <p className="text-sm text-destructive">
{error instanceof ApiClientError {error instanceof ApiClientError
@@ -292,42 +439,60 @@ export function PlansPage() {
</tr> </tr>
</thead> </thead>
<tbody className="divide-y divide-border/40"> <tbody className="divide-y divide-border/40">
{data?.map((plan) => ( {data?.map((plan) => {
<tr key={plan.code} className="transition-colors hover:bg-accent/30"> const rules = plan.rules as Record<string, unknown> | null;
<td className="px-5 py-4"> const pricing = rules?.pricing as Record<string, unknown> | undefined;
<Badge variant="secondary" className="font-mono text-xs"> const overrides = pricing?.overrides as Record<string, unknown> | undefined;
{plan.code} const overrideCountries = overrides ? Object.keys(overrides) : [];
</Badge>
</td> return (
<td className="px-5 py-4 font-medium">{plan.name}</td> <tr key={plan.code} className="transition-colors hover:bg-accent/30">
<td className="px-5 py-4 text-right font-medium"> <td className="px-5 py-4">
${Number(plan.price).toFixed(2)} <Badge variant="secondary" className="font-mono text-xs">
</td> {plan.code}
<td className="hidden px-5 py-4 text-center text-sm text-muted-foreground sm:table-cell"> </Badge>
{plan.complexCount} </td>
</td> <td className="px-5 py-4 font-medium">{plan.name}</td>
<td className="px-5 py-4 text-right"> <td className="px-5 py-4 text-right">
<div className="flex justify-end gap-1"> <div className="flex flex-col items-end gap-1">
<Button <span className="font-medium">${Number(plan.price).toFixed(2)} USD</span>
variant="ghost" {overrideCountries.length > 0 && (
size="icon" <div className="flex flex-wrap gap-1">
className="size-8 rounded-lg" {overrideCountries.map((country) => (
onClick={() => setEditingPlan(plan)} <Badge key={country} variant="secondary" className="text-xs">
> {country}
<Pencil className="size-3.5" /> </Badge>
</Button> ))}
<Button </div>
variant="ghost" )}
size="icon" </div>
className="size-8 rounded-lg text-destructive hover:bg-destructive/10 hover:text-destructive" </td>
onClick={() => setDeletingPlan(plan)} <td className="hidden px-5 py-4 text-center text-sm text-muted-foreground sm:table-cell">
> {plan.complexCount}
<Trash2 className="size-3.5" /> </td>
</Button> <td className="px-5 py-4 text-right">
</div> <div className="flex justify-end gap-1">
</td> <Button
</tr> variant="ghost"
))} size="icon"
className="size-8 rounded-lg"
onClick={() => setEditingPlan(plan)}
>
<Pencil className="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon"
className="size-8 rounded-lg text-destructive hover:bg-destructive/10 hover:text-destructive"
onClick={() => setDeletingPlan(plan)}
>
<Trash2 className="size-3.5" />
</Button>
</div>
</td>
</tr>
);
})}
</tbody> </tbody>
</table> </table>
</div> </div>

View File

@@ -58,7 +58,11 @@ export function PlanSelectStep({ form, plans }: PlanSelectStepProps) {
<div className="mb-3"> <div className="mb-3">
<h3 className="text-xl font-bold">{plan.name}</h3> <h3 className="text-xl font-bold">{plan.name}</h3>
<div className="mt-1"> <div className="mt-1">
<span className="text-3xl font-bold">${plan.price}</span> <span className="text-3xl font-bold">
{plan.currency === 'ARS'
? `AR$${plan.price.toLocaleString('es-AR')}`
: `$${plan.price.toFixed(2)}`}
</span>
<span className="text-sm text-muted-foreground">/mes</span> <span className="text-sm text-muted-foreground">/mes</span>
</div> </div>
</div> </div>

View File

@@ -50,7 +50,14 @@ export function ReviewStep({ data, selectedPlan }: ReviewStepProps) {
<Section title="Plan seleccionado"> <Section title="Plan seleccionado">
{selectedPlan ? ( {selectedPlan ? (
<> <>
<Row label="Plan" value={`${selectedPlan.name} - $${selectedPlan.price}/mes`} /> <Row
label="Plan"
value={`${selectedPlan.name} - ${
selectedPlan.currency === 'ARS'
? `AR$${selectedPlan.price.toLocaleString('es-AR')}`
: `$${selectedPlan.price.toFixed(2)}`
}/mes`}
/>
<div className="mt-2 space-y-1"> <div className="mt-2 space-y-1">
{[ {[
['publicBookingPage', 'Página de booking pública'], ['publicBookingPage', 'Página de booking pública'],

View File

@@ -1,2 +1,3 @@
[test] [test]
exclude = ["**/dist/**", "**/node_modules/**"]
preload = ["./apps/backend/test/support/prisma.mock.ts"] preload = ["./apps/backend/test/support/prisma.mock.ts"]

View File

@@ -33,7 +33,24 @@ export const planRulesV1Schema = z.object({
}), }),
}) })
export const planRulesSchema = z.discriminatedUnion('version', [planRulesV1Schema]) export const planPriceOverrideSchema = z.object({
amount: z.number().nonnegative(),
currency: z.string().length(3),
})
export const planRulesV2Schema = planRulesV1Schema.extend({
version: z.literal('v2'),
pricing: z
.object({
overrides: z.record(z.string(), planPriceOverrideSchema),
})
.optional(),
})
export const planRulesSchema = z.discriminatedUnion('version', [
planRulesV1Schema,
planRulesV2Schema,
])
export const planSchema = z.object({ export const planSchema = z.object({
code: z.string().trim().min(1).max(10), code: z.string().trim().min(1).max(10),
@@ -60,12 +77,14 @@ export const planWithFeaturesSchema = z.object({
code: z.string().trim().min(1).max(10), code: z.string().trim().min(1).max(10),
name: z.string().trim().min(1).max(30), name: z.string().trim().min(1).max(30),
price: z.number().nonnegative(), price: z.number().nonnegative(),
currency: z.string().length(3),
features: planFeatureFlagsSchema, features: planFeatureFlagsSchema,
limits: planLimitsSchema, limits: planLimitsSchema,
}) })
export type PlanFeatureFlags = z.infer<typeof planFeatureFlagsSchema> export type PlanFeatureFlags = z.infer<typeof planFeatureFlagsSchema>
export type PlanRulesV1 = z.infer<typeof planRulesV1Schema> export type PlanRulesV1 = z.infer<typeof planRulesV1Schema>
export type PlanRulesV2 = z.infer<typeof planRulesV2Schema>
export type PlanRules = z.infer<typeof planRulesSchema> export type PlanRules = z.infer<typeof planRulesSchema>
export type Plan = z.infer<typeof planSchema> export type Plan = z.infer<typeof planSchema>
export type PlanSummary = z.infer<typeof planSummarySchema> export type PlanSummary = z.infer<typeof planSummarySchema>