All files / src/pages/admin calculator-config.tsx

98.14% Statements 53/54
87.09% Branches 27/31
100% Functions 17/17
100% Lines 53/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213                              29x 29x   29x 29x 29x 29x 29x   29x 23x 7x 7x           8x 8x 8x 8x       1x 1x 1x 1x 1x   1x         3x 3x 3x 3x 3x 2x 1x 1x     1x   1x     1x   3x       29x 8x             21x           189x           6x           21x                                                     1x     1x     1x     1x                             1x                                 21x 1x 1x 1x                       84x 1x 1x 1x                               1x                        
import type { CalculatorConfig } from "@interioring/utils/calculator";
import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { Button } from "../../components/ui/button";
import { Card, CardContent, CardHeader } from "../../components/ui/card";
import { useAdminCalculatorConfig } from "../../hooks/queries/useAdminQueries";
import { adminApi } from "../../lib/api";
import { queryKeys } from "../../lib/query-keys";
 
// Admin editor for the marketplace cost-calculator pricing config. The most-
// edited levers (fees, bands, gating, per-city/per-tier multipliers) get
// structured inputs; the full config (room line items, categories, timeline)
// is editable via the raw JSON area. Both edit the same draft.
 
export function AdminCalculatorConfigPage() {
	const queryClient = useQueryClient();
	const { data, isLoading } = useAdminCalculatorConfig();
 
	const [draft, setDraft] = useState<CalculatorConfig | null>(null);
	const [jsonText, setJsonText] = useState("");
	const [jsonError, setJsonError] = useState<string | null>(null);
	const [saving, setSaving] = useState(false);
	const [status, setStatus] = useState<string | null>(null);
 
	useEffect(() => {
		if (data && !draft) {
			setDraft(data);
			setJsonText(JSON.stringify(data, null, 2));
		}
	}, [data, draft]);
 
	// Structured edits flow through here so the JSON view stays in sync.
	function applyDraft(next: CalculatorConfig) {
		setDraft(next);
		setJsonText(JSON.stringify(next, null, 2));
		setJsonError(null);
		setStatus(null);
	}
 
	function onJsonChange(text: string) {
		setJsonText(text);
		setStatus(null);
		try {
			setDraft(JSON.parse(text) as CalculatorConfig);
			setJsonError(null);
		} catch (err) {
			setJsonError(err instanceof Error ? err.message : "Invalid JSON");
		}
	}
 
	async function save() {
		Iif (!draft || jsonError) return;
		setSaving(true);
		setStatus(null);
		try {
			const res = await adminApi.updateCalculatorConfig(draft);
			if (res.success && res.data) {
				applyDraft(res.data);
				queryClient.invalidateQueries({
					queryKey: queryKeys.admin.calculatorConfig.all,
				});
				setStatus(`Saved — version ${res.data.version}.`);
			} else {
				setStatus(res.error?.message ?? "Save failed.");
			}
		} catch (err) {
			setStatus(err instanceof Error ? err.message : "Save failed.");
		} finally {
			setSaving(false);
		}
	}
 
	if (isLoading || !draft) {
		return (
			<div className="p-6 text-foreground-muted">
				Loading calculator config…
			</div>
		);
	}
 
	const numberField = (
		label: string,
		value: number,
		onChange: (n: number) => void,
		step = 0.01,
	) => (
		<label className="flex flex-col gap-1 text-sm">
			<span className="text-foreground-muted">{label}</span>
			<input
				type="number"
				step={step}
				value={value}
				onChange={(e) => onChange(Number(e.target.value))}
				className="rounded-md border border-border-default bg-background-elevated px-3 py-2"
			/>
		</label>
	);
 
	return (
		<div className="space-y-6 p-6">
			<div className="flex items-center justify-between">
				<div>
					<h1 className="text-2xl font-semibold">Cost Calculator Config</h1>
					<p className="text-sm text-foreground-muted">
						Pricing is admin-managed — changes go live without a deploy. Current
						version {draft.version}.
					</p>
				</div>
				<Button onClick={save} disabled={saving || !!jsonError}>
					{saving ? "Saving…" : "Save changes"}
				</Button>
			</div>
 
			{status && (
				<div className="rounded-md bg-secondary-100 px-4 py-2 text-sm">
					{status}
				</div>
			)}
 
			<Card>
				<CardHeader>
					<h2 className="font-medium">Global levers</h2>
				</CardHeader>
				<CardContent className="grid grid-cols-2 gap-4 md:grid-cols-4">
					{numberField("Design fee %", draft.designFeePct, (n) =>
						applyDraft({ ...draft, designFeePct: n }),
					)}
					{numberField("GST %", draft.gstPct, (n) =>
						applyDraft({ ...draft, gstPct: n }),
					)}
					{numberField("Band — full home", draft.bands.full, (n) =>
						applyDraft({ ...draft, bands: { ...draft.bands, full: n } }),
					)}
					{numberField("Band — picked rooms", draft.bands.partial, (n) =>
						applyDraft({ ...draft, bands: { ...draft.bands, partial: n } }),
					)}
				</CardContent>
			</Card>
 
			<Card>
				<CardHeader>
					<h2 className="font-medium">Result presentation</h2>
				</CardHeader>
				<CardContent className="flex flex-wrap items-center gap-6">
					<label className="flex items-center gap-2 text-sm">
						<input
							type="checkbox"
							checked={draft.ui.gated}
							onChange={(e) =>
								applyDraft({
									...draft,
									ui: { ...draft.ui, gated: e.target.checked },
								})
							}
						/>
						<span>Gate breakdown behind register</span>
					</label>
				</CardContent>
			</Card>
 
			<Card>
				<CardHeader>
					<h2 className="font-medium">City multipliers</h2>
				</CardHeader>
				<CardContent className="grid grid-cols-2 gap-4 md:grid-cols-3">
					{draft.cities.map((city, i) =>
						numberField(`${city.name}`, city.mult, (n) => {
							const cities = [...draft.cities];
							cities[i] = { ...city, mult: n };
							applyDraft({ ...draft, cities });
						}),
					)}
				</CardContent>
			</Card>
 
			<Card>
				<CardHeader>
					<h2 className="font-medium">Tier multipliers</h2>
				</CardHeader>
				<CardContent className="grid grid-cols-2 gap-4 md:grid-cols-4">
					{draft.tiers.map((tier, i) =>
						numberField(`${tier.name}`, tier.mult, (n) => {
							const tiers = [...draft.tiers];
							tiers[i] = { ...tier, mult: n };
							applyDraft({ ...draft, tiers });
						}),
					)}
				</CardContent>
			</Card>
 
			<Card>
				<CardHeader>
					<h2 className="font-medium">Advanced — full config (JSON)</h2>
					<p className="text-sm text-foreground-muted">
						Edit rooms, line items, categories, works and timeline here.
					</p>
				</CardHeader>
				<CardContent className="space-y-2">
					<textarea
						value={jsonText}
						onChange={(e) => onJsonChange(e.target.value)}
						spellCheck={false}
						className="h-96 w-full rounded-md border border-border-default bg-background-elevated p-3 font-mono text-xs"
					/>
					{jsonError && (
						<p className="text-sm text-error">Invalid JSON: {jsonError}</p>
					)}
				</CardContent>
			</Card>
		</div>
	);
}