freshyo/apps/superadmin-ui/src/routes/global-products.tsx
2026-10-14 17:27:52 +05:30

647 lines
25 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createFileRoute } from '@tanstack/react-router'
import { useEffect, useState } from 'react'
import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
import { Plus, Trash2, X } from 'lucide-react'
import { ProtectedRoute } from '../components/ProtectedRoute'
import { AppShell } from '../components/AppShell'
import { RegionTabs, type RegionTabKey } from '../components/RegionTabs'
import { SimpleSelect } from '@/components/ui/simple-select'
import { alert, confirm } from '@/components/ui/dialog-host'
import { trpc } from '../lib/trpc-client'
import { useUploadToObjectStorage } from '../hooks/useUploadToObjectStorage'
export const Route = createFileRoute('/global-products')({
component: () => (
<ProtectedRoute>
<AppShell>
<ProductsPage />
</AppShell>
</ProtectedRoute>
),
})
const PAGE_SIZE = 20
interface FeatureDraft {
featureName: string
featureValue: string
}
interface SkuDraft {
id?: number
name: string
price: string
marketPrice: string
isOutOfStock: boolean
isOffer: boolean
isComboOnly: boolean
isDeleted: boolean
isSuspended: boolean
images: string[]
pendingFiles: { blob: Blob; mimeType: string }[]
pendingPreviews: string[]
features: FeatureDraft[]
comboItems: { skuId: number }[]
}
const emptySku = (): SkuDraft => ({
name: '',
price: '',
marketPrice: '',
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
images: [],
pendingFiles: [],
pendingPreviews: [],
features: [{ featureName: 'quantity', featureValue: '1kg' }],
comboItems: [],
})
const skuToDraft = (sku: any): SkuDraft => ({
id: sku.id,
name: sku.name ?? '',
price: sku.price != null ? String(sku.price) : '',
marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : '',
isOutOfStock: sku.isOutOfStock ?? false,
isOffer: sku.isOffer ?? false,
isComboOnly: sku.isComboOnly ?? false,
isDeleted: sku.isDeleted ?? false,
isSuspended: sku.isSuspended ?? false,
images: (sku.images ?? []).map(String),
pendingFiles: [],
pendingPreviews: [],
features: (sku.features ?? []).map((f: any) => ({
featureName: f.featureName ?? '',
featureValue: f.featureValue ?? '',
})),
comboItems: (sku.comboItems ?? []).map((ci: any) => ({ skuId: ci.skuId })),
})
function ProductsPage() {
const regionsQuery = trpc.superadmin.regions.list.useQuery()
const regions = (regionsQuery.data ?? []) as { id: number; name: string }[]
const [tab, setTab] = useState<RegionTabKey>('global')
return (
<AppContainer>
<div className="bg-gray-50 p-4">
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Products</MyText>
<MyText className="mb-4 block text-gray-600">
The Global tab holds the catalogue shared across every region; each region tab lists that
region's own products (which can be elevated to global).
</MyText>
<RegionTabs regions={regions} value={tab} onChange={setTab} />
{tab === 'global' ? <GlobalProductsTab /> : <RegionProductsTab regionId={tab} />}
</div>
</AppContainer>
)
}
function RegionProductsTab({ regionId }: { regionId: number }) {
const utils = trpc.useUtils()
const storesQuery = trpc.superadmin.globalStores.list.useQuery()
const [searchInput, setSearchInput] = useState('')
const [search, setSearch] = useState('')
const [page, setPage] = useState(0)
// Debounce the search box; reset to page 0 when the query changes.
useEffect(() => {
const t = setTimeout(() => {
setSearch(searchInput)
setPage(0)
}, 300)
return () => clearTimeout(t)
}, [searchInput])
// Tabs reuse this component, so start each region on its first page.
useEffect(() => {
setPage(0)
}, [regionId])
const listQuery = trpc.superadmin.products.list.useQuery({
regionId,
search: search || undefined,
limit: PAGE_SIZE,
offset: page * PAGE_SIZE,
})
const elevate = trpc.superadmin.products.elevate.useMutation()
const [elevatingId, setElevatingId] = useState<number | null>(null)
const [storeChoice, setStoreChoice] = useState<number | ''>('')
const products = (listQuery.data?.products ?? []) as any[]
const total = listQuery.data?.total ?? 0
const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE))
const stores = storesQuery.data ?? []
const doElevate = async (productId: number) => {
if (storeChoice === '') {
void alert('Choose a global store')
return
}
try {
await elevate.mutateAsync({ productId, storeId: Number(storeChoice) })
setElevatingId(null)
setStoreChoice('')
await utils.superadmin.products.list.invalidate()
await utils.superadmin.globalProducts.list.invalidate()
} catch (e: any) {
void alert(e.message || 'Failed to elevate product')
}
}
return (
<div>
<div className="mb-4 flex flex-wrap items-center gap-3">
<input
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
placeholder="Search by product name, SKU or description…"
className="min-w-[220px] flex-1 rounded-lg border border-gray-200 px-3 py-2 text-gray-900"
/>
</div>
{listQuery.isLoading && <MyText className="text-gray-500">Loading products…</MyText>}
{!listQuery.isLoading && products.length === 0 && (
<MyText className="text-gray-500">No products in this region yet.</MyText>
)}
<div className="grid gap-3">
{products.map((product) => {
const isGlobal = product.regionId == null
return (
<div key={product.id} className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
<div className="flex items-start justify-between gap-2">
<div>
<MyText className="block font-semibold text-gray-900">{product.name}</MyText>
<MyText className="block text-sm text-gray-500">
{product.region?.name ?? 'Global'} · {product.store?.name ?? 'No store'} ·{' '}
{product.skus?.length ?? 0} SKU(s)
</MyText>
</div>
<div className="flex items-center gap-2">
<span
className={`rounded-full px-2 py-0.5 text-[10px] font-bold ${
isGlobal ? 'bg-purple-100 text-purple-700' : 'bg-gray-100 text-gray-600'
}`}
>
{isGlobal ? 'GLOBAL' : 'REGIONAL'}
</span>
{!isGlobal ? (
<MyButton
onClick={() => {
setElevatingId(elevatingId === product.id ? null : product.id)
setStoreChoice('')
}}
>
Elevate to global
</MyButton>
) : null}
</div>
</div>
{elevatingId === product.id && !isGlobal ? (
<div className="mt-3 flex flex-wrap items-center gap-2 border-t border-gray-100 pt-3">
<MyText className="text-sm text-gray-500">Attach to global store:</MyText>
<SimpleSelect
value={storeChoice}
onValueChange={(value) => setStoreChoice(value === '' ? '' : Number(value))}
placeholder="Select…"
className="w-auto"
options={stores.map((s: any) => ({ value: s.id, label: s.name }))}
/>
<MyButton onClick={() => doElevate(product.id)} disabled={elevate.isPending}>
{elevate.isPending ? 'Elevating…' : 'Confirm'}
</MyButton>
<button type="button" onClick={() => setElevatingId(null)} className="text-sm text-gray-500">
Cancel
</button>
</div>
) : null}
</div>
)
})}
</div>
<div className="mt-4 flex items-center justify-between">
<MyText className="text-sm text-gray-500">
{total} product(s) · page {page + 1} of {pageCount}
</MyText>
<div className="flex gap-2">
<MyButton onClick={() => setPage((p) => Math.max(0, p - 1))} disabled={page === 0}>
Prev
</MyButton>
<MyButton
onClick={() => setPage((p) => Math.min(pageCount - 1, p + 1))}
disabled={page >= pageCount - 1}
>
Next
</MyButton>
</div>
</div>
</div>
)
}
function GlobalProductsTab() {
const listQuery = trpc.superadmin.globalProducts.list.useQuery()
const utils = trpc.useUtils()
const [editingId, setEditingId] = useState<number | null>(null)
const remove = trpc.superadmin.globalProducts.delete.useMutation({
onSuccess: async () => { await utils.superadmin.globalProducts.list.invalidate() },
onError: (e) => void alert(e.message),
})
const refresh = () => utils.superadmin.globalProducts.list.invalidate()
const products = (listQuery.data?.products ?? []) as any[]
const editing = products.find((p) => p.id === editingId) ?? null
return (
<div>
<MyText className="mb-4 block text-gray-600">
Products shared across every region. Creating one seeds the initial price &amp; stock into
each region; editing the structure leaves each region's market data untouched.
</MyText>
{editing ? (
<GlobalProductForm
product={editing}
onSaved={() => { setEditingId(null); refresh() }}
onCancel={() => setEditingId(null)}
/>
) : (
<GlobalProductForm onSaved={refresh} />
)}
{listQuery.isLoading && <MyText className="text-gray-500">Loading products…</MyText>}
<div className="mt-6 grid gap-3">
{products.map((product) => (
<div key={product.id} className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
<div className="mb-2 flex items-start justify-between gap-2">
<div>
<MyText className="block font-semibold text-gray-900">{product.name}</MyText>
<MyText className="block text-sm text-gray-500">
{product.store?.name ?? 'No store'} · {product.skus?.length ?? 0} SKU(s)
{product.productType === 'combo' ? ' · combo' : ''}
</MyText>
</div>
<div className="flex items-center gap-2">
<span className="rounded-full bg-purple-100 px-2 py-0.5 text-[10px] font-bold text-purple-700">
GLOBAL
</span>
<MyButton onClick={() => setEditingId(product.id)}>Edit</MyButton>
<button
type="button"
onClick={async () => {
if (await confirm(`Delete global product "${product.name}"?`)) remove.mutate({ id: product.id })
}}
className="rounded-lg bg-red-500 p-2 text-white"
aria-label="Delete product"
>
<Trash2 size={14} />
</button>
</div>
</div>
<div className="flex flex-wrap gap-2">
{(product.skus ?? []).map((sku: any) => (
<span key={sku.id} className="rounded-lg bg-gray-100 px-2 py-1 text-xs text-gray-700">
{(sku.features ?? []).map((f: any) => f.featureValue).join(' ') || 'SKU'} ·{' '}
{(sku.marketStats ?? []).length > 0
? `${(sku.marketStats ?? []).length} region rows`
: 'no market data'}
</span>
))}
</div>
</div>
))}
</div>
</div>
)
}
function GlobalProductForm({
product,
onSaved,
onCancel,
}: {
product?: any
onSaved: () => void
onCancel?: () => void
}) {
const storesQuery = trpc.superadmin.globalStores.list.useQuery()
const create = trpc.superadmin.globalProducts.create.useMutation()
const update = trpc.superadmin.globalProducts.update.useMutation()
const { upload, isUploading } = useUploadToObjectStorage()
const isEdit = !!product
const [name, setName] = useState(product?.name ?? '')
const [shortDescription, setShortDescription] = useState(product?.shortDescription ?? '')
const [longDescription, setLongDescription] = useState(product?.longDescription ?? '')
const [storeId, setStoreId] = useState<number | null>(product?.storeId ?? null)
const [productType, setProductType] = useState<'item' | 'combo'>(product?.productType ?? 'item')
const [skus, setSkus] = useState<SkuDraft[]>(
isEdit && product?.skus?.length ? product.skus.map(skuToDraft) : [emptySku()]
)
const [error, setError] = useState<string | null>(null)
const stores = storesQuery.data ?? []
const pending = create.isPending || update.isPending
const updateSku = (index: number, patch: Partial<SkuDraft>) =>
setSkus((prev) => prev.map((s, i) => (i === index ? { ...s, ...patch } : s)))
const updateFeature = (skuIndex: number, fIndex: number, patch: Partial<FeatureDraft>) =>
setSkus((prev) =>
prev.map((s, i) =>
i === skuIndex ? { ...s, features: s.features.map((f, fi) => (fi === fIndex ? { ...f, ...patch } : f)) } : s
)
)
const handleAddImages = (skuIndex: number, e: any) => {
const files = Array.from((e.target.files || []) as FileList)
if (files.length === 0) return
const drafts = files.map((file: File) => ({ blob: file as Blob, mimeType: file.type || 'image/jpeg' }))
const previews = files.map((file: File) => URL.createObjectURL(file))
setSkus((prev) =>
prev.map((s, i) =>
i === skuIndex
? {
...s,
pendingFiles: [...s.pendingFiles, ...drafts],
pendingPreviews: [...s.pendingPreviews, ...previews],
}
: s
)
)
e.target.value = ''
}
const canSubmit =
name.trim() !== '' &&
!!storeId &&
skus.length > 0 &&
skus.every(
(s) =>
s.price.trim() !== '' &&
parseFloat(s.price) >= 0 &&
s.features.some((f) => f.featureValue.trim() !== '')
) &&
!pending &&
!isUploading
const submit = async () => {
setError(null)
try {
const skusPayload = []
for (const s of skus) {
let images = s.images
if (s.pendingFiles.length > 0) {
const { keys } = await upload({ images: s.pendingFiles, contextString: 'product_info' })
images = [...s.images, ...keys]
}
skusPayload.push({
id: s.id,
name: s.name || null,
price: parseFloat(s.price),
marketPrice: s.marketPrice.trim() !== '' ? parseFloat(s.marketPrice) : null,
images,
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: s.isOutOfStock,
isOffer: s.isOffer,
isComboOnly: s.isComboOnly,
isDeleted: s.isDeleted,
isSuspended: s.isSuspended,
features: s.features
.filter((f) => f.featureValue.trim() !== '')
.map((f) => ({ featureName: f.featureName.trim() || null, featureValue: f.featureValue })),
comboItems: s.comboItems,
})
}
const payload = {
name,
shortDescription: shortDescription || undefined,
longDescription: longDescription || undefined,
storeId: storeId as number,
incrementStep: 1,
productType,
skus: skusPayload,
}
if (isEdit) {
await update.mutateAsync({ id: product.id, ...payload } as any)
} else {
await create.mutateAsync(payload as any)
setName('')
setShortDescription('')
setLongDescription('')
setSkus([emptySku()])
}
onSaved()
} catch (e: any) {
setError(e.message || 'Failed to save product')
}
}
return (
<div className="rounded-xl border border-gray-200 bg-white p-4">
<div className="mb-3 flex items-center justify-between">
<MyText className="block font-semibold text-gray-900">
{isEdit ? `Edit global product: ${product.name}` : 'New global product'}
</MyText>
{isEdit && onCancel ? (
<button type="button" onClick={onCancel} className="flex items-center gap-1 text-sm text-gray-500">
<X size={14} /> Cancel
</button>
) : null}
</div>
<div className="grid gap-3 sm:grid-cols-2">
<PInput topLabel="Name" value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Fresh Chicken" />
<label className="block">
<span className="mb-1 block text-sm font-medium text-gray-500">Global store</span>
<SimpleSelect
value={storeId}
onValueChange={(value) => setStoreId(value ? Number(value) : null)}
placeholder="Select a global store…"
options={stores.map((store: any) => ({ value: store.id, label: store.name }))}
/>
</label>
<PInput topLabel="Short description" value={shortDescription} onChange={(e) => setShortDescription(e.target.value)} />
<PInput topLabel="Long description" value={longDescription} onChange={(e) => setLongDescription(e.target.value)} />
<label className="block">
<span className="mb-1 block text-sm font-medium text-gray-500">Type</span>
<SimpleSelect
value={productType}
onValueChange={(value) => setProductType(value as 'item' | 'combo')}
options={[
{ value: 'item', label: 'Item' },
{ value: 'combo', label: 'Combo' },
]}
/>
</label>
</div>
<div className="mt-5">
<div className="mb-3 flex items-center justify-between">
<MyText className="block text-sm font-semibold text-gray-700">SKUs ({skus.length})</MyText>
<MyButton onClick={() => setSkus((prev) => [...prev, emptySku()])}>
<Plus className="mr-1 inline h-4 w-4" /> Add SKU
</MyButton>
</div>
{skus.map((sku, index) => (
<div key={sku.id ?? `new-${index}`} className="mb-3 rounded-lg border border-gray-200 bg-gray-50 p-3">
<div className="grid gap-3 sm:grid-cols-2">
<PInput topLabel="SKU name (optional)" value={sku.name} onChange={(e) => updateSku(index, { name: e.target.value })} />
<PInput topLabel="Price (₹)" value={sku.price} onChange={(e) => updateSku(index, { price: e.target.value })} placeholder="e.g. 199" />
<PInput topLabel="Market price (₹)" value={sku.marketPrice} onChange={(e) => updateSku(index, { marketPrice: e.target.value })} placeholder="Optional" />
</div>
<div className="mt-3">
<MyText className="mb-1 block text-xs font-semibold uppercase tracking-wider text-gray-400">
Images
</MyText>
<div className="flex flex-wrap items-center gap-2">
{sku.images.map((key) => (
<span
key={key}
className="flex items-center gap-1 rounded-lg bg-white px-2 py-1 text-xs text-gray-700 ring-1 ring-gray-200"
>
{key.split('/').pop()}
<button
type="button"
onClick={() => updateSku(index, { images: sku.images.filter((k) => k !== key) })}
className="text-red-500"
>
×
</button>
</span>
))}
{sku.pendingPreviews.map((preview, pIndex) => (
<span key={preview} className="relative">
<img src={preview} alt="" className="h-14 w-14 rounded-lg object-cover ring-1 ring-gray-200" />
<button
type="button"
onClick={() =>
updateSku(index, {
pendingPreviews: sku.pendingPreviews.filter((_, i) => i !== pIndex),
pendingFiles: sku.pendingFiles.filter((_, i) => i !== pIndex),
})
}
className="absolute -right-1 -top-1 rounded-full bg-red-500 px-1 text-xs text-white"
>
×
</button>
</span>
))}
<label className="cursor-pointer rounded-lg border border-dashed border-gray-300 px-3 py-1 text-sm font-medium text-blue-600">
+ Add images
<input
type="file"
accept="image/*"
multiple
className="hidden"
onChange={(e) => handleAddImages(index, e)}
/>
</label>
</div>
</div>
<div className="mt-3">
<MyText className="mb-1 block text-xs font-semibold uppercase tracking-wider text-gray-400">
Features
</MyText>
{sku.features.map((feature, fIndex) => (
<div key={fIndex} className="mb-2 flex items-center gap-2">
<input
value={feature.featureName}
onChange={(e) => updateFeature(index, fIndex, { featureName: e.target.value })}
placeholder="name (e.g. quantity)"
className="w-40 rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-900"
/>
<input
value={feature.featureValue}
onChange={(e) => updateFeature(index, fIndex, { featureValue: e.target.value })}
placeholder="value (e.g. 1kg)"
className="flex-1 rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-900"
/>
{sku.features.length > 1 && (
<button
type="button"
onClick={() => updateSku(index, { features: sku.features.filter((_, i) => i !== fIndex) })}
className="text-sm text-red-600"
>
Remove
</button>
)}
</div>
))}
<button
type="button"
onClick={() => updateSku(index, { features: [...sku.features, { featureName: '', featureValue: '' }] })}
className="text-sm font-medium text-blue-600"
>
+ Add feature
</button>
</div>
<div className="mt-3 flex flex-wrap items-center gap-4">
<label className="flex items-center gap-2 text-sm text-gray-700">
<input type="checkbox" checked={sku.isOutOfStock} onChange={() => updateSku(index, { isOutOfStock: !sku.isOutOfStock })} />
Out of stock
</label>
<label className="flex items-center gap-2 text-sm text-gray-700">
<input type="checkbox" checked={sku.isOffer} onChange={() => updateSku(index, { isOffer: !sku.isOffer })} />
Offer SKU
</label>
<label className="flex items-center gap-2 text-sm text-gray-700">
<input type="checkbox" checked={sku.isComboOnly} onChange={() => updateSku(index, { isComboOnly: !sku.isComboOnly })} />
Combo only
</label>
<label className="flex items-center gap-2 text-sm text-gray-700">
<input type="checkbox" checked={sku.isDeleted} onChange={() => updateSku(index, { isDeleted: !sku.isDeleted })} />
Deleted
</label>
<label className="flex items-center gap-2 text-sm text-gray-700">
<input type="checkbox" checked={sku.isSuspended} onChange={() => updateSku(index, { isSuspended: !sku.isSuspended })} />
Suspended (global)
</label>
{skus.length > 1 && (
<button
type="button"
onClick={() => setSkus((prev) => prev.filter((_, i) => i !== index))}
className="ml-auto text-sm text-red-600"
>
Remove SKU
</button>
)}
</div>
</div>
))}
</div>
{error ? <MyText className="mb-2 block text-sm text-red-600">{error}</MyText> : null}
<div className="flex gap-2">
<MyButton onClick={submit} disabled={!canSubmit}>
{pending ? 'Saving…' : isEdit ? 'Save changes' : 'Create global product'}
</MyButton>
{isEdit && onCancel ? (
<MyButton onClick={onCancel} className="bg-gray-200 text-gray-800">
Cancel
</MyButton>
) : null}
</div>
</div>
)
}