318 lines
11 KiB
TypeScript
318 lines
11 KiB
TypeScript
import { createFileRoute } from '@tanstack/react-router'
|
|
import { useState } from 'react'
|
|
import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
|
|
import { ProtectedRoute } from '../components/ProtectedRoute'
|
|
import { AppShell } from '../components/AppShell'
|
|
import { trpc } from '../lib/trpc-client'
|
|
|
|
export const Route = createFileRoute('/regions')({
|
|
component: () => (
|
|
<ProtectedRoute>
|
|
<AppShell>
|
|
<RegionsPage />
|
|
</AppShell>
|
|
</ProtectedRoute>
|
|
),
|
|
})
|
|
|
|
const SETTING_KEYS = [
|
|
'minRegularOrderValue',
|
|
'freeDeliveryThreshold',
|
|
'deliveryCharge',
|
|
'flashFreeDeliveryThreshold',
|
|
'flashDeliveryCharge',
|
|
'popularItems',
|
|
'allItemsOrder',
|
|
'isFlashDeliveryEnabled',
|
|
'supportMobile',
|
|
'supportEmail',
|
|
'welcomeMessage',
|
|
] as const
|
|
|
|
const SETTING_LABELS: Record<string, string> = {
|
|
minRegularOrderValue: 'Minimum Regular Order Value',
|
|
freeDeliveryThreshold: 'Free Delivery Threshold',
|
|
deliveryCharge: 'Delivery Charge',
|
|
flashFreeDeliveryThreshold: 'Flash Free Delivery Threshold',
|
|
flashDeliveryCharge: 'Flash Delivery Charge',
|
|
popularItems: 'Popular Items (JSON)',
|
|
allItemsOrder: 'All Items Order (JSON)',
|
|
isFlashDeliveryEnabled: 'Enable Flash Delivery',
|
|
supportMobile: 'Support Mobile',
|
|
supportEmail: 'Support Email',
|
|
welcomeMessage: 'Welcome Message',
|
|
}
|
|
|
|
function RegionsPage() {
|
|
const regionsQuery = trpc.superadmin.regions.list.useQuery()
|
|
const createRegion = trpc.superadmin.regions.create.useMutation({
|
|
onSuccess: () => regionsQuery.refetch(),
|
|
})
|
|
|
|
const [selectedRegionId, setSelectedRegionId] = useState<number | null>(null)
|
|
const [newRegionName, setNewRegionName] = useState('')
|
|
const [newRegionDescription, setNewRegionDescription] = useState('')
|
|
|
|
const regions = regionsQuery.data ?? []
|
|
|
|
return (
|
|
<AppContainer>
|
|
<div className="bg-gray-50 p-4">
|
|
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Regions</MyText>
|
|
<MyText className="mb-6 block text-gray-600">
|
|
Create regions and manage the delivery bounds and settings for each region.
|
|
</MyText>
|
|
|
|
<div className="mb-6 rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
|
|
<MyText className="mb-3 block font-semibold text-gray-900">Add a region</MyText>
|
|
<div className="grid gap-3 sm:grid-cols-2">
|
|
<PInput
|
|
topLabel="Name"
|
|
value={newRegionName}
|
|
onChange={(e) => setNewRegionName(e.target.value)}
|
|
placeholder="e.g. Mahabubnagar"
|
|
/>
|
|
<PInput
|
|
topLabel="Description"
|
|
value={newRegionDescription}
|
|
onChange={(e) => setNewRegionDescription(e.target.value)}
|
|
placeholder="Optional"
|
|
/>
|
|
</div>
|
|
<MyButton
|
|
disabled={!newRegionName.trim() || createRegion.isPending}
|
|
onClick={async () => {
|
|
const region = await createRegion.mutateAsync({
|
|
name: newRegionName.trim(),
|
|
description: newRegionDescription.trim() || null,
|
|
})
|
|
setNewRegionName('')
|
|
setNewRegionDescription('')
|
|
setSelectedRegionId(region.id)
|
|
}}
|
|
className="mt-4 rounded-lg bg-blue-500 px-4 py-2 text-white disabled:opacity-50"
|
|
>
|
|
{createRegion.isPending ? 'Creating...' : 'Create region'}
|
|
</MyButton>
|
|
</div>
|
|
|
|
{regionsQuery.isLoading && <MyText className="text-gray-500">Loading regions...</MyText>}
|
|
|
|
<div className="mb-6 grid gap-3 sm:grid-cols-2">
|
|
{regions.map((region) => (
|
|
<button
|
|
key={region.id}
|
|
type="button"
|
|
onClick={() => setSelectedRegionId(region.id)}
|
|
className={`rounded-xl border p-4 text-left shadow-sm transition-colors ${
|
|
selectedRegionId === region.id
|
|
? 'border-blue-400 bg-blue-50'
|
|
: 'border-gray-200 bg-white hover:border-blue-300'
|
|
}`}
|
|
>
|
|
<MyText className="block font-semibold text-gray-900">{region.name}</MyText>
|
|
<MyText className="block text-sm text-gray-500">
|
|
{region.description || 'No description'}
|
|
</MyText>
|
|
</button>
|
|
))}
|
|
</div>
|
|
|
|
{selectedRegionId && <RegionDetail regionId={selectedRegionId} />}
|
|
</div>
|
|
</AppContainer>
|
|
)
|
|
}
|
|
|
|
function RegionDetail({ regionId }: { regionId: number }) {
|
|
const regionQuery = trpc.superadmin.regions.get.useQuery({ id: regionId })
|
|
const [activeBoundId, setActiveBoundId] = useState<number | null>(null)
|
|
const [showAddBound, setShowAddBound] = useState(false)
|
|
|
|
const bounds = regionQuery.data?.bounds ?? []
|
|
const effectiveBoundId = bounds.length > 0 ? bounds[0].id : null
|
|
|
|
const activeBound = bounds.find((b) => b.id === activeBoundId) ?? bounds[0] ?? null
|
|
|
|
return (
|
|
<div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
|
|
<div className="mb-4 flex items-center justify-between">
|
|
<MyText className="block font-semibold text-gray-900">
|
|
{regionQuery.data?.name} — bounds
|
|
</MyText>
|
|
<MyButton
|
|
onClick={() => setShowAddBound((v) => !v)}
|
|
className="rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-700"
|
|
>
|
|
{showAddBound ? 'Cancel' : 'Add bound'}
|
|
</MyButton>
|
|
</div>
|
|
|
|
{showAddBound && (
|
|
<AddBoundForm
|
|
regionId={regionId}
|
|
onCreated={(id) => {
|
|
setShowAddBound(false)
|
|
setActiveBoundId(id)
|
|
regionQuery.refetch()
|
|
}}
|
|
/>
|
|
)}
|
|
|
|
{bounds.length === 0 && !showAddBound && (
|
|
<MyText className="block text-gray-500">
|
|
No bounds yet. Add at least one bound so this region can take orders.
|
|
</MyText>
|
|
)}
|
|
|
|
{bounds.length > 0 && (
|
|
<>
|
|
<div className="mb-4 flex flex-wrap gap-2">
|
|
{bounds.map((bound) => {
|
|
const isActive = activeBound?.id === bound.id
|
|
return (
|
|
<button
|
|
key={bound.id}
|
|
type="button"
|
|
onClick={() => setActiveBoundId(bound.id)}
|
|
className={`rounded-lg border px-3 py-2 text-sm font-medium ${
|
|
isActive ? 'border-blue-400 bg-blue-50 text-blue-700' : 'border-gray-200 text-gray-700'
|
|
}`}
|
|
>
|
|
{bound.description || `Bound #${bound.id}`} (P{bound.priority})
|
|
{bound.id === effectiveBoundId && (
|
|
<span className="ml-2 rounded bg-green-100 px-1.5 py-0.5 text-[10px] font-bold text-green-700">
|
|
EFFECTIVE
|
|
</span>
|
|
)}
|
|
</button>
|
|
)
|
|
})}
|
|
</div>
|
|
|
|
<MyText className="mb-4 block text-sm text-gray-500">
|
|
Only the lowest-priority bound's settings currently apply to checkout, regardless of
|
|
address coordinates.
|
|
</MyText>
|
|
|
|
{activeBound && <BoundSettingsEditor boundId={activeBound.id} />}
|
|
</>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function AddBoundForm({ regionId, onCreated }: { regionId: number; onCreated: (id: number) => void }) {
|
|
const [description, setDescription] = useState('')
|
|
const [priority, setPriority] = useState('')
|
|
const [geojson, setGeojson] = useState('')
|
|
const [error, setError] = useState<string | null>(null)
|
|
|
|
const createBound = trpc.superadmin.regions.createBound.useMutation()
|
|
|
|
return (
|
|
<div className="mb-6 rounded-lg border border-gray-200 bg-gray-50 p-4">
|
|
<div className="grid gap-3 sm:grid-cols-2">
|
|
<PInput
|
|
topLabel="Description"
|
|
value={description}
|
|
onChange={(e) => setDescription(e.target.value)}
|
|
placeholder="e.g. Mbnr-1"
|
|
/>
|
|
<PInput
|
|
topLabel="Priority (lower = higher precedence)"
|
|
value={priority}
|
|
onChange={(e) => setPriority(e.target.value)}
|
|
placeholder="1"
|
|
/>
|
|
</div>
|
|
<div className="mt-3">
|
|
<MyText className="mb-1 block text-sm font-medium text-gray-700">GeoJSON</MyText>
|
|
<textarea
|
|
value={geojson}
|
|
onChange={(e) => setGeojson(e.target.value)}
|
|
rows={6}
|
|
placeholder='{"type":"FeatureCollection","features":[...]}'
|
|
className="w-full rounded-lg border border-gray-300 p-3 font-mono text-xs"
|
|
/>
|
|
</div>
|
|
{error && <MyText className="mt-2 block text-sm text-red-600">{error}</MyText>}
|
|
<MyButton
|
|
onClick={async () => {
|
|
setError(null)
|
|
try {
|
|
const parsed = JSON.parse(geojson)
|
|
const bound = await createBound.mutateAsync({
|
|
regionId,
|
|
description: description.trim() || null,
|
|
priority: priority.trim(),
|
|
geojson: parsed,
|
|
})
|
|
onCreated(bound.id)
|
|
} catch (e) {
|
|
setError((e as Error).message || 'Invalid GeoJSON or duplicate priority')
|
|
}
|
|
}}
|
|
disabled={createBound.isPending || !priority.trim() || !geojson.trim()}
|
|
className="mt-3 rounded-lg bg-blue-500 px-4 py-2 text-white disabled:opacity-50"
|
|
>
|
|
{createBound.isPending ? 'Saving...' : 'Create bound'}
|
|
</MyButton>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function BoundSettingsEditor({ boundId }: { boundId: number }) {
|
|
const settingsQuery = trpc.superadmin.regions.boundSettings.useQuery({ boundId })
|
|
const updateSettings = trpc.superadmin.regions.updateBoundSettings.useMutation({
|
|
onSuccess: () => settingsQuery.refetch(),
|
|
})
|
|
|
|
const [draft, setDraft] = useState<Record<string, string>>({})
|
|
const [initialised, setInitialised] = useState<number | null>(null)
|
|
|
|
const settings = settingsQuery.data ?? {}
|
|
|
|
// Re-initialise the draft whenever the selected bound changes.
|
|
if (initialised !== boundId && settingsQuery.isSuccess) {
|
|
const next: Record<string, string> = {}
|
|
for (const key of SETTING_KEYS) {
|
|
next[key] = settings[key] ?? ''
|
|
}
|
|
setDraft(next)
|
|
setInitialised(boundId)
|
|
}
|
|
|
|
if (settingsQuery.isLoading) {
|
|
return <MyText className="block text-gray-500">Loading settings...</MyText>
|
|
}
|
|
|
|
const handleSave = () => {
|
|
updateSettings.mutate({
|
|
boundId,
|
|
settings: SETTING_KEYS.map((key) => ({ key, value: draft[key] ?? '' })),
|
|
})
|
|
}
|
|
|
|
return (
|
|
<div>
|
|
<MyText className="mb-3 block font-semibold text-gray-900">Bound settings</MyText>
|
|
{SETTING_KEYS.map((key) => (
|
|
<div key={key} className="mb-3">
|
|
<PInput
|
|
topLabel={SETTING_LABELS[key] || key}
|
|
value={draft[key] ?? ''}
|
|
onChange={(e) => setDraft((prev) => ({ ...prev, [key]: e.target.value }))}
|
|
/>
|
|
</div>
|
|
))}
|
|
<MyButton
|
|
onClick={handleSave}
|
|
disabled={updateSettings.isPending}
|
|
className="mt-2 rounded-lg bg-blue-500 px-4 py-2 text-white disabled:opacity-50"
|
|
>
|
|
{updateSettings.isPending ? 'Saving...' : 'Save settings'}
|
|
</MyButton>
|
|
</div>
|
|
)
|
|
}
|