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

@@ -9,11 +9,18 @@ import {
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { AdminLayout } from '@/features/admin/admin-layout';
import { ApiClientError, apiClient } from '@/lib/api-client';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
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';
type Plan = {
@@ -25,6 +32,61 @@ type Plan = {
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({
mode,
plan,
@@ -38,6 +100,9 @@ function PlanFormDialog({
const [code, setCode] = useState(plan?.code ?? '');
const [name, setName] = useState(plan?.name ?? '');
const [price, setPrice] = useState(String(plan?.price ?? ''));
const [priceOverrides, setPriceOverrides] = useState<PriceOverride[]>(() =>
mode === 'edit' && plan ? initOverrides(plan.rules) : []
);
const createMutation = useMutation({
mutationFn: (data: { code: string; name: string; price: number; rules: object }) =>
@@ -49,7 +114,7 @@ function PlanFormDialog({
});
const updateMutation = useMutation({
mutationFn: (data: { name?: string; price?: number }) =>
mutationFn: (data: { name?: string; price?: number; rules?: unknown }) =>
apiClient.admin.updatePlan(plan!.code, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['admin-plans'] });
@@ -62,22 +127,36 @@ function PlanFormDialog({
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const rules = buildRulesData(mode, plan?.rules, priceOverrides);
if (mode === 'create') {
createMutation.mutate({
code,
name,
price: Number.parseFloat(price),
rules: {},
rules: rules as object,
});
} else {
updateMutation.mutate({
name,
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 (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="rounded-2xl sm:max-w-md">
@@ -118,7 +197,9 @@ function PlanFormDialog({
</div>
<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
id="price"
type="number"
@@ -131,6 +212,72 @@ function PlanFormDialog({
/>
</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 && (
<p className="text-sm text-destructive">
{error instanceof ApiClientError
@@ -292,42 +439,60 @@ export function PlansPage() {
</tr>
</thead>
<tbody className="divide-y divide-border/40">
{data?.map((plan) => (
<tr key={plan.code} className="transition-colors hover:bg-accent/30">
<td className="px-5 py-4">
<Badge variant="secondary" className="font-mono text-xs">
{plan.code}
</Badge>
</td>
<td className="px-5 py-4 font-medium">{plan.name}</td>
<td className="px-5 py-4 text-right font-medium">
${Number(plan.price).toFixed(2)}
</td>
<td className="hidden px-5 py-4 text-center text-sm text-muted-foreground sm:table-cell">
{plan.complexCount}
</td>
<td className="px-5 py-4 text-right">
<div className="flex justify-end gap-1">
<Button
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>
))}
{data?.map((plan) => {
const rules = plan.rules as Record<string, unknown> | null;
const pricing = rules?.pricing as Record<string, unknown> | undefined;
const overrides = pricing?.overrides as Record<string, unknown> | undefined;
const overrideCountries = overrides ? Object.keys(overrides) : [];
return (
<tr key={plan.code} className="transition-colors hover:bg-accent/30">
<td className="px-5 py-4">
<Badge variant="secondary" className="font-mono text-xs">
{plan.code}
</Badge>
</td>
<td className="px-5 py-4 font-medium">{plan.name}</td>
<td className="px-5 py-4 text-right">
<div className="flex flex-col items-end gap-1">
<span className="font-medium">${Number(plan.price).toFixed(2)} USD</span>
{overrideCountries.length > 0 && (
<div className="flex flex-wrap gap-1">
{overrideCountries.map((country) => (
<Badge key={country} variant="secondary" className="text-xs">
{country}
</Badge>
))}
</div>
)}
</div>
</td>
<td className="hidden px-5 py-4 text-center text-sm text-muted-foreground sm:table-cell">
{plan.complexCount}
</td>
<td className="px-5 py-4 text-right">
<div className="flex justify-end gap-1">
<Button
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>
</table>
</div>

View File

@@ -58,7 +58,11 @@ export function PlanSelectStep({ form, plans }: PlanSelectStepProps) {
<div className="mb-3">
<h3 className="text-xl font-bold">{plan.name}</h3>
<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>
</div>
</div>

View File

@@ -50,7 +50,14 @@ export function ReviewStep({ data, selectedPlan }: ReviewStepProps) {
<Section title="Plan seleccionado">
{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">
{[
['publicBookingPage', 'Página de booking pública'],