enh
This commit is contained in:
parent
e88f82c4c9
commit
5af1afd8ba
121 changed files with 8586 additions and 1091 deletions
|
|
@ -196,7 +196,9 @@ export default function EditProduct() {
|
||||||
name: values.name,
|
name: values.name,
|
||||||
shortDescription: values.shortDescription || undefined,
|
shortDescription: values.shortDescription || undefined,
|
||||||
longDescription: values.longDescription || undefined,
|
longDescription: values.longDescription || undefined,
|
||||||
regionId: values.regionId,
|
// Null (global product) becomes undefined: the backend falls back to
|
||||||
|
// the staffer's region, which is the desired regional scoping.
|
||||||
|
regionId: values.regionId ?? undefined,
|
||||||
productType: values.productType,
|
productType: values.productType,
|
||||||
incrementStep: 1,
|
incrementStep: 1,
|
||||||
skus,
|
skus,
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,6 @@ import * as Yup from 'yup'
|
||||||
import { MyTextInput, BottomDropdown, MyText, tw, ImageUploaderNeo, ImageUploaderNeoItem, ImageUploaderNeoPayload, Checkbox, InfoDialog } from 'common-ui'
|
import { MyTextInput, BottomDropdown, MyText, tw, ImageUploaderNeo, ImageUploaderNeoItem, ImageUploaderNeoPayload, Checkbox, InfoDialog } from 'common-ui'
|
||||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||||
import { trpc } from '../trpc-client'
|
import { trpc } from '../trpc-client'
|
||||||
import { useIsSuperAdmin } from '../../hooks/useIsSuperAdmin'
|
|
||||||
import type { CreateComboItemInput, CreateSkuInput } from '@packages/shared'
|
import type { CreateComboItemInput, CreateSkuInput } from '@packages/shared'
|
||||||
import type { SkuFeatureLike } from '@packages/shared'
|
import type { SkuFeatureLike } from '@packages/shared'
|
||||||
|
|
||||||
|
|
@ -153,7 +152,7 @@ const productValidationSchema = Yup.object().shape({
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
|
|
||||||
const makeProductValidationSchema = (regions: RegionOption[]) =>
|
const makeProductValidationSchema = (regions: RegionOption[], onlyRegionId?: number | null) =>
|
||||||
productValidationSchema.concat(
|
productValidationSchema.concat(
|
||||||
Yup.object().shape({
|
Yup.object().shape({
|
||||||
storeIdsByRegion: Yup.mixed().test(
|
storeIdsByRegion: Yup.mixed().test(
|
||||||
|
|
@ -161,8 +160,13 @@ const makeProductValidationSchema = (regions: RegionOption[]) =>
|
||||||
'Store is required for every region',
|
'Store is required for every region',
|
||||||
function (value: any) {
|
function (value: any) {
|
||||||
if (this.parent?.availableInAllRegions !== true) return true
|
if (this.parent?.availableInAllRegions !== true) return true
|
||||||
|
// Regional staff editing a global product: only their own region
|
||||||
|
// must have a store. (Superadmin-role editors cover all regions.)
|
||||||
|
const applicable = onlyRegionId != null
|
||||||
|
? regions.filter((r) => r.id === onlyRegionId)
|
||||||
|
: regions
|
||||||
const map: Record<number, number> = value ?? {}
|
const map: Record<number, number> = value ?? {}
|
||||||
for (const region of regions) {
|
for (const region of applicable) {
|
||||||
const storeId = map[region.id]
|
const storeId = map[region.id]
|
||||||
if (storeId == null || Number(storeId) < 1) {
|
if (storeId == null || Number(storeId) < 1) {
|
||||||
return this.createError({
|
return this.createError({
|
||||||
|
|
@ -189,7 +193,7 @@ const collectErrorMessages = (errors: unknown, depth = 0): string[] => {
|
||||||
return []
|
return []
|
||||||
}
|
}
|
||||||
|
|
||||||
type RegionStoreOption = { id: number; name: string; regionId?: number }
|
type RegionStoreOption = { id: number; name: string; regionId?: number | null; availableInAllRegions?: boolean }
|
||||||
type RegionOption = { id: number; name: string }
|
type RegionOption = { id: number; name: string }
|
||||||
|
|
||||||
// On edit, an all-regions product has no per-region store payload from the API,
|
// On edit, an all-regions product has no per-region store payload from the API,
|
||||||
|
|
@ -240,10 +244,21 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
clearImages: () => setVariantImages(initialValues.variants.map(() => [])),
|
clearImages: () => setVariantImages(initialValues.variants.map(() => [])),
|
||||||
}), [initialValues.variants])
|
}), [initialValues.variants])
|
||||||
|
|
||||||
const isSuperAdmin = useIsSuperAdmin()
|
// All-region products are managed from superadmin-ui only: the flag is
|
||||||
// Non-superadmins may not flip all-regions availability (backend 403s either
|
// hidden here (so global products can never be created from this app).
|
||||||
// direction); lock the checkbox on all-region products.
|
// Regional staff may still edit a global product, but every write applies
|
||||||
const allRegionsLocked = !isSuperAdmin && !!initialValues.availableInAllRegions
|
// to their own region only (backend scopes via the staffer's region).
|
||||||
|
const isAllRegionsProduct = !!initialValues.availableInAllRegions
|
||||||
|
|
||||||
|
// Staffer identity for scoping global-product edits. Superadmin-role staff
|
||||||
|
// keep the full per-region UI; everyone else is collapsed to their region.
|
||||||
|
const { data: selfData } = trpc.admin.staffUser.getSelf.useQuery(undefined, {
|
||||||
|
staleTime: Infinity,
|
||||||
|
retry: false,
|
||||||
|
})
|
||||||
|
const staffIsSuperAdmin = selfData?.staff?.roleName === 'super_admin'
|
||||||
|
const staffRegionId: number | null = selfData?.staff?.regionId ?? null
|
||||||
|
const editingGlobalAsRegional = isAllRegionsProduct && !staffIsSuperAdmin
|
||||||
|
|
||||||
const { data: storesData } = trpc.admin.store.getStores.useQuery()
|
const { data: storesData } = trpc.admin.store.getStores.useQuery()
|
||||||
const allStores: RegionStoreOption[] = useMemo(
|
const allStores: RegionStoreOption[] = useMemo(
|
||||||
|
|
@ -262,7 +277,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
)
|
)
|
||||||
const storesForRegion = (regionId: number) =>
|
const storesForRegion = (regionId: number) =>
|
||||||
allRegionsStores
|
allRegionsStores
|
||||||
.filter((store) => store.regionId === regionId)
|
.filter((store) => store.regionId === regionId || store.availableInAllRegions)
|
||||||
.map((store) => ({ label: store.name, value: store.id }))
|
.map((store) => ({ label: store.name, value: store.id }))
|
||||||
|
|
||||||
const { data: regionsData } = trpc.admin.region.getRegions.useQuery()
|
const { data: regionsData } = trpc.admin.region.getRegions.useQuery()
|
||||||
|
|
@ -270,7 +285,21 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
() => (regionsData?.regions || []).map((region) => ({ id: region.id, name: region.name })),
|
() => (regionsData?.regions || []).map((region) => ({ id: region.id, name: region.name })),
|
||||||
[regionsData]
|
[regionsData]
|
||||||
)
|
)
|
||||||
const validationSchema = useMemo(() => makeProductValidationSchema(regions), [regions])
|
// Regions whose stores are editable in this form: just the staffer's own
|
||||||
|
// when they are regionally editing a global product, else everything.
|
||||||
|
const editableRegions = useMemo(
|
||||||
|
() => (editingGlobalAsRegional && staffRegionId != null
|
||||||
|
? regions.filter((r) => r.id === staffRegionId)
|
||||||
|
: regions),
|
||||||
|
[editingGlobalAsRegional, staffRegionId, regions]
|
||||||
|
)
|
||||||
|
const staffRegionName = regions.find((r) => r.id === staffRegionId)?.name ?? 'your region'
|
||||||
|
const validationSchema = useMemo(
|
||||||
|
// -1 matches no region: while the staffer's region is still loading the
|
||||||
|
// check passes vacuously (the backend enforces region scope regardless).
|
||||||
|
() => makeProductValidationSchema(regions, editingGlobalAsRegional ? (staffRegionId ?? -1) : null),
|
||||||
|
[regions, editingGlobalAsRegional, staffRegionId]
|
||||||
|
)
|
||||||
|
|
||||||
const { data: skusData } = trpc.common.product.getAllSkusSummary.useQuery()
|
const { data: skusData } = trpc.common.product.getAllSkusSummary.useQuery()
|
||||||
const skuOptions = (skusData?.skus || []).map((sku) => ({
|
const skuOptions = (skusData?.skus || []).map((sku) => ({
|
||||||
|
|
@ -344,26 +373,19 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
enableReinitialize
|
enableReinitialize
|
||||||
>
|
>
|
||||||
{({ handleChange, handleSubmit, values, setFieldValue, validateForm }) => {
|
{({ handleChange, handleSubmit, values, setFieldValue, validateForm }) => {
|
||||||
const currentStoreName = storeOptions.find((option) => option.value === values.storeId)?.label
|
// Name-match prefill source for the own-region store dropdown when a
|
||||||
const handleToggleAllRegions = () => {
|
// regional staffer edits a global product (the API sends no per-region
|
||||||
if (allRegionsLocked) return
|
// store payload, so match by the product's current store name).
|
||||||
const next = !values.availableInAllRegions
|
const editStoreName = allStores.find((s) => s.id === initialValues.storeId)?.name
|
||||||
setFieldValue('availableInAllRegions', next)
|
|
||||||
if (next) {
|
|
||||||
const prefill: Record<number, number> = {}
|
|
||||||
if (currentStoreName) {
|
|
||||||
for (const region of regions) {
|
|
||||||
const match = allStores.find(
|
|
||||||
(store) => store.regionId === region.id && store.name === currentStoreName
|
|
||||||
)
|
|
||||||
if (match) prefill[region.id] = match.id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setFieldValue('storeIdsByRegion', prefill)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return (
|
return (
|
||||||
<ScrollView style={tw`flex-1`} contentContainerStyle={tw`px-4 pt-4 pb-10`} keyboardShouldPersistTaps="handled">
|
<ScrollView style={tw`flex-1`} contentContainerStyle={tw`px-4 pt-4 pb-10`} keyboardShouldPersistTaps="handled">
|
||||||
|
{editingGlobalAsRegional && (
|
||||||
|
<View style={tw`mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3`}>
|
||||||
|
<MyText style={tw`text-sm font-medium text-amber-800`}>
|
||||||
|
Global product — changes you save here apply to {staffRegionName} only.
|
||||||
|
</MyText>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
<MyTextInput
|
<MyTextInput
|
||||||
testID="product-name-input"
|
testID="product-name-input"
|
||||||
topLabel="Product Name"
|
topLabel="Product Name"
|
||||||
|
|
@ -392,16 +414,6 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
onChangeText={handleChange('longDescription')}
|
onChangeText={handleChange('longDescription')}
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
/>
|
/>
|
||||||
<View style={tw`flex-row items-center mb-4`}>
|
|
||||||
<Checkbox
|
|
||||||
testID="product-all-regions-checkbox"
|
|
||||||
checked={!!values.availableInAllRegions}
|
|
||||||
onPress={handleToggleAllRegions}
|
|
||||||
disabled={allRegionsLocked}
|
|
||||||
style={tw`mr-3`}
|
|
||||||
/>
|
|
||||||
<MyText style={tw`text-gray-700 font-medium`}>Available in all regions</MyText>
|
|
||||||
</View>
|
|
||||||
|
|
||||||
{!values.availableInAllRegions ? (
|
{!values.availableInAllRegions ? (
|
||||||
<BottomDropdown
|
<BottomDropdown
|
||||||
|
|
@ -415,7 +427,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
regions.map((region) => {
|
editableRegions.map((region) => {
|
||||||
const regionStores = storesForRegion(region.id)
|
const regionStores = storesForRegion(region.id)
|
||||||
return (
|
return (
|
||||||
<View key={region.id}>
|
<View key={region.id}>
|
||||||
|
|
@ -441,7 +453,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
})
|
})
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<RegionStorePrefill stores={allRegionsStores} regions={regions} currentStoreName={currentStoreName} />
|
<RegionStorePrefill stores={allRegionsStores} regions={editableRegions} currentStoreName={editStoreName} />
|
||||||
|
|
||||||
<BottomDropdown
|
<BottomDropdown
|
||||||
testID="product-type-dropdown"
|
testID="product-type-dropdown"
|
||||||
|
|
|
||||||
|
|
@ -187,6 +187,8 @@ export default function BannerForm({
|
||||||
onChange={handleChange('redirectUrl')}
|
onChange={handleChange('redirectUrl')}
|
||||||
onBlur={handleBlur('redirectUrl')}
|
onBlur={handleBlur('redirectUrl')}
|
||||||
type="url"
|
type="url"
|
||||||
|
autoCorrect="off"
|
||||||
|
autoCapitalize="none"
|
||||||
style={{ marginBottom: errors.redirectUrl && touched.redirectUrl ? 8 : 16 }}
|
style={{ marginBottom: errors.redirectUrl && touched.redirectUrl ? 8 : 16 }}
|
||||||
/>
|
/>
|
||||||
{errors.redirectUrl && touched.redirectUrl && (
|
{errors.redirectUrl && touched.redirectUrl && (
|
||||||
|
|
|
||||||
|
|
@ -97,6 +97,7 @@ export function MultiSelect({
|
||||||
}}
|
}}
|
||||||
onSearch={onSearch}
|
onSearch={onSearch}
|
||||||
className="mb-3"
|
className="mb-3"
|
||||||
|
testID={testID ? `${testID}-search` : undefined}
|
||||||
/>
|
/>
|
||||||
<div className="overflow-y-auto" style={{ maxHeight: 320 }}>
|
<div className="overflow-y-auto" style={{ maxHeight: 320 }}>
|
||||||
{filtered.map((option) => {
|
{filtered.map((option) => {
|
||||||
|
|
@ -104,7 +105,7 @@ export function MultiSelect({
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={String(option.value)}
|
key={String(option.value)}
|
||||||
data-testid="multiselect-option"
|
data-testid={testID ? `${testID}-option-${option.value}` : undefined}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!option.disabled) toggle(option.value)
|
if (!option.disabled) toggle(option.value)
|
||||||
}}
|
}}
|
||||||
|
|
@ -138,6 +139,7 @@ export function MultiSelect({
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setOpen(false)}
|
onClick={() => setOpen(false)}
|
||||||
|
data-testid={testID ? `${testID}-done` : undefined}
|
||||||
className="flex-1 p-3 rounded-lg bg-blue-500 text-white text-center font-semibold text-sm"
|
className="flex-1 p-3 rounded-lg bg-blue-500 text-white text-center font-semibold text-sm"
|
||||||
>
|
>
|
||||||
Done
|
Done
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import React from 'react'
|
import React from 'react'
|
||||||
import { p as P, BottomDialog, Checkbox } from 'web-components'
|
import { p as P, BottomDialog, Checkbox } from 'web-components'
|
||||||
import { trpc } from '@/lib/trpc-client'
|
import { trpc } from '@/lib/trpc-client'
|
||||||
import { ChevronRight, Eye, Pencil, XCircle, MapPin, Map, MessageCircle, Phone } from 'lucide-react'
|
import { ChevronRight, Eye, Pencil, XCircle, MapPin, Map, MessageCircle, Phone, PartyPopper } from 'lucide-react'
|
||||||
|
|
||||||
interface OrderOptionsMenuProps {
|
interface OrderOptionsMenuProps {
|
||||||
open: boolean
|
open: boolean
|
||||||
|
|
@ -19,6 +19,7 @@ interface OrderOptionsMenuProps {
|
||||||
latitude?: number | null
|
latitude?: number | null
|
||||||
longitude?: number | null
|
longitude?: number | null
|
||||||
status?: string
|
status?: string
|
||||||
|
isFirstOrder?: boolean
|
||||||
}
|
}
|
||||||
onViewDetails: () => void
|
onViewDetails: () => void
|
||||||
onTogglePackaged: () => void
|
onTogglePackaged: () => void
|
||||||
|
|
@ -89,6 +90,20 @@ export function OrderOptionsMenu({
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { data: constants } = trpc.admin.const.getConstants.useQuery()
|
||||||
|
const welcomeMessage = constants?.find((c) => c.key === 'welcomeMessage')?.value
|
||||||
|
|
||||||
|
const handleWelcomeWhatsApp = () => {
|
||||||
|
const phone = extractPhone(order.address)
|
||||||
|
if (!phone) {
|
||||||
|
window.alert('No phone number found')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const message = welcomeMessage ? String(welcomeMessage) : ''
|
||||||
|
const text = message ? `&text=${encodeURIComponent(message)}` : ''
|
||||||
|
window.open(`https://wa.me/91${phone}${text}`, '_blank')
|
||||||
|
}
|
||||||
|
|
||||||
const handleDial = () => {
|
const handleDial = () => {
|
||||||
const phone = extractPhone(order.address)
|
const phone = extractPhone(order.address)
|
||||||
if (phone) {
|
if (phone) {
|
||||||
|
|
@ -319,6 +334,31 @@ export function OrderOptionsMenu({
|
||||||
</div>
|
</div>
|
||||||
<ChevronRight className="h-6 w-6 text-gray-400 ml-auto" />
|
<ChevronRight className="h-6 w-6 text-gray-400 ml-auto" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
{order.isFirstOrder && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="send-welcome-msg"
|
||||||
|
onClick={() => {
|
||||||
|
handleWelcomeWhatsApp()
|
||||||
|
onClose()
|
||||||
|
}}
|
||||||
|
className="flex flex-row items-center p-4 bg-emerald-50 border border-emerald-200 rounded-xl mb-3 shadow-sm w-full text-left"
|
||||||
|
>
|
||||||
|
<div className="w-10 h-10 rounded-full bg-emerald-100 items-center justify-center mr-4 flex shrink-0">
|
||||||
|
<PartyPopper className="h-5 w-5 text-emerald-600" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<P className="font-semibold text-emerald-800 text-base block">
|
||||||
|
Send Welcome Msg
|
||||||
|
</P>
|
||||||
|
<P className="text-emerald-600 text-xs block">
|
||||||
|
First order — welcome the customer on WhatsApp
|
||||||
|
</P>
|
||||||
|
</div>
|
||||||
|
<ChevronRight className="h-6 w-6 text-gray-400 ml-auto" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,6 @@ import type { ImageUploaderNeoItem, ImageUploaderNeoPayload } from 'web-componen
|
||||||
import SearchableSelect from './SearchableSelect'
|
import SearchableSelect from './SearchableSelect'
|
||||||
import { Plus, Trash2, X, RotateCcw, Info } from 'lucide-react'
|
import { Plus, Trash2, X, RotateCcw, Info } from 'lucide-react'
|
||||||
import { trpc } from '@/lib/trpc-client'
|
import { trpc } from '@/lib/trpc-client'
|
||||||
import { useIsSuperAdmin } from '../hooks/useIsSuperAdmin'
|
|
||||||
import type { CreateComboItemInput, CreateSkuInput } from '@packages/shared'
|
import type { CreateComboItemInput, CreateSkuInput } from '@packages/shared'
|
||||||
import type { SkuFeatureLike } from '@packages/shared'
|
import type { SkuFeatureLike } from '@packages/shared'
|
||||||
|
|
||||||
|
|
@ -258,10 +257,9 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
clearImages: () => setVariantImages(initialValues.variants.map(() => [])),
|
clearImages: () => setVariantImages(initialValues.variants.map(() => [])),
|
||||||
}), [initialValues.variants])
|
}), [initialValues.variants])
|
||||||
|
|
||||||
const isSuperAdmin = useIsSuperAdmin()
|
// All-region products are managed from superadmin-ui only: the flag is
|
||||||
// Non-superadmins may not flip all-regions availability (backend 403s either
|
// hidden here, and edits to such products are read-only in this app.
|
||||||
// direction); lock the checkbox on all-region products.
|
const isAllRegionsProduct = !!initialValues.availableInAllRegions
|
||||||
const allRegionsLocked = !isSuperAdmin && !!initialValues.availableInAllRegions
|
|
||||||
|
|
||||||
const { data: storesData } = trpc.admin.store.getStores.useQuery()
|
const { data: storesData } = trpc.admin.store.getStores.useQuery()
|
||||||
const allStores: RegionStoreOption[] = useMemo(
|
const allStores: RegionStoreOption[] = useMemo(
|
||||||
|
|
@ -362,32 +360,22 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
enableReinitialize
|
enableReinitialize
|
||||||
>
|
>
|
||||||
{({ handleChange, handleSubmit, values, setFieldValue, validateForm }) => {
|
{({ handleChange, handleSubmit, values, setFieldValue, validateForm }) => {
|
||||||
const currentStoreName = storeOptions.find((option) => option.value === values.storeId)?.label
|
|
||||||
const handleToggleAllRegions = () => {
|
|
||||||
if (allRegionsLocked) return
|
|
||||||
const next = !values.availableInAllRegions
|
|
||||||
setFieldValue('availableInAllRegions', next)
|
|
||||||
if (next) {
|
|
||||||
const prefill: Record<number, number> = {}
|
|
||||||
if (currentStoreName) {
|
|
||||||
for (const region of regions) {
|
|
||||||
const match = allStores.find(
|
|
||||||
(store) => store.regionId === region.id && store.name === currentStoreName
|
|
||||||
)
|
|
||||||
if (match) prefill[region.id] = match.id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setFieldValue('storeIdsByRegion', prefill)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return (
|
return (
|
||||||
<div className="flex-1 overflow-auto pb-10">
|
<div className="flex-1 overflow-auto pb-10">
|
||||||
|
{isAllRegionsProduct && (
|
||||||
|
<div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3">
|
||||||
|
<p className="text-sm font-medium text-amber-800">
|
||||||
|
This product serves all regions and is managed from superadmin. Changes here are disabled.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<PInput
|
<PInput
|
||||||
topLabel="Product Name"
|
topLabel="Product Name"
|
||||||
placeholder="Enter product name"
|
placeholder="Enter product name"
|
||||||
value={values.name}
|
value={values.name}
|
||||||
onChange={handleChange('name')}
|
onChange={handleChange('name')}
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
|
data-testid="product-name-input"
|
||||||
/>
|
/>
|
||||||
<PInput
|
<PInput
|
||||||
topLabel="Short Description"
|
topLabel="Short Description"
|
||||||
|
|
@ -397,6 +385,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
value={values.shortDescription}
|
value={values.shortDescription}
|
||||||
onChange={handleChange('shortDescription')}
|
onChange={handleChange('shortDescription')}
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
|
data-testid="product-short-description-input"
|
||||||
/>
|
/>
|
||||||
<PInput
|
<PInput
|
||||||
topLabel="Long Description"
|
topLabel="Long Description"
|
||||||
|
|
@ -406,18 +395,11 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
value={values.longDescription}
|
value={values.longDescription}
|
||||||
onChange={handleChange('longDescription')}
|
onChange={handleChange('longDescription')}
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
|
data-testid="product-long-description-input"
|
||||||
/>
|
/>
|
||||||
<div className="flex flex-row items-center mb-4" data-testid="product-all-regions-row">
|
|
||||||
<Checkbox
|
|
||||||
checked={!!values.availableInAllRegions}
|
|
||||||
onPress={handleToggleAllRegions}
|
|
||||||
disabled={allRegionsLocked}
|
|
||||||
/>
|
|
||||||
<P className="text-gray-700 font-medium ml-3">Available in all regions</P>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{!values.availableInAllRegions ? (
|
{!values.availableInAllRegions ? (
|
||||||
<div className="mb-4" data-testid="product-store-select">
|
<div className="mb-4">
|
||||||
<P className="mb-1 text-sm text-gray-500 font-medium">Store</P>
|
<P className="mb-1 text-sm text-gray-500 font-medium">Store</P>
|
||||||
<Dropdown
|
<Dropdown
|
||||||
label="Select store"
|
label="Select store"
|
||||||
|
|
@ -425,13 +407,14 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
options={storeOptions}
|
options={storeOptions}
|
||||||
onValueChange={(value) => setFieldValue('storeId', Number(value))}
|
onValueChange={(value) => setFieldValue('storeId', Number(value))}
|
||||||
className="w-full"
|
className="w-full"
|
||||||
|
testID="product-store-dropdown"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
regions.map((region) => {
|
regions.map((region) => {
|
||||||
const regionStores = storesForRegion(region.id)
|
const regionStores = storesForRegion(region.id)
|
||||||
return (
|
return (
|
||||||
<div key={region.id} className="mb-4" data-testid={`product-region-${region.id}-store-select`}>
|
<div key={region.id} className="mb-4">
|
||||||
<P className="mb-1 text-sm text-gray-500 font-medium">Store — {region.name}</P>
|
<P className="mb-1 text-sm text-gray-500 font-medium">Store — {region.name}</P>
|
||||||
{regionStores.length === 0 && (
|
{regionStores.length === 0 && (
|
||||||
<p className="mb-1 text-xs text-red-500">
|
<p className="mb-1 text-xs text-red-500">
|
||||||
|
|
@ -446,15 +429,16 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
setFieldValue(`storeIdsByRegion.${region.id}`, Number(value))
|
setFieldValue(`storeIdsByRegion.${region.id}`, Number(value))
|
||||||
}
|
}
|
||||||
className="w-full"
|
className="w-full"
|
||||||
|
testID={`product-region-${region.id}-store-dropdown`}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<RegionStorePrefill stores={allRegionsStores} regions={regions} currentStoreName={currentStoreName} />
|
<RegionStorePrefill stores={allRegionsStores} regions={regions} currentStoreName={undefined} />
|
||||||
|
|
||||||
<div className="mb-4" data-testid="product-type-select">
|
<div className="mb-4">
|
||||||
<P className="mb-1 text-sm text-gray-500 font-medium">Product Type</P>
|
<P className="mb-1 text-sm text-gray-500 font-medium">Product Type</P>
|
||||||
<Dropdown
|
<Dropdown
|
||||||
label="Select product type"
|
label="Select product type"
|
||||||
|
|
@ -465,6 +449,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
]}
|
]}
|
||||||
onValueChange={(value) => setFieldValue('productType', value as 'item' | 'combo')}
|
onValueChange={(value) => setFieldValue('productType', value as 'item' | 'combo')}
|
||||||
className="w-full"
|
className="w-full"
|
||||||
|
testID="product-type-dropdown"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
@ -475,6 +460,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
<P className="text-lg font-bold text-gray-800">Variants</P>
|
<P className="text-lg font-bold text-gray-800">Variants</P>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
data-testid="add-variant-button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
push(defaultVariant())
|
push(defaultVariant())
|
||||||
setVariantImages((prev) => [...prev, []])
|
setVariantImages((prev) => [...prev, []])
|
||||||
|
|
@ -503,6 +489,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
{(values.variants.length > 1 || isExistingSku) && (
|
{(values.variants.length > 1 || isExistingSku) && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
data-testid={`variant-${vIndex}-remove`}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (isExistingSku) {
|
if (isExistingSku) {
|
||||||
// Mark existing SKU as deleted (sent to backend on save).
|
// Mark existing SKU as deleted (sent to backend on save).
|
||||||
|
|
@ -529,6 +516,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
value={variant.name ?? ''}
|
value={variant.name ?? ''}
|
||||||
onChange={handleChange(`variants.${vIndex}.name`)}
|
onChange={handleChange(`variants.${vIndex}.name`)}
|
||||||
style={{ marginBottom: 12 }}
|
style={{ marginBottom: 12 }}
|
||||||
|
data-testid={`variant-${vIndex}-sku-name`}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<FieldArray name={`variants.${vIndex}.features`}>
|
<FieldArray name={`variants.${vIndex}.features`}>
|
||||||
|
|
@ -557,6 +545,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
<PInput
|
<PInput
|
||||||
placeholder="Name"
|
placeholder="Name"
|
||||||
value={attr.featureName ?? ''}
|
value={attr.featureName ?? ''}
|
||||||
|
data-testid={`variant-${vIndex}-attr-${aIndex}-name`}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
setFieldValue(
|
setFieldValue(
|
||||||
`variants.${vIndex}.features.${aIndex}.featureName`,
|
`variants.${vIndex}.features.${aIndex}.featureName`,
|
||||||
|
|
@ -571,6 +560,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
<PInput
|
<PInput
|
||||||
placeholder={isQuantityFeature(attr) ? 'e.g. 0.5 kg' : 'Value'}
|
placeholder={isQuantityFeature(attr) ? 'e.g. 0.5 kg' : 'Value'}
|
||||||
value={attr.featureValue}
|
value={attr.featureValue}
|
||||||
|
data-testid={`variant-${vIndex}-attr-${aIndex}-value`}
|
||||||
onChange={handleChange(`variants.${vIndex}.features.${aIndex}.featureValue`)}
|
onChange={handleChange(`variants.${vIndex}.features.${aIndex}.featureValue`)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -607,6 +597,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
placeholder="MRP"
|
placeholder="MRP"
|
||||||
type="number"
|
type="number"
|
||||||
inputMode="numeric"
|
inputMode="numeric"
|
||||||
|
data-testid={`variant-${vIndex}-market-price`}
|
||||||
value={variant.marketPrice?.toString() ?? ''}
|
value={variant.marketPrice?.toString() ?? ''}
|
||||||
onChange={handleChange(`variants.${vIndex}.marketPrice`)}
|
onChange={handleChange(`variants.${vIndex}.marketPrice`)}
|
||||||
/>
|
/>
|
||||||
|
|
@ -617,6 +608,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
placeholder="Selling price"
|
placeholder="Selling price"
|
||||||
type="number"
|
type="number"
|
||||||
inputMode="numeric"
|
inputMode="numeric"
|
||||||
|
data-testid={`variant-${vIndex}-price`}
|
||||||
value={variant.price?.toString() ?? ''}
|
value={variant.price?.toString() ?? ''}
|
||||||
onChange={handleChange(`variants.${vIndex}.price`)}
|
onChange={handleChange(`variants.${vIndex}.price`)}
|
||||||
/>
|
/>
|
||||||
|
|
@ -626,6 +618,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
<div className="flex flex-row items-center mb-3">
|
<div className="flex flex-row items-center mb-3">
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={variant.isFlashAvailable}
|
checked={variant.isFlashAvailable}
|
||||||
|
testID={`variant-${vIndex}-flash`}
|
||||||
onPress={() => {
|
onPress={() => {
|
||||||
setFieldValue(`variants.${vIndex}.isFlashAvailable`, !variant.isFlashAvailable)
|
setFieldValue(`variants.${vIndex}.isFlashAvailable`, !variant.isFlashAvailable)
|
||||||
if (variant.isFlashAvailable) setFieldValue(`variants.${vIndex}.flashPrice`, null)
|
if (variant.isFlashAvailable) setFieldValue(`variants.${vIndex}.flashPrice`, null)
|
||||||
|
|
@ -637,6 +630,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
<div className="flex flex-row items-center mb-3">
|
<div className="flex flex-row items-center mb-3">
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={variant.isOffer}
|
checked={variant.isOffer}
|
||||||
|
testID={`variant-${vIndex}-offer`}
|
||||||
onPress={() => setFieldValue(`variants.${vIndex}.isOffer`, !variant.isOffer)}
|
onPress={() => setFieldValue(`variants.${vIndex}.isOffer`, !variant.isOffer)}
|
||||||
/>
|
/>
|
||||||
<P className="text-gray-700 font-medium ml-3">Offer SKU</P>
|
<P className="text-gray-700 font-medium ml-3">Offer SKU</P>
|
||||||
|
|
@ -646,6 +640,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
<div className="flex flex-row items-center mb-3">
|
<div className="flex flex-row items-center mb-3">
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={variant.isComboOnly}
|
checked={variant.isComboOnly}
|
||||||
|
testID={`variant-${vIndex}-combo-only`}
|
||||||
onPress={() => setFieldValue(`variants.${vIndex}.isComboOnly`, !variant.isComboOnly)}
|
onPress={() => setFieldValue(`variants.${vIndex}.isComboOnly`, !variant.isComboOnly)}
|
||||||
/>
|
/>
|
||||||
<P className="text-gray-700 font-medium ml-3">Combo Only SKU</P>
|
<P className="text-gray-700 font-medium ml-3">Combo Only SKU</P>
|
||||||
|
|
@ -653,9 +648,10 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{mode === 'edit' && (
|
{mode === 'edit' && (
|
||||||
<div className="flex flex-row items-center mb-3" data-testid={`variant-suspend-row-${vIndex}`}>
|
<div className="flex flex-row items-center mb-3">
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={variant.isSuspended}
|
checked={variant.isSuspended}
|
||||||
|
testID={`variant-${vIndex}-suspend`}
|
||||||
onPress={() => setFieldValue(`variants.${vIndex}.isSuspended`, !variant.isSuspended)}
|
onPress={() => setFieldValue(`variants.${vIndex}.isSuspended`, !variant.isSuspended)}
|
||||||
/>
|
/>
|
||||||
<P className="text-gray-700 font-medium ml-3">Suspend SKU</P>
|
<P className="text-gray-700 font-medium ml-3">Suspend SKU</P>
|
||||||
|
|
@ -668,6 +664,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
placeholder="Enter flash price"
|
placeholder="Enter flash price"
|
||||||
type="number"
|
type="number"
|
||||||
inputMode="numeric"
|
inputMode="numeric"
|
||||||
|
data-testid={`variant-${vIndex}-flash-price`}
|
||||||
value={variant.flashPrice?.toString() ?? ''}
|
value={variant.flashPrice?.toString() ?? ''}
|
||||||
onChange={handleChange(`variants.${vIndex}.flashPrice`)}
|
onChange={handleChange(`variants.${vIndex}.flashPrice`)}
|
||||||
style={{ marginBottom: 12 }}
|
style={{ marginBottom: 12 }}
|
||||||
|
|
@ -676,6 +673,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
|
|
||||||
<ImageUploaderNeo
|
<ImageUploaderNeo
|
||||||
images={variantImages[vIndex] || []}
|
images={variantImages[vIndex] || []}
|
||||||
|
testID={`variant-${vIndex}-image-add`}
|
||||||
onImageAdd={(payloads) =>
|
onImageAdd={(payloads) =>
|
||||||
setVariantImages((prev) => {
|
setVariantImages((prev) => {
|
||||||
const next = [...prev]
|
const next = [...prev]
|
||||||
|
|
@ -699,6 +697,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
<P className="font-medium text-gray-600">Included Items</P>
|
<P className="font-medium text-gray-600">Included Items</P>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
data-testid={`variant-${vIndex}-combo-add`}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
const items = variant.comboItems || []
|
const items = variant.comboItems || []
|
||||||
items.push({ skuId: 0 })
|
items.push({ skuId: 0 })
|
||||||
|
|
@ -716,6 +715,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
<SearchableSelect
|
<SearchableSelect
|
||||||
label="SKU"
|
label="SKU"
|
||||||
value={ci.skuId}
|
value={ci.skuId}
|
||||||
|
testID={`variant-${vIndex}-combo-sku-${cIndex}`}
|
||||||
options={skuOptions.map((opt: { label: string; value: number }) => ({
|
options={skuOptions.map((opt: { label: string; value: number }) => ({
|
||||||
...opt,
|
...opt,
|
||||||
// Disable SKUs already picked in another row of this combo.
|
// Disable SKUs already picked in another row of this combo.
|
||||||
|
|
@ -757,6 +757,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
data-testid="add-variant-button-footer"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
push(defaultVariant())
|
push(defaultVariant())
|
||||||
setVariantImages((prev) => [...prev, []])
|
setVariantImages((prev) => [...prev, []])
|
||||||
|
|
@ -772,8 +773,12 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
data-testid="product-submit-button"
|
data-testid="create-product-button"
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
|
if (isAllRegionsProduct) {
|
||||||
|
window.alert('This product serves all regions and can only be edited from superadmin.')
|
||||||
|
return
|
||||||
|
}
|
||||||
const validationErrors = await validateForm()
|
const validationErrors = await validateForm()
|
||||||
if (Object.keys(validationErrors).length > 0) {
|
if (Object.keys(validationErrors).length > 0) {
|
||||||
const variantsMessages = collectErrorMessages(validationErrors.variants)
|
const variantsMessages = collectErrorMessages(validationErrors.variants)
|
||||||
|
|
@ -784,7 +789,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
}
|
}
|
||||||
handleSubmit()
|
handleSubmit()
|
||||||
}}
|
}}
|
||||||
disabled={isLoading}
|
disabled={isLoading || isAllRegionsProduct}
|
||||||
className={`px-4 py-3 rounded-lg shadow-lg items-center mt-4 text-white text-lg font-bold w-full disabled:opacity-70 ${isLoading ? 'bg-gray-400' : 'bg-blue-500'}`}
|
className={`px-4 py-3 rounded-lg shadow-lg items-center mt-4 text-white text-lg font-bold w-full disabled:opacity-70 ${isLoading ? 'bg-gray-400' : 'bg-blue-500'}`}
|
||||||
>
|
>
|
||||||
{(() => {
|
{(() => {
|
||||||
|
|
|
||||||
|
|
@ -82,6 +82,7 @@ export function SearchableSelect({
|
||||||
}}
|
}}
|
||||||
onSearch={onSearch}
|
onSearch={onSearch}
|
||||||
className="mb-3"
|
className="mb-3"
|
||||||
|
testID={testID ? `${testID}-search` : undefined}
|
||||||
/>
|
/>
|
||||||
<div className="overflow-y-auto" style={{ maxHeight: 320 }}>
|
<div className="overflow-y-auto" style={{ maxHeight: 320 }}>
|
||||||
{filtered.map((option) => {
|
{filtered.map((option) => {
|
||||||
|
|
@ -92,6 +93,7 @@ export function SearchableSelect({
|
||||||
type="button"
|
type="button"
|
||||||
disabled={option.disabled}
|
disabled={option.disabled}
|
||||||
onClick={() => handleSelect(option.value)}
|
onClick={() => handleSelect(option.value)}
|
||||||
|
data-testid={testID ? `${testID}-option-${option.value}` : undefined}
|
||||||
className={`flex flex-row items-center w-full p-3 border-b border-gray-100 text-left ${option.disabled ? 'opacity-50' : 'cursor-pointer hover:bg-gray-50'} ${selected ? 'bg-blue-50' : ''}`}
|
className={`flex flex-row items-center w-full p-3 border-b border-gray-100 text-left ${option.disabled ? 'opacity-50' : 'cursor-pointer hover:bg-gray-50'} ${selected ? 'bg-blue-50' : ''}`}
|
||||||
>
|
>
|
||||||
<span className={`text-sm flex-1 ${selected ? 'font-semibold text-blue-700' : 'text-gray-800'}`}>
|
<span className={`text-sm flex-1 ${selected ? 'font-semibold text-blue-700' : 'text-gray-800'}`}>
|
||||||
|
|
|
||||||
|
|
@ -180,6 +180,7 @@ export default function SlotForm({
|
||||||
|
|
||||||
<div className="mb-4">
|
<div className="mb-4">
|
||||||
<ProductsSelector
|
<ProductsSelector
|
||||||
|
testID="snippet-products-selector"
|
||||||
value={snippet.skuIds || []}
|
value={snippet.skuIds || []}
|
||||||
onChange={(newSkuIds) => setFieldValue(`vendorSnippetList.${index}.skuIds`, newSkuIds)}
|
onChange={(newSkuIds) => setFieldValue(`vendorSnippetList.${index}.skuIds`, newSkuIds)}
|
||||||
groups={mappedGroups.filter(group =>
|
groups={mappedGroups.filter(group =>
|
||||||
|
|
|
||||||
|
|
@ -133,6 +133,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
|
||||||
onChange={handleChange('name')}
|
onChange={handleChange('name')}
|
||||||
error={!!(touched.name && errors.name)}
|
error={!!(touched.name && errors.name)}
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
|
data-testid="store-name-input"
|
||||||
/>
|
/>
|
||||||
<PInput
|
<PInput
|
||||||
topLabel="Description"
|
topLabel="Description"
|
||||||
|
|
@ -143,6 +144,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
|
||||||
onChange={handleChange('description')}
|
onChange={handleChange('description')}
|
||||||
error={!!(touched.description && errors.description)}
|
error={!!(touched.description && errors.description)}
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
|
data-testid="store-description-input"
|
||||||
/>
|
/>
|
||||||
<div className="mb-4">
|
<div className="mb-4">
|
||||||
<P className="mb-1 text-sm text-gray-500 font-medium">Owner</P>
|
<P className="mb-1 text-sm text-gray-500 font-medium">Owner</P>
|
||||||
|
|
@ -152,6 +154,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
|
||||||
options={staffOptions}
|
options={staffOptions}
|
||||||
onValueChange={(value) => setFieldValue('owner', Number(value))}
|
onValueChange={(value) => setFieldValue('owner', Number(value))}
|
||||||
className="mb-4"
|
className="mb-4"
|
||||||
|
testID="store-owner-dropdown"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<ProductsSelector
|
<ProductsSelector
|
||||||
|
|
@ -162,6 +165,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
|
||||||
placeholder="Select products"
|
placeholder="Select products"
|
||||||
isDisabled={(sku) => sku.storeId !== null && sku.storeId !== storeId}
|
isDisabled={(sku) => sku.storeId !== null && sku.storeId !== storeId}
|
||||||
labelFormat={(sku) => `${sku.productName} - ₹${sku.price}`}
|
labelFormat={(sku) => `${sku.productName} - ₹${sku.price}`}
|
||||||
|
testID="store-products-selector"
|
||||||
/>
|
/>
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
<P className="text-sm font-bold text-gray-700 mb-3 uppercase tracking-wider block">Store Image</P>
|
<P className="text-sm font-bold text-gray-700 mb-3 uppercase tracking-wider block">Store Image</P>
|
||||||
|
|
@ -183,6 +187,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
|
||||||
type="button"
|
type="button"
|
||||||
onClick={submit}
|
onClick={submit}
|
||||||
disabled={isLoading || isUploading}
|
disabled={isLoading || isUploading}
|
||||||
|
data-testid="store-submit-button"
|
||||||
className={`px-4 py-2 rounded-lg shadow-lg items-center mt-2 text-white text-lg font-bold w-full disabled:opacity-70 ${isLoading || isUploading ? 'bg-gray-400' : 'bg-blue-500'}`}
|
className={`px-4 py-2 rounded-lg shadow-lg items-center mt-2 text-white text-lg font-bold w-full disabled:opacity-70 ${isLoading || isUploading ? 'bg-gray-400' : 'bg-blue-500'}`}
|
||||||
>
|
>
|
||||||
{isUploading ? 'Uploading...' : isLoading ? (mode === 'create' ? 'Creating...' : 'Updating...') : (mode === 'create' ? 'Create Store' : 'Update Store')}
|
{isUploading ? 'Uploading...' : isLoading ? (mode === 'create' ? 'Creating...' : 'Updating...') : (mode === 'create' ? 'Create Store' : 'Update Store')}
|
||||||
|
|
|
||||||
|
|
@ -214,6 +214,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
value={values.tagName}
|
value={values.tagName}
|
||||||
onChange={handleChange('tagName')}
|
onChange={handleChange('tagName')}
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
|
data-testid="tag-name-input"
|
||||||
/>
|
/>
|
||||||
{errors.tagName && touched.tagName ? (
|
{errors.tagName && touched.tagName ? (
|
||||||
<P className="text-red-500 text-sm -mt-2 mb-4 block">{errors.tagName}</P>
|
<P className="text-red-500 text-sm -mt-2 mb-4 block">{errors.tagName}</P>
|
||||||
|
|
@ -227,6 +228,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
value={values.tagDescription}
|
value={values.tagDescription}
|
||||||
onChange={handleChange('tagDescription')}
|
onChange={handleChange('tagDescription')}
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
|
data-testid="tag-description-input"
|
||||||
/>
|
/>
|
||||||
{errors.tagDescription && touched.tagDescription ? (
|
{errors.tagDescription && touched.tagDescription ? (
|
||||||
<P className="text-red-500 text-sm -mt-2 mb-4 block">{errors.tagDescription}</P>
|
<P className="text-red-500 text-sm -mt-2 mb-4 block">{errors.tagDescription}</P>
|
||||||
|
|
@ -240,6 +242,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
|
|
||||||
<ImageUploaderNeo
|
<ImageUploaderNeo
|
||||||
images={images}
|
images={images}
|
||||||
|
testID="tag-image-add"
|
||||||
onImageAdd={(payload: ImageUploaderNeoPayload[]) => {
|
onImageAdd={(payload: ImageUploaderNeoPayload[]) => {
|
||||||
setImages((prev) => [...prev, ...payload.map((img) => ({
|
setImages((prev) => [...prev, ...payload.map((img) => ({
|
||||||
imgUrl: img.url,
|
imgUrl: img.url,
|
||||||
|
|
@ -260,6 +263,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
<div className="flex flex-row items-center mb-6">
|
<div className="flex flex-row items-center mb-6">
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={isDashboardTagChecked}
|
checked={isDashboardTagChecked}
|
||||||
|
testID="tag-dashboard-checkbox"
|
||||||
onPress={() => {
|
onPress={() => {
|
||||||
const newValue = !isDashboardTagChecked
|
const newValue = !isDashboardTagChecked
|
||||||
setIsDashboardTagChecked(newValue)
|
setIsDashboardTagChecked(newValue)
|
||||||
|
|
@ -277,6 +281,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
<MultiSelect
|
<MultiSelect
|
||||||
label="Select Related Stores"
|
label="Select Related Stores"
|
||||||
placeholder="Select stores..."
|
placeholder="Select stores..."
|
||||||
|
testID="tag-stores-dropdown"
|
||||||
value={values.relatedStores.map(id => id.toString())}
|
value={values.relatedStores.map(id => id.toString())}
|
||||||
options={stores.map(store => ({
|
options={stores.map(store => ({
|
||||||
label: store.name,
|
label: store.name,
|
||||||
|
|
@ -301,6 +306,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
label="Select Products"
|
label="Select Products"
|
||||||
placeholder="Search and select products..."
|
placeholder="Search and select products..."
|
||||||
showGroups={false}
|
showGroups={false}
|
||||||
|
testID="tag-products-selector"
|
||||||
/>
|
/>
|
||||||
<div className="mt-4">
|
<div className="mt-4">
|
||||||
{selectedProducts.length > 0 && (
|
{selectedProducts.length > 0 && (
|
||||||
|
|
@ -331,6 +337,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => handleSubmit()}
|
onClick={() => handleSubmit()}
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
|
data-testid="tag-submit-button"
|
||||||
className={`px-4 py-3 rounded-lg shadow-lg items-center text-white text-lg font-bold w-full disabled:opacity-70 ${isLoading ? 'bg-gray-400' : 'bg-blue-500'}`}
|
className={`px-4 py-3 rounded-lg shadow-lg items-center text-white text-lg font-bold w-full disabled:opacity-70 ${isLoading ? 'bg-gray-400' : 'bg-blue-500'}`}
|
||||||
>
|
>
|
||||||
{isLoading ? (mode === 'create' ? 'Creating...' : 'Updating...') : (mode === 'create' ? 'Create Tag' : 'Update Tag')}
|
{isLoading ? (mode === 'create' ? 'Creating...' : 'Updating...') : (mode === 'create' ? 'Create Tag' : 'Update Tag')}
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,7 @@ const CONST_LABELS: Record<string, string> = {
|
||||||
isFlashDeliveryEnabled: 'Enable Flash Delivery',
|
isFlashDeliveryEnabled: 'Enable Flash Delivery',
|
||||||
supportMobile: 'Support Mobile',
|
supportMobile: 'Support Mobile',
|
||||||
supportEmail: 'Support Email',
|
supportEmail: 'Support Email',
|
||||||
|
internalAppVersion: 'Internal App Version',
|
||||||
welcomeMessage: 'Welcome Message',
|
welcomeMessage: 'Welcome Message',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -40,20 +41,21 @@ const CONST_VISIBILITY: Record<string, boolean> = {
|
||||||
deliveryCharge: true,
|
deliveryCharge: true,
|
||||||
flashFreeDeliveryThreshold: true,
|
flashFreeDeliveryThreshold: true,
|
||||||
flashDeliveryCharge: true,
|
flashDeliveryCharge: true,
|
||||||
platformFeePercent: true,
|
platformFeePercent: false,
|
||||||
taxRate: false,
|
taxRate: false,
|
||||||
minOrderAmountForCoupon: true,
|
minOrderAmountForCoupon: false,
|
||||||
maxCouponDiscount: false,
|
maxCouponDiscount: false,
|
||||||
flashDeliverySlotId: true,
|
flashDeliverySlotId: false,
|
||||||
readableOrderId: false,
|
readableOrderId: false,
|
||||||
versionNum: true,
|
versionNum: false,
|
||||||
playStoreUrl: true,
|
playStoreUrl: false,
|
||||||
appStoreUrl: true,
|
appStoreUrl: false,
|
||||||
popularItems: true,
|
popularItems: false,
|
||||||
allItemsOrder: true,
|
allItemsOrder: true,
|
||||||
isFlashDeliveryEnabled: true,
|
isFlashDeliveryEnabled: true,
|
||||||
supportMobile: true,
|
supportMobile: true,
|
||||||
supportEmail: true,
|
supportEmail: true,
|
||||||
|
internalAppVersion: false,
|
||||||
welcomeMessage: true,
|
welcomeMessage: true,
|
||||||
tester: false,
|
tester: false,
|
||||||
}
|
}
|
||||||
|
|
@ -190,7 +192,24 @@ function CustomizeApp() {
|
||||||
const router = {
|
const router = {
|
||||||
push: (to: string) => navigate({ to: to as any }),
|
push: (to: string) => navigate({ to: to as any }),
|
||||||
}
|
}
|
||||||
const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery()
|
const [activeBoundId, setActiveBoundId] = React.useState<number | null>(null)
|
||||||
|
const [boundsReady, setBoundsReady] = React.useState(false)
|
||||||
|
const { data: boundsData } = trpc.admin.region.getMyRegionBounds.useQuery(undefined, {
|
||||||
|
staleTime: Infinity,
|
||||||
|
})
|
||||||
|
const bounds = boundsData?.bounds ?? []
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (!boundsReady && bounds.length > 0) {
|
||||||
|
setActiveBoundId(bounds[0].id)
|
||||||
|
setBoundsReady(true)
|
||||||
|
}
|
||||||
|
}, [bounds, boundsReady])
|
||||||
|
|
||||||
|
const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery(
|
||||||
|
activeBoundId != null ? { boundId: activeBoundId } : undefined,
|
||||||
|
{ enabled: boundsReady || bounds.length === 0 }
|
||||||
|
)
|
||||||
const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation()
|
const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation()
|
||||||
|
|
||||||
const handleSubmit = (values: ConstantFormData) => {
|
const handleSubmit = (values: ConstantFormData) => {
|
||||||
|
|
@ -208,7 +227,10 @@ function CustomizeApp() {
|
||||||
}
|
}
|
||||||
|
|
||||||
updateConstants(
|
updateConstants(
|
||||||
{ constants: changedConstants },
|
{
|
||||||
|
constants: changedConstants,
|
||||||
|
...(activeBoundId != null ? { boundId: activeBoundId } : {}),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
onSuccess: (response) => {
|
onSuccess: (response) => {
|
||||||
window.alert(`Updated ${response.updatedCount} constants successfully.`)
|
window.alert(`Updated ${response.updatedCount} constants successfully.`)
|
||||||
|
|
@ -251,7 +273,26 @@ function CustomizeApp() {
|
||||||
Modify application constants. Changes will take effect immediately.
|
Modify application constants. Changes will take effect immediately.
|
||||||
</MyText>
|
</MyText>
|
||||||
|
|
||||||
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
|
{bounds.length > 0 && (
|
||||||
|
<div className="mb-6 flex flex-row flex-wrap" data-testid="const-bound-tabs">
|
||||||
|
{bounds.map((bound, index) => {
|
||||||
|
const active = bound.id === activeBoundId
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={bound.id}
|
||||||
|
type="button"
|
||||||
|
data-testid={`const-bound-tab-${bound.id}`}
|
||||||
|
onClick={() => setActiveBoundId(bound.id)}
|
||||||
|
className={`mr-2 mb-2 rounded-full border px-4 py-2 text-sm font-semibold ${active ? 'border-blue-500 bg-blue-500 text-white' : 'border-gray-200 bg-white text-gray-700'}`}
|
||||||
|
>
|
||||||
|
{bound.name || `Bound ${index + 1}`}{index === 0 ? ' (Default)' : ''}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Formik key={activeBoundId ?? 'region'} initialValues={initialValues} onSubmit={handleSubmit}>
|
||||||
{({ handleSubmit, values, setFieldValue }) => (
|
{({ handleSubmit, values, setFieldValue }) => (
|
||||||
<div>
|
<div>
|
||||||
{constants.map((constant) => {
|
{constants.map((constant) => {
|
||||||
|
|
|
||||||
|
|
@ -392,6 +392,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType, refetch: () => void }
|
||||||
latitude: order.latitude,
|
latitude: order.latitude,
|
||||||
longitude: order.longitude,
|
longitude: order.longitude,
|
||||||
status: order.status,
|
status: order.status,
|
||||||
|
isFirstOrder: order.isFirstOrder,
|
||||||
}}
|
}}
|
||||||
onViewDetails={handleMenuOption}
|
onViewDetails={handleMenuOption}
|
||||||
onTogglePackaged={() => handleMarkPackaged(!order.isPackaged)}
|
onTogglePackaged={() => handleMarkPackaged(!order.isPackaged)}
|
||||||
|
|
|
||||||
|
|
@ -61,7 +61,8 @@ interface OrderWithSequence {
|
||||||
addressId: number,
|
addressId: number,
|
||||||
adminNotes?: string | null,
|
adminNotes?: string | null,
|
||||||
customerName?: string | null,
|
customerName?: string | null,
|
||||||
assignedUserName?: string | null
|
assignedUserName?: string | null,
|
||||||
|
isFirstOrder?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SlotProgressProps {
|
interface SlotProgressProps {
|
||||||
|
|
@ -721,6 +722,7 @@ function DeliverySequences() {
|
||||||
adminNotes: selectedOrder?.adminNotes || null,
|
adminNotes: selectedOrder?.adminNotes || null,
|
||||||
latitude: selectedOrder?.latitude || null,
|
latitude: selectedOrder?.latitude || null,
|
||||||
longitude: selectedOrder?.longitude || null,
|
longitude: selectedOrder?.longitude || null,
|
||||||
|
isFirstOrder: selectedOrder?.isFirstOrder,
|
||||||
}}
|
}}
|
||||||
onViewDetails={() => {
|
onViewDetails={() => {
|
||||||
if (selectedOrder) {
|
if (selectedOrder) {
|
||||||
|
|
|
||||||
|
|
@ -124,7 +124,7 @@ function Products() {
|
||||||
<>
|
<>
|
||||||
<div className="mb-6 flex flex-row items-center justify-between">
|
<div className="mb-6 flex flex-row items-center justify-between">
|
||||||
<MyText className="text-2xl font-bold text-gray-800">Products</MyText>
|
<MyText className="text-2xl font-bold text-gray-800">Products</MyText>
|
||||||
<MyButton onClick={() => navigate({ to: '/dashboard/products/new' })}>
|
<MyButton onClick={() => navigate({ to: '/dashboard/products/new' })} data-testid="add-product-button">
|
||||||
Add Product
|
Add Product
|
||||||
</MyButton>
|
</MyButton>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -201,6 +201,7 @@ function SlotDetails() {
|
||||||
<button
|
<button
|
||||||
onClick={() => navigate({ to: '/dashboard/slots/$id/edit', params: { id: String(slot.id) } })}
|
onClick={() => navigate({ to: '/dashboard/slots/$id/edit', params: { id: String(slot.id) } })}
|
||||||
aria-label="Edit slot"
|
aria-label="Edit slot"
|
||||||
|
data-testid="edit-slot-fab"
|
||||||
className="fixed flex h-16 w-16 items-center justify-center rounded-[24px] shadow-lg"
|
className="fixed flex h-16 w-16 items-center justify-center rounded-[24px] shadow-lg"
|
||||||
style={{ bottom: 32, right: 24, zIndex: 100, background: 'linear-gradient(135deg,#F83758,#E91E63)' }}
|
style={{ bottom: 32, right: 24, zIndex: 100, background: 'linear-gradient(135deg,#F83758,#E91E63)' }}
|
||||||
>
|
>
|
||||||
|
|
|
||||||
73
apps/backend/scripts/delete-orders-before.sql
Normal file
73
apps/backend/scripts/delete-orders-before.sql
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
-- ============================================================
|
||||||
|
-- delete-orders-before.sql
|
||||||
|
--
|
||||||
|
-- Deletes every order created BEFORE the cutoff below, together
|
||||||
|
-- with its dependent rows (coupon usage, complaints, incidents,
|
||||||
|
-- payments, refunds, status, items).
|
||||||
|
--
|
||||||
|
-- HOW TO USE
|
||||||
|
-- 1. Edit the cutoff date in the helper step below (single place).
|
||||||
|
-- 2. Run (remote):
|
||||||
|
-- bunx wrangler d1 execute <db-name> --remote --config <wrangler.toml> \
|
||||||
|
-- --file scripts/delete-orders-before.sql
|
||||||
|
-- (omit --remote for the local dev DB.)
|
||||||
|
--
|
||||||
|
-- DATE FORMAT — orders.created_at is stored as an ISO-8601 string,
|
||||||
|
-- e.g. '2025-12-24T02:50:33.284Z'. Accepted cutoff values:
|
||||||
|
-- * Date only : 'YYYY-MM-DD' e.g. '2026-01-01' <-- recommended
|
||||||
|
-- * Full timestamp : 'YYYY-MM-DDTHH:MM:SS.sssZ' e.g. '2026-01-01T00:00:00.000Z'
|
||||||
|
-- * Space format : 'YYYY-MM-DD HH:MM:SS' e.g. '2026-01-01 00:00:00'
|
||||||
|
-- Where the placeholders mean, in order left to right:
|
||||||
|
-- YYYY = year (2026-01-01 -> 2026)
|
||||||
|
-- MM = month (01-12) e.g. Jan = 01, Feb = 02, Mar = 03, Apr = 04,
|
||||||
|
-- DD = day of month (01-31)
|
||||||
|
-- HH = hour 00-23, MM = minutes, SS = seconds
|
||||||
|
-- Example: 25 March 2024 is written '2024-03-25'.
|
||||||
|
-- Rows strictly EARLIER than the value are removed.
|
||||||
|
--
|
||||||
|
-- WARNING: destructive and NOT reversible. Back up first:
|
||||||
|
-- bunx wrangler d1 export <db-name> --remote --output dumps/backup.sql
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
-- Helper: capture the targeted orders once, so the cutoff appears in ONE place.
|
||||||
|
-- (Dropped at the end; dropped first too, so a re-run never reuses stale ids.)
|
||||||
|
DROP TABLE IF EXISTS `_old_orders`;
|
||||||
|
CREATE TABLE `_old_orders` AS
|
||||||
|
SELECT `id`, `payment_info_id` FROM `orders`
|
||||||
|
WHERE `created_at` < '2026-08-28'; -- <<< EDIT THE CUTOFF DATE HERE
|
||||||
|
|
||||||
|
-- 1) coupon_usage references both orders and order_items -> delete first.
|
||||||
|
DELETE FROM `coupon_usage`
|
||||||
|
WHERE `order_id` IN (SELECT `id` FROM `_old_orders`)
|
||||||
|
OR `order_item_id` IN (
|
||||||
|
SELECT `id` FROM `order_items`
|
||||||
|
WHERE `order_id` IN (SELECT `id` FROM `_old_orders`)
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
|
||||||
|
-- 2) remaining direct children of orders.
|
||||||
|
DELETE FROM `complaints` WHERE `order_id` IN (SELECT `id` FROM `_old_orders`);
|
||||||
|
--> statement-breakpoint
|
||||||
|
DELETE FROM `user_incidents` WHERE `order_id` IN (SELECT `id` FROM `_old_orders`);
|
||||||
|
--> statement-breakpoint
|
||||||
|
DELETE FROM `payments` WHERE `order_id` IN (SELECT `id` FROM `_old_orders`);
|
||||||
|
--> statement-breakpoint
|
||||||
|
DELETE FROM `refunds` WHERE `order_id` IN (SELECT `id` FROM `_old_orders`);
|
||||||
|
--> statement-breakpoint
|
||||||
|
DELETE FROM `order_status` WHERE `order_id` IN (SELECT `id` FROM `_old_orders`);
|
||||||
|
--> statement-breakpoint
|
||||||
|
|
||||||
|
-- 3) order_items (no longer referenced by coupon_usage).
|
||||||
|
DELETE FROM `order_items` WHERE `order_id` IN (SELECT `id` FROM `_old_orders`);
|
||||||
|
--> statement-breakpoint
|
||||||
|
|
||||||
|
-- 4) the orders.
|
||||||
|
DELETE FROM `orders` WHERE `id` IN (SELECT `id` FROM `_old_orders`);
|
||||||
|
--> statement-breakpoint
|
||||||
|
|
||||||
|
-- 5) OPTIONAL: remove now-orphaned payment_info rows. Comment out to keep them.
|
||||||
|
DELETE FROM `payment_info`
|
||||||
|
WHERE `id` IN (SELECT `payment_info_id` FROM `_old_orders` WHERE `payment_info_id` IS NOT NULL);
|
||||||
|
--> statement-breakpoint
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS `_old_orders`;
|
||||||
|
|
@ -3,7 +3,7 @@ import type { Context } from 'hono'
|
||||||
import { cors } from 'hono/cors'
|
import { cors } from 'hono/cors'
|
||||||
import { logger } from 'hono/logger'
|
import { logger } from 'hono/logger'
|
||||||
import { trpcServer } from '@hono/trpc-server'
|
import { trpcServer } from '@hono/trpc-server'
|
||||||
import { getStaffUserById, getStaffRoleById, isUserSuspended } from '@/src/dbService'
|
import { getStaffUserById, getStaffRoleById, getSuperadminById, isUserSuspended } from '@/src/dbService'
|
||||||
import mainRouter from '@/src/main-router'
|
import mainRouter from '@/src/main-router'
|
||||||
import { appRouter } from '@/src/trpc/router'
|
import { appRouter } from '@/src/trpc/router'
|
||||||
import { TRPCError } from '@trpc/server'
|
import { TRPCError } from '@trpc/server'
|
||||||
|
|
@ -30,6 +30,7 @@ export const createApp = () => {
|
||||||
createContext: async ({ req }, c) => {
|
createContext: async ({ req }, c) => {
|
||||||
let user = null
|
let user = null
|
||||||
let staffUser = null
|
let staffUser = null
|
||||||
|
let superadmin = null
|
||||||
const authHeader = req.headers.get('authorization')
|
const authHeader = req.headers.get('authorization')
|
||||||
const callerInterface = req.headers.get('caller-interface')
|
const callerInterface = req.headers.get('caller-interface')
|
||||||
|
|
||||||
|
|
@ -57,7 +58,17 @@ export const createApp = () => {
|
||||||
const decoded = payload as any
|
const decoded = payload as any
|
||||||
|
|
||||||
// Check if this is a staff token (has staffId)
|
// Check if this is a staff token (has staffId)
|
||||||
if (decoded.staffId) {
|
if (decoded.superadminId) {
|
||||||
|
// This is a superadmin token, verify the row exists
|
||||||
|
const row = await getSuperadminById(decoded.superadminId)
|
||||||
|
|
||||||
|
if (row) {
|
||||||
|
superadmin = {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (decoded.staffId) {
|
||||||
// This is a staff token, verify staff exists
|
// This is a staff token, verify staff exists
|
||||||
const staff = await getStaffUserById(decoded.staffId)
|
const staff = await getStaffUserById(decoded.staffId)
|
||||||
|
|
||||||
|
|
@ -90,7 +101,7 @@ export const createApp = () => {
|
||||||
// Invalid token, both user and staffUser remain null
|
// Invalid token, both user and staffUser remain null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { req, c, user, staffUser, callerInterface }
|
return { req, c, user, staffUser, superadmin, callerInterface }
|
||||||
},
|
},
|
||||||
onError({ error, path, type, ctx }) {
|
onError({ error, path, type, ctx }) {
|
||||||
console.error('🚨 tRPC Error :', {
|
console.error('🚨 tRPC Error :', {
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ export type {
|
||||||
UserMiniInfo,
|
UserMiniInfo,
|
||||||
Store,
|
Store,
|
||||||
StaffUser,
|
StaffUser,
|
||||||
|
Superadmin,
|
||||||
StaffRole,
|
StaffRole,
|
||||||
AdminOrderRow,
|
AdminOrderRow,
|
||||||
AdminOrderDetails,
|
AdminOrderDetails,
|
||||||
|
|
|
||||||
74
apps/backend/src/map-assets/jcl.geojson
Normal file
74
apps/backend/src/map-assets/jcl.geojson
Normal file
|
|
@ -0,0 +1,74 @@
|
||||||
|
{
|
||||||
|
"type": "FeatureCollection",
|
||||||
|
"features": [
|
||||||
|
{
|
||||||
|
"type": "Feature",
|
||||||
|
"properties": {
|
||||||
|
"name": "Jadcherla"
|
||||||
|
},
|
||||||
|
"geometry": {
|
||||||
|
"type": "Polygon",
|
||||||
|
"coordinates": [
|
||||||
|
[
|
||||||
|
[
|
||||||
|
78.1403916,
|
||||||
|
16.744066
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.1548681,
|
||||||
|
16.7415277
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.1593669,
|
||||||
|
16.7523755
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.1621315,
|
||||||
|
16.7630654
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.1620705,
|
||||||
|
16.7692272
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.1564687,
|
||||||
|
16.7758419
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.1513873,
|
||||||
|
16.7783785
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.1455877,
|
||||||
|
16.7796921
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.1326433,
|
||||||
|
16.781202
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.123043,
|
||||||
|
16.7805196
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.118775,
|
||||||
|
16.7757046
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.1173809,
|
||||||
|
16.7685992
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.1205895,
|
||||||
|
16.7633171
|
||||||
|
],
|
||||||
|
[
|
||||||
|
78.1403916,
|
||||||
|
16.744066
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -127,10 +127,10 @@ export const productRouter = router({
|
||||||
if (!currentProduct) {
|
if (!currentProduct) {
|
||||||
throw new ApiError('Product not found', 404)
|
throw new ApiError('Product not found', 404)
|
||||||
}
|
}
|
||||||
if (!isSuperAdmin(ctx)) {
|
|
||||||
if (currentProduct.availableInAllRegions) {
|
if (currentProduct.availableInAllRegions) {
|
||||||
throw new ApiError('Only super admins can delete all-regions products', 403)
|
throw new ApiError('All-region products can only be deleted from superadmin', 403)
|
||||||
}
|
}
|
||||||
|
if (!isSuperAdmin(ctx)) {
|
||||||
if (currentProduct.regionId !== ctx.staffUser?.regionId) {
|
if (currentProduct.regionId !== ctx.staffUser?.regionId) {
|
||||||
throw new ApiError('Product does not belong to your region', 403)
|
throw new ApiError('Product does not belong to your region', 403)
|
||||||
}
|
}
|
||||||
|
|
@ -212,6 +212,11 @@ export const productRouter = router({
|
||||||
.mutation(async ({ input, ctx }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
.mutation(async ({ input, ctx }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
||||||
const { name, shortDescription, longDescription, storeId, regionId, availableInAllRegions, storeIdsByRegion, incrementStep, productType, skus } = input
|
const { name, shortDescription, longDescription, storeId, regionId, availableInAllRegions, storeIdsByRegion, incrementStep, productType, skus } = input
|
||||||
|
|
||||||
|
// All-region products are managed from superadmin-ui only.
|
||||||
|
if (availableInAllRegions) {
|
||||||
|
throw new ApiError('All-region products can only be created from superadmin', 403)
|
||||||
|
}
|
||||||
|
|
||||||
const normalizedStoreIdsByRegion = storeIdsByRegion
|
const normalizedStoreIdsByRegion = storeIdsByRegion
|
||||||
? Object.fromEntries(Object.entries(storeIdsByRegion).map(([k, v]) => [Number(k), v]))
|
? Object.fromEntries(Object.entries(storeIdsByRegion).map(([k, v]) => [Number(k), v]))
|
||||||
: undefined
|
: undefined
|
||||||
|
|
@ -317,11 +322,10 @@ export const productRouter = router({
|
||||||
|
|
||||||
const currentProduct = await getProductByIdInDb(id, undefined)
|
const currentProduct = await getProductByIdInDb(id, undefined)
|
||||||
assertOwnRestrictedProduct(ctx, currentProduct)
|
assertOwnRestrictedProduct(ctx, currentProduct)
|
||||||
if (!isSuperAdmin(ctx)) {
|
// All-region products are managed from superadmin-ui only.
|
||||||
const nextAllRegions = availableInAllRegions ?? currentProduct!.availableInAllRegions
|
const nextAllRegions = availableInAllRegions ?? currentProduct!.availableInAllRegions
|
||||||
if (nextAllRegions !== currentProduct!.availableInAllRegions) {
|
if (nextAllRegions !== currentProduct!.availableInAllRegions) {
|
||||||
throw new ApiError('Only super admins can change all-regions availability', 403)
|
throw new ApiError('All-region availability can only be changed from superadmin', 403)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const normalizedStoreIdsByRegion = storeIdsByRegion
|
const normalizedStoreIdsByRegion = storeIdsByRegion
|
||||||
|
|
|
||||||
|
|
@ -84,10 +84,16 @@ export const storeRouter = router({
|
||||||
owner: z.number().min(1, "Owner is required"),
|
owner: z.number().min(1, "Owner is required"),
|
||||||
products: z.array(z.number()).optional(),
|
products: z.array(z.number()).optional(),
|
||||||
regionId: z.number().int().positive().optional(),
|
regionId: z.number().int().positive().optional(),
|
||||||
|
availableInAllRegions: z.boolean().optional(),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input, ctx }): Promise<{ store: Store; message: string }> => {
|
.mutation(async ({ input, ctx }): Promise<{ store: Store; message: string }> => {
|
||||||
const { name, description, imageUrl, owner, products } = input;
|
const { name, description, imageUrl, owner, products } = input;
|
||||||
|
|
||||||
|
// All-region stores are managed from superadmin-ui only.
|
||||||
|
if (input.availableInAllRegions) {
|
||||||
|
throw new ApiError("All-region stores can only be created from superadmin", 403);
|
||||||
|
}
|
||||||
|
|
||||||
const imageKey = imageUrl ? extractKeyFromPresignedUrl(imageUrl) : undefined;
|
const imageKey = imageUrl ? extractKeyFromPresignedUrl(imageUrl) : undefined;
|
||||||
|
|
||||||
const newStore = await createStoreInDb(
|
const newStore = await createStoreInDb(
|
||||||
|
|
@ -119,6 +125,7 @@ export const storeRouter = router({
|
||||||
owner: z.number().min(1, "Owner is required"),
|
owner: z.number().min(1, "Owner is required"),
|
||||||
products: z.array(z.number()).optional(),
|
products: z.array(z.number()).optional(),
|
||||||
regionId: z.number().int().positive().optional(),
|
regionId: z.number().int().positive().optional(),
|
||||||
|
availableInAllRegions: z.boolean().optional(),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input, ctx }): Promise<{ store: Store; message: string }> => {
|
.mutation(async ({ input, ctx }): Promise<{ store: Store; message: string }> => {
|
||||||
const { id, name, description, imageUrl, owner, products } = input;
|
const { id, name, description, imageUrl, owner, products } = input;
|
||||||
|
|
@ -128,6 +135,10 @@ export const storeRouter = router({
|
||||||
if (!existingStore) {
|
if (!existingStore) {
|
||||||
throw new ApiError("Store not found", 404);
|
throw new ApiError("Store not found", 404);
|
||||||
}
|
}
|
||||||
|
// All-region stores are managed from superadmin-ui only.
|
||||||
|
if (existingStore.regionId == null || input.availableInAllRegions) {
|
||||||
|
throw new ApiError("All-region stores can only be edited from superadmin", 403);
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
ctx.staffUser?.staffRoleName !== 'super_admin' &&
|
ctx.staffUser?.staffRoleName !== 'super_admin' &&
|
||||||
existingStore.regionId !== ctx.staffUser?.regionId
|
existingStore.regionId !== ctx.staffUser?.regionId
|
||||||
|
|
|
||||||
47
apps/backend/src/trpc/apis/superadmin-apis/apis/auth.ts
Normal file
47
apps/backend/src/trpc/apis/superadmin-apis/apis/auth.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
import { router, publicProcedure } from '@/src/trpc/trpc-index'
|
||||||
|
import { z } from 'zod';
|
||||||
|
import bcrypt from 'bcryptjs';
|
||||||
|
import { SignJWT } from 'jose';
|
||||||
|
import { getEncodedJwtSecret } from '@/src/lib/env-exporter';
|
||||||
|
import { ApiError } from '@/src/lib/api-error'
|
||||||
|
import { getSuperadminByName } from '@/src/dbService'
|
||||||
|
|
||||||
|
export const superadminAuthRouter = router({
|
||||||
|
login: publicProcedure
|
||||||
|
.input(z.object({
|
||||||
|
name: z.string(),
|
||||||
|
password: z.string(),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }) => {
|
||||||
|
const { name, password } = input;
|
||||||
|
|
||||||
|
if (!name || !password) {
|
||||||
|
throw new ApiError('Name and password are required', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const row = await getSuperadminByName(name);
|
||||||
|
|
||||||
|
if (!row) {
|
||||||
|
throw new ApiError('Invalid credentials', 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isPasswordValid = await bcrypt.compare(password, row.password);
|
||||||
|
if (!isPasswordValid) {
|
||||||
|
throw new ApiError('Invalid credentials', 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = await new SignJWT({ superadminId: row.id, name: row.name })
|
||||||
|
.setProtectedHeader({ alg: 'HS256' })
|
||||||
|
.setExpirationTime('30d')
|
||||||
|
.sign(getEncodedJwtSecret());
|
||||||
|
|
||||||
|
return {
|
||||||
|
message: 'Login successful',
|
||||||
|
token,
|
||||||
|
superadmin: {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
});
|
||||||
109
apps/backend/src/trpc/apis/superadmin-apis/apis/const.ts
Normal file
109
apps/backend/src/trpc/apis/superadmin-apis/apis/const.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { DEFAULT_REGION_ID } from '@packages/shared';
|
||||||
|
import { computeConstants } from '@/src/lib/const-store'
|
||||||
|
import { refreshGenKv } from '@/src/lib/gen-store'
|
||||||
|
import { CONST_KEYS, REGION_CONST_KEYS_ARRAY } from '@/src/lib/const-keys'
|
||||||
|
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
|
||||||
|
import {
|
||||||
|
getAllConstants as getAllConstantsFromDb,
|
||||||
|
upsertConstants as upsertConstantsInDb,
|
||||||
|
getRegionConstants as getRegionConstantsFromDb,
|
||||||
|
upsertRegionConstants as upsertRegionConstantsInDb,
|
||||||
|
getRegionById as getRegionByIdFromDb,
|
||||||
|
} from '@/src/dbService'
|
||||||
|
import type { Constant, ConstantUpdateResult } from '@packages/shared'
|
||||||
|
|
||||||
|
// Constants that are baked into the versioned cache files (products.json etc.)
|
||||||
|
// — changing them requires regenerating the cache so the user app picks it up.
|
||||||
|
const CACHE_AFFECTING_KEYS: string[] = [
|
||||||
|
CONST_KEYS.tagsOrder,
|
||||||
|
]
|
||||||
|
|
||||||
|
// Superadmins have no region of their own. Regional constant keys still need
|
||||||
|
// one, so the wrappers accept an explicit regionId and default to the legacy
|
||||||
|
// region (DEFAULT_REGION_ID) — matching what the admin.* scope did for the
|
||||||
|
// superadmin-ui's region-bound staff row.
|
||||||
|
export const superadminConstRouter = router({
|
||||||
|
getConstants: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
regionId: z.number().int().positive().optional(),
|
||||||
|
boundId: z.number().int().positive().optional(),
|
||||||
|
}).optional())
|
||||||
|
.query(async ({ input }): Promise<Constant[]> => {
|
||||||
|
const regionId = input?.regionId ?? DEFAULT_REGION_ID;
|
||||||
|
const boundId = input?.boundId ?? null;
|
||||||
|
if (boundId != null) {
|
||||||
|
const region = await getRegionByIdFromDb(regionId);
|
||||||
|
if (!region?.bounds?.some((b) => b.id === boundId)) {
|
||||||
|
throw new Error('Bound does not belong to the region');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const [globals, regional] = await Promise.all([
|
||||||
|
getAllConstantsFromDb(),
|
||||||
|
getRegionConstantsFromDb(regionId, boundId),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return [...globals, ...regional];
|
||||||
|
}),
|
||||||
|
|
||||||
|
updateConstants: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
constants: z.array(z.object({
|
||||||
|
key: z.string(),
|
||||||
|
value: z.any(),
|
||||||
|
})),
|
||||||
|
regionId: z.number().int().positive().optional(),
|
||||||
|
boundId: z.number().int().positive().optional(),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }): Promise<ConstantUpdateResult> => {
|
||||||
|
const { constants } = input;
|
||||||
|
const regionId = input.regionId ?? DEFAULT_REGION_ID;
|
||||||
|
const boundId = input.boundId ?? null;
|
||||||
|
if (boundId != null) {
|
||||||
|
const region = await getRegionByIdFromDb(regionId);
|
||||||
|
if (!region?.bounds?.some((b) => b.id === boundId)) {
|
||||||
|
throw new Error('Bound does not belong to the region');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const validKeys = Object.values(CONST_KEYS) as string[];
|
||||||
|
const invalidKeys = constants
|
||||||
|
.filter(c => !validKeys.includes(c.key))
|
||||||
|
.map(c => c.key);
|
||||||
|
|
||||||
|
if (invalidKeys.length > 0) {
|
||||||
|
throw new Error(`Invalid constant keys: ${invalidKeys.join(', ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(input)
|
||||||
|
const regional = constants.filter((c) => REGION_CONST_KEYS_ARRAY.includes(c.key));
|
||||||
|
const global = constants.filter((c) => !REGION_CONST_KEYS_ARRAY.includes(c.key));
|
||||||
|
|
||||||
|
if (global.length > 0) {
|
||||||
|
await upsertConstantsInDb(global);
|
||||||
|
}
|
||||||
|
if (regional.length > 0) {
|
||||||
|
await upsertRegionConstantsInDb(regionId, boundId, regional);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh all constants in Redis after database update
|
||||||
|
await computeConstants();
|
||||||
|
|
||||||
|
// Mirror the full essentialConsts response into KV for client reads.
|
||||||
|
await refreshGenKv(regionId, boundId);
|
||||||
|
|
||||||
|
// Constants like tagsOrder are baked into the versioned cache files.
|
||||||
|
// Regenerate the cache (bumps cacheVersion) so the user app fetches the
|
||||||
|
// new data (e.g., the new tab order on the home page).
|
||||||
|
if (constants.some((c) => CACHE_AFFECTING_KEYS.includes(c.key))) {
|
||||||
|
await scheduleStoreInitialization()
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
updatedCount: constants.length,
|
||||||
|
keys: constants.map(c => c.key),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
});
|
||||||
341
apps/backend/src/trpc/apis/superadmin-apis/apis/product.ts
Normal file
341
apps/backend/src/trpc/apis/superadmin-apis/apis/product.ts
Normal file
|
|
@ -0,0 +1,341 @@
|
||||||
|
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
|
||||||
|
import { z } from 'zod'
|
||||||
|
import { ApiError } from '@/src/lib/api-error'
|
||||||
|
import { scaffoldAssetUrl, claimUploadUrl, extractKeyFromPresignedUrl, deleteImageUtil } from '@/src/lib/s3-client'
|
||||||
|
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
|
||||||
|
import { createAvailabilityCacheFile } from '@/src/lib/cloud_cache'
|
||||||
|
import {
|
||||||
|
getAllProducts as getAllProductsInDb,
|
||||||
|
getProductById as getProductByIdInDb,
|
||||||
|
deleteProduct as deleteProductInDb,
|
||||||
|
toggleProductOutOfStock as toggleProductOutOfStockInDb,
|
||||||
|
getAllSkusSummary as getAllSkusSummaryInDb,
|
||||||
|
checkProductExistsByName,
|
||||||
|
createProduct as createProductInDb,
|
||||||
|
updateProduct as updateProductInDb,
|
||||||
|
} from '@/src/dbService'
|
||||||
|
import type {
|
||||||
|
AdminProductWithRelations,
|
||||||
|
AdminProductListResponse,
|
||||||
|
AdminProductResponse,
|
||||||
|
AdminDeleteProductResult,
|
||||||
|
AdminToggleOutOfStockResult,
|
||||||
|
} from '@packages/shared'
|
||||||
|
|
||||||
|
const regionStatsInput = z.record(
|
||||||
|
z.string(),
|
||||||
|
z.object({
|
||||||
|
price: z.number().positive().optional().nullable(),
|
||||||
|
marketPrice: z.number().optional().nullable(),
|
||||||
|
flashPrice: z.number().optional().nullable(),
|
||||||
|
isFlashAvailable: z.boolean().optional(),
|
||||||
|
isOffer: z.boolean().optional(),
|
||||||
|
isSuspended: z.boolean().optional(),
|
||||||
|
isOutOfStock: z.boolean().optional(),
|
||||||
|
storeId: z.number().int().positive().optional().nullable(),
|
||||||
|
}).optional()
|
||||||
|
).optional()
|
||||||
|
|
||||||
|
const skuInput = z.object({
|
||||||
|
id: z.number().optional(),
|
||||||
|
name: z.string().optional().nullable(),
|
||||||
|
price: z.number().positive('Price must be positive'),
|
||||||
|
marketPrice: z.number().optional().nullable(),
|
||||||
|
images: z.array(z.string()).optional().default([]),
|
||||||
|
isFlashAvailable: z.boolean().optional().default(false),
|
||||||
|
flashPrice: z.number().optional().nullable(),
|
||||||
|
isOutOfStock: z.boolean().optional().default(false),
|
||||||
|
isOffer: z.boolean().optional().default(false),
|
||||||
|
isComboOnly: z.boolean().optional().default(false),
|
||||||
|
isDeleted: z.boolean().optional().default(false),
|
||||||
|
isSuspended: z.boolean().optional().default(false),
|
||||||
|
features: z.array(z.object({
|
||||||
|
featureName: z.string().nullable().optional(),
|
||||||
|
featureValue: z.string().min(1, 'Value is required'),
|
||||||
|
})).min(1, 'At least one feature is required'),
|
||||||
|
comboItems: z.array(z.object({
|
||||||
|
skuId: z.number().int().positive(),
|
||||||
|
})).optional(),
|
||||||
|
regionStats: regionStatsInput,
|
||||||
|
})
|
||||||
|
|
||||||
|
export const superadminProductRouter = router({
|
||||||
|
getAllSkusSummary: superadminProcedure
|
||||||
|
.query(async () => {
|
||||||
|
const skus = await getAllSkusSummaryInDb(undefined)
|
||||||
|
return { skus }
|
||||||
|
}),
|
||||||
|
|
||||||
|
getProducts: superadminProcedure
|
||||||
|
.query(async (): Promise<AdminProductListResponse> => {
|
||||||
|
const products = await getAllProductsInDb(undefined)
|
||||||
|
|
||||||
|
const productsWithImageUrls = products.map((product) => ({
|
||||||
|
...product,
|
||||||
|
skus: product.skus.map((sku) => ({
|
||||||
|
...sku,
|
||||||
|
images: scaffoldAssetUrl((sku.images as string[]) || []),
|
||||||
|
})),
|
||||||
|
}))
|
||||||
|
|
||||||
|
return {
|
||||||
|
products: productsWithImageUrls,
|
||||||
|
count: productsWithImageUrls.length,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
|
||||||
|
getProductById: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
id: z.number(),
|
||||||
|
}))
|
||||||
|
.query(async ({ input }): Promise<AdminProductResponse> => {
|
||||||
|
const { id } = input;
|
||||||
|
|
||||||
|
const product = await getProductByIdInDb(id, undefined)
|
||||||
|
|
||||||
|
if (!product) {
|
||||||
|
throw new ApiError('Product not found', 404)
|
||||||
|
}
|
||||||
|
|
||||||
|
const productWithImageUrls = {
|
||||||
|
...product,
|
||||||
|
skus: product.skus.map((sku) => ({
|
||||||
|
...sku,
|
||||||
|
images: scaffoldAssetUrl((sku.images as string[]) || []),
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
product: productWithImageUrls,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
|
||||||
|
deleteProduct: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
id: z.number(),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }): Promise<AdminDeleteProductResult> => {
|
||||||
|
const { id } = input;
|
||||||
|
|
||||||
|
const currentProduct = await getProductByIdInDb(id, undefined)
|
||||||
|
if (!currentProduct) {
|
||||||
|
throw new ApiError('Product not found', 404)
|
||||||
|
}
|
||||||
|
|
||||||
|
const deletedProduct = await deleteProductInDb(id)
|
||||||
|
|
||||||
|
if (!deletedProduct) {
|
||||||
|
throw new ApiError('Product not found', 404)
|
||||||
|
}
|
||||||
|
|
||||||
|
await scheduleStoreInitialization()
|
||||||
|
|
||||||
|
return {
|
||||||
|
message: 'Product deleted successfully',
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
|
||||||
|
toggleOutOfStock: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
id: z.number(),
|
||||||
|
regionId: z.number().int().positive(),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }): Promise<AdminToggleOutOfStockResult> => {
|
||||||
|
const { id, regionId } = input;
|
||||||
|
|
||||||
|
const currentProduct = await getProductByIdInDb(id, undefined)
|
||||||
|
if (!currentProduct) {
|
||||||
|
throw new ApiError('Product not found', 404)
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await toggleProductOutOfStockInDb(id, regionId)
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
throw new ApiError('Product not found', 404)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only the availability cache needs regenerating for a stock flip.
|
||||||
|
await createAvailabilityCacheFile().catch((err) => {
|
||||||
|
console.error('Failed to regenerate availability cache after stock update:', err)
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
productId: result.id,
|
||||||
|
isOutOfStock: result.isOutOfStock,
|
||||||
|
message: `Product marked as ${result.isOutOfStock ? 'out of stock' : 'in stock'}`,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
|
||||||
|
createProduct: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
name: z.string().min(1, 'Name is required'),
|
||||||
|
shortDescription: z.string().optional(),
|
||||||
|
longDescription: z.string().optional(),
|
||||||
|
storeId: z.number().min(1, 'Store is required').optional(),
|
||||||
|
// Creator/primary region. Required in both modes: for all-region
|
||||||
|
// products it decides initial stock/prices (other regions start OOS);
|
||||||
|
// product_info.region_id itself is still nulled by the flag.
|
||||||
|
regionId: z.number().int().positive('Region is required'),
|
||||||
|
availableInAllRegions: z.boolean().optional(),
|
||||||
|
storeIdsByRegion: z.record(z.string(), z.number()).optional(),
|
||||||
|
incrementStep: z.number().optional().default(1),
|
||||||
|
productType: z.enum(['item', 'combo']).optional().default('item'),
|
||||||
|
skus: z.array(skuInput.omit({ id: true })).min(1, 'At least one SKU is required'),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
||||||
|
const { name, shortDescription, longDescription, storeId, regionId, availableInAllRegions, storeIdsByRegion, incrementStep, productType, skus } = input
|
||||||
|
|
||||||
|
const normalizedStoreIdsByRegion = storeIdsByRegion
|
||||||
|
? Object.fromEntries(Object.entries(storeIdsByRegion).map(([k, v]) => [Number(k), v]))
|
||||||
|
: undefined
|
||||||
|
|
||||||
|
const existingProduct = await checkProductExistsByName(name.trim())
|
||||||
|
if (existingProduct) {
|
||||||
|
throw new ApiError('A product with this name already exists', 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
const allUploadUrls: string[] = skus.flatMap((sku) => sku.images)
|
||||||
|
|
||||||
|
const skuInputs = skus.map((sku) => ({
|
||||||
|
name: sku.name ?? null,
|
||||||
|
price: sku.price,
|
||||||
|
marketPrice: sku.marketPrice ?? null,
|
||||||
|
images: sku.images.map((url) => extractKeyFromPresignedUrl(url)),
|
||||||
|
isFlashAvailable: sku.isFlashAvailable,
|
||||||
|
flashPrice: sku.flashPrice ?? null,
|
||||||
|
isOutOfStock: sku.isOutOfStock,
|
||||||
|
isOffer: sku.isOffer,
|
||||||
|
isComboOnly: sku.isComboOnly,
|
||||||
|
isDeleted: sku.isDeleted ?? false,
|
||||||
|
isSuspended: sku.isSuspended,
|
||||||
|
features: sku.features.map((f) => ({
|
||||||
|
featureName: f.featureName?.trim() || null,
|
||||||
|
featureValue: f.featureValue,
|
||||||
|
})),
|
||||||
|
comboItems: (sku.comboItems || []).map((ci) => ({ skuId: ci.skuId })),
|
||||||
|
regionStats: sku.regionStats ?? undefined,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const newProduct = await createProductInDb({
|
||||||
|
name,
|
||||||
|
shortDescription,
|
||||||
|
longDescription,
|
||||||
|
storeId,
|
||||||
|
regionId,
|
||||||
|
availableInAllRegions,
|
||||||
|
storeIdsByRegion: normalizedStoreIdsByRegion,
|
||||||
|
incrementStep,
|
||||||
|
productType,
|
||||||
|
skus: skuInputs,
|
||||||
|
} as any)
|
||||||
|
|
||||||
|
if (allUploadUrls.length > 0) {
|
||||||
|
await Promise.all(allUploadUrls.map((url) => claimUploadUrl(url)))
|
||||||
|
}
|
||||||
|
|
||||||
|
await scheduleStoreInitialization()
|
||||||
|
|
||||||
|
const productWithImageUrls = {
|
||||||
|
...newProduct,
|
||||||
|
skus: newProduct.skus.map((sku) => ({
|
||||||
|
...sku,
|
||||||
|
images: scaffoldAssetUrl((sku.images as string[]) || []),
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
product: productWithImageUrls,
|
||||||
|
message: 'Product created successfully',
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
|
||||||
|
updateProduct: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string().min(1, 'Name is required'),
|
||||||
|
shortDescription: z.string().optional(),
|
||||||
|
longDescription: z.string().optional(),
|
||||||
|
storeId: z.number().min(1, 'Store is required').optional(),
|
||||||
|
regionId: z.number().int().positive().optional(),
|
||||||
|
availableInAllRegions: z.boolean().optional(),
|
||||||
|
storeIdsByRegion: z.record(z.string(), z.number()).optional(),
|
||||||
|
incrementStep: z.number().optional().default(1),
|
||||||
|
productType: z.enum(['item', 'combo']).optional(),
|
||||||
|
skus: z.array(skuInput).min(1, 'At least one SKU is required'),
|
||||||
|
deletedImageKeys: z.array(z.string()).optional().default([]),
|
||||||
|
newImageUrls: z.array(z.string()).optional().default([]),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
||||||
|
const { id, name, shortDescription, longDescription, storeId, regionId, availableInAllRegions, storeIdsByRegion, incrementStep, productType, skus, deletedImageKeys, newImageUrls } = input
|
||||||
|
|
||||||
|
const currentProduct = await getProductByIdInDb(id, undefined)
|
||||||
|
if (!currentProduct) {
|
||||||
|
throw new ApiError('Product not found', 404)
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedStoreIdsByRegion = storeIdsByRegion
|
||||||
|
? Object.fromEntries(Object.entries(storeIdsByRegion).map(([k, v]) => [Number(k), v]))
|
||||||
|
: undefined
|
||||||
|
|
||||||
|
if (deletedImageKeys.length > 0) {
|
||||||
|
await deleteImageUtil({ keys: deletedImageKeys })
|
||||||
|
}
|
||||||
|
|
||||||
|
const skuInputs = skus.map((sku) => ({
|
||||||
|
id: sku.id,
|
||||||
|
name: sku.name ?? null,
|
||||||
|
price: sku.price,
|
||||||
|
marketPrice: sku.marketPrice ?? null,
|
||||||
|
images: sku.images.map((url) => extractKeyFromPresignedUrl(url)),
|
||||||
|
isFlashAvailable: sku.isFlashAvailable,
|
||||||
|
flashPrice: sku.flashPrice ?? null,
|
||||||
|
isOutOfStock: sku.isOutOfStock,
|
||||||
|
isOffer: sku.isOffer,
|
||||||
|
isComboOnly: sku.isComboOnly,
|
||||||
|
isDeleted: sku.isDeleted ?? false,
|
||||||
|
isSuspended: sku.isSuspended,
|
||||||
|
features: sku.features.map((f) => ({
|
||||||
|
featureName: f.featureName?.trim() || null,
|
||||||
|
featureValue: f.featureValue,
|
||||||
|
})),
|
||||||
|
comboItems: (sku.comboItems || []).map((ci) => ({ skuId: ci.skuId })),
|
||||||
|
regionStats: sku.regionStats ?? undefined,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const updatedProduct = await updateProductInDb(id, {
|
||||||
|
name,
|
||||||
|
shortDescription,
|
||||||
|
longDescription,
|
||||||
|
storeId,
|
||||||
|
regionId,
|
||||||
|
availableInAllRegions,
|
||||||
|
storeIdsByRegion: normalizedStoreIdsByRegion,
|
||||||
|
incrementStep,
|
||||||
|
productType,
|
||||||
|
skus: skuInputs,
|
||||||
|
} as any)
|
||||||
|
|
||||||
|
if (!updatedProduct) {
|
||||||
|
throw new ApiError('Product not found', 404)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newImageUrls.length > 0) {
|
||||||
|
await Promise.all(newImageUrls.map((url) => claimUploadUrl(url)))
|
||||||
|
}
|
||||||
|
|
||||||
|
await scheduleStoreInitialization()
|
||||||
|
|
||||||
|
const productWithImageUrls = {
|
||||||
|
...updatedProduct,
|
||||||
|
skus: updatedProduct.skus.map((sku) => ({
|
||||||
|
...sku,
|
||||||
|
images: scaffoldAssetUrl((sku.images as string[]) || []),
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
product: productWithImageUrls,
|
||||||
|
message: 'Product updated successfully',
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
});
|
||||||
147
apps/backend/src/trpc/apis/superadmin-apis/apis/region.ts
Normal file
147
apps/backend/src/trpc/apis/superadmin-apis/apis/region.ts
Normal file
|
|
@ -0,0 +1,147 @@
|
||||||
|
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
|
||||||
|
import { z } from 'zod'
|
||||||
|
import { ApiError } from '@/src/lib/api-error'
|
||||||
|
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
|
||||||
|
import {
|
||||||
|
getRegions as getRegionsFromDb,
|
||||||
|
getRegionById as getRegionByIdFromDb,
|
||||||
|
createRegion as createRegionInDb,
|
||||||
|
updateRegion as updateRegionInDb,
|
||||||
|
addRegionBound as addRegionBoundInDb,
|
||||||
|
deleteRegionBound as deleteRegionBoundFromDb,
|
||||||
|
backfillMarketStatsForRegion as backfillMarketStatsForRegionInDb,
|
||||||
|
} from '@/src/dbService'
|
||||||
|
import type { Region } from '@packages/shared'
|
||||||
|
|
||||||
|
const boundInput = z.object({
|
||||||
|
id: z.number().int().positive().optional(),
|
||||||
|
geojson: z.string().min(1, 'GeoJSON is required'),
|
||||||
|
name: z.string().min(1, 'Bound name is required'),
|
||||||
|
description: z.string().min(1, 'Bound description is required'),
|
||||||
|
priority: z.number().int().min(0).optional(),
|
||||||
|
})
|
||||||
|
|
||||||
|
const telegramCredInput = z.object({
|
||||||
|
botToken: z.string().min(1, 'Bot token is required'),
|
||||||
|
chatId: z.string().min(1, 'Chat ID is required'),
|
||||||
|
})
|
||||||
|
|
||||||
|
/** Reject duplicate priorities within one bounds payload. */
|
||||||
|
function assertUniquePriorities(bounds: { priority?: number }[] | undefined): void {
|
||||||
|
if (!bounds) return
|
||||||
|
const seen = new Set<number>()
|
||||||
|
for (const bound of bounds) {
|
||||||
|
const priority = bound.priority ?? 0
|
||||||
|
if (seen.has(priority)) {
|
||||||
|
throw new ApiError(`Duplicate bound priority ${priority}: priorities must be unique within a region`, 400)
|
||||||
|
}
|
||||||
|
seen.add(priority)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const superadminRegionRouter = router({
|
||||||
|
getRegions: superadminProcedure.query(
|
||||||
|
async (): Promise<{ regions: Region[]; count: number }> => {
|
||||||
|
const regions = await getRegionsFromDb()
|
||||||
|
return { regions, count: regions.length }
|
||||||
|
}
|
||||||
|
),
|
||||||
|
|
||||||
|
getRegionById: superadminProcedure
|
||||||
|
.input(z.object({ id: z.number() }))
|
||||||
|
.query(async ({ input }): Promise<{ region: Region }> => {
|
||||||
|
const region = await getRegionByIdFromDb(input.id)
|
||||||
|
if (!region) {
|
||||||
|
throw new ApiError('Region not found', 404)
|
||||||
|
}
|
||||||
|
return { region }
|
||||||
|
}),
|
||||||
|
|
||||||
|
createRegion: superadminProcedure
|
||||||
|
.input(
|
||||||
|
z.object({
|
||||||
|
name: z.string().min(1, 'Name is required'),
|
||||||
|
description: z.string().nullish(),
|
||||||
|
bounds: z.array(boundInput).optional(),
|
||||||
|
creds: z.array(telegramCredInput).min(1, 'At least one Telegram cred is required'),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.mutation(async ({ input }): Promise<{ region: Region; message: string }> => {
|
||||||
|
assertUniquePriorities(input.bounds)
|
||||||
|
const region = await createRegionInDb({
|
||||||
|
name: input.name,
|
||||||
|
description: input.description ?? null,
|
||||||
|
bounds: input.bounds,
|
||||||
|
creds: input.creds,
|
||||||
|
})
|
||||||
|
|
||||||
|
// New region: give every existing SKU an (out-of-stock) market-stats row.
|
||||||
|
await backfillMarketStatsForRegionInDb(region.id)
|
||||||
|
|
||||||
|
// Regenerate cache files so the new region gets its own set.
|
||||||
|
await scheduleStoreInitialization()
|
||||||
|
|
||||||
|
return { region, message: 'Region created successfully' }
|
||||||
|
}),
|
||||||
|
|
||||||
|
updateRegion: superadminProcedure
|
||||||
|
.input(
|
||||||
|
z.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string().min(1, 'Name is required').optional(),
|
||||||
|
description: z.string().nullish(),
|
||||||
|
bounds: z.array(boundInput).optional(),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.mutation(async ({ input }): Promise<{ region: Region; message: string }> => {
|
||||||
|
assertUniquePriorities(input.bounds)
|
||||||
|
const region = await updateRegionInDb(input.id, {
|
||||||
|
name: input.name,
|
||||||
|
description: input.description,
|
||||||
|
bounds: input.bounds,
|
||||||
|
})
|
||||||
|
if (!region) {
|
||||||
|
throw new ApiError('Region not found', 404)
|
||||||
|
}
|
||||||
|
return { region, message: 'Region updated successfully' }
|
||||||
|
}),
|
||||||
|
|
||||||
|
// Regions are non-deletable: many tables reference region_id.
|
||||||
|
deleteRegion: superadminProcedure
|
||||||
|
.input(z.object({ id: z.number() }))
|
||||||
|
.mutation(async (): Promise<{ message: string }> => {
|
||||||
|
throw new ApiError('Regions cannot be deleted', 400)
|
||||||
|
}),
|
||||||
|
|
||||||
|
addRegionBound: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
regionId: z.number(),
|
||||||
|
geojson: z.string().min(1),
|
||||||
|
name: z.string().min(1, 'Bound name is required'),
|
||||||
|
description: z.string().min(1, 'Bound description is required'),
|
||||||
|
priority: z.number().int().min(0).optional(),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }) => {
|
||||||
|
const region = await getRegionByIdFromDb(input.regionId)
|
||||||
|
if (!region) {
|
||||||
|
throw new ApiError('Region not found', 404)
|
||||||
|
}
|
||||||
|
if (region.bounds?.some((b) => (b.priority ?? 0) === (input.priority ?? 0))) {
|
||||||
|
throw new ApiError(`Duplicate bound priority ${input.priority ?? 0}: priorities must be unique within a region`, 400)
|
||||||
|
}
|
||||||
|
const bound = await addRegionBoundInDb(input.regionId, {
|
||||||
|
geojson: input.geojson,
|
||||||
|
name: input.name,
|
||||||
|
description: input.description,
|
||||||
|
priority: input.priority,
|
||||||
|
})
|
||||||
|
return { bound, message: 'Bound added successfully' }
|
||||||
|
}),
|
||||||
|
|
||||||
|
deleteRegionBound: superadminProcedure
|
||||||
|
.input(z.object({ id: z.number() }))
|
||||||
|
.mutation(async ({ input }): Promise<{ message: string }> => {
|
||||||
|
await deleteRegionBoundFromDb(input.id)
|
||||||
|
return { message: 'Bound deleted successfully' }
|
||||||
|
}),
|
||||||
|
});
|
||||||
173
apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts
Normal file
173
apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts
Normal file
|
|
@ -0,0 +1,173 @@
|
||||||
|
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
|
||||||
|
import { z } from 'zod';
|
||||||
|
import bcrypt from 'bcryptjs';
|
||||||
|
import { ApiError } from '@/src/lib/api-error'
|
||||||
|
import {
|
||||||
|
checkStaffUserExists,
|
||||||
|
checkStaffRoleExists,
|
||||||
|
createStaffUser,
|
||||||
|
getAllRoles,
|
||||||
|
getAllStaff,
|
||||||
|
getRegions as getRegionsFromDb,
|
||||||
|
getStaffUserById as getStaffUserByIdFromDb,
|
||||||
|
updateStaffUserInfo as updateStaffUserInfoInDb,
|
||||||
|
deleteStaffUser as deleteStaffUserFromDb,
|
||||||
|
} from '@/src/dbService'
|
||||||
|
import { notifyAllAdmins } from '@/src/lib/admin-notif'
|
||||||
|
|
||||||
|
export const superadminStaffRouter = router({
|
||||||
|
getStaff: superadminProcedure
|
||||||
|
.query(async () => {
|
||||||
|
const [staff, regions] = await Promise.all([getAllStaff(), getRegionsFromDb()]);
|
||||||
|
const regionById = new Map(regions.map((r: any) => [r.id, r.name]));
|
||||||
|
|
||||||
|
return {
|
||||||
|
staff: staff.map((user: any) => ({
|
||||||
|
id: user.id,
|
||||||
|
name: user.name,
|
||||||
|
regionId: user.regionId,
|
||||||
|
regionName: regionById.get(user.regionId) ?? null,
|
||||||
|
roleId: user.role?.id ?? null,
|
||||||
|
roleName: user.role?.roleName ?? null,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
createStaffUser: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
name: z.string().min(1, 'Name is required'),
|
||||||
|
password: z.string().min(6, 'Password must be at least 6 characters'),
|
||||||
|
roleId: z.number().int().positive('Role is required'),
|
||||||
|
regionId: z.number().int().positive('Region is required'),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }) => {
|
||||||
|
const { name, password, roleId, regionId } = input;
|
||||||
|
|
||||||
|
// Check if staff user already exists
|
||||||
|
const existingUser = await checkStaffUserExists(name);
|
||||||
|
|
||||||
|
if (existingUser) {
|
||||||
|
throw new ApiError('Staff user with this name already exists', 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if role exists
|
||||||
|
const roleExists = await checkStaffRoleExists(roleId);
|
||||||
|
|
||||||
|
if (!roleExists) {
|
||||||
|
throw new ApiError('Invalid role selected', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash password
|
||||||
|
const hashedPassword = await bcrypt.hash(password, 12);
|
||||||
|
|
||||||
|
// Create staff user
|
||||||
|
const newUser = await createStaffUser(name, hashedPassword, roleId, regionId);
|
||||||
|
|
||||||
|
return { success: true, user: { id: newUser.id, name: newUser.name, regionId: newUser.regionId } };
|
||||||
|
}),
|
||||||
|
|
||||||
|
getRoles: superadminProcedure
|
||||||
|
.query(async () => {
|
||||||
|
const roles = await getAllRoles();
|
||||||
|
|
||||||
|
return {
|
||||||
|
roles: roles.map((role: any) => ({
|
||||||
|
id: role.id,
|
||||||
|
name: role.roleName,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
|
||||||
|
updateStaffUser: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
id: z.number().int().positive(),
|
||||||
|
name: z.string().min(1, 'Name is required').optional(),
|
||||||
|
roleId: z.number().int().positive().optional(),
|
||||||
|
regionId: z.number().int().positive().optional(),
|
||||||
|
password: z.string().min(6, 'Password must be at least 6 characters').optional(),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }) => {
|
||||||
|
const existing = await getStaffUserByIdFromDb(input.id);
|
||||||
|
if (!existing) {
|
||||||
|
throw new ApiError('Staff user not found', 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.name !== undefined && input.name.trim() !== existing.name) {
|
||||||
|
const taken = await checkStaffUserExists(input.name.trim());
|
||||||
|
if (taken) {
|
||||||
|
throw new ApiError('Staff user with this name already exists', 409);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.roleId !== undefined) {
|
||||||
|
const roleExists = await checkStaffRoleExists(input.roleId);
|
||||||
|
if (!roleExists) {
|
||||||
|
throw new ApiError('Invalid role selected', 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await updateStaffUserInfoInDb(input.id, {
|
||||||
|
name: input.name,
|
||||||
|
roleId: input.roleId,
|
||||||
|
regionId: input.regionId,
|
||||||
|
password: input.password !== undefined ? await bcrypt.hash(input.password, 12) : undefined,
|
||||||
|
});
|
||||||
|
if (!updated) {
|
||||||
|
throw new ApiError('Staff user not found', 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, user: { id: updated.id, name: updated.name, regionId: updated.regionId } };
|
||||||
|
}),
|
||||||
|
|
||||||
|
deleteStaffUser: superadminProcedure
|
||||||
|
.input(z.object({ id: z.number().int().positive() }))
|
||||||
|
.mutation(async ({ input }) => {
|
||||||
|
const existing = await getStaffUserByIdFromDb(input.id);
|
||||||
|
if (!existing) {
|
||||||
|
throw new ApiError('Staff user not found', 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await deleteStaffUserFromDb(input.id);
|
||||||
|
if (!result.deleted) {
|
||||||
|
const { blocker } = result;
|
||||||
|
if (blocker.type === 'stores') {
|
||||||
|
throw new ApiError(
|
||||||
|
`Cannot delete ${existing.name}: they own ${blocker.count} store${blocker.count === 1 ? '' : 's'}. Reassign or remove those stores first.`,
|
||||||
|
409
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (blocker.type === 'coupons') {
|
||||||
|
throw new ApiError(
|
||||||
|
`Cannot delete ${existing.name}: they created ${blocker.count} coupon${blocker.count === 1 ? '' : 's'}. Those coupons keep them as creator.`,
|
||||||
|
409
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw new ApiError(
|
||||||
|
`Cannot delete ${existing.name}: they filed ${blocker.count} user incident report${blocker.count === 1 ? '' : 's'}.`,
|
||||||
|
409
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, message: 'Staff user deleted successfully' };
|
||||||
|
}),
|
||||||
|
|
||||||
|
sendAdminNotification: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
title: z.string().min(1, 'Title is required'),
|
||||||
|
text: z.string().min(1, 'Message is required'),
|
||||||
|
imageUrl: z.string().optional(),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }) => {
|
||||||
|
const { title, text, imageUrl } = input;
|
||||||
|
|
||||||
|
const queuedCount = await notifyAllAdmins({
|
||||||
|
title,
|
||||||
|
body: text,
|
||||||
|
imageUrl: imageUrl || null,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: `Notification queued for ${queuedCount} admins`,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
});
|
||||||
172
apps/backend/src/trpc/apis/superadmin-apis/apis/store.ts
Normal file
172
apps/backend/src/trpc/apis/superadmin-apis/apis/store.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { ApiError } from '@/src/lib/api-error'
|
||||||
|
import { extractKeyFromPresignedUrl, deleteImageUtil, scaffoldAssetUrl } from '@/src/lib/s3-client'
|
||||||
|
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
|
||||||
|
import {
|
||||||
|
getAllStores as getAllStoresFromDb,
|
||||||
|
getStoreById as getStoreByIdFromDb,
|
||||||
|
createStore as createStoreInDb,
|
||||||
|
updateStore as updateStoreInDb,
|
||||||
|
deleteStore as deleteStoreFromDb,
|
||||||
|
} from '@/src/dbService'
|
||||||
|
import type { Store } from '@packages/shared'
|
||||||
|
|
||||||
|
export const superadminStoreRouter = router({
|
||||||
|
getStores: superadminProcedure
|
||||||
|
.query(async (): Promise<{ stores: any[]; count: number }> => {
|
||||||
|
const stores = await getAllStoresFromDb(undefined);
|
||||||
|
|
||||||
|
await Promise.all(stores.map(async store => {
|
||||||
|
if(store.imageUrl)
|
||||||
|
store.imageUrl = scaffoldAssetUrl(store.imageUrl)
|
||||||
|
})).catch((e) => {
|
||||||
|
throw new ApiError("Unable to find store image urls")
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
stores,
|
||||||
|
count: stores.length,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
|
||||||
|
getStoreById: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
id: z.number(),
|
||||||
|
}))
|
||||||
|
.query(async ({ input }): Promise<{ store: any }> => {
|
||||||
|
const { id } = input;
|
||||||
|
|
||||||
|
const store = await getStoreByIdFromDb(id);
|
||||||
|
|
||||||
|
if (!store) {
|
||||||
|
throw new ApiError("Store not found", 404);
|
||||||
|
}
|
||||||
|
store.imageUrl = scaffoldAssetUrl(store.imageUrl);
|
||||||
|
return {
|
||||||
|
store,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
|
||||||
|
createStore: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
name: z.string().min(1, "Name is required"),
|
||||||
|
description: z.string().optional(),
|
||||||
|
imageUrl: z.string().optional(),
|
||||||
|
owner: z.number().min(1, "Owner is required"),
|
||||||
|
products: z.array(z.number()).optional(),
|
||||||
|
// Home region. Omitted (with availableInAllRegions) = all-region store.
|
||||||
|
regionId: z.number().int().positive().nullable().optional(),
|
||||||
|
availableInAllRegions: z.boolean().optional(),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }): Promise<{ store: Store; message: string }> => {
|
||||||
|
const { name, description, imageUrl, owner, products, availableInAllRegions } = input;
|
||||||
|
const regionId = availableInAllRegions ? null : (input.regionId ?? null);
|
||||||
|
|
||||||
|
if (!availableInAllRegions && regionId == null) {
|
||||||
|
throw new ApiError("Region is required for region-exclusive stores", 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const imageKey = imageUrl ? extractKeyFromPresignedUrl(imageUrl) : undefined;
|
||||||
|
|
||||||
|
const newStore = await createStoreInDb(
|
||||||
|
{
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
imageUrl: imageKey,
|
||||||
|
owner,
|
||||||
|
regionId,
|
||||||
|
availableInAllRegions: availableInAllRegions ?? false,
|
||||||
|
},
|
||||||
|
products
|
||||||
|
);
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await scheduleStoreInitialization()
|
||||||
|
|
||||||
|
return {
|
||||||
|
store: newStore,
|
||||||
|
message: "Store created successfully",
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
|
||||||
|
updateStore: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string().min(1, "Name is required"),
|
||||||
|
description: z.string().optional(),
|
||||||
|
imageUrl: z.string().optional(),
|
||||||
|
owner: z.number().min(1, "Owner is required"),
|
||||||
|
products: z.array(z.number()).optional(),
|
||||||
|
regionId: z.number().int().positive().nullable().optional(),
|
||||||
|
availableInAllRegions: z.boolean().optional(),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }): Promise<{ store: Store; message: string }> => {
|
||||||
|
const { id, name, description, imageUrl, owner, products, availableInAllRegions } = input;
|
||||||
|
|
||||||
|
const existingStore = await getStoreByIdFromDb(id);
|
||||||
|
|
||||||
|
if (!existingStore) {
|
||||||
|
throw new ApiError("Store not found", 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
const regionId = availableInAllRegions ? null : (input.regionId ?? existingStore.regionId ?? null);
|
||||||
|
if (!availableInAllRegions && regionId == null) {
|
||||||
|
throw new ApiError("Region is required for region-exclusive stores", 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldImageKey = existingStore.imageUrl;
|
||||||
|
const newImageKey = imageUrl ? extractKeyFromPresignedUrl(imageUrl) : oldImageKey;
|
||||||
|
|
||||||
|
// Delete old image only if:
|
||||||
|
// 1. New image provided and keys are different, OR
|
||||||
|
// 2. No new image but old exists (clearing the image)
|
||||||
|
if (oldImageKey && (
|
||||||
|
(newImageKey && newImageKey !== oldImageKey) ||
|
||||||
|
(!newImageKey)
|
||||||
|
)) {
|
||||||
|
try {
|
||||||
|
await deleteImageUtil({keys: [oldImageKey]});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete old image:', error);
|
||||||
|
// Continue with update even if deletion fails
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedStore = await updateStoreInDb(
|
||||||
|
id,
|
||||||
|
{
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
imageUrl: newImageKey,
|
||||||
|
owner,
|
||||||
|
regionId,
|
||||||
|
...(availableInAllRegions !== undefined ? { availableInAllRegions } : {}),
|
||||||
|
},
|
||||||
|
products
|
||||||
|
);
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes
|
||||||
|
await scheduleStoreInitialization()
|
||||||
|
|
||||||
|
return {
|
||||||
|
store: updatedStore,
|
||||||
|
message: "Store updated successfully",
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
|
||||||
|
deleteStore: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
storeId: z.number(),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }): Promise<{ message: string }> => {
|
||||||
|
const { storeId } = input;
|
||||||
|
|
||||||
|
const result = await deleteStoreFromDb(storeId);
|
||||||
|
|
||||||
|
// Reinitialize stores to reflect changes (outside transaction)
|
||||||
|
await scheduleStoreInitialization()
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,20 @@
|
||||||
|
import { router } from '@/src/trpc/trpc-index'
|
||||||
|
import { superadminAuthRouter } from '@/src/trpc/apis/superadmin-apis/apis/auth'
|
||||||
|
import { superadminRegionRouter } from '@/src/trpc/apis/superadmin-apis/apis/region'
|
||||||
|
import { superadminStaffRouter } from '@/src/trpc/apis/superadmin-apis/apis/staff'
|
||||||
|
import { superadminConstRouter } from '@/src/trpc/apis/superadmin-apis/apis/const'
|
||||||
|
import { superadminStoreRouter } from '@/src/trpc/apis/superadmin-apis/apis/store'
|
||||||
|
import { superadminProductRouter } from '@/src/trpc/apis/superadmin-apis/apis/product'
|
||||||
|
import { superadminUploadRouter } from '@/src/trpc/apis/superadmin-apis/apis/upload'
|
||||||
|
|
||||||
|
export const superadminRouter = router({
|
||||||
|
auth: superadminAuthRouter,
|
||||||
|
region: superadminRegionRouter,
|
||||||
|
staffUser: superadminStaffRouter,
|
||||||
|
const: superadminConstRouter,
|
||||||
|
store: superadminStoreRouter,
|
||||||
|
product: superadminProductRouter,
|
||||||
|
upload: superadminUploadRouter,
|
||||||
|
});
|
||||||
|
|
||||||
|
export type SuperadminRouter = typeof superadminRouter;
|
||||||
56
apps/backend/src/trpc/apis/superadmin-apis/apis/upload.ts
Normal file
56
apps/backend/src/trpc/apis/superadmin-apis/apis/upload.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { ApiError } from '@/src/lib/api-error'
|
||||||
|
import { generateUploadUrl } from '@/src/lib/s3-client'
|
||||||
|
|
||||||
|
export const superadminUploadRouter = router({
|
||||||
|
generateUploadUrls: superadminProcedure
|
||||||
|
.input(z.object({
|
||||||
|
contextString: z.enum(['review', 'review_response', 'product_info', 'notification', 'store', 'complaint', 'profile', 'tags']),
|
||||||
|
mimeTypes: z.array(z.string()),
|
||||||
|
}))
|
||||||
|
.mutation(async ({ input }): Promise<{ uploadUrls: string[] }> => {
|
||||||
|
const { contextString, mimeTypes } = input;
|
||||||
|
|
||||||
|
const uploadUrls: string[] = [];
|
||||||
|
const keys: string[] = [];
|
||||||
|
|
||||||
|
for (const mimeType of mimeTypes) {
|
||||||
|
// Generate key based on context and mime type
|
||||||
|
let folder: string;
|
||||||
|
if (contextString === 'review') {
|
||||||
|
folder = 'review-images';
|
||||||
|
} else if (contextString === 'product_info') {
|
||||||
|
folder = 'product-images';
|
||||||
|
} else if (contextString === 'store') {
|
||||||
|
folder = 'store-images';
|
||||||
|
} else if (contextString === 'review_response') {
|
||||||
|
folder = 'review-response-images';
|
||||||
|
} else if (contextString === 'complaint') {
|
||||||
|
folder = 'complaint-images';
|
||||||
|
} else if (contextString === 'profile') {
|
||||||
|
folder = 'profile-images';
|
||||||
|
} else if (contextString === 'tags') {
|
||||||
|
folder = 'tags';
|
||||||
|
} else {
|
||||||
|
folder = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
const extension = mimeType === 'image/jpeg' ? '.jpg' :
|
||||||
|
mimeType === 'image/png' ? '.png' :
|
||||||
|
mimeType === 'image/gif' ? '.gif' : '.jpg';
|
||||||
|
const key = `${folder}/${Date.now()}${extension}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const uploadUrl = await generateUploadUrl(key, mimeType);
|
||||||
|
uploadUrls.push(uploadUrl);
|
||||||
|
keys.push(key);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error generating upload URL:', error);
|
||||||
|
throw new ApiError('Failed to generate upload URL', 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { uploadUrls };
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
@ -2,6 +2,7 @@ import { router } from '@/src/trpc/trpc-index'
|
||||||
import { adminRouter } from '@/src/trpc/apis/admin-apis/apis/admin-trpc-index'
|
import { adminRouter } from '@/src/trpc/apis/admin-apis/apis/admin-trpc-index'
|
||||||
import { userRouter } from '@/src/trpc/apis/user-apis/apis/user-trpc-index'
|
import { userRouter } from '@/src/trpc/apis/user-apis/apis/user-trpc-index'
|
||||||
import { commonApiRouter } from '@/src/trpc/apis/common-apis/common-trpc-index'
|
import { commonApiRouter } from '@/src/trpc/apis/common-apis/common-trpc-index'
|
||||||
|
import { superadminRouter } from '@/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index'
|
||||||
import { scaffoldProducts, scaffoldAvailability } from './apis/common-apis/common';
|
import { scaffoldProducts, scaffoldAvailability } from './apis/common-apis/common';
|
||||||
import { scaffoldStores, scaffoldStoreWithProducts } from './apis/user-apis/apis/stores';
|
import { scaffoldStores, scaffoldStoreWithProducts } from './apis/user-apis/apis/stores';
|
||||||
import { scaffoldSlotsWithProducts } from './apis/user-apis/apis/slots';
|
import { scaffoldSlotsWithProducts } from './apis/user-apis/apis/slots';
|
||||||
|
|
@ -13,6 +14,7 @@ export const appRouter = router({
|
||||||
admin: adminRouter,
|
admin: adminRouter,
|
||||||
user: userRouter,
|
user: userRouter,
|
||||||
common: commonApiRouter,
|
common: commonApiRouter,
|
||||||
|
superadmin: superadminRouter,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,10 @@ export interface Context {
|
||||||
staffRoleId: number | null;
|
staffRoleId: number | null;
|
||||||
staffRoleName: string | null;
|
staffRoleName: string | null;
|
||||||
} | null;
|
} | null;
|
||||||
|
superadmin?: {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
} | null;
|
||||||
callerInterface?: string | null;
|
callerInterface?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -45,7 +49,7 @@ const errorLoggerMiddleware = middleware(async ({ path, type, next, ctx }) => {
|
||||||
path,
|
path,
|
||||||
type,
|
type,
|
||||||
duration: `${duration}ms`,
|
duration: `${duration}ms`,
|
||||||
userId: ctx?.user?.userId || ctx?.staffUser?.id || 'anonymous',
|
userId: ctx?.user?.userId || ctx?.staffUser?.id || ctx?.superadmin?.id || 'anonymous',
|
||||||
error: {
|
error: {
|
||||||
name: err.name,
|
name: err.name,
|
||||||
message: err.message,
|
message: err.message,
|
||||||
|
|
@ -91,6 +95,23 @@ export const adminProcedure = t.procedure.use(errorLoggerMiddleware).use(
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Superadmin-only. Requires an authenticated superadmin (superadmins table,
|
||||||
|
// superadmin.* scope) — distinct from superAdminProcedure below, which gates
|
||||||
|
// the super_admin *role* on staff_users rows for the admin.* scope.
|
||||||
|
export const superadminProcedure = t.procedure.use(errorLoggerMiddleware).use(
|
||||||
|
middleware(async ({ ctx, next }) => {
|
||||||
|
if (!ctx.superadmin) {
|
||||||
|
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Superadmin authentication required' });
|
||||||
|
}
|
||||||
|
return next({
|
||||||
|
ctx: {
|
||||||
|
...ctx,
|
||||||
|
superadmin: ctx.superadmin,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
// Superadmin-only. Requires an authenticated staff user whose role is super_admin.
|
// Superadmin-only. Requires an authenticated staff user whose role is super_admin.
|
||||||
export const superAdminProcedure = t.procedure.use(errorLoggerMiddleware).use(
|
export const superAdminProcedure = t.procedure.use(errorLoggerMiddleware).use(
|
||||||
middleware(async ({ ctx, next }) => {
|
middleware(async ({ ctx, next }) => {
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,14 @@
|
||||||
import React, { useState } from 'react'
|
import React, { useState } from 'react'
|
||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { LayoutDashboard, Send, Settings2, MapPin, UserPlus, Menu, X, LogOut } from 'lucide-react'
|
import { LayoutDashboard, Send, Settings2, MapPin, UserPlus, Menu, X, LogOut, Store, Package } from 'lucide-react'
|
||||||
import { useAuth } from '../lib/auth-context'
|
import { useAuth } from '../lib/auth-context'
|
||||||
|
|
||||||
const NAV = [
|
const NAV = [
|
||||||
{ to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
{ to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
||||||
{ to: '/admins', label: 'Create Admin', icon: UserPlus },
|
{ to: '/admins', label: 'Admins', icon: UserPlus },
|
||||||
{ to: '/regions', label: 'Regions', icon: MapPin },
|
{ to: '/regions', label: 'Regions', icon: MapPin },
|
||||||
|
{ to: '/stores', label: 'Stores', icon: Store },
|
||||||
|
{ to: '/products', label: 'Products', icon: Package },
|
||||||
{ to: '/send-notifications', label: 'Send Admin Notifications', icon: Send },
|
{ to: '/send-notifications', label: 'Send Admin Notifications', icon: Send },
|
||||||
{ to: '/constants', label: 'App Constants', icon: Settings2 },
|
{ to: '/constants', label: 'App Constants', icon: Settings2 },
|
||||||
] as const
|
] as const
|
||||||
|
|
|
||||||
154
apps/superadmin-ui/src/components/MultiSelect.tsx
Normal file
154
apps/superadmin-ui/src/components/MultiSelect.tsx
Normal file
|
|
@ -0,0 +1,154 @@
|
||||||
|
import { useMemo, useState } from 'react'
|
||||||
|
import { BottomDialog, Checkbox, SearchBar, p as P } from 'web-components'
|
||||||
|
import { Check, ChevronDown } from 'lucide-react'
|
||||||
|
|
||||||
|
export interface MultiSelectOption {
|
||||||
|
label: string
|
||||||
|
value: string | number
|
||||||
|
disabled?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MultiSelectProps {
|
||||||
|
label?: string
|
||||||
|
topLabel?: string
|
||||||
|
options: MultiSelectOption[]
|
||||||
|
value: (string | number)[]
|
||||||
|
onValueChange: (v: (string | number)[]) => void
|
||||||
|
placeholder?: string
|
||||||
|
disabled?: boolean
|
||||||
|
onSearch?: (q: string) => void
|
||||||
|
error?: boolean
|
||||||
|
className?: string
|
||||||
|
testID?: string
|
||||||
|
// Tolerated for screen compatibility (RN BottomDropdown leftovers) — ignored on web
|
||||||
|
multiple?: boolean
|
||||||
|
triggerComponent?: any
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MultiSelect({
|
||||||
|
label,
|
||||||
|
topLabel,
|
||||||
|
options,
|
||||||
|
value,
|
||||||
|
onValueChange,
|
||||||
|
placeholder,
|
||||||
|
disabled = false,
|
||||||
|
onSearch,
|
||||||
|
error = false,
|
||||||
|
className,
|
||||||
|
testID,
|
||||||
|
}: MultiSelectProps) {
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
|
||||||
|
const selectedSet = useMemo(() => new Set(value.map((v) => String(v))), [value])
|
||||||
|
|
||||||
|
const displayText = useMemo(() => {
|
||||||
|
if (value.length === 0) return placeholder ?? label ?? 'Select...'
|
||||||
|
if (value.length === 1) {
|
||||||
|
const found = options.find((o) => String(o.value) === String(value[0]))
|
||||||
|
return found ? found.label : (placeholder ?? label ?? 'Select...')
|
||||||
|
}
|
||||||
|
return `${value.length} selected`
|
||||||
|
}, [value, options, placeholder, label])
|
||||||
|
|
||||||
|
const filtered = useMemo(() => {
|
||||||
|
const q = query.trim().toLowerCase()
|
||||||
|
if (!q) return options
|
||||||
|
return options.filter((o) => o.label.toLowerCase().includes(q))
|
||||||
|
}, [options, query])
|
||||||
|
|
||||||
|
const toggle = (optionValue: string | number) => {
|
||||||
|
const key = String(optionValue)
|
||||||
|
if (selectedSet.has(key)) {
|
||||||
|
onValueChange(value.filter((v) => String(v) !== key))
|
||||||
|
} else {
|
||||||
|
onValueChange([...value, optionValue])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const heading = topLabel ?? label
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={className} data-testid={testID}>
|
||||||
|
{heading ? (
|
||||||
|
<P className="mb-1 text-sm text-gray-500 font-medium">{heading}</P>
|
||||||
|
) : null}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => setOpen(true)}
|
||||||
|
className={`flex w-full items-center justify-between rounded-md border bg-white px-3 py-2 text-sm text-left disabled:cursor-not-allowed disabled:opacity-50 ${error ? 'border-red-500' : 'border-gray-300'}`}
|
||||||
|
>
|
||||||
|
<span className={`truncate ${value.length === 0 ? 'text-gray-400' : 'text-gray-800'}`}>
|
||||||
|
{displayText}
|
||||||
|
</span>
|
||||||
|
<ChevronDown className="h-4 w-4 shrink-0 text-gray-400" />
|
||||||
|
</button>
|
||||||
|
<BottomDialog open={open} onClose={() => setOpen(false)}>
|
||||||
|
<div className="p-4">
|
||||||
|
<P className="text-lg font-semibold mb-4">{heading ?? placeholder ?? 'Select'}</P>
|
||||||
|
<SearchBar
|
||||||
|
placeholder="Search..."
|
||||||
|
value={query}
|
||||||
|
onChange={(q) => {
|
||||||
|
setQuery(q)
|
||||||
|
onSearch?.(q)
|
||||||
|
}}
|
||||||
|
onSearch={onSearch}
|
||||||
|
className="mb-3"
|
||||||
|
testID={testID ? `${testID}-search` : undefined}
|
||||||
|
/>
|
||||||
|
<div className="overflow-y-auto" style={{ maxHeight: 320 }}>
|
||||||
|
{filtered.map((option) => {
|
||||||
|
const checked = selectedSet.has(String(option.value))
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={String(option.value)}
|
||||||
|
data-testid={testID ? `${testID}-option-${option.value}` : undefined}
|
||||||
|
onClick={() => {
|
||||||
|
if (!option.disabled) toggle(option.value)
|
||||||
|
}}
|
||||||
|
className={`flex flex-row items-center p-3 border-b border-gray-100 ${option.disabled ? 'opacity-50' : 'cursor-pointer hover:bg-gray-50'}`}
|
||||||
|
>
|
||||||
|
<span onClick={(e) => e.stopPropagation()}>
|
||||||
|
<Checkbox
|
||||||
|
checked={checked}
|
||||||
|
onPress={() => {
|
||||||
|
if (!option.disabled) toggle(option.value)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
<span className="ml-3 text-sm text-gray-800 flex-1">{option.label}</span>
|
||||||
|
{checked ? <Check className="h-4 w-4 text-blue-600" /> : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
{filtered.length === 0 ? (
|
||||||
|
<P className="text-center text-gray-500 text-sm p-4">No options found</P>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-row gap-2 mt-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onValueChange([])}
|
||||||
|
className="flex-1 p-3 rounded-lg bg-gray-100 text-gray-700 text-center font-semibold text-sm"
|
||||||
|
>
|
||||||
|
Clear
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
data-testid={testID ? `${testID}-done` : undefined}
|
||||||
|
className="flex-1 p-3 rounded-lg bg-blue-500 text-white text-center font-semibold text-sm"
|
||||||
|
>
|
||||||
|
Done
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</BottomDialog>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default MultiSelect
|
||||||
1049
apps/superadmin-ui/src/components/ProductForm.tsx
Normal file
1049
apps/superadmin-ui/src/components/ProductForm.tsx
Normal file
File diff suppressed because it is too large
Load diff
181
apps/superadmin-ui/src/components/ProductsSelector.tsx
Normal file
181
apps/superadmin-ui/src/components/ProductsSelector.tsx
Normal file
|
|
@ -0,0 +1,181 @@
|
||||||
|
import React, { useState, useMemo } from 'react'
|
||||||
|
import { trpc } from '@/lib/trpc-client'
|
||||||
|
import type { SkuSummary as SharedSkuSummary } from '@packages/shared'
|
||||||
|
import MultiSelect from './MultiSelect'
|
||||||
|
import SearchableSelect from './SearchableSelect'
|
||||||
|
|
||||||
|
// Selector works with skus that may not have images resolved yet
|
||||||
|
type SkuSummary = Omit<SharedSkuSummary, 'images'>
|
||||||
|
|
||||||
|
interface Group {
|
||||||
|
id: number
|
||||||
|
groupName: string
|
||||||
|
products: { id: number }[]
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProductsSelectorProps {
|
||||||
|
value: number | number[]
|
||||||
|
onChange: (value: number | number[]) => void
|
||||||
|
multiple?: boolean
|
||||||
|
label?: string
|
||||||
|
placeholder?: string
|
||||||
|
disabled?: boolean
|
||||||
|
error?: boolean
|
||||||
|
isDisabled?: (product: SkuSummary) => boolean
|
||||||
|
labelFormat?: (product: SkuSummary) => string
|
||||||
|
groups?: Group[]
|
||||||
|
selectedGroupIds?: number[]
|
||||||
|
onGroupChange?: (groupIds: number[]) => void
|
||||||
|
showGroups?: boolean
|
||||||
|
testID?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ProductsSelector({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
multiple = true,
|
||||||
|
label = 'Select Products',
|
||||||
|
placeholder = 'Select products',
|
||||||
|
disabled = false,
|
||||||
|
error = false,
|
||||||
|
isDisabled,
|
||||||
|
labelFormat,
|
||||||
|
groups = [],
|
||||||
|
showGroups = true,
|
||||||
|
selectedGroupIds = [],
|
||||||
|
onGroupChange,
|
||||||
|
testID,
|
||||||
|
}: ProductsSelectorProps) {
|
||||||
|
const { data: skusData } = trpc.superadmin.product.getAllSkusSummary.useQuery()
|
||||||
|
const allSkus: SkuSummary[] = skusData?.skus || []
|
||||||
|
const [searchQuery, setSearchQuery] = useState('')
|
||||||
|
|
||||||
|
// Handle group selection changes
|
||||||
|
const handleGroupChange = (newGroupIds: number[]) => {
|
||||||
|
if (!onGroupChange) return
|
||||||
|
|
||||||
|
const previousGroupIds = selectedGroupIds
|
||||||
|
|
||||||
|
const addedGroups = newGroupIds.filter(id => !previousGroupIds.includes(id))
|
||||||
|
const removedGroups = previousGroupIds.filter(id => !newGroupIds.includes(id))
|
||||||
|
|
||||||
|
let currentSkus = Array.isArray(value) ? [...value] : value ? [value] : []
|
||||||
|
|
||||||
|
const addedSkus = addedGroups.flatMap(groupId => {
|
||||||
|
const group = groups.find(g => g.id === groupId)
|
||||||
|
if (!group) return []
|
||||||
|
const productIds = new Set(group.products.map(p => p.id))
|
||||||
|
return allSkus.filter(s => productIds.has(s.productId)).map(s => s.id)
|
||||||
|
})
|
||||||
|
|
||||||
|
const removedSkus = removedGroups.flatMap(groupId => {
|
||||||
|
const group = groups.find(g => g.id === groupId)
|
||||||
|
if (!group) return []
|
||||||
|
const productIds = new Set(group.products.map(p => p.id))
|
||||||
|
return allSkus.filter(s => productIds.has(s.productId)).map(s => s.id)
|
||||||
|
})
|
||||||
|
|
||||||
|
currentSkus = [...new Set([...currentSkus, ...addedSkus])]
|
||||||
|
currentSkus = currentSkus.filter(id => !removedSkus.includes(id))
|
||||||
|
|
||||||
|
onGroupChange(newGroupIds)
|
||||||
|
if (multiple) {
|
||||||
|
onChange(currentSkus.length > 0 ? currentSkus : [])
|
||||||
|
} else {
|
||||||
|
onChange(currentSkus.length > 0 ? currentSkus[0] : 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filter products based on search query
|
||||||
|
const filteredSkus = useMemo(() => {
|
||||||
|
if (!searchQuery.trim()) return allSkus
|
||||||
|
|
||||||
|
const query = searchQuery.toLowerCase()
|
||||||
|
return allSkus.filter(sku =>
|
||||||
|
sku.label.toLowerCase().includes(query) ||
|
||||||
|
sku.productName.toLowerCase().includes(query)
|
||||||
|
)
|
||||||
|
}, [allSkus, searchQuery])
|
||||||
|
|
||||||
|
// Build dropdown options
|
||||||
|
const productOptions = useMemo(() => {
|
||||||
|
return filteredSkus.map((sku) => {
|
||||||
|
const isFromGroup = selectedGroupIds.length > 0 && groups.some(group => {
|
||||||
|
if (!selectedGroupIds.includes(group.id)) return false
|
||||||
|
return group.products.some(p => p.id === sku.productId)
|
||||||
|
})
|
||||||
|
|
||||||
|
const isProductDisabled = isDisabled ? isDisabled(sku) : false
|
||||||
|
|
||||||
|
const displayLabel = labelFormat
|
||||||
|
? labelFormat(sku)
|
||||||
|
: sku.label
|
||||||
|
|
||||||
|
return {
|
||||||
|
label: `${displayLabel}${isFromGroup ? ' (from group)' : ''}`,
|
||||||
|
value: sku.id.toString(),
|
||||||
|
disabled: isProductDisabled,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}, [filteredSkus, selectedGroupIds, groups, isDisabled, labelFormat])
|
||||||
|
|
||||||
|
// Build group options if groups are provided
|
||||||
|
const groupOptions = useMemo(() => {
|
||||||
|
return groups.map(group => ({
|
||||||
|
label: group.groupName,
|
||||||
|
value: group.id.toString(),
|
||||||
|
}))
|
||||||
|
}, [groups])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="w-full">
|
||||||
|
{showGroups && groups.length > 0 && (
|
||||||
|
<div className="mb-4">
|
||||||
|
<MultiSelect
|
||||||
|
testID="product-groups-dropdown"
|
||||||
|
label="Select Product Groups"
|
||||||
|
options={groupOptions}
|
||||||
|
value={selectedGroupIds.map(id => id.toString())}
|
||||||
|
onValueChange={(selectedValue) => {
|
||||||
|
const selectedValues = Array.isArray(selectedValue) ? selectedValue : typeof selectedValue === 'string' ? [selectedValue] : []
|
||||||
|
const newGroupIds = selectedValues.map(v => parseInt(v as string))
|
||||||
|
handleGroupChange(newGroupIds)
|
||||||
|
}}
|
||||||
|
placeholder="Select product groups (optional)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{multiple ? (
|
||||||
|
<MultiSelect
|
||||||
|
label={label}
|
||||||
|
testID={testID}
|
||||||
|
options={productOptions}
|
||||||
|
value={Array.isArray(value) ? value.map(id => id.toString()) : []}
|
||||||
|
onValueChange={(selectedValue) => {
|
||||||
|
const selectedValues = Array.isArray(selectedValue) ? selectedValue : typeof selectedValue === 'string' ? [selectedValue] : []
|
||||||
|
onChange(selectedValues.map(v => Number(v)))
|
||||||
|
}}
|
||||||
|
placeholder={placeholder}
|
||||||
|
disabled={disabled}
|
||||||
|
error={error}
|
||||||
|
onSearch={setSearchQuery}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<SearchableSelect
|
||||||
|
label={label}
|
||||||
|
testID={testID}
|
||||||
|
options={productOptions}
|
||||||
|
value={value ? value.toString() : ''}
|
||||||
|
onValueChange={(selectedValue) => {
|
||||||
|
onChange(Number(selectedValue))
|
||||||
|
}}
|
||||||
|
placeholder={placeholder}
|
||||||
|
disabled={disabled}
|
||||||
|
error={error}
|
||||||
|
onSearch={setSearchQuery}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
116
apps/superadmin-ui/src/components/SearchableSelect.tsx
Normal file
116
apps/superadmin-ui/src/components/SearchableSelect.tsx
Normal file
|
|
@ -0,0 +1,116 @@
|
||||||
|
import { useMemo, useState } from 'react'
|
||||||
|
import { BottomDialog, SearchBar, p as P } from 'web-components'
|
||||||
|
import { Check, ChevronDown } from 'lucide-react'
|
||||||
|
|
||||||
|
export interface SearchableSelectOption {
|
||||||
|
label: string
|
||||||
|
value: string | number
|
||||||
|
disabled?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SearchableSelectProps {
|
||||||
|
label: string
|
||||||
|
options: SearchableSelectOption[]
|
||||||
|
value: string | number
|
||||||
|
onValueChange: (v: string | number) => void
|
||||||
|
onSearch?: (q: string) => void
|
||||||
|
placeholder?: string
|
||||||
|
disabled?: boolean
|
||||||
|
error?: boolean
|
||||||
|
className?: string
|
||||||
|
testID?: string
|
||||||
|
// Tolerated for screen compatibility (RN BottomDropdown leftover) — ignored on web
|
||||||
|
triggerComponent?: any
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SearchableSelect({
|
||||||
|
label,
|
||||||
|
options,
|
||||||
|
value,
|
||||||
|
onValueChange,
|
||||||
|
onSearch,
|
||||||
|
placeholder,
|
||||||
|
disabled = false,
|
||||||
|
error = false,
|
||||||
|
className,
|
||||||
|
testID,
|
||||||
|
}: SearchableSelectProps) {
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
|
||||||
|
const selectedLabel = useMemo(() => {
|
||||||
|
const found = options.find((o) => String(o.value) === String(value))
|
||||||
|
return found ? found.label : null
|
||||||
|
}, [options, value])
|
||||||
|
|
||||||
|
const displayText = selectedLabel ?? placeholder ?? label
|
||||||
|
|
||||||
|
const filtered = useMemo(() => {
|
||||||
|
const q = query.trim().toLowerCase()
|
||||||
|
if (!q) return options
|
||||||
|
return options.filter((o) => o.label.toLowerCase().includes(q))
|
||||||
|
}, [options, query])
|
||||||
|
|
||||||
|
const handleSelect = (optionValue: string | number) => {
|
||||||
|
onValueChange(optionValue)
|
||||||
|
setOpen(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={className} data-testid={testID}>
|
||||||
|
<P className="mb-1 text-sm text-gray-500 font-medium">{label}</P>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => setOpen(true)}
|
||||||
|
className={`flex w-full items-center justify-between rounded-md border bg-white px-3 py-2 text-sm text-left disabled:cursor-not-allowed disabled:opacity-50 ${error ? 'border-red-500' : 'border-gray-300'}`}
|
||||||
|
>
|
||||||
|
<span className={`truncate ${selectedLabel ? 'text-gray-800' : 'text-gray-400'}`}>
|
||||||
|
{displayText}
|
||||||
|
</span>
|
||||||
|
<ChevronDown className="h-4 w-4 shrink-0 text-gray-400" />
|
||||||
|
</button>
|
||||||
|
<BottomDialog open={open} onClose={() => setOpen(false)}>
|
||||||
|
<div className="p-4">
|
||||||
|
<P className="text-lg font-semibold mb-4">{label}</P>
|
||||||
|
<SearchBar
|
||||||
|
placeholder="Search..."
|
||||||
|
value={query}
|
||||||
|
onChange={(q) => {
|
||||||
|
setQuery(q)
|
||||||
|
onSearch?.(q)
|
||||||
|
}}
|
||||||
|
onSearch={onSearch}
|
||||||
|
className="mb-3"
|
||||||
|
testID={testID ? `${testID}-search` : undefined}
|
||||||
|
/>
|
||||||
|
<div className="overflow-y-auto" style={{ maxHeight: 320 }}>
|
||||||
|
{filtered.map((option) => {
|
||||||
|
const selected = String(option.value) === String(value)
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={String(option.value)}
|
||||||
|
type="button"
|
||||||
|
disabled={option.disabled}
|
||||||
|
onClick={() => handleSelect(option.value)}
|
||||||
|
data-testid={testID ? `${testID}-option-${option.value}` : undefined}
|
||||||
|
className={`flex flex-row items-center w-full p-3 border-b border-gray-100 text-left ${option.disabled ? 'opacity-50' : 'cursor-pointer hover:bg-gray-50'} ${selected ? 'bg-blue-50' : ''}`}
|
||||||
|
>
|
||||||
|
<span className={`text-sm flex-1 ${selected ? 'font-semibold text-blue-700' : 'text-gray-800'}`}>
|
||||||
|
{option.label}
|
||||||
|
</span>
|
||||||
|
{selected ? <Check className="h-4 w-4 text-blue-600" /> : null}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
{filtered.length === 0 ? (
|
||||||
|
<P className="text-center text-gray-500 text-sm p-4">No options found</P>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</BottomDialog>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SearchableSelect
|
||||||
235
apps/superadmin-ui/src/components/StoreForm.tsx
Normal file
235
apps/superadmin-ui/src/components/StoreForm.tsx
Normal file
|
|
@ -0,0 +1,235 @@
|
||||||
|
import { useState, useEffect, useMemo, useRef, type ChangeEvent } from 'react'
|
||||||
|
import { Formik } from 'formik'
|
||||||
|
import * as Yup from 'yup'
|
||||||
|
import { pInput as PInput, Dropdown, p as P, ImageUploader, Checkbox } from 'web-components'
|
||||||
|
import ProductsSelector from './ProductsSelector'
|
||||||
|
import { trpc } from '@/lib/trpc-client'
|
||||||
|
import { useUploadToObjectStorage } from '../hooks/useUploadToObjectStorage'
|
||||||
|
import type { CreateStoreInput } from '@packages/shared'
|
||||||
|
|
||||||
|
// Store form values — required description + product selection on top of CreateStoreInput
|
||||||
|
export type StoreFormData = Omit<CreateStoreInput, 'description'> & {
|
||||||
|
description: string
|
||||||
|
products: number[]
|
||||||
|
regionId?: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StoreFormProps {
|
||||||
|
mode: 'create' | 'edit'
|
||||||
|
initialValues: StoreFormData
|
||||||
|
onSubmit: (values: StoreFormData) => void
|
||||||
|
isLoading: boolean
|
||||||
|
storeId?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const validationSchema = Yup.object().shape({
|
||||||
|
name: Yup.string().required('Name is required'),
|
||||||
|
description: Yup.string(),
|
||||||
|
imageUrl: Yup.string(),
|
||||||
|
owner: Yup.number().required('Owner is required'),
|
||||||
|
products: Yup.array().of(Yup.number()),
|
||||||
|
regionId: Yup.number().when('availableInAllRegions', {
|
||||||
|
is: false,
|
||||||
|
then: (schema) => schema.required('Region is required').min(1, 'Region is required'),
|
||||||
|
otherwise: (schema) => schema.notRequired().nullable(),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreFormProps) {
|
||||||
|
const { data: staffData } = trpc.superadmin.staffUser.getStaff.useQuery()
|
||||||
|
const { data: productsData } = trpc.superadmin.product.getProducts.useQuery()
|
||||||
|
const { data: regionsData } = trpc.superadmin.region.getRegions.useQuery(undefined, { staleTime: Infinity })
|
||||||
|
const regions = (regionsData as any)?.regions ?? []
|
||||||
|
|
||||||
|
const [formInitialValues, setFormInitialValues] = useState<StoreFormData>(initialValues)
|
||||||
|
const [selectedImages, setSelectedImages] = useState<{ blob: Blob; mimeType: string }[]>([])
|
||||||
|
const [displayImages, setDisplayImages] = useState<{ uri?: string }[]>([])
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
|
// For edit mode, pre-select SKUs belonging to this store's products
|
||||||
|
const initialSelectedProducts = useMemo(() => {
|
||||||
|
if (mode !== 'edit' || !productsData?.products) return []
|
||||||
|
return productsData.products
|
||||||
|
.filter(p => p.store?.id === storeId)
|
||||||
|
.flatMap(p => (p.skus || []).map(sku => sku.id))
|
||||||
|
}, [mode, productsData?.products, storeId])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setFormInitialValues({
|
||||||
|
...initialValues,
|
||||||
|
products: initialSelectedProducts,
|
||||||
|
})
|
||||||
|
}, [initialValues, initialSelectedProducts])
|
||||||
|
|
||||||
|
const existingImageUrls = useMemo(
|
||||||
|
() => (formInitialValues.imageUrl ? [formInitialValues.imageUrl] : []),
|
||||||
|
[formInitialValues.imageUrl]
|
||||||
|
)
|
||||||
|
|
||||||
|
const staffOptions = staffData?.staff.map((staff: { id: number; name: string }) => ({
|
||||||
|
label: staff.name,
|
||||||
|
value: staff.id,
|
||||||
|
})) || []
|
||||||
|
|
||||||
|
const { uploadSingle, isUploading } = useUploadToObjectStorage()
|
||||||
|
|
||||||
|
const handleImagePick = () => {
|
||||||
|
fileInputRef.current?.click()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const files = Array.from(e.target.files || [])
|
||||||
|
if (files.length === 0) {
|
||||||
|
setSelectedImages([])
|
||||||
|
setDisplayImages([])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const file = files[0]
|
||||||
|
setSelectedImages([{ blob: file, mimeType: file.type || 'image/jpeg' }])
|
||||||
|
setDisplayImages([{ uri: URL.createObjectURL(file) }])
|
||||||
|
e.target.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRemoveImage = (uri: string) => {
|
||||||
|
const index = displayImages.findIndex(img => img.uri === uri)
|
||||||
|
if (index !== -1) {
|
||||||
|
const newDisplay = displayImages.filter((_, i) => i !== index)
|
||||||
|
const newFiles = selectedImages.filter((_, i) => i !== index)
|
||||||
|
setDisplayImages(newDisplay)
|
||||||
|
setSelectedImages(newFiles)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Formik
|
||||||
|
initialValues={formInitialValues}
|
||||||
|
validationSchema={validationSchema}
|
||||||
|
onSubmit={onSubmit}
|
||||||
|
enableReinitialize
|
||||||
|
>
|
||||||
|
{({ handleChange, handleSubmit, values, setFieldValue, errors, touched }) => {
|
||||||
|
const submit = async () => {
|
||||||
|
try {
|
||||||
|
let imageUrl: string | undefined
|
||||||
|
|
||||||
|
if (selectedImages.length > 0) {
|
||||||
|
const { blob, mimeType } = selectedImages[0]
|
||||||
|
const { presignedUrl } = await uploadSingle(blob, mimeType, 'store')
|
||||||
|
imageUrl = presignedUrl
|
||||||
|
}
|
||||||
|
|
||||||
|
onSubmit({ ...values, imageUrl })
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Upload error:', error)
|
||||||
|
window.alert('Error: Failed to upload image')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept="image/*"
|
||||||
|
onChange={handleFileChange}
|
||||||
|
className="hidden"
|
||||||
|
/>
|
||||||
|
<PInput
|
||||||
|
topLabel="Store Name"
|
||||||
|
placeholder="Enter store name"
|
||||||
|
value={values.name}
|
||||||
|
onChange={handleChange('name')}
|
||||||
|
error={!!(touched.name && errors.name)}
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
data-testid="store-name-input"
|
||||||
|
/>
|
||||||
|
<PInput
|
||||||
|
topLabel="Description"
|
||||||
|
placeholder="Enter store description"
|
||||||
|
multiline
|
||||||
|
numberOfLines={3}
|
||||||
|
value={values.description}
|
||||||
|
onChange={handleChange('description')}
|
||||||
|
error={!!(touched.description && errors.description)}
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
data-testid="store-description-input"
|
||||||
|
/>
|
||||||
|
<div className="mb-4">
|
||||||
|
<P className="mb-1 text-sm text-gray-500 font-medium">Owner</P>
|
||||||
|
<Dropdown
|
||||||
|
label="Select owner"
|
||||||
|
value={values.owner}
|
||||||
|
options={staffOptions}
|
||||||
|
onValueChange={(value) => setFieldValue('owner', Number(value))}
|
||||||
|
className="mb-4"
|
||||||
|
testID="store-owner-dropdown"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-row items-center mb-4">
|
||||||
|
<Checkbox
|
||||||
|
checked={!!values.availableInAllRegions}
|
||||||
|
onPress={() => {
|
||||||
|
const next = !values.availableInAllRegions
|
||||||
|
setFieldValue('availableInAllRegions', next)
|
||||||
|
if (next) setFieldValue('regionId', null)
|
||||||
|
}}
|
||||||
|
testID="store-all-regions-checkbox"
|
||||||
|
/>
|
||||||
|
<P className="text-gray-700 font-medium ml-3">Available in all regions</P>
|
||||||
|
</div>
|
||||||
|
{!values.availableInAllRegions && (
|
||||||
|
<div className="mb-4">
|
||||||
|
<P className="mb-1 text-sm text-gray-500 font-medium">Home Region</P>
|
||||||
|
<Dropdown
|
||||||
|
label="Select home region"
|
||||||
|
value={(values as StoreFormData).regionId ?? ''}
|
||||||
|
options={regions.map((r: any) => ({ label: r.name, value: r.id }))}
|
||||||
|
onValueChange={(value) => setFieldValue('regionId', Number(value))}
|
||||||
|
className="mb-4"
|
||||||
|
testID="store-region-dropdown"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<ProductsSelector
|
||||||
|
value={values.products || []}
|
||||||
|
onChange={(value) => setFieldValue('products', value)}
|
||||||
|
multiple={true}
|
||||||
|
label="Products"
|
||||||
|
placeholder="Select products"
|
||||||
|
isDisabled={(sku) => sku.storeId !== null && sku.storeId !== storeId}
|
||||||
|
labelFormat={(sku) => `${sku.productName} - ₹${sku.price}`}
|
||||||
|
testID="store-products-selector"
|
||||||
|
/>
|
||||||
|
<div className="mb-6">
|
||||||
|
<P className="text-sm font-bold text-gray-700 mb-3 uppercase tracking-wider block">Store Image</P>
|
||||||
|
<ImageUploader
|
||||||
|
images={displayImages}
|
||||||
|
existingImageUrls={existingImageUrls}
|
||||||
|
onAddImage={handleImagePick}
|
||||||
|
onRemoveImage={handleRemoveImage}
|
||||||
|
onRemoveExistingImage={() =>
|
||||||
|
setFormInitialValues((prev) => ({
|
||||||
|
...prev,
|
||||||
|
imageUrl: undefined,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
allowMultiple={false}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={submit}
|
||||||
|
disabled={isLoading || isUploading}
|
||||||
|
data-testid="store-submit-button"
|
||||||
|
className={`px-4 py-2 rounded-lg shadow-lg items-center mt-2 text-white text-lg font-bold w-full disabled:opacity-70 ${isLoading || isUploading ? 'bg-gray-400' : 'bg-blue-500'}`}
|
||||||
|
>
|
||||||
|
{isUploading ? 'Uploading...' : isLoading ? (mode === 'create' ? 'Creating...' : 'Updating...') : (mode === 'create' ? 'Create Store' : 'Update Store')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
</Formik>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default StoreForm
|
||||||
105
apps/superadmin-ui/src/hooks/useUploadToObjectStorage.ts
Normal file
105
apps/superadmin-ui/src/hooks/useUploadToObjectStorage.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import type { ContextString, UploadInput, UploadBatchInput, UploadResult } from '@packages/shared'
|
||||||
|
|
||||||
|
// Verbatim port of admin-ui useUploadToObjectStore (trpc import path only).
|
||||||
|
export function useUploadToObjectStorage() {
|
||||||
|
const [isUploading, setIsUploading] = useState(false)
|
||||||
|
const [error, setError] = useState<Error | null>(null)
|
||||||
|
const [progress, setProgress] = useState<{ completed: number; total: number } | null>(null)
|
||||||
|
|
||||||
|
const generateUploadUrls = trpc.superadmin.upload.generateUploadUrls.useMutation()
|
||||||
|
|
||||||
|
const upload = async (input: UploadBatchInput): Promise<UploadResult> => {
|
||||||
|
setIsUploading(true)
|
||||||
|
setError(null)
|
||||||
|
setProgress({ completed: 0, total: input.images.length })
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { images, contextString } = input
|
||||||
|
|
||||||
|
if (images.length === 0) {
|
||||||
|
return { keys: [], presignedUrls: [] }
|
||||||
|
}
|
||||||
|
|
||||||
|
const mimeTypes = images.map((img) => img.mimeType)
|
||||||
|
const { uploadUrls } = await generateUploadUrls.mutateAsync({
|
||||||
|
contextString,
|
||||||
|
mimeTypes,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (uploadUrls.length !== images.length) {
|
||||||
|
throw new Error(`Expected ${images.length} URLs, got ${uploadUrls.length}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const uploadPromises = images.map(async (image, index) => {
|
||||||
|
const presignedUrl = uploadUrls[index]
|
||||||
|
const { blob, mimeType } = image
|
||||||
|
|
||||||
|
const response = await fetch(presignedUrl, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: blob,
|
||||||
|
headers: { 'Content-Type': mimeType },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Upload ${index + 1} failed with status ${response.status}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
setProgress((prev) => (prev ? { ...prev, completed: prev.completed + 1 } : null))
|
||||||
|
|
||||||
|
return {
|
||||||
|
key: extractKeyFromPresignedUrl(presignedUrl),
|
||||||
|
presignedUrl,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const results = await Promise.all(uploadPromises)
|
||||||
|
|
||||||
|
return {
|
||||||
|
keys: results.map((r) => r.key),
|
||||||
|
presignedUrls: results.map((r) => r.presignedUrl),
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const uploadError = err instanceof Error ? err : new Error('Upload failed')
|
||||||
|
setError(uploadError)
|
||||||
|
throw uploadError
|
||||||
|
} finally {
|
||||||
|
setIsUploading(false)
|
||||||
|
setProgress(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const uploadSingle = async (
|
||||||
|
blob: Blob,
|
||||||
|
mimeType: string,
|
||||||
|
contextString: ContextString,
|
||||||
|
): Promise<{ key: string; presignedUrl: string }> => {
|
||||||
|
const result = await upload({
|
||||||
|
images: [{ blob, mimeType }],
|
||||||
|
contextString,
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
key: result.keys[0],
|
||||||
|
presignedUrl: result.presignedUrls[0],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
upload,
|
||||||
|
uploadSingle,
|
||||||
|
isUploading,
|
||||||
|
error,
|
||||||
|
progress,
|
||||||
|
isPending: generateUploadUrls.isPending,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractKeyFromPresignedUrl(url: string): string {
|
||||||
|
const u = new URL(url)
|
||||||
|
let rawKey = u.pathname.replace(/^\/+/, '')
|
||||||
|
rawKey = rawKey.split('/').slice(1).join('/')
|
||||||
|
return decodeURIComponent(rawKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
export type { UploadInput }
|
||||||
|
|
@ -2,13 +2,13 @@ import React, { createContext, useContext, useState, useEffect, useCallback } fr
|
||||||
import { trpc } from './trpc-client'
|
import { trpc } from './trpc-client'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
|
|
||||||
interface Staff {
|
interface Superadmin {
|
||||||
id: number
|
id: number
|
||||||
name: string
|
name: string
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AuthState {
|
interface AuthState {
|
||||||
staff: Staff | null
|
staff: Superadmin | null
|
||||||
isAuthenticated: boolean
|
isAuthenticated: boolean
|
||||||
isLoading: boolean
|
isLoading: boolean
|
||||||
token: string | null
|
token: string | null
|
||||||
|
|
@ -32,7 +32,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
})
|
})
|
||||||
const [loginError, setLoginError] = useState<string | null>(null)
|
const [loginError, setLoginError] = useState<string | null>(null)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const loginMutation = trpc.admin.staffUser.login.useMutation()
|
const loginMutation = trpc.superadmin.auth.login.useMutation()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const storedToken = localStorage.getItem('auth_token')
|
const storedToken = localStorage.getItem('auth_token')
|
||||||
|
|
@ -55,7 +55,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
const data = await loginMutation.mutateAsync({ name, password })
|
const data = await loginMutation.mutateAsync({ name, password })
|
||||||
localStorage.setItem('auth_token', data.token)
|
localStorage.setItem('auth_token', data.token)
|
||||||
setState({
|
setState({
|
||||||
staff: data.staff,
|
staff: data.superadmin,
|
||||||
token: data.token,
|
token: data.token,
|
||||||
isAuthenticated: true,
|
isAuthenticated: true,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
|
|
|
||||||
|
|
@ -14,10 +14,18 @@ import { Route as AdminsRouteImport } from './routes/admins'
|
||||||
import { Route as ConstantsRouteImport } from './routes/constants'
|
import { Route as ConstantsRouteImport } from './routes/constants'
|
||||||
import { Route as DashboardRouteImport } from './routes/dashboard'
|
import { Route as DashboardRouteImport } from './routes/dashboard'
|
||||||
import { Route as LoginRouteImport } from './routes/login'
|
import { Route as LoginRouteImport } from './routes/login'
|
||||||
|
import { Route as ProductsRouteImport } from './routes/products'
|
||||||
import { Route as RegionsRouteImport } from './routes/regions'
|
import { Route as RegionsRouteImport } from './routes/regions'
|
||||||
import { Route as SendNotificationsRouteImport } from './routes/send-notifications'
|
import { Route as SendNotificationsRouteImport } from './routes/send-notifications'
|
||||||
|
import { Route as StoresRouteImport } from './routes/stores'
|
||||||
|
import { Route as AdminsNewRouteImport } from './routes/admins.new'
|
||||||
|
import { Route as ProductsNewRouteImport } from './routes/products.new'
|
||||||
import { Route as RegionsNewRouteImport } from './routes/regions.new'
|
import { Route as RegionsNewRouteImport } from './routes/regions.new'
|
||||||
|
import { Route as StoresNewRouteImport } from './routes/stores.new'
|
||||||
|
import { Route as AdminsIdEditRouteImport } from './routes/admins.$id.edit'
|
||||||
|
import { Route as ProductsIdEditRouteImport } from './routes/products.$id.edit'
|
||||||
import { Route as RegionsIdEditRouteImport } from './routes/regions.$id.edit'
|
import { Route as RegionsIdEditRouteImport } from './routes/regions.$id.edit'
|
||||||
|
import { Route as StoresIdEditRouteImport } from './routes/stores.$id.edit'
|
||||||
|
|
||||||
const IndexRoute = IndexRouteImport.update({
|
const IndexRoute = IndexRouteImport.update({
|
||||||
id: '/',
|
id: '/',
|
||||||
|
|
@ -44,6 +52,11 @@ const LoginRoute = LoginRouteImport.update({
|
||||||
path: '/login',
|
path: '/login',
|
||||||
getParentRoute: () => rootRouteImport,
|
getParentRoute: () => rootRouteImport,
|
||||||
} as any)
|
} as any)
|
||||||
|
const ProductsRoute = ProductsRouteImport.update({
|
||||||
|
id: '/products',
|
||||||
|
path: '/products',
|
||||||
|
getParentRoute: () => rootRouteImport,
|
||||||
|
} as any)
|
||||||
const RegionsRoute = RegionsRouteImport.update({
|
const RegionsRoute = RegionsRouteImport.update({
|
||||||
id: '/regions',
|
id: '/regions',
|
||||||
path: '/regions',
|
path: '/regions',
|
||||||
|
|
@ -54,50 +67,109 @@ const SendNotificationsRoute = SendNotificationsRouteImport.update({
|
||||||
path: '/send-notifications',
|
path: '/send-notifications',
|
||||||
getParentRoute: () => rootRouteImport,
|
getParentRoute: () => rootRouteImport,
|
||||||
} as any)
|
} as any)
|
||||||
|
const StoresRoute = StoresRouteImport.update({
|
||||||
|
id: '/stores',
|
||||||
|
path: '/stores',
|
||||||
|
getParentRoute: () => rootRouteImport,
|
||||||
|
} as any)
|
||||||
|
const AdminsNewRoute = AdminsNewRouteImport.update({
|
||||||
|
id: '/new',
|
||||||
|
path: '/new',
|
||||||
|
getParentRoute: () => AdminsRoute,
|
||||||
|
} as any)
|
||||||
|
const ProductsNewRoute = ProductsNewRouteImport.update({
|
||||||
|
id: '/new',
|
||||||
|
path: '/new',
|
||||||
|
getParentRoute: () => ProductsRoute,
|
||||||
|
} as any)
|
||||||
const RegionsNewRoute = RegionsNewRouteImport.update({
|
const RegionsNewRoute = RegionsNewRouteImport.update({
|
||||||
id: '/new',
|
id: '/new',
|
||||||
path: '/new',
|
path: '/new',
|
||||||
getParentRoute: () => RegionsRoute,
|
getParentRoute: () => RegionsRoute,
|
||||||
} as any)
|
} as any)
|
||||||
|
const StoresNewRoute = StoresNewRouteImport.update({
|
||||||
|
id: '/new',
|
||||||
|
path: '/new',
|
||||||
|
getParentRoute: () => StoresRoute,
|
||||||
|
} as any)
|
||||||
|
const AdminsIdEditRoute = AdminsIdEditRouteImport.update({
|
||||||
|
id: '/$id/edit',
|
||||||
|
path: '/$id/edit',
|
||||||
|
getParentRoute: () => AdminsRoute,
|
||||||
|
} as any)
|
||||||
|
const ProductsIdEditRoute = ProductsIdEditRouteImport.update({
|
||||||
|
id: '/$id/edit',
|
||||||
|
path: '/$id/edit',
|
||||||
|
getParentRoute: () => ProductsRoute,
|
||||||
|
} as any)
|
||||||
const RegionsIdEditRoute = RegionsIdEditRouteImport.update({
|
const RegionsIdEditRoute = RegionsIdEditRouteImport.update({
|
||||||
id: '/$id/edit',
|
id: '/$id/edit',
|
||||||
path: '/$id/edit',
|
path: '/$id/edit',
|
||||||
getParentRoute: () => RegionsRoute,
|
getParentRoute: () => RegionsRoute,
|
||||||
} as any)
|
} as any)
|
||||||
|
const StoresIdEditRoute = StoresIdEditRouteImport.update({
|
||||||
|
id: '/$id/edit',
|
||||||
|
path: '/$id/edit',
|
||||||
|
getParentRoute: () => StoresRoute,
|
||||||
|
} as any)
|
||||||
|
|
||||||
export interface FileRoutesByFullPath {
|
export interface FileRoutesByFullPath {
|
||||||
'/': typeof IndexRoute
|
'/': typeof IndexRoute
|
||||||
'/admins': typeof AdminsRoute
|
'/admins': typeof AdminsRouteWithChildren
|
||||||
'/constants': typeof ConstantsRoute
|
'/constants': typeof ConstantsRoute
|
||||||
'/dashboard': typeof DashboardRoute
|
'/dashboard': typeof DashboardRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
|
'/products': typeof ProductsRouteWithChildren
|
||||||
'/regions': typeof RegionsRouteWithChildren
|
'/regions': typeof RegionsRouteWithChildren
|
||||||
'/send-notifications': typeof SendNotificationsRoute
|
'/send-notifications': typeof SendNotificationsRoute
|
||||||
|
'/stores': typeof StoresRouteWithChildren
|
||||||
|
'/admins/new': typeof AdminsNewRoute
|
||||||
|
'/products/new': typeof ProductsNewRoute
|
||||||
'/regions/new': typeof RegionsNewRoute
|
'/regions/new': typeof RegionsNewRoute
|
||||||
|
'/stores/new': typeof StoresNewRoute
|
||||||
|
'/admins/$id/edit': typeof AdminsIdEditRoute
|
||||||
|
'/products/$id/edit': typeof ProductsIdEditRoute
|
||||||
'/regions/$id/edit': typeof RegionsIdEditRoute
|
'/regions/$id/edit': typeof RegionsIdEditRoute
|
||||||
|
'/stores/$id/edit': typeof StoresIdEditRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesByTo {
|
export interface FileRoutesByTo {
|
||||||
'/': typeof IndexRoute
|
'/': typeof IndexRoute
|
||||||
'/admins': typeof AdminsRoute
|
'/admins': typeof AdminsRouteWithChildren
|
||||||
'/constants': typeof ConstantsRoute
|
'/constants': typeof ConstantsRoute
|
||||||
'/dashboard': typeof DashboardRoute
|
'/dashboard': typeof DashboardRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
|
'/products': typeof ProductsRouteWithChildren
|
||||||
'/regions': typeof RegionsRouteWithChildren
|
'/regions': typeof RegionsRouteWithChildren
|
||||||
'/send-notifications': typeof SendNotificationsRoute
|
'/send-notifications': typeof SendNotificationsRoute
|
||||||
|
'/stores': typeof StoresRouteWithChildren
|
||||||
|
'/admins/new': typeof AdminsNewRoute
|
||||||
|
'/products/new': typeof ProductsNewRoute
|
||||||
'/regions/new': typeof RegionsNewRoute
|
'/regions/new': typeof RegionsNewRoute
|
||||||
|
'/stores/new': typeof StoresNewRoute
|
||||||
|
'/admins/$id/edit': typeof AdminsIdEditRoute
|
||||||
|
'/products/$id/edit': typeof ProductsIdEditRoute
|
||||||
'/regions/$id/edit': typeof RegionsIdEditRoute
|
'/regions/$id/edit': typeof RegionsIdEditRoute
|
||||||
|
'/stores/$id/edit': typeof StoresIdEditRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesById {
|
export interface FileRoutesById {
|
||||||
__root__: typeof rootRouteImport
|
__root__: typeof rootRouteImport
|
||||||
'/': typeof IndexRoute
|
'/': typeof IndexRoute
|
||||||
'/admins': typeof AdminsRoute
|
'/admins': typeof AdminsRouteWithChildren
|
||||||
'/constants': typeof ConstantsRoute
|
'/constants': typeof ConstantsRoute
|
||||||
'/dashboard': typeof DashboardRoute
|
'/dashboard': typeof DashboardRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
|
'/products': typeof ProductsRouteWithChildren
|
||||||
'/regions': typeof RegionsRouteWithChildren
|
'/regions': typeof RegionsRouteWithChildren
|
||||||
'/send-notifications': typeof SendNotificationsRoute
|
'/send-notifications': typeof SendNotificationsRoute
|
||||||
|
'/stores': typeof StoresRouteWithChildren
|
||||||
|
'/admins/new': typeof AdminsNewRoute
|
||||||
|
'/products/new': typeof ProductsNewRoute
|
||||||
'/regions/new': typeof RegionsNewRoute
|
'/regions/new': typeof RegionsNewRoute
|
||||||
|
'/stores/new': typeof StoresNewRoute
|
||||||
|
'/admins/$id/edit': typeof AdminsIdEditRoute
|
||||||
|
'/products/$id/edit': typeof ProductsIdEditRoute
|
||||||
'/regions/$id/edit': typeof RegionsIdEditRoute
|
'/regions/$id/edit': typeof RegionsIdEditRoute
|
||||||
|
'/stores/$id/edit': typeof StoresIdEditRoute
|
||||||
}
|
}
|
||||||
export interface FileRouteTypes {
|
export interface FileRouteTypes {
|
||||||
fileRoutesByFullPath: FileRoutesByFullPath
|
fileRoutesByFullPath: FileRoutesByFullPath
|
||||||
|
|
@ -107,10 +179,18 @@ export interface FileRouteTypes {
|
||||||
| '/constants'
|
| '/constants'
|
||||||
| '/dashboard'
|
| '/dashboard'
|
||||||
| '/login'
|
| '/login'
|
||||||
|
| '/products'
|
||||||
| '/regions'
|
| '/regions'
|
||||||
| '/send-notifications'
|
| '/send-notifications'
|
||||||
|
| '/stores'
|
||||||
|
| '/admins/new'
|
||||||
|
| '/products/new'
|
||||||
| '/regions/new'
|
| '/regions/new'
|
||||||
|
| '/stores/new'
|
||||||
|
| '/admins/$id/edit'
|
||||||
|
| '/products/$id/edit'
|
||||||
| '/regions/$id/edit'
|
| '/regions/$id/edit'
|
||||||
|
| '/stores/$id/edit'
|
||||||
fileRoutesByTo: FileRoutesByTo
|
fileRoutesByTo: FileRoutesByTo
|
||||||
to:
|
to:
|
||||||
| '/'
|
| '/'
|
||||||
|
|
@ -118,10 +198,18 @@ export interface FileRouteTypes {
|
||||||
| '/constants'
|
| '/constants'
|
||||||
| '/dashboard'
|
| '/dashboard'
|
||||||
| '/login'
|
| '/login'
|
||||||
|
| '/products'
|
||||||
| '/regions'
|
| '/regions'
|
||||||
| '/send-notifications'
|
| '/send-notifications'
|
||||||
|
| '/stores'
|
||||||
|
| '/admins/new'
|
||||||
|
| '/products/new'
|
||||||
| '/regions/new'
|
| '/regions/new'
|
||||||
|
| '/stores/new'
|
||||||
|
| '/admins/$id/edit'
|
||||||
|
| '/products/$id/edit'
|
||||||
| '/regions/$id/edit'
|
| '/regions/$id/edit'
|
||||||
|
| '/stores/$id/edit'
|
||||||
id:
|
id:
|
||||||
| '__root__'
|
| '__root__'
|
||||||
| '/'
|
| '/'
|
||||||
|
|
@ -129,20 +217,30 @@ export interface FileRouteTypes {
|
||||||
| '/constants'
|
| '/constants'
|
||||||
| '/dashboard'
|
| '/dashboard'
|
||||||
| '/login'
|
| '/login'
|
||||||
|
| '/products'
|
||||||
| '/regions'
|
| '/regions'
|
||||||
| '/send-notifications'
|
| '/send-notifications'
|
||||||
|
| '/stores'
|
||||||
|
| '/admins/new'
|
||||||
|
| '/products/new'
|
||||||
| '/regions/new'
|
| '/regions/new'
|
||||||
|
| '/stores/new'
|
||||||
|
| '/admins/$id/edit'
|
||||||
|
| '/products/$id/edit'
|
||||||
| '/regions/$id/edit'
|
| '/regions/$id/edit'
|
||||||
|
| '/stores/$id/edit'
|
||||||
fileRoutesById: FileRoutesById
|
fileRoutesById: FileRoutesById
|
||||||
}
|
}
|
||||||
export interface RootRouteChildren {
|
export interface RootRouteChildren {
|
||||||
IndexRoute: typeof IndexRoute
|
IndexRoute: typeof IndexRoute
|
||||||
AdminsRoute: typeof AdminsRoute
|
AdminsRoute: typeof AdminsRouteWithChildren
|
||||||
ConstantsRoute: typeof ConstantsRoute
|
ConstantsRoute: typeof ConstantsRoute
|
||||||
DashboardRoute: typeof DashboardRoute
|
DashboardRoute: typeof DashboardRoute
|
||||||
LoginRoute: typeof LoginRoute
|
LoginRoute: typeof LoginRoute
|
||||||
|
ProductsRoute: typeof ProductsRouteWithChildren
|
||||||
RegionsRoute: typeof RegionsRouteWithChildren
|
RegionsRoute: typeof RegionsRouteWithChildren
|
||||||
SendNotificationsRoute: typeof SendNotificationsRoute
|
SendNotificationsRoute: typeof SendNotificationsRoute
|
||||||
|
StoresRoute: typeof StoresRouteWithChildren
|
||||||
}
|
}
|
||||||
|
|
||||||
declare module '@tanstack/react-router' {
|
declare module '@tanstack/react-router' {
|
||||||
|
|
@ -182,6 +280,13 @@ declare module '@tanstack/react-router' {
|
||||||
preLoaderRoute: typeof LoginRouteImport
|
preLoaderRoute: typeof LoginRouteImport
|
||||||
parentRoute: typeof rootRouteImport
|
parentRoute: typeof rootRouteImport
|
||||||
}
|
}
|
||||||
|
'/products': {
|
||||||
|
id: '/products'
|
||||||
|
path: '/products'
|
||||||
|
fullPath: '/products'
|
||||||
|
preLoaderRoute: typeof ProductsRouteImport
|
||||||
|
parentRoute: typeof rootRouteImport
|
||||||
|
}
|
||||||
'/regions': {
|
'/regions': {
|
||||||
id: '/regions'
|
id: '/regions'
|
||||||
path: '/regions'
|
path: '/regions'
|
||||||
|
|
@ -196,6 +301,27 @@ declare module '@tanstack/react-router' {
|
||||||
preLoaderRoute: typeof SendNotificationsRouteImport
|
preLoaderRoute: typeof SendNotificationsRouteImport
|
||||||
parentRoute: typeof rootRouteImport
|
parentRoute: typeof rootRouteImport
|
||||||
}
|
}
|
||||||
|
'/stores': {
|
||||||
|
id: '/stores'
|
||||||
|
path: '/stores'
|
||||||
|
fullPath: '/stores'
|
||||||
|
preLoaderRoute: typeof StoresRouteImport
|
||||||
|
parentRoute: typeof rootRouteImport
|
||||||
|
}
|
||||||
|
'/admins/new': {
|
||||||
|
id: '/admins/new'
|
||||||
|
path: '/new'
|
||||||
|
fullPath: '/admins/new'
|
||||||
|
preLoaderRoute: typeof AdminsNewRouteImport
|
||||||
|
parentRoute: typeof AdminsRoute
|
||||||
|
}
|
||||||
|
'/products/new': {
|
||||||
|
id: '/products/new'
|
||||||
|
path: '/new'
|
||||||
|
fullPath: '/products/new'
|
||||||
|
preLoaderRoute: typeof ProductsNewRouteImport
|
||||||
|
parentRoute: typeof ProductsRoute
|
||||||
|
}
|
||||||
'/regions/new': {
|
'/regions/new': {
|
||||||
id: '/regions/new'
|
id: '/regions/new'
|
||||||
path: '/new'
|
path: '/new'
|
||||||
|
|
@ -203,6 +329,27 @@ declare module '@tanstack/react-router' {
|
||||||
preLoaderRoute: typeof RegionsNewRouteImport
|
preLoaderRoute: typeof RegionsNewRouteImport
|
||||||
parentRoute: typeof RegionsRoute
|
parentRoute: typeof RegionsRoute
|
||||||
}
|
}
|
||||||
|
'/stores/new': {
|
||||||
|
id: '/stores/new'
|
||||||
|
path: '/new'
|
||||||
|
fullPath: '/stores/new'
|
||||||
|
preLoaderRoute: typeof StoresNewRouteImport
|
||||||
|
parentRoute: typeof StoresRoute
|
||||||
|
}
|
||||||
|
'/admins/$id/edit': {
|
||||||
|
id: '/admins/$id/edit'
|
||||||
|
path: '/$id/edit'
|
||||||
|
fullPath: '/admins/$id/edit'
|
||||||
|
preLoaderRoute: typeof AdminsIdEditRouteImport
|
||||||
|
parentRoute: typeof AdminsRoute
|
||||||
|
}
|
||||||
|
'/products/$id/edit': {
|
||||||
|
id: '/products/$id/edit'
|
||||||
|
path: '/$id/edit'
|
||||||
|
fullPath: '/products/$id/edit'
|
||||||
|
preLoaderRoute: typeof ProductsIdEditRouteImport
|
||||||
|
parentRoute: typeof ProductsRoute
|
||||||
|
}
|
||||||
'/regions/$id/edit': {
|
'/regions/$id/edit': {
|
||||||
id: '/regions/$id/edit'
|
id: '/regions/$id/edit'
|
||||||
path: '/$id/edit'
|
path: '/$id/edit'
|
||||||
|
|
@ -210,8 +357,42 @@ declare module '@tanstack/react-router' {
|
||||||
preLoaderRoute: typeof RegionsIdEditRouteImport
|
preLoaderRoute: typeof RegionsIdEditRouteImport
|
||||||
parentRoute: typeof RegionsRoute
|
parentRoute: typeof RegionsRoute
|
||||||
}
|
}
|
||||||
|
'/stores/$id/edit': {
|
||||||
|
id: '/stores/$id/edit'
|
||||||
|
path: '/$id/edit'
|
||||||
|
fullPath: '/stores/$id/edit'
|
||||||
|
preLoaderRoute: typeof StoresIdEditRouteImport
|
||||||
|
parentRoute: typeof StoresRoute
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AdminsRouteChildren {
|
||||||
|
AdminsNewRoute: typeof AdminsNewRoute
|
||||||
|
AdminsIdEditRoute: typeof AdminsIdEditRoute
|
||||||
|
}
|
||||||
|
|
||||||
|
const AdminsRouteChildren: AdminsRouteChildren = {
|
||||||
|
AdminsNewRoute: AdminsNewRoute,
|
||||||
|
AdminsIdEditRoute: AdminsIdEditRoute,
|
||||||
|
}
|
||||||
|
|
||||||
|
const AdminsRouteWithChildren =
|
||||||
|
AdminsRoute._addFileChildren(AdminsRouteChildren)
|
||||||
|
|
||||||
|
interface ProductsRouteChildren {
|
||||||
|
ProductsNewRoute: typeof ProductsNewRoute
|
||||||
|
ProductsIdEditRoute: typeof ProductsIdEditRoute
|
||||||
|
}
|
||||||
|
|
||||||
|
const ProductsRouteChildren: ProductsRouteChildren = {
|
||||||
|
ProductsNewRoute: ProductsNewRoute,
|
||||||
|
ProductsIdEditRoute: ProductsIdEditRoute,
|
||||||
|
}
|
||||||
|
|
||||||
|
const ProductsRouteWithChildren = ProductsRoute._addFileChildren(
|
||||||
|
ProductsRouteChildren,
|
||||||
|
)
|
||||||
|
|
||||||
interface RegionsRouteChildren {
|
interface RegionsRouteChildren {
|
||||||
RegionsNewRoute: typeof RegionsNewRoute
|
RegionsNewRoute: typeof RegionsNewRoute
|
||||||
|
|
@ -226,14 +407,29 @@ const RegionsRouteChildren: RegionsRouteChildren = {
|
||||||
const RegionsRouteWithChildren =
|
const RegionsRouteWithChildren =
|
||||||
RegionsRoute._addFileChildren(RegionsRouteChildren)
|
RegionsRoute._addFileChildren(RegionsRouteChildren)
|
||||||
|
|
||||||
|
interface StoresRouteChildren {
|
||||||
|
StoresNewRoute: typeof StoresNewRoute
|
||||||
|
StoresIdEditRoute: typeof StoresIdEditRoute
|
||||||
|
}
|
||||||
|
|
||||||
|
const StoresRouteChildren: StoresRouteChildren = {
|
||||||
|
StoresNewRoute: StoresNewRoute,
|
||||||
|
StoresIdEditRoute: StoresIdEditRoute,
|
||||||
|
}
|
||||||
|
|
||||||
|
const StoresRouteWithChildren =
|
||||||
|
StoresRoute._addFileChildren(StoresRouteChildren)
|
||||||
|
|
||||||
const rootRouteChildren: RootRouteChildren = {
|
const rootRouteChildren: RootRouteChildren = {
|
||||||
IndexRoute: IndexRoute,
|
IndexRoute: IndexRoute,
|
||||||
AdminsRoute: AdminsRoute,
|
AdminsRoute: AdminsRouteWithChildren,
|
||||||
ConstantsRoute: ConstantsRoute,
|
ConstantsRoute: ConstantsRoute,
|
||||||
DashboardRoute: DashboardRoute,
|
DashboardRoute: DashboardRoute,
|
||||||
LoginRoute: LoginRoute,
|
LoginRoute: LoginRoute,
|
||||||
|
ProductsRoute: ProductsRouteWithChildren,
|
||||||
RegionsRoute: RegionsRouteWithChildren,
|
RegionsRoute: RegionsRouteWithChildren,
|
||||||
SendNotificationsRoute: SendNotificationsRoute,
|
SendNotificationsRoute: SendNotificationsRoute,
|
||||||
|
StoresRoute: StoresRouteWithChildren,
|
||||||
}
|
}
|
||||||
export const routeTree = rootRouteImport
|
export const routeTree = rootRouteImport
|
||||||
._addFileChildren(rootRouteChildren)
|
._addFileChildren(rootRouteChildren)
|
||||||
|
|
|
||||||
177
apps/superadmin-ui/src/routes/admins.$id.edit.tsx
Normal file
177
apps/superadmin-ui/src/routes/admins.$id.edit.tsx
Normal file
|
|
@ -0,0 +1,177 @@
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { createFileRoute, useNavigate, useParams } from '@tanstack/react-router'
|
||||||
|
import { ArrowLeft } from 'lucide-react'
|
||||||
|
import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/admins/$id/edit')({
|
||||||
|
component: EditAdmin,
|
||||||
|
})
|
||||||
|
|
||||||
|
function EditAdmin() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const { id } = useParams({ from: '/admins/$id/edit' })
|
||||||
|
const staffId = Number(id)
|
||||||
|
|
||||||
|
const [name, setName] = useState('')
|
||||||
|
const [password, setPassword] = useState('')
|
||||||
|
const [roleId, setRoleId] = useState<number | ''>('')
|
||||||
|
const [regionId, setRegionId] = useState<number | ''>('')
|
||||||
|
const [hydrated, setHydrated] = useState(false)
|
||||||
|
|
||||||
|
const { data, isLoading, error } = trpc.superadmin.staffUser.getStaff.useQuery()
|
||||||
|
const { data: rolesData } = trpc.superadmin.staffUser.getRoles.useQuery()
|
||||||
|
const { data: regionsData } = trpc.superadmin.region.getRegions.useQuery()
|
||||||
|
|
||||||
|
const roles = rolesData?.roles ?? []
|
||||||
|
const regions = regionsData?.regions ?? []
|
||||||
|
const member = data?.staff.find((s) => s.id === staffId)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (member && !hydrated) {
|
||||||
|
setName(member.name)
|
||||||
|
setRoleId(member.roleId ?? '')
|
||||||
|
setRegionId(member.regionId ?? '')
|
||||||
|
setHydrated(true)
|
||||||
|
}
|
||||||
|
}, [member, hydrated])
|
||||||
|
|
||||||
|
const updateStaffUser = trpc.superadmin.staffUser.updateStaffUser.useMutation({
|
||||||
|
onSuccess: () => {
|
||||||
|
navigate({ to: '/admins' })
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
window.alert(`Error\n\n${err.message || 'Failed to update admin'}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const handleSubmit = () => {
|
||||||
|
if (!name.trim()) {
|
||||||
|
window.alert('Validation\n\nName is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (password.length > 0 && password.length < 6) {
|
||||||
|
window.alert('Validation\n\nNew password must be at least 6 characters.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!roleId) {
|
||||||
|
window.alert('Validation\n\nRole is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!regionId) {
|
||||||
|
window.alert('Validation\n\nRegion is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
updateStaffUser.mutate({
|
||||||
|
id: staffId,
|
||||||
|
name: name.trim(),
|
||||||
|
roleId: Number(roleId),
|
||||||
|
regionId: Number(regionId),
|
||||||
|
...(password.length > 0 ? { password } : {}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<MyText className="block py-8 text-center text-gray-500">Loading admin...</MyText>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error || !member) {
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<MyText className="block py-8 text-center text-red-600">
|
||||||
|
{error ? 'Error loading admin' : 'Admin not found'}
|
||||||
|
</MyText>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="bg-gray-50 p-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => navigate({ to: '/admins' })}
|
||||||
|
className="mb-4 flex items-center gap-1.5 text-sm font-medium text-gray-600 hover:text-gray-900"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4" />
|
||||||
|
Back to Admins
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Edit Admin</MyText>
|
||||||
|
<MyText className="mb-6 block text-gray-600">
|
||||||
|
Update {member.name}'s details. Leave the password blank to keep it unchanged.
|
||||||
|
</MyText>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<PInput
|
||||||
|
id="admin-edit-name"
|
||||||
|
topLabel="Name"
|
||||||
|
placeholder="e.g. ravi"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<PInput
|
||||||
|
id="admin-edit-password"
|
||||||
|
topLabel="New Password (optional)"
|
||||||
|
placeholder="Leave blank to keep current password"
|
||||||
|
value={password}
|
||||||
|
type="password"
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<MyText className="mb-1 block text-sm font-medium text-gray-700">Role</MyText>
|
||||||
|
<select
|
||||||
|
id="admin-edit-role"
|
||||||
|
value={roleId}
|
||||||
|
onChange={(e) => setRoleId(e.target.value ? Number(e.target.value) : '')}
|
||||||
|
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
||||||
|
>
|
||||||
|
<option value="">Select a role</option>
|
||||||
|
{roles.map((role) => (
|
||||||
|
<option key={role.id} value={role.id}>
|
||||||
|
{role.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-6">
|
||||||
|
<MyText className="mb-1 block text-sm font-medium text-gray-700">Region</MyText>
|
||||||
|
<select
|
||||||
|
id="admin-edit-region"
|
||||||
|
value={regionId}
|
||||||
|
onChange={(e) => setRegionId(e.target.value ? Number(e.target.value) : '')}
|
||||||
|
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
||||||
|
>
|
||||||
|
<option value="">Select a region</option>
|
||||||
|
{regions.map((region) => (
|
||||||
|
<option key={region.id} value={region.id}>
|
||||||
|
{region.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<MyButton
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={updateStaffUser.isPending}
|
||||||
|
fullWidth
|
||||||
|
className={`rounded-lg bg-blue-600 p-4 text-base text-white hover:bg-blue-700 ${
|
||||||
|
updateStaffUser.isPending ? 'opacity-50' : ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{updateStaffUser.isPending ? 'Saving...' : 'Save Changes'}
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
145
apps/superadmin-ui/src/routes/admins.new.tsx
Normal file
145
apps/superadmin-ui/src/routes/admins.new.tsx
Normal file
|
|
@ -0,0 +1,145 @@
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||||
|
import { UserPlus, ArrowLeft } from 'lucide-react'
|
||||||
|
import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/admins/new')({
|
||||||
|
component: NewAdmin,
|
||||||
|
})
|
||||||
|
|
||||||
|
function NewAdmin() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const [name, setName] = useState('')
|
||||||
|
const [password, setPassword] = useState('')
|
||||||
|
const [roleId, setRoleId] = useState<number | ''>('')
|
||||||
|
const [regionId, setRegionId] = useState<number | ''>('')
|
||||||
|
|
||||||
|
const { data: rolesData } = trpc.superadmin.staffUser.getRoles.useQuery()
|
||||||
|
const { data: regionsData } = trpc.superadmin.region.getRegions.useQuery()
|
||||||
|
|
||||||
|
const roles = rolesData?.roles ?? []
|
||||||
|
const regions = regionsData?.regions ?? []
|
||||||
|
|
||||||
|
const createStaffUser = trpc.superadmin.staffUser.createStaffUser.useMutation({
|
||||||
|
onSuccess: () => {
|
||||||
|
navigate({ to: '/admins' })
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
window.alert(`Error\n\n${err.message || 'Failed to create admin'}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const handleSubmit = () => {
|
||||||
|
if (!name.trim()) {
|
||||||
|
window.alert('Validation\n\nName is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (password.length < 6) {
|
||||||
|
window.alert('Validation\n\nPassword must be at least 6 characters.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!roleId) {
|
||||||
|
window.alert('Validation\n\nRole is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!regionId) {
|
||||||
|
window.alert('Validation\n\nRegion is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
createStaffUser.mutate({
|
||||||
|
name: name.trim(),
|
||||||
|
password,
|
||||||
|
roleId: Number(roleId),
|
||||||
|
regionId: Number(regionId),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="bg-gray-50 p-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => navigate({ to: '/admins' })}
|
||||||
|
className="mb-4 flex items-center gap-1.5 text-sm font-medium text-gray-600 hover:text-gray-900"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4" />
|
||||||
|
Back to Admins
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Add Admin</MyText>
|
||||||
|
<MyText className="mb-6 block text-gray-600">
|
||||||
|
Create a staff user and assign them to a region.
|
||||||
|
</MyText>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<PInput
|
||||||
|
id="admin-name"
|
||||||
|
topLabel="Name"
|
||||||
|
placeholder="e.g. ravi"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<PInput
|
||||||
|
id="admin-password"
|
||||||
|
topLabel="Password"
|
||||||
|
placeholder="At least 6 characters"
|
||||||
|
value={password}
|
||||||
|
type="password"
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<MyText className="mb-1 block text-sm font-medium text-gray-700">Role</MyText>
|
||||||
|
<select
|
||||||
|
id="admin-role"
|
||||||
|
value={roleId}
|
||||||
|
onChange={(e) => setRoleId(e.target.value ? Number(e.target.value) : '')}
|
||||||
|
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
||||||
|
>
|
||||||
|
<option value="">Select a role</option>
|
||||||
|
{roles.map((role) => (
|
||||||
|
<option key={role.id} value={role.id}>
|
||||||
|
{role.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-6">
|
||||||
|
<MyText className="mb-1 block text-sm font-medium text-gray-700">Region</MyText>
|
||||||
|
<select
|
||||||
|
id="admin-region"
|
||||||
|
value={regionId}
|
||||||
|
onChange={(e) => setRegionId(e.target.value ? Number(e.target.value) : '')}
|
||||||
|
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
||||||
|
>
|
||||||
|
<option value="">Select a region</option>
|
||||||
|
{regions.map((region) => (
|
||||||
|
<option key={region.id} value={region.id}>
|
||||||
|
{region.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<MyButton
|
||||||
|
id="create-admin-submit"
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={createStaffUser.isPending}
|
||||||
|
fullWidth
|
||||||
|
className={`flex items-center justify-center gap-2 rounded-lg bg-blue-600 p-4 text-base text-white hover:bg-blue-700 ${
|
||||||
|
createStaffUser.isPending ? 'opacity-50' : ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<UserPlus className="h-4 w-4" />
|
||||||
|
{createStaffUser.isPending ? 'Creating...' : 'Create Admin'}
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
import { useState } from 'react'
|
import { createFileRoute, Link, Outlet, useLocation, useNavigate } from '@tanstack/react-router'
|
||||||
import { createFileRoute } from '@tanstack/react-router'
|
import { Pencil, Plus, Trash2, UserCog } from 'lucide-react'
|
||||||
import { UserPlus } from 'lucide-react'
|
import { AppContainer, MyButton, p as MyText } from 'web-components'
|
||||||
import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
|
|
||||||
import { trpc } from '../lib/trpc-client'
|
import { trpc } from '../lib/trpc-client'
|
||||||
import { ProtectedRoute } from '../components/ProtectedRoute'
|
import { ProtectedRoute } from '../components/ProtectedRoute'
|
||||||
import { AppShell } from '../components/AppShell'
|
import { AppShell } from '../components/AppShell'
|
||||||
|
|
@ -10,133 +9,135 @@ export const Route = createFileRoute('/admins')({
|
||||||
component: () => (
|
component: () => (
|
||||||
<ProtectedRoute>
|
<ProtectedRoute>
|
||||||
<AppShell>
|
<AppShell>
|
||||||
<CreateAdmin />
|
<Admins />
|
||||||
</AppShell>
|
</AppShell>
|
||||||
</ProtectedRoute>
|
</ProtectedRoute>
|
||||||
),
|
),
|
||||||
})
|
})
|
||||||
|
|
||||||
function CreateAdmin() {
|
// This route is the layout for /admins plus its children
|
||||||
const [name, setName] = useState('')
|
// (/admins/new and /admins/$id/edit). Render the list only on the exact
|
||||||
const [password, setPassword] = useState('')
|
// /admins path; otherwise hand off to the child route.
|
||||||
const [roleId, setRoleId] = useState<number | ''>('')
|
function Admins() {
|
||||||
const [regionId, setRegionId] = useState<number | ''>('')
|
const location = useLocation()
|
||||||
|
|
||||||
const { data: rolesData } = trpc.admin.staffUser.getRoles.useQuery()
|
if (location.pathname !== '/admins') {
|
||||||
const { data: regionsData } = trpc.admin.region.getRegions.useQuery()
|
return <Outlet />
|
||||||
|
}
|
||||||
|
|
||||||
const roles = rolesData?.roles ?? []
|
return <AdminsList />
|
||||||
const regions = regionsData?.regions ?? []
|
}
|
||||||
|
|
||||||
const createStaffUser = trpc.admin.staffUser.createStaffUser.useMutation({
|
function AdminsList() {
|
||||||
onSuccess: (res) => {
|
const navigate = useNavigate()
|
||||||
window.alert('Success\n\nAdmin created successfully.')
|
const utils = trpc.useUtils()
|
||||||
setName('')
|
|
||||||
setPassword('')
|
const { data, isLoading, error, refetch } = trpc.superadmin.staffUser.getStaff.useQuery()
|
||||||
setRoleId('')
|
|
||||||
setRegionId('')
|
const deleteStaffUser = trpc.superadmin.staffUser.deleteStaffUser.useMutation({
|
||||||
|
onSuccess: () => {
|
||||||
|
void utils.superadmin.staffUser.getStaff.invalidate()
|
||||||
},
|
},
|
||||||
onError: (err) => {
|
onError: (err) => {
|
||||||
window.alert(`Error\n\n${err.message || 'Failed to create admin'}`)
|
window.alert(`Error\n\n${err.message || 'Failed to delete admin'}`)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const handleSubmit = () => {
|
const staff = data?.staff ?? []
|
||||||
if (!name.trim()) {
|
|
||||||
window.alert('Validation\n\nName is required.')
|
const handleDelete = (id: number, name: string) => {
|
||||||
return
|
if (!window.confirm(`Delete admin "${name}"? This cannot be undone.`)) return
|
||||||
}
|
deleteStaffUser.mutate({ id })
|
||||||
if (password.length < 6) {
|
|
||||||
window.alert('Validation\n\nPassword must be at least 6 characters.')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (!roleId) {
|
|
||||||
window.alert('Validation\n\nRole is required.')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (!regionId) {
|
|
||||||
window.alert('Validation\n\nRegion is required.')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
createStaffUser.mutate({
|
|
||||||
name: name.trim(),
|
|
||||||
password,
|
|
||||||
roleId: Number(roleId),
|
|
||||||
regionId: Number(regionId),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AppContainer>
|
<AppContainer>
|
||||||
<div className="bg-gray-50 p-4">
|
<div className="bg-gray-50 p-4">
|
||||||
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Create Admin</MyText>
|
<div className="mb-6 flex items-center justify-between">
|
||||||
<MyText className="mb-6 block text-gray-600">
|
<div>
|
||||||
Create a staff user and assign them to a region.
|
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Admins</MyText>
|
||||||
|
<MyText className="block text-gray-600">
|
||||||
|
Staff users and the region each one manages.
|
||||||
</MyText>
|
</MyText>
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
<PInput
|
|
||||||
topLabel="Name"
|
|
||||||
placeholder="e.g. ravi"
|
|
||||||
value={name}
|
|
||||||
onChange={(e) => setName(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
<PInput
|
|
||||||
topLabel="Password"
|
|
||||||
placeholder="At least 6 characters"
|
|
||||||
value={password}
|
|
||||||
type="password"
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mb-4">
|
|
||||||
<MyText className="mb-1 block text-sm font-medium text-gray-700">Role</MyText>
|
|
||||||
<select
|
|
||||||
value={roleId}
|
|
||||||
onChange={(e) => setRoleId(e.target.value ? Number(e.target.value) : '')}
|
|
||||||
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
|
||||||
>
|
|
||||||
<option value="">Select a role</option>
|
|
||||||
{roles.map((role) => (
|
|
||||||
<option key={role.id} value={role.id}>
|
|
||||||
{role.name}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mb-6">
|
|
||||||
<MyText className="mb-1 block text-sm font-medium text-gray-700">Region</MyText>
|
|
||||||
<select
|
|
||||||
value={regionId}
|
|
||||||
onChange={(e) => setRegionId(e.target.value ? Number(e.target.value) : '')}
|
|
||||||
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
|
||||||
>
|
|
||||||
<option value="">Select a region</option>
|
|
||||||
{regions.map((region) => (
|
|
||||||
<option key={region.id} value={region.id}>
|
|
||||||
{region.name}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<MyButton
|
<MyButton
|
||||||
onClick={handleSubmit}
|
onClick={() => navigate({ to: '/admins/new' })}
|
||||||
disabled={createStaffUser.isPending}
|
className="flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2.5 text-white hover:bg-blue-700"
|
||||||
fullWidth
|
|
||||||
className={`flex items-center justify-center gap-2 rounded-lg bg-blue-600 p-4 text-base text-white hover:bg-blue-700 ${
|
|
||||||
createStaffUser.isPending ? 'opacity-50' : ''
|
|
||||||
}`}
|
|
||||||
>
|
>
|
||||||
<UserPlus className="h-4 w-4" />
|
<Plus className="h-4 w-4" />
|
||||||
{createStaffUser.isPending ? 'Creating...' : 'Create Admin'}
|
Add Admin
|
||||||
</MyButton>
|
</MyButton>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{isLoading && (
|
||||||
|
<MyText className="block py-8 text-center text-gray-500">Loading admins...</MyText>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="flex flex-col items-center py-8">
|
||||||
|
<MyText className="mb-4 block text-red-600">Error loading admins</MyText>
|
||||||
|
<MyButton
|
||||||
|
onClick={() => refetch()}
|
||||||
|
className="rounded-lg bg-blue-500 px-4 py-2 text-white"
|
||||||
|
>
|
||||||
|
Retry
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isLoading && !error && staff.length === 0 && (
|
||||||
|
<div className="flex flex-col items-center rounded-xl border border-dashed border-gray-300 bg-white py-12">
|
||||||
|
<UserCog className="mb-3 h-8 w-8 text-gray-400" />
|
||||||
|
<MyText className="block text-gray-600">No admins yet.</MyText>
|
||||||
|
<MyText className="block text-sm text-gray-400">
|
||||||
|
Click "Add Admin" to create the first one.
|
||||||
|
</MyText>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
{staff.map((member) => (
|
||||||
|
<div
|
||||||
|
key={member.id}
|
||||||
|
className="flex flex-col rounded-xl border border-gray-200 bg-white p-5 shadow-sm"
|
||||||
|
>
|
||||||
|
<div className="mb-1 flex items-start gap-3">
|
||||||
|
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-blue-50">
|
||||||
|
<UserCog className="h-5 w-5 text-blue-600" />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<MyText className="block truncate font-semibold text-gray-900">
|
||||||
|
{member.name}
|
||||||
|
</MyText>
|
||||||
|
<MyText className="block text-sm text-gray-500">
|
||||||
|
{member.roleName || 'No role'} · {member.regionName || 'No region'}
|
||||||
|
</MyText>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-auto flex gap-2 pt-4">
|
||||||
|
<Link
|
||||||
|
to="/admins/$id/edit"
|
||||||
|
params={{ id: String(member.id) }}
|
||||||
|
className="flex flex-1 items-center justify-center gap-2 rounded-lg border border-gray-200 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
<Pencil className="h-4 w-4" />
|
||||||
|
Edit
|
||||||
|
</Link>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleDelete(member.id, member.name)}
|
||||||
|
disabled={deleteStaffUser.isPending}
|
||||||
|
className="flex flex-1 items-center justify-center gap-2 rounded-lg border border-red-200 px-3 py-2 text-sm font-medium text-red-600 hover:bg-red-50 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</AppContainer>
|
</AppContainer>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -168,8 +168,8 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
|
||||||
}
|
}
|
||||||
|
|
||||||
function CustomizeApp() {
|
function CustomizeApp() {
|
||||||
const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery()
|
const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.superadmin.const.getConstants.useQuery()
|
||||||
const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation()
|
const { mutate: updateConstants, isPending: isUpdating } = trpc.superadmin.const.updateConstants.useMutation()
|
||||||
|
|
||||||
const handleSubmit = (values: ConstantFormData) => {
|
const handleSubmit = (values: ConstantFormData) => {
|
||||||
const changedConstants = (constants || [])
|
const changedConstants = (constants || [])
|
||||||
|
|
|
||||||
|
|
@ -17,8 +17,8 @@ export const Route = createFileRoute('/dashboard')({
|
||||||
const CARDS = [
|
const CARDS = [
|
||||||
{
|
{
|
||||||
to: '/admins',
|
to: '/admins',
|
||||||
title: 'Create Admin',
|
title: 'Admins',
|
||||||
description: 'Create a staff user and assign them to a region.',
|
description: 'View, create, edit and delete staff users.',
|
||||||
icon: UserPlus,
|
icon: UserPlus,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
|
||||||
301
apps/superadmin-ui/src/routes/products.$id.edit.tsx
Normal file
301
apps/superadmin-ui/src/routes/products.$id.edit.tsx
Normal file
|
|
@ -0,0 +1,301 @@
|
||||||
|
import React, { useRef, useMemo } from 'react'
|
||||||
|
import { createFileRoute, useParams } from '@tanstack/react-router'
|
||||||
|
import { AppContainer, p as MyText, type ImageUploaderNeoItem, type ImageUploaderNeoPayload } from 'web-components'
|
||||||
|
import ProductForm, { type ProductFormRef } from '../components/ProductForm'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { useUploadToObjectStorage } from '../hooks/useUploadToObjectStorage'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/products/$id/edit')({
|
||||||
|
component: EditProduct,
|
||||||
|
})
|
||||||
|
|
||||||
|
function EditProduct() {
|
||||||
|
const { id } = useParams({ from: '/products/$id/edit' })
|
||||||
|
const productId = Number(id)
|
||||||
|
const productFormRef = useRef<ProductFormRef>(null)
|
||||||
|
|
||||||
|
const { data: productResponse, isLoading: isFetching, refetch } = trpc.superadmin.product.getProductById.useQuery(
|
||||||
|
{ id: productId },
|
||||||
|
{ enabled: !!productId }
|
||||||
|
)
|
||||||
|
const { refetch: refetchProducts } = trpc.superadmin.product.getProducts.useQuery(undefined, {
|
||||||
|
enabled: false,
|
||||||
|
})
|
||||||
|
const { data: regionsData } = trpc.superadmin.region.getRegions.useQuery(undefined, { staleTime: Infinity })
|
||||||
|
|
||||||
|
const updateProduct = trpc.superadmin.product.updateProduct.useMutation()
|
||||||
|
const { upload, isUploading } = useUploadToObjectStorage()
|
||||||
|
|
||||||
|
const productData = productResponse?.product
|
||||||
|
|
||||||
|
const initialValues = useMemo(() => {
|
||||||
|
if (!productData) {
|
||||||
|
return {
|
||||||
|
name: '',
|
||||||
|
shortDescription: '',
|
||||||
|
longDescription: '',
|
||||||
|
regionId: undefined as number | undefined,
|
||||||
|
availableInAllRegions: false,
|
||||||
|
storeIdsByRegion: {} as Record<number, number>,
|
||||||
|
storeId: 0,
|
||||||
|
productType: 'item' as const,
|
||||||
|
matchForAll: false,
|
||||||
|
regionStats: {} as Record<string, any[]>,
|
||||||
|
variants: [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Per-region stats init, aligned with variants by index. Missing rows
|
||||||
|
// fall back to blanks (the form fills from the primary tab on save).
|
||||||
|
const regionStats: Record<string, any[]> = {}
|
||||||
|
for (const sku of (productData.skus || []) as any[]) {
|
||||||
|
for (const row of (sku.marketStats || []) as any[]) {
|
||||||
|
const key = String(row.regionId)
|
||||||
|
if (!regionStats[key]) regionStats[key] = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
;(productData.skus || []).forEach((sku: any, i: number) => {
|
||||||
|
for (const key of Object.keys(regionStats)) {
|
||||||
|
const row = ((sku as any).marketStats || []).find((r: any) => String(r.regionId) === key)
|
||||||
|
regionStats[key][i] = row
|
||||||
|
? {
|
||||||
|
price: row.ourPrice != null ? Number(row.ourPrice) : '',
|
||||||
|
marketPrice: row.marketPrice != null ? Number(row.marketPrice) : '',
|
||||||
|
flashPrice: row.flashPrice != null ? Number(row.flashPrice) : '',
|
||||||
|
isFlashAvailable: !!row.isFlashAvailable,
|
||||||
|
isOffer: !!row.isOffer,
|
||||||
|
isSuspended: !!row.isSuspended,
|
||||||
|
isOutOfStock: !!row.isOutOfStock,
|
||||||
|
}
|
||||||
|
: { price: '', marketPrice: '', flashPrice: '', isFlashAvailable: false, isOffer: false, isSuspended: false, isOutOfStock: false }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
name: productData.name,
|
||||||
|
shortDescription: productData.shortDescription || '',
|
||||||
|
longDescription: productData.longDescription || '',
|
||||||
|
regionId: productData.regionId,
|
||||||
|
availableInAllRegions: productData.availableInAllRegions ?? false,
|
||||||
|
storeIdsByRegion: {} as Record<number, number>,
|
||||||
|
storeId: productData.store?.id ?? 1,
|
||||||
|
productType: (productData.productType as 'item' | 'combo') || 'item',
|
||||||
|
matchForAll: false,
|
||||||
|
regionStats,
|
||||||
|
variants: (productData.skus || []).map((sku) => ({
|
||||||
|
id: sku.id,
|
||||||
|
name: sku.name || '',
|
||||||
|
price: sku.price ? parseFloat(sku.price) : undefined,
|
||||||
|
marketPrice: sku.marketPrice ? parseFloat(sku.marketPrice) : null,
|
||||||
|
isFlashAvailable: sku.isFlashAvailable || false,
|
||||||
|
flashPrice: sku.flashPrice ? parseFloat(sku.flashPrice) : null,
|
||||||
|
isOffer: sku.isOffer || false,
|
||||||
|
isComboOnly: sku.isComboOnly || false,
|
||||||
|
isDeleted: sku.isDeleted || false,
|
||||||
|
isSuspended: sku.isSuspended || false,
|
||||||
|
features: (sku.features || []).map((f) => ({
|
||||||
|
featureName: f.featureName,
|
||||||
|
featureValue: f.featureValue,
|
||||||
|
})),
|
||||||
|
comboItems: (sku.comboItems || []).map((ci: any) => ({
|
||||||
|
skuId: ci.skuId,
|
||||||
|
})),
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}, [productData])
|
||||||
|
|
||||||
|
const existingVariantImages = useMemo(() => {
|
||||||
|
if (!productData) return []
|
||||||
|
return (productData.skus || []).map((sku) =>
|
||||||
|
(sku.images || []).map((url) => ({ imgUrl: url, mimeType: null } as ImageUploaderNeoItem))
|
||||||
|
)
|
||||||
|
}, [productData])
|
||||||
|
|
||||||
|
const existingVariantImageKeys = useMemo(() => {
|
||||||
|
if (!productData) return []
|
||||||
|
return (productData.skus || []).map((sku) =>
|
||||||
|
(sku.imageKeys || []).map(String)
|
||||||
|
)
|
||||||
|
}, [productData])
|
||||||
|
|
||||||
|
const handleSubmit = async (values: any, variantImages: ImageUploaderNeoPayload[][], deletedImageKeys: string[]) => {
|
||||||
|
try {
|
||||||
|
const firstRegionId = regionsData?.regions?.[0]?.id
|
||||||
|
const primaryRegionId = values.availableInAllRegions
|
||||||
|
? firstRegionId
|
||||||
|
: values.regionId
|
||||||
|
const primaryStats: any[] = (values.regionStats ?? {})[String(primaryRegionId)] ?? []
|
||||||
|
|
||||||
|
for (const entry of primaryStats) {
|
||||||
|
const price = Number(entry?.price)
|
||||||
|
if (entry == null || !Number.isFinite(price) || price <= 0) {
|
||||||
|
window.alert('Please enter a valid price for every variant')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const seenSignatures = new Set<string>()
|
||||||
|
for (const variant of values.variants) {
|
||||||
|
const features = variant.features || []
|
||||||
|
const hasQuantity = features.some(
|
||||||
|
(a: any) => (a.featureName ?? '').trim().toLowerCase() === 'quantity'
|
||||||
|
)
|
||||||
|
if (!hasQuantity) {
|
||||||
|
window.alert('Every SKU must have a quantity feature')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const signature = features
|
||||||
|
.map((a: any) => `${(a.featureName ?? '').trim().toLowerCase()}::${a.featureValue.trim().toLowerCase()}`)
|
||||||
|
.sort()
|
||||||
|
.join('|')
|
||||||
|
if (seenSignatures.has(signature)) {
|
||||||
|
window.alert('Two variants have the same attributes')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seenSignatures.add(signature)
|
||||||
|
}
|
||||||
|
|
||||||
|
const allBlobs: { blob: Blob, mimeType: string }[] = []
|
||||||
|
const imageCounts: number[] = variantImages.map((imgs) =>
|
||||||
|
imgs.filter((img) => img.mimeType !== null).length
|
||||||
|
)
|
||||||
|
|
||||||
|
for (const imgs of variantImages) {
|
||||||
|
for (const img of imgs) {
|
||||||
|
if (img.mimeType === null) continue
|
||||||
|
const response = await fetch(img.url)
|
||||||
|
const blob = await response.blob()
|
||||||
|
allBlobs.push({ blob, mimeType: img.mimeType || 'image/jpeg' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let allUploadUrls: string[] = []
|
||||||
|
if (allBlobs.length > 0) {
|
||||||
|
const result = await upload({ images: allBlobs, contextString: 'product_info' })
|
||||||
|
allUploadUrls = result.presignedUrls
|
||||||
|
}
|
||||||
|
|
||||||
|
let urlCursor = 0
|
||||||
|
const skus = values.variants.map((variant: any, vIndex: number) => {
|
||||||
|
const count = imageCounts[vIndex]
|
||||||
|
const newUrls = allUploadUrls.slice(urlCursor, urlCursor + count)
|
||||||
|
urlCursor += count
|
||||||
|
|
||||||
|
const existingUrls = variantImages[vIndex]
|
||||||
|
?.filter((img) => img.mimeType === null)
|
||||||
|
.map((img) => img.url) || []
|
||||||
|
|
||||||
|
const allUrls = [...existingUrls, ...newUrls]
|
||||||
|
const stats = primaryStats[vIndex] ?? {}
|
||||||
|
|
||||||
|
const applicableRegionIds: number[] = values.availableInAllRegions
|
||||||
|
? (regionsData?.regions ?? []).map((r: any) => r.id)
|
||||||
|
: (primaryRegionId != null ? [primaryRegionId] : [])
|
||||||
|
const perRegion: Record<number, any> = {}
|
||||||
|
for (const rid of applicableRegionIds) {
|
||||||
|
if (rid === primaryRegionId) continue
|
||||||
|
const entry = ((values.regionStats ?? {})[String(rid)] ?? [])[vIndex]
|
||||||
|
if (entry) {
|
||||||
|
perRegion[rid] = {
|
||||||
|
price: Number(entry.price),
|
||||||
|
marketPrice: entry.marketPrice ?? undefined,
|
||||||
|
flashPrice: entry.flashPrice ?? undefined,
|
||||||
|
isFlashAvailable: !!entry.isFlashAvailable,
|
||||||
|
isOffer: !!entry.isOffer,
|
||||||
|
isSuspended: !!entry.isSuspended,
|
||||||
|
isOutOfStock: !!entry.isOutOfStock,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: variant.id,
|
||||||
|
name: variant.name || null,
|
||||||
|
price: Number(stats.price) as number,
|
||||||
|
marketPrice: stats.marketPrice ?? undefined,
|
||||||
|
images: allUrls,
|
||||||
|
isFlashAvailable: stats.isFlashAvailable || false,
|
||||||
|
flashPrice: stats.flashPrice ?? undefined,
|
||||||
|
isOffer: stats.isOffer || false,
|
||||||
|
isComboOnly: variant.isComboOnly || false,
|
||||||
|
isDeleted: variant.isDeleted || false,
|
||||||
|
isSuspended: stats.isSuspended || false,
|
||||||
|
regionStats: Object.keys(perRegion).length > 0 ? perRegion : undefined,
|
||||||
|
features: variant.features.map((attr: any) => ({
|
||||||
|
featureName: attr.featureName,
|
||||||
|
featureValue: attr.featureValue,
|
||||||
|
})),
|
||||||
|
comboItems: (variant.comboItems || []).map((ci: any) => ({
|
||||||
|
skuId: ci.skuId,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const storeIdsByRegion = Object.entries(values.storeIdsByRegion || {}).reduce(
|
||||||
|
(acc, [regionId, storeId]) => {
|
||||||
|
const sid = Number(storeId)
|
||||||
|
if (Number.isFinite(sid) && sid > 0) acc[Number(regionId)] = sid
|
||||||
|
return acc
|
||||||
|
},
|
||||||
|
{} as Record<number, number>
|
||||||
|
)
|
||||||
|
|
||||||
|
await updateProduct.mutateAsync({
|
||||||
|
id: productId,
|
||||||
|
name: values.name,
|
||||||
|
shortDescription: values.shortDescription || undefined,
|
||||||
|
longDescription: values.longDescription || undefined,
|
||||||
|
// Creator region scopes price/stock writes. A global product has no
|
||||||
|
// region of its own, so fall back to the first region (same rule as
|
||||||
|
// product creation); other regions' rows are left untouched.
|
||||||
|
regionId: values.regionId ?? regionsData?.regions?.[0]?.id,
|
||||||
|
productType: values.productType,
|
||||||
|
incrementStep: 1,
|
||||||
|
skus,
|
||||||
|
deletedImageKeys,
|
||||||
|
newImageUrls: allUploadUrls,
|
||||||
|
availableInAllRegions: !!values.availableInAllRegions,
|
||||||
|
storeIdsByRegion,
|
||||||
|
} as any)
|
||||||
|
|
||||||
|
await refetch()
|
||||||
|
await refetchProducts()
|
||||||
|
window.alert('Product updated successfully!')
|
||||||
|
productFormRef.current?.clearImages()
|
||||||
|
} catch (error: any) {
|
||||||
|
window.alert(error.message || 'Failed to update product')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isFetching) {
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="flex flex-1 items-center justify-center">
|
||||||
|
<MyText className="text-gray-600">Loading product...</MyText>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!productData) {
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="flex flex-1 items-center justify-center">
|
||||||
|
<MyText className="text-red-600">Product not found</MyText>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<ProductForm
|
||||||
|
ref={productFormRef}
|
||||||
|
mode="edit"
|
||||||
|
initialValues={initialValues}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
isLoading={updateProduct.isPending || isUploading}
|
||||||
|
existingVariantImages={existingVariantImages}
|
||||||
|
existingVariantImageKeys={existingVariantImageKeys}
|
||||||
|
/>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
201
apps/superadmin-ui/src/routes/products.new.tsx
Normal file
201
apps/superadmin-ui/src/routes/products.new.tsx
Normal file
|
|
@ -0,0 +1,201 @@
|
||||||
|
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||||
|
import { AppContainer, p as MyText } from 'web-components'
|
||||||
|
import ProductForm from '../components/ProductForm'
|
||||||
|
import type { ImageUploaderNeoPayload } from 'web-components'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { useUploadToObjectStorage } from '../hooks/useUploadToObjectStorage'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/products/new')({
|
||||||
|
component: AddProduct,
|
||||||
|
})
|
||||||
|
|
||||||
|
function AddProduct() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
|
const createProduct = trpc.superadmin.product.createProduct.useMutation()
|
||||||
|
const { data: regionsData } = trpc.superadmin.region.getRegions.useQuery()
|
||||||
|
const { refetch: refetchProducts } = trpc.superadmin.product.getProducts.useQuery(undefined, {
|
||||||
|
enabled: false,
|
||||||
|
})
|
||||||
|
const { upload, isUploading } = useUploadToObjectStorage()
|
||||||
|
|
||||||
|
const handleSubmit = async (values: any, variantImages: ImageUploaderNeoPayload[][], _deletedImageKeys?: string[]) => {
|
||||||
|
try {
|
||||||
|
// Creator/primary region: the picked region in single mode; the first
|
||||||
|
// region in all-regions mode (it gets the initial stock/prices).
|
||||||
|
const firstRegionId = regionsData?.regions?.[0]?.id
|
||||||
|
const primaryRegionId = values.availableInAllRegions
|
||||||
|
? firstRegionId
|
||||||
|
: values.regionId
|
||||||
|
const primaryStats: any[] = (values.regionStats ?? {})[String(primaryRegionId)] ?? []
|
||||||
|
|
||||||
|
for (const entry of primaryStats) {
|
||||||
|
const price = Number(entry?.price)
|
||||||
|
if (entry == null || !Number.isFinite(price) || price <= 0) {
|
||||||
|
window.alert('Please enter a valid price for every variant')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const seenSignatures = new Set<string>()
|
||||||
|
for (const variant of values.variants) {
|
||||||
|
const features = variant.features || []
|
||||||
|
const hasQuantity = features.some(
|
||||||
|
(a: any) => (a.featureName ?? '').trim().toLowerCase() === 'quantity'
|
||||||
|
)
|
||||||
|
if (!hasQuantity) {
|
||||||
|
window.alert('Every SKU must have a quantity feature')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const signature = features
|
||||||
|
.map((a: any) => `${(a.featureName ?? '').trim().toLowerCase()}::${a.featureValue.trim().toLowerCase()}`)
|
||||||
|
.sort()
|
||||||
|
.join('|')
|
||||||
|
if (seenSignatures.has(signature)) {
|
||||||
|
window.alert('Two variants have the same attributes')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seenSignatures.add(signature)
|
||||||
|
}
|
||||||
|
|
||||||
|
const allBlobs: { blob: Blob, mimeType: string }[] = []
|
||||||
|
const imageCounts: number[] = variantImages.map((imgs) => imgs.length)
|
||||||
|
|
||||||
|
for (const imgs of variantImages) {
|
||||||
|
for (const img of imgs) {
|
||||||
|
const response = await fetch(img.url)
|
||||||
|
const blob = await response.blob()
|
||||||
|
allBlobs.push({ blob, mimeType: img.mimeType || 'image/jpeg' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let allUploadUrls: string[] = []
|
||||||
|
if (allBlobs.length > 0) {
|
||||||
|
const result = await upload({ images: allBlobs, contextString: 'product_info' })
|
||||||
|
allUploadUrls = result.presignedUrls
|
||||||
|
}
|
||||||
|
|
||||||
|
let urlCursor = 0
|
||||||
|
const skus = values.variants.map((variant: any, vIndex: number) => {
|
||||||
|
const count = imageCounts[vIndex]
|
||||||
|
const variantUrls = allUploadUrls.slice(urlCursor, urlCursor + count)
|
||||||
|
urlCursor += count
|
||||||
|
const stats = primaryStats[vIndex] ?? {}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: variant.name || null,
|
||||||
|
price: Number(stats.price) as number,
|
||||||
|
marketPrice: stats.marketPrice ?? undefined,
|
||||||
|
images: variantUrls,
|
||||||
|
isFlashAvailable: stats.isFlashAvailable || false,
|
||||||
|
flashPrice: stats.flashPrice ?? undefined,
|
||||||
|
isOffer: stats.isOffer || false,
|
||||||
|
isComboOnly: variant.isComboOnly || false,
|
||||||
|
isDeleted: variant.isDeleted || false,
|
||||||
|
isSuspended: stats.isSuspended || false,
|
||||||
|
features: variant.features.map((attr: any) => ({
|
||||||
|
featureName: attr.featureName,
|
||||||
|
featureValue: attr.featureValue,
|
||||||
|
})),
|
||||||
|
comboItems: (variant.comboItems || []).map((ci: any) => ({
|
||||||
|
skuId: ci.skuId,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const storeIdsByRegion = Object.entries(values.storeIdsByRegion || {}).reduce(
|
||||||
|
(acc, [regionId, storeId]) => {
|
||||||
|
const sid = Number(storeId)
|
||||||
|
if (Number.isFinite(sid) && sid > 0) acc[Number(regionId)] = sid
|
||||||
|
return acc
|
||||||
|
},
|
||||||
|
{} as Record<number, number>
|
||||||
|
)
|
||||||
|
|
||||||
|
// Per-region overrides for every applicable region except the primary
|
||||||
|
// (whose values travel as the base SKU fields above).
|
||||||
|
const applicableRegionIds: number[] = values.availableInAllRegions
|
||||||
|
? (regionsData?.regions ?? []).map((r: any) => r.id)
|
||||||
|
: (primaryRegionId != null ? [primaryRegionId] : [])
|
||||||
|
const toBackendEntry = (entry: any) => ({
|
||||||
|
price: Number(entry.price),
|
||||||
|
marketPrice: entry.marketPrice ?? undefined,
|
||||||
|
flashPrice: entry.flashPrice ?? undefined,
|
||||||
|
isFlashAvailable: !!entry.isFlashAvailable,
|
||||||
|
isOffer: !!entry.isOffer,
|
||||||
|
isSuspended: !!entry.isSuspended,
|
||||||
|
isOutOfStock: !!entry.isOutOfStock,
|
||||||
|
})
|
||||||
|
const skusWithStats = skus.map((sku: any, vIndex: number) => {
|
||||||
|
const perRegion: Record<number, any> = {}
|
||||||
|
for (const rid of applicableRegionIds) {
|
||||||
|
if (rid === primaryRegionId) continue
|
||||||
|
const entry = ((values.regionStats ?? {})[String(rid)] ?? [])[vIndex]
|
||||||
|
if (entry) perRegion[rid] = toBackendEntry(entry)
|
||||||
|
}
|
||||||
|
return { ...sku, regionStats: Object.keys(perRegion).length > 0 ? perRegion : undefined }
|
||||||
|
})
|
||||||
|
|
||||||
|
await createProduct.mutateAsync({
|
||||||
|
name: values.name,
|
||||||
|
shortDescription: values.shortDescription || undefined,
|
||||||
|
longDescription: values.longDescription || undefined,
|
||||||
|
productType: values.productType,
|
||||||
|
incrementStep: 1,
|
||||||
|
skus: skusWithStats,
|
||||||
|
regionId: primaryRegionId,
|
||||||
|
availableInAllRegions: !!values.availableInAllRegions,
|
||||||
|
storeIdsByRegion,
|
||||||
|
})
|
||||||
|
|
||||||
|
await refetchProducts()
|
||||||
|
window.alert('Product created successfully!')
|
||||||
|
navigate({ to: '/products' })
|
||||||
|
} catch (error: any) {
|
||||||
|
window.alert(error.message || 'Failed to create product')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const initialValues = {
|
||||||
|
name: '',
|
||||||
|
shortDescription: '',
|
||||||
|
longDescription: '',
|
||||||
|
regionId: undefined as number | undefined,
|
||||||
|
availableInAllRegions: false,
|
||||||
|
storeIdsByRegion: {} as Record<number, number>,
|
||||||
|
storeId: 1,
|
||||||
|
productType: 'item' as const,
|
||||||
|
matchForAll: true,
|
||||||
|
regionStats: {} as Record<string, any[]>,
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
id: undefined as number | undefined,
|
||||||
|
name: '',
|
||||||
|
price: undefined,
|
||||||
|
marketPrice: null,
|
||||||
|
isFlashAvailable: false,
|
||||||
|
flashPrice: null,
|
||||||
|
isOffer: false,
|
||||||
|
isComboOnly: false,
|
||||||
|
isDeleted: false,
|
||||||
|
isSuspended: false,
|
||||||
|
features: [{ featureName: 'quantity', featureValue: '' }],
|
||||||
|
comboItems: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div>
|
||||||
|
<MyText className="mb-6 block text-2xl font-bold text-gray-800">Add New Product</MyText>
|
||||||
|
<ProductForm
|
||||||
|
mode="create"
|
||||||
|
initialValues={initialValues}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
isLoading={createProduct.isPending || isUploading}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
152
apps/superadmin-ui/src/routes/products.tsx
Normal file
152
apps/superadmin-ui/src/routes/products.tsx
Normal file
|
|
@ -0,0 +1,152 @@
|
||||||
|
import { createFileRoute, Link, Outlet, useLocation, useNavigate } from '@tanstack/react-router'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { Package, Pencil, Plus } from 'lucide-react'
|
||||||
|
import { AppContainer, MyButton, p as MyText } from 'web-components'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { ProtectedRoute } from '../components/ProtectedRoute'
|
||||||
|
import { AppShell } from '../components/AppShell'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/products')({
|
||||||
|
component: () => (
|
||||||
|
<ProtectedRoute>
|
||||||
|
<AppShell>
|
||||||
|
<Products />
|
||||||
|
</AppShell>
|
||||||
|
</ProtectedRoute>
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
|
// This route is the layout for /products plus its children
|
||||||
|
// (/products/new and /products/$id/edit). Render the list only on the exact
|
||||||
|
// /products path; otherwise hand off to the child route.
|
||||||
|
function Products() {
|
||||||
|
const location = useLocation()
|
||||||
|
|
||||||
|
if (location.pathname !== '/products') {
|
||||||
|
return <Outlet />
|
||||||
|
}
|
||||||
|
|
||||||
|
return <ProductsList />
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProductsList() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const [activeTab, setActiveTab] = useState<number | 'global'>('global')
|
||||||
|
|
||||||
|
const { data, isLoading, error, refetch } = trpc.superadmin.product.getProducts.useQuery()
|
||||||
|
const { data: regionsData } = trpc.superadmin.region.getRegions.useQuery(undefined, { staleTime: Infinity })
|
||||||
|
|
||||||
|
const products = (data as any)?.products ?? []
|
||||||
|
const regions = (regionsData as any)?.regions ?? []
|
||||||
|
|
||||||
|
const globalProducts = products.filter((p: any) => p.availableInAllRegions === true)
|
||||||
|
const productsByRegion = (regionId: number) =>
|
||||||
|
products.filter((p: any) => !p.availableInAllRegions && p.regionId === regionId)
|
||||||
|
const visibleProducts = activeTab === 'global' ? globalProducts : productsByRegion(activeTab)
|
||||||
|
const countFor = (tab: number | 'global') =>
|
||||||
|
tab === 'global' ? globalProducts.length : productsByRegion(tab).length
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="bg-gray-50 p-4">
|
||||||
|
<div className="mb-6 flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Products</MyText>
|
||||||
|
<MyText className="block text-gray-600">
|
||||||
|
Products with no region serve all regions.
|
||||||
|
</MyText>
|
||||||
|
</div>
|
||||||
|
<MyButton
|
||||||
|
onClick={() => navigate({ to: '/products/new' })}
|
||||||
|
className="flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2.5 text-white hover:bg-blue-700"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
Add Product
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isLoading && (
|
||||||
|
<MyText className="block py-8 text-center text-gray-500">Loading products...</MyText>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="flex flex-col items-center py-8">
|
||||||
|
<MyText className="mb-4 block text-red-600">Error loading products</MyText>
|
||||||
|
<MyButton
|
||||||
|
onClick={() => refetch()}
|
||||||
|
className="rounded-lg bg-blue-500 px-4 py-2 text-white"
|
||||||
|
>
|
||||||
|
Retry
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isLoading && !error && (
|
||||||
|
<div className="mb-5 flex gap-1 overflow-x-auto" data-testid="product-tabs">
|
||||||
|
<button
|
||||||
|
key="global"
|
||||||
|
type="button"
|
||||||
|
data-testid="product-tab-global"
|
||||||
|
onClick={() => setActiveTab('global')}
|
||||||
|
className={`shrink-0 rounded-full px-4 py-2 text-sm font-bold ${activeTab === 'global' ? 'bg-blue-600 text-white' : 'bg-white text-gray-600 border border-gray-200'}`}
|
||||||
|
>
|
||||||
|
Global ({countFor('global')})
|
||||||
|
</button>
|
||||||
|
{regions.map((region: any) => (
|
||||||
|
<button
|
||||||
|
key={region.id}
|
||||||
|
type="button"
|
||||||
|
data-testid={`product-tab-${region.id}`}
|
||||||
|
onClick={() => setActiveTab(region.id)}
|
||||||
|
className={`shrink-0 rounded-full px-4 py-2 text-sm font-bold ${activeTab === region.id ? 'bg-blue-600 text-white' : 'bg-white text-gray-600 border border-gray-200'}`}
|
||||||
|
>
|
||||||
|
{region.name} ({countFor(region.id)})
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isLoading && !error && visibleProducts.length === 0 && (
|
||||||
|
<div className="flex flex-col items-center rounded-xl border border-dashed border-gray-300 bg-white py-12">
|
||||||
|
<Package className="mb-3 h-8 w-8 text-gray-400" />
|
||||||
|
<MyText className="block text-gray-600">
|
||||||
|
{activeTab === 'global'
|
||||||
|
? 'No global products yet.'
|
||||||
|
: `No products in ${regions.find((r: any) => r.id === activeTab)?.name ?? 'this region'} yet.`}
|
||||||
|
</MyText>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2" data-testid={`product-grid-${activeTab}`}>
|
||||||
|
{visibleProducts.map((product: any) => (
|
||||||
|
<div
|
||||||
|
key={product.id}
|
||||||
|
className="flex flex-col rounded-xl border border-gray-200 bg-white p-5 shadow-sm"
|
||||||
|
>
|
||||||
|
<MyText className="block truncate font-semibold text-gray-900">
|
||||||
|
{product.name}
|
||||||
|
</MyText>
|
||||||
|
<MyText className="mt-1 block text-sm text-gray-500">
|
||||||
|
{product.availableInAllRegions
|
||||||
|
? 'All regions'
|
||||||
|
: `Region #${product.regionId ?? '—'}`}
|
||||||
|
{' · '}
|
||||||
|
{(product.skus || []).length} variant{(product.skus || []).length === 1 ? '' : 's'}
|
||||||
|
</MyText>
|
||||||
|
<div className="mt-4 flex gap-2">
|
||||||
|
<Link
|
||||||
|
to="/products/$id/edit"
|
||||||
|
params={{ id: String(product.id) }}
|
||||||
|
className="flex flex-1 items-center justify-center gap-2 rounded-lg border border-gray-200 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
<Pencil className="h-4 w-4" />
|
||||||
|
Edit
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -20,12 +20,12 @@ function EditRegion() {
|
||||||
>([])
|
>([])
|
||||||
const [hydrated, setHydrated] = useState(false)
|
const [hydrated, setHydrated] = useState(false)
|
||||||
|
|
||||||
const { data, isLoading, error } = trpc.admin.region.getRegionById.useQuery(
|
const { data, isLoading, error } = trpc.superadmin.region.getRegionById.useQuery(
|
||||||
{ id: regionId },
|
{ id: regionId },
|
||||||
{ enabled: Number.isFinite(regionId) }
|
{ enabled: Number.isFinite(regionId) }
|
||||||
)
|
)
|
||||||
|
|
||||||
const updateRegion = trpc.admin.region.updateRegion.useMutation({
|
const updateRegion = trpc.superadmin.region.updateRegion.useMutation({
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
navigate({ to: '/regions' })
|
navigate({ to: '/regions' })
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,7 @@ function NewRegion() {
|
||||||
{ botToken: '', chatId: '' },
|
{ botToken: '', chatId: '' },
|
||||||
])
|
])
|
||||||
|
|
||||||
const createRegion = trpc.admin.region.createRegion.useMutation({
|
const createRegion = trpc.superadmin.region.createRegion.useMutation({
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
navigate({ to: '/regions' })
|
navigate({ to: '/regions' })
|
||||||
},
|
},
|
||||||
|
|
@ -116,6 +116,7 @@ function NewRegion() {
|
||||||
|
|
||||||
<div className="mb-4">
|
<div className="mb-4">
|
||||||
<PInput
|
<PInput
|
||||||
|
id="region-name"
|
||||||
topLabel="Name"
|
topLabel="Name"
|
||||||
placeholder="e.g. Mahabubnagar Town"
|
placeholder="e.g. Mahabubnagar Town"
|
||||||
value={name}
|
value={name}
|
||||||
|
|
@ -125,6 +126,7 @@ function NewRegion() {
|
||||||
|
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
<PInput
|
<PInput
|
||||||
|
id="region-description"
|
||||||
topLabel="Description"
|
topLabel="Description"
|
||||||
placeholder="Optional description"
|
placeholder="Optional description"
|
||||||
value={description}
|
value={description}
|
||||||
|
|
@ -139,6 +141,7 @@ function NewRegion() {
|
||||||
Bounds (GeoJSON)
|
Bounds (GeoJSON)
|
||||||
</MyText>
|
</MyText>
|
||||||
<MyButton
|
<MyButton
|
||||||
|
id="add-bound-button"
|
||||||
onClick={addBound}
|
onClick={addBound}
|
||||||
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-50"
|
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-50"
|
||||||
>
|
>
|
||||||
|
|
@ -166,12 +169,14 @@ function NewRegion() {
|
||||||
</div>
|
</div>
|
||||||
<div className="mb-2 grid grid-cols-2 gap-2">
|
<div className="mb-2 grid grid-cols-2 gap-2">
|
||||||
<PInput
|
<PInput
|
||||||
|
id={`bound-${index}-name`}
|
||||||
topLabel="Name (required)"
|
topLabel="Name (required)"
|
||||||
placeholder="e.g. Mbnr-1"
|
placeholder="e.g. Mbnr-1"
|
||||||
value={bound.name}
|
value={bound.name}
|
||||||
onChange={(e) => updateBound(index, 'name', e.target.value)}
|
onChange={(e) => updateBound(index, 'name', e.target.value)}
|
||||||
/>
|
/>
|
||||||
<PInput
|
<PInput
|
||||||
|
id={`bound-${index}-priority`}
|
||||||
topLabel="Priority"
|
topLabel="Priority"
|
||||||
placeholder="e.g. 1"
|
placeholder="e.g. 1"
|
||||||
value={String(bound.priority)}
|
value={String(bound.priority)}
|
||||||
|
|
@ -180,6 +185,7 @@ function NewRegion() {
|
||||||
</div>
|
</div>
|
||||||
<div className="mb-2">
|
<div className="mb-2">
|
||||||
<PInput
|
<PInput
|
||||||
|
id={`bound-${index}-description`}
|
||||||
topLabel="Description (required)"
|
topLabel="Description (required)"
|
||||||
placeholder="e.g. Town core coverage area"
|
placeholder="e.g. Town core coverage area"
|
||||||
value={bound.description}
|
value={bound.description}
|
||||||
|
|
@ -187,6 +193,7 @@ function NewRegion() {
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<PInput
|
<PInput
|
||||||
|
id={`bound-${index}-geojson`}
|
||||||
placeholder='Paste GeoJSON, e.g. {"type":"Polygon","coordinates":[...]}'
|
placeholder='Paste GeoJSON, e.g. {"type":"Polygon","coordinates":[...]}'
|
||||||
value={bound.geojson}
|
value={bound.geojson}
|
||||||
multiline
|
multiline
|
||||||
|
|
@ -228,6 +235,7 @@ function NewRegion() {
|
||||||
</div>
|
</div>
|
||||||
<div className="mb-2">
|
<div className="mb-2">
|
||||||
<PInput
|
<PInput
|
||||||
|
id={`cred-${index}-bot-token`}
|
||||||
topLabel="Bot Token"
|
topLabel="Bot Token"
|
||||||
placeholder="e.g. 123456:ABC-DEF..."
|
placeholder="e.g. 123456:ABC-DEF..."
|
||||||
value={cred.botToken}
|
value={cred.botToken}
|
||||||
|
|
@ -235,6 +243,7 @@ function NewRegion() {
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<PInput
|
<PInput
|
||||||
|
id={`cred-${index}-chat-id`}
|
||||||
topLabel="Chat ID"
|
topLabel="Chat ID"
|
||||||
placeholder="e.g. 5147760058 or -1001234567890"
|
placeholder="e.g. 5147760058 or -1001234567890"
|
||||||
value={cred.chatId}
|
value={cred.chatId}
|
||||||
|
|
@ -244,6 +253,7 @@ function NewRegion() {
|
||||||
))}
|
))}
|
||||||
|
|
||||||
<MyButton
|
<MyButton
|
||||||
|
id="create-region-submit"
|
||||||
onClick={handleSubmit}
|
onClick={handleSubmit}
|
||||||
disabled={createRegion.isPending}
|
disabled={createRegion.isPending}
|
||||||
fullWidth
|
fullWidth
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,7 @@ function Regions() {
|
||||||
function RegionsList() {
|
function RegionsList() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const { data, isLoading, error, refetch } = trpc.admin.region.getRegions.useQuery()
|
const { data, isLoading, error, refetch } = trpc.superadmin.region.getRegions.useQuery()
|
||||||
|
|
||||||
const regions = data?.regions ?? []
|
const regions = data?.regions ?? []
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ function SendAdminNotifications() {
|
||||||
const [text, setText] = useState('')
|
const [text, setText] = useState('')
|
||||||
const [imageUrl, setImageUrl] = useState('')
|
const [imageUrl, setImageUrl] = useState('')
|
||||||
|
|
||||||
const { mutate, isPending } = trpc.admin.staffUser.sendAdminNotification.useMutation({
|
const { mutate, isPending } = trpc.superadmin.staffUser.sendAdminNotification.useMutation({
|
||||||
onSuccess: (response) => {
|
onSuccess: (response) => {
|
||||||
window.alert(`Success\n\n${response.message}`)
|
window.alert(`Success\n\n${response.message}`)
|
||||||
setTitle('')
|
setTitle('')
|
||||||
|
|
|
||||||
91
apps/superadmin-ui/src/routes/stores.$id.edit.tsx
Normal file
91
apps/superadmin-ui/src/routes/stores.$id.edit.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
||||||
|
import { createFileRoute, useNavigate, useParams } from '@tanstack/react-router'
|
||||||
|
import { AppContainer, p as MyText } from 'web-components'
|
||||||
|
import StoreForm, { type StoreFormData } from '../components/StoreForm'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/stores/$id/edit')({
|
||||||
|
component: EditStore,
|
||||||
|
})
|
||||||
|
|
||||||
|
function EditStore() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const { id } = useParams({ from: '/stores/$id/edit' })
|
||||||
|
|
||||||
|
const storeId = parseInt(id as string)
|
||||||
|
|
||||||
|
const { data: storeData, isLoading: isLoadingStore, refetch } = trpc.superadmin.store.getStoreById.useQuery(
|
||||||
|
{ id: storeId },
|
||||||
|
{ enabled: !!storeId }
|
||||||
|
)
|
||||||
|
|
||||||
|
const updateStoreMutation = trpc.superadmin.store.updateStore.useMutation()
|
||||||
|
|
||||||
|
const handleSubmit = (values: StoreFormData) => {
|
||||||
|
updateStoreMutation.mutate(
|
||||||
|
{
|
||||||
|
id: storeId,
|
||||||
|
name: values.name,
|
||||||
|
description: values.description || undefined,
|
||||||
|
owner: values.owner,
|
||||||
|
products: values.products,
|
||||||
|
regionId: values.availableInAllRegions ? null : (values.regionId ?? undefined),
|
||||||
|
availableInAllRegions: values.availableInAllRegions,
|
||||||
|
} as any,
|
||||||
|
{
|
||||||
|
onSuccess: (data) => {
|
||||||
|
refetch()
|
||||||
|
window.alert(`Success: ${data.message}`)
|
||||||
|
navigate({ to: '/stores' })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
window.alert(error.message || 'Failed to update store')
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoadingStore) {
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="flex flex-1 flex-col items-center justify-center">
|
||||||
|
<MyText>Loading store...</MyText>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const store = (storeData as any)?.store
|
||||||
|
if (!store) {
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="flex flex-1 flex-col items-center justify-center">
|
||||||
|
<MyText>Store not found</MyText>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const initialValues: StoreFormData = {
|
||||||
|
name: store.name,
|
||||||
|
description: store.description || '',
|
||||||
|
owner: store.owner?.id ?? store.owner,
|
||||||
|
products: [],
|
||||||
|
regionId: store.regionId ?? null,
|
||||||
|
availableInAllRegions: !!store.availableInAllRegions,
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div>
|
||||||
|
<MyText className="mb-6 block text-2xl font-bold text-gray-800">Edit Store</MyText>
|
||||||
|
<StoreForm
|
||||||
|
mode="edit"
|
||||||
|
initialValues={initialValues}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
isLoading={updateStoreMutation.isPending}
|
||||||
|
storeId={storeId}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
54
apps/superadmin-ui/src/routes/stores.new.tsx
Normal file
54
apps/superadmin-ui/src/routes/stores.new.tsx
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||||
|
import { AppContainer, p as MyText } from 'web-components'
|
||||||
|
import StoreForm, { type StoreFormData } from '../components/StoreForm'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/stores/new')({
|
||||||
|
component: AddStore,
|
||||||
|
})
|
||||||
|
|
||||||
|
function AddStore() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
|
const createStoreMutation = trpc.superadmin.store.createStore.useMutation()
|
||||||
|
const { refetch: refetchStores } = trpc.superadmin.store.getStores.useQuery(undefined, {
|
||||||
|
enabled: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
const handleSubmit = (values: StoreFormData) => {
|
||||||
|
createStoreMutation.mutate(
|
||||||
|
{
|
||||||
|
name: values.name,
|
||||||
|
description: values.description || undefined,
|
||||||
|
products: values.products,
|
||||||
|
owner: values.owner,
|
||||||
|
regionId: values.availableInAllRegions ? null : (values.regionId ?? null),
|
||||||
|
availableInAllRegions: !!values.availableInAllRegions,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
onSuccess: async (data) => {
|
||||||
|
await refetchStores()
|
||||||
|
window.alert(`Success: ${data.message}`)
|
||||||
|
navigate({ to: '/stores' })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
window.alert(error.message || 'Failed to create store')
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div>
|
||||||
|
<MyText className="mb-6 block text-2xl font-bold text-gray-800">Add New Store</MyText>
|
||||||
|
<StoreForm
|
||||||
|
mode="create"
|
||||||
|
initialValues={{ name: '', description: '', owner: 0, products: [], regionId: null, availableInAllRegions: false }}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
isLoading={createStoreMutation.isPending}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
150
apps/superadmin-ui/src/routes/stores.tsx
Normal file
150
apps/superadmin-ui/src/routes/stores.tsx
Normal file
|
|
@ -0,0 +1,150 @@
|
||||||
|
import { createFileRoute, Link, Outlet, useLocation, useNavigate } from '@tanstack/react-router'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { Store, Pencil, Plus } from 'lucide-react'
|
||||||
|
import { AppContainer, MyButton, p as MyText } from 'web-components'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { ProtectedRoute } from '../components/ProtectedRoute'
|
||||||
|
import { AppShell } from '../components/AppShell'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/stores')({
|
||||||
|
component: () => (
|
||||||
|
<ProtectedRoute>
|
||||||
|
<AppShell>
|
||||||
|
<Stores />
|
||||||
|
</AppShell>
|
||||||
|
</ProtectedRoute>
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
|
// This route is the layout for /stores plus its children
|
||||||
|
// (/stores/new and /stores/$id/edit). Render the list only on the exact
|
||||||
|
// /stores path; otherwise hand off to the child route.
|
||||||
|
function Stores() {
|
||||||
|
const location = useLocation()
|
||||||
|
|
||||||
|
if (location.pathname !== '/stores') {
|
||||||
|
return <Outlet />
|
||||||
|
}
|
||||||
|
|
||||||
|
return <StoresList />
|
||||||
|
}
|
||||||
|
|
||||||
|
function StoresList() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const [activeTab, setActiveTab] = useState<number | 'global'>('global')
|
||||||
|
|
||||||
|
const { data, isLoading, error, refetch } = trpc.superadmin.store.getStores.useQuery()
|
||||||
|
const { data: regionsData } = trpc.superadmin.region.getRegions.useQuery(undefined, { staleTime: Infinity })
|
||||||
|
|
||||||
|
const stores = (data as any)?.stores ?? []
|
||||||
|
const regions = (regionsData as any)?.regions ?? []
|
||||||
|
|
||||||
|
const globalStores = stores.filter((s: any) => s.availableInAllRegions === true)
|
||||||
|
const storesByRegion = (regionId: number) =>
|
||||||
|
stores.filter((s: any) => !s.availableInAllRegions && s.regionId === regionId)
|
||||||
|
const visibleStores = activeTab === 'global' ? globalStores : storesByRegion(activeTab)
|
||||||
|
const countFor = (tab: number | 'global') =>
|
||||||
|
tab === 'global' ? globalStores.length : storesByRegion(tab).length
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="bg-gray-50 p-4">
|
||||||
|
<div className="mb-6 flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Stores</MyText>
|
||||||
|
<MyText className="block text-gray-600">
|
||||||
|
Stores with no home region serve all regions.
|
||||||
|
</MyText>
|
||||||
|
</div>
|
||||||
|
<MyButton
|
||||||
|
onClick={() => navigate({ to: '/stores/new' })}
|
||||||
|
className="flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2.5 text-white hover:bg-blue-700"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
Add Store
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isLoading && (
|
||||||
|
<MyText className="block py-8 text-center text-gray-500">Loading stores...</MyText>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="flex flex-col items-center py-8">
|
||||||
|
<MyText className="mb-4 block text-red-600">Error loading stores</MyText>
|
||||||
|
<MyButton
|
||||||
|
onClick={() => refetch()}
|
||||||
|
className="rounded-lg bg-blue-500 px-4 py-2 text-white"
|
||||||
|
>
|
||||||
|
Retry
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isLoading && !error && (
|
||||||
|
<div className="mb-5 flex gap-1 overflow-x-auto" data-testid="store-tabs">
|
||||||
|
<button
|
||||||
|
key="global"
|
||||||
|
type="button"
|
||||||
|
data-testid="store-tab-global"
|
||||||
|
onClick={() => setActiveTab('global')}
|
||||||
|
className={`shrink-0 rounded-full px-4 py-2 text-sm font-bold ${activeTab === 'global' ? 'bg-blue-600 text-white' : 'bg-white text-gray-600 border border-gray-200'}`}
|
||||||
|
>
|
||||||
|
Global ({countFor('global')})
|
||||||
|
</button>
|
||||||
|
{regions.map((region: any) => (
|
||||||
|
<button
|
||||||
|
key={region.id}
|
||||||
|
type="button"
|
||||||
|
data-testid={`store-tab-${region.id}`}
|
||||||
|
onClick={() => setActiveTab(region.id)}
|
||||||
|
className={`shrink-0 rounded-full px-4 py-2 text-sm font-bold ${activeTab === region.id ? 'bg-blue-600 text-white' : 'bg-white text-gray-600 border border-gray-200'}`}
|
||||||
|
>
|
||||||
|
{region.name} ({countFor(region.id)})
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isLoading && !error && visibleStores.length === 0 && (
|
||||||
|
<div className="flex flex-col items-center rounded-xl border border-dashed border-gray-300 bg-white py-12">
|
||||||
|
<Store className="mb-3 h-8 w-8 text-gray-400" />
|
||||||
|
<MyText className="block text-gray-600">
|
||||||
|
{activeTab === 'global'
|
||||||
|
? 'No global stores yet.'
|
||||||
|
: `No stores in ${regions.find((r: any) => r.id === activeTab)?.name ?? 'this region'} yet.`}
|
||||||
|
</MyText>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2" data-testid={`store-grid-${activeTab}`}>
|
||||||
|
{visibleStores.map((store: any) => (
|
||||||
|
<div
|
||||||
|
key={store.id}
|
||||||
|
className="flex flex-col rounded-xl border border-gray-200 bg-white p-5 shadow-sm"
|
||||||
|
>
|
||||||
|
<MyText className="block truncate font-semibold text-gray-900">
|
||||||
|
{store.name}
|
||||||
|
</MyText>
|
||||||
|
<MyText className="mt-1 block text-sm text-gray-500">
|
||||||
|
{store.availableInAllRegions ? 'All regions' : `Region #${store.regionId ?? '—'}`}
|
||||||
|
{' · '}
|
||||||
|
Owner: {store.owner?.name ?? `#${store.ownerId ?? store.owner}`}
|
||||||
|
</MyText>
|
||||||
|
<div className="mt-4 flex gap-2">
|
||||||
|
<Link
|
||||||
|
to="/stores/$id/edit"
|
||||||
|
params={{ id: String(store.id) }}
|
||||||
|
className="flex flex-1 items-center justify-center gap-2 rounded-lg border border-gray-200 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
<Pencil className="h-4 w-4" />
|
||||||
|
Edit
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
BIN
apps/test2.sqlite-shm
Normal file
BIN
apps/test2.sqlite-shm
Normal file
Binary file not shown.
0
apps/test2.sqlite-wal
Normal file
0
apps/test2.sqlite-wal
Normal file
|
|
@ -21,14 +21,24 @@ const RegionGate: React.FC<ReactParentComponent> = ({ children }) => {
|
||||||
const [attempt, setAttempt] = useState(0);
|
const [attempt, setAttempt] = useState(0);
|
||||||
const passedRef = useRef(false);
|
const passedRef = useRef(false);
|
||||||
const appState = useRef(AppState.currentState);
|
const appState = useRef(AppState.currentState);
|
||||||
|
// Set once the first detection completes: later re-runs refresh silently
|
||||||
|
// behind the settled screen instead of flashing the full loading view.
|
||||||
|
const settledRef = useRef(false);
|
||||||
|
const lastRunRef = useRef(0);
|
||||||
|
// True while the user is in OS Settings (via the primary action): the
|
||||||
|
// return re-check must bypass the flapping cooldown below.
|
||||||
|
const expectReturnRef = useRef(false);
|
||||||
|
|
||||||
const runDetection = async () => {
|
const runDetection = async () => {
|
||||||
if (passedRef.current) return;
|
if (passedRef.current) return;
|
||||||
|
lastRunRef.current = Date.now();
|
||||||
setDetecting(true);
|
setDetecting(true);
|
||||||
|
if (!settledRef.current) {
|
||||||
setDenied(false);
|
setDenied(false);
|
||||||
setServicesOff(false);
|
setServicesOff(false);
|
||||||
setDetectError(false);
|
setDetectError(false);
|
||||||
setCoords(null);
|
setCoords(null);
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const { status } = await Location.requestForegroundPermissionsAsync();
|
const { status } = await Location.requestForegroundPermissionsAsync();
|
||||||
if (passedRef.current) return;
|
if (passedRef.current) return;
|
||||||
|
|
@ -48,7 +58,10 @@ const RegionGate: React.FC<ReactParentComponent> = ({ children }) => {
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!passedRef.current) setDetectError(true);
|
if (!passedRef.current) setDetectError(true);
|
||||||
} finally {
|
} finally {
|
||||||
if (!passedRef.current) setDetecting(false);
|
if (!passedRef.current) {
|
||||||
|
setDetecting(false);
|
||||||
|
settledRef.current = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -57,12 +70,17 @@ const RegionGate: React.FC<ReactParentComponent> = ({ children }) => {
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [attempt]);
|
}, [attempt]);
|
||||||
|
|
||||||
// Re-check when returning from OS/app Settings.
|
// Re-check when returning from OS/app Settings. Cooldown guards against
|
||||||
|
// AppState flapping: a background re-run must never flash loading anyway
|
||||||
|
// (see settledRef), but there is no reason to spam the OS location stack.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const sub = AppState.addEventListener('change', (next) => {
|
const sub = AppState.addEventListener('change', (next) => {
|
||||||
if (appState.current.match(/inactive|background/) && next === 'active') {
|
if (appState.current.match(/inactive|background/) && next === 'active') {
|
||||||
|
if (expectReturnRef.current || Date.now() - lastRunRef.current > 15000) {
|
||||||
setAttempt((a) => a + 1);
|
setAttempt((a) => a + 1);
|
||||||
}
|
}
|
||||||
|
expectReturnRef.current = false;
|
||||||
|
}
|
||||||
appState.current = next;
|
appState.current = next;
|
||||||
});
|
});
|
||||||
return () => sub.remove();
|
return () => sub.remove();
|
||||||
|
|
@ -104,6 +122,7 @@ const RegionGate: React.FC<ReactParentComponent> = ({ children }) => {
|
||||||
setAttempt((a) => a + 1);
|
setAttempt((a) => a + 1);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
expectReturnRef.current = true;
|
||||||
await Linking.openSettings();
|
await Linking.openSettings();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -112,7 +131,7 @@ const RegionGate: React.FC<ReactParentComponent> = ({ children }) => {
|
||||||
return <>{children}</>;
|
return <>{children}</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (detecting || regionLoading || (!!coords && !resolved && !resolveFailed)) {
|
if ((detecting && !settledRef.current) || regionLoading || (!!coords && !resolved && !resolveFailed)) {
|
||||||
return (
|
return (
|
||||||
<View style={tw`flex-1 items-center justify-center bg-white`} testID="region-gate-loading">
|
<View style={tw`flex-1 items-center justify-center bg-white`} testID="region-gate-loading">
|
||||||
<ActivityIndicator size="large" />
|
<ActivityIndicator size="large" />
|
||||||
|
|
|
||||||
|
|
@ -98,7 +98,8 @@ export function buildProductsCacheUrl(
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${assetsDomain}${cachePathPrefix}${apiCacheKey}/v-${cacheVersion}/${filename}`
|
const url = `${assetsDomain}${apiCacheKey}/${cachePathPrefix}v-${cacheVersion}/${filename}`
|
||||||
|
return url
|
||||||
}
|
}
|
||||||
|
|
||||||
function useAvailabilityCacheUrl(): string | null {
|
function useAvailabilityCacheUrl(): string | null {
|
||||||
|
|
@ -118,7 +119,8 @@ export function buildAvailabilityCacheUrl(
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${assetsDomain}${cachePathPrefix}av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}`
|
const url = `${assetsDomain}${cachePathPrefix}av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}`
|
||||||
|
return url
|
||||||
}
|
}
|
||||||
|
|
||||||
function useSlotsCacheUrl(): string | null {
|
function useSlotsCacheUrl(): string | null {
|
||||||
|
|
@ -138,7 +140,8 @@ export function buildSlotsCacheUrl(
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${assetsDomain}${cachePathPrefix}slots/v-${slotsVersionNum}/${CACHE_FILENAMES.slots}`
|
const url = `${assetsDomain}${cachePathPrefix}slots/v-${slotsVersionNum}/${CACHE_FILENAMES.slots}`
|
||||||
|
return url
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAllProducts() {
|
export function useAllProducts() {
|
||||||
|
|
@ -260,7 +263,7 @@ export function useStoreWithProducts(storeId: number) {
|
||||||
const cachePathPrefix = essentialConsts?.cachePathPrefix ?? ''
|
const cachePathPrefix = essentialConsts?.cachePathPrefix ?? ''
|
||||||
|
|
||||||
const cacheUrl = assetsDomain && apiCacheKey
|
const cacheUrl = assetsDomain && apiCacheKey
|
||||||
? `${assetsDomain}${cachePathPrefix}${apiCacheKey}/v-${cacheVersion}/stores/${storeId}.json`
|
? `${assetsDomain}${apiCacheKey}/${cachePathPrefix}v-${cacheVersion}/stores/${storeId}.json`
|
||||||
: null
|
: null
|
||||||
const version = cacheUrl ?? ''
|
const version = cacheUrl ?? ''
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -73,7 +73,7 @@ export default function AddToCartDialog() {
|
||||||
const availableSlots = availableSlotIds
|
const availableSlots = availableSlotIds
|
||||||
.map((slotId) => slotMap[slotId])
|
.map((slotId) => slotMap[slotId])
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.filter((slot) => dayjs(slot.deliveryTime).isAfter(dayjs()))
|
.filter((slot) => dayjs(slot.deliveryTime).isAfter(dayjs()) && dayjs(slot.freezeTime).isAfter(dayjs()))
|
||||||
|
|
||||||
const cartItem = cartData?.items?.find((item: any) => item.skuId === product?.id)
|
const cartItem = cartData?.items?.find((item: any) => item.skuId === product?.id)
|
||||||
const isUpdate = (cartItem?.quantity || 0) >= 1
|
const isUpdate = (cartItem?.quantity || 0) >= 1
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import React, { useState } from 'react'
|
import React, { useState } from 'react'
|
||||||
import { trpc } from '../lib/trpc-client'
|
import { trpc } from '../lib/trpc-client'
|
||||||
import { p, pInput as PInput, MyButton, div } from 'web-components'
|
import { useRegion } from '../contexts/RegionContext'
|
||||||
|
import { p, pInput as PInput, MyButton, div, Dropdown } from 'web-components'
|
||||||
import { MapPin, X, Plus } from 'lucide-react'
|
import { MapPin, X, Plus } from 'lucide-react'
|
||||||
import * as Yup from 'yup'
|
import * as Yup from 'yup'
|
||||||
import type { AddressFormProps } from '@packages/shared'
|
import type { AddressFormProps } from '@packages/shared'
|
||||||
|
|
@ -14,12 +15,22 @@ const validationSchema = Yup.object({
|
||||||
state: Yup.string().required('State is required'),
|
state: Yup.string().required('State is required'),
|
||||||
pincode: Yup.string().required('Pincode is required').matches(/^\d{6}$/, 'Pincode must be 6 digits'),
|
pincode: Yup.string().required('Pincode is required').matches(/^\d{6}$/, 'Pincode must be 6 digits'),
|
||||||
isDefault: Yup.boolean(),
|
isDefault: Yup.boolean(),
|
||||||
|
regionId: Yup.number()
|
||||||
|
.typeError('Region is required')
|
||||||
|
.required('Region is required')
|
||||||
|
.min(1, 'Region is required'),
|
||||||
})
|
})
|
||||||
|
|
||||||
export function AddressForm({ onSuccess, initialValues, isEdit = false }: AddressFormProps) {
|
export function AddressForm({ onSuccess, initialValues, isEdit = false }: AddressFormProps) {
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||||
const [submitError, setSubmitError] = useState<string | null>(null)
|
const [submitError, setSubmitError] = useState<string | null>(null)
|
||||||
const [showGoogleMapsField, setShowGoogleMapsField] = useState(!!initialValues?.googleMapsUrl)
|
const [showGoogleMapsField, setShowGoogleMapsField] = useState(!!initialValues?.googleMapsUrl)
|
||||||
|
const { regionId: activeRegionId } = useRegion()
|
||||||
|
const { data: regionsData } = trpc.common.getRegions.useQuery(undefined, { staleTime: Infinity })
|
||||||
|
const regionOptions = ((regionsData as any)?.regions ?? []).map((region: any) => ({
|
||||||
|
label: region.name,
|
||||||
|
value: region.id,
|
||||||
|
}))
|
||||||
const [currentLocation, setCurrentLocation] = useState<{ latitude: number; longitude: number } | null>(
|
const [currentLocation, setCurrentLocation] = useState<{ latitude: number; longitude: number } | null>(
|
||||||
initialValues?.latitude && initialValues?.longitude
|
initialValues?.latitude && initialValues?.longitude
|
||||||
? { latitude: initialValues.latitude, longitude: initialValues.longitude }
|
? { latitude: initialValues.latitude, longitude: initialValues.longitude }
|
||||||
|
|
@ -36,6 +47,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false }: Addres
|
||||||
pincode: initialValues?.pincode || '509001',
|
pincode: initialValues?.pincode || '509001',
|
||||||
isDefault: initialValues?.isDefault || false,
|
isDefault: initialValues?.isDefault || false,
|
||||||
googleMapsUrl: initialValues?.googleMapsUrl || '',
|
googleMapsUrl: initialValues?.googleMapsUrl || '',
|
||||||
|
regionId: initialValues?.regionId ?? activeRegionId ?? '',
|
||||||
})
|
})
|
||||||
|
|
||||||
const [errors, setErrors] = useState<Record<string, string>>({})
|
const [errors, setErrors] = useState<Record<string, string>>({})
|
||||||
|
|
@ -62,7 +74,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false }: Addres
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const handleChange = (field: string, value: string | boolean) => {
|
const handleChange = (field: string, value: string | boolean | number) => {
|
||||||
setValues((prev) => ({ ...prev, [field]: value }))
|
setValues((prev) => ({ ...prev, [field]: value }))
|
||||||
if (errors[field]) {
|
if (errors[field]) {
|
||||||
setErrors((prev) => ({ ...prev, [field]: '' }))
|
setErrors((prev) => ({ ...prev, [field]: '' }))
|
||||||
|
|
@ -77,6 +89,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false }: Addres
|
||||||
|
|
||||||
const payload = {
|
const payload = {
|
||||||
...values,
|
...values,
|
||||||
|
regionId: Number((values as { regionId?: unknown }).regionId),
|
||||||
latitude: currentLocation?.latitude,
|
latitude: currentLocation?.latitude,
|
||||||
longitude: currentLocation?.longitude,
|
longitude: currentLocation?.longitude,
|
||||||
googleMapsUrl: values.googleMapsUrl || undefined,
|
googleMapsUrl: values.googleMapsUrl || undefined,
|
||||||
|
|
@ -226,6 +239,17 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false }: Addres
|
||||||
<p>Set as default address</p>
|
<p>Set as default address</p>
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<Dropdown
|
||||||
|
label="Region"
|
||||||
|
value={(values as { regionId?: string | number }).regionId ?? ''}
|
||||||
|
options={regionOptions}
|
||||||
|
onValueChange={(value) => handleChange('regionId', Number(value))}
|
||||||
|
testID="address-region-dropdown"
|
||||||
|
/>
|
||||||
|
{errors.regionId && <p className="mt-1 text-sm text-red-500">{errors.regionId}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
<MyButton
|
<MyButton
|
||||||
fullWidth
|
fullWidth
|
||||||
textContent={isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')}
|
textContent={isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')}
|
||||||
|
|
|
||||||
273
apps/web-ui/src/components/AddressRegionWatcher.tsx
Normal file
273
apps/web-ui/src/components/AddressRegionWatcher.tsx
Normal file
|
|
@ -0,0 +1,273 @@
|
||||||
|
import React, { useEffect, useRef, useState } from 'react'
|
||||||
|
import dayjs from 'dayjs'
|
||||||
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { BottomDialog, LoadingDialog } from 'web-components'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { useAuth } from '../lib/auth-context'
|
||||||
|
import { useRegion } from '../contexts/RegionContext'
|
||||||
|
import { useAddressStore } from '../lib/stores/address-store'
|
||||||
|
import {
|
||||||
|
useRegionSwitchContext,
|
||||||
|
fetchRegionSlotMap,
|
||||||
|
snapshotCartContext,
|
||||||
|
reconcileCartLines,
|
||||||
|
CART_TYPES,
|
||||||
|
type RegionSwitchLineResult,
|
||||||
|
} from '../hooks/useRegionSwitch'
|
||||||
|
import {
|
||||||
|
getLocalCart,
|
||||||
|
saveLocalCart,
|
||||||
|
saveCartSnapshot,
|
||||||
|
setRegionSwitchInProgress,
|
||||||
|
type LocalCartItem,
|
||||||
|
} from '../hooks/cart-query-hooks'
|
||||||
|
|
||||||
|
const BIG_SHIFT_MS = 60 * 60 * 1000
|
||||||
|
|
||||||
|
interface PreviewLine extends RegionSwitchLineResult {
|
||||||
|
bigShift: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AddressPreview {
|
||||||
|
currentId: number
|
||||||
|
prevId: number | null
|
||||||
|
targetId: number
|
||||||
|
targetName: string
|
||||||
|
lines: PreviewLine[]
|
||||||
|
linesByType: Record<string, LocalCartItem[]>
|
||||||
|
}
|
||||||
|
|
||||||
|
const isBigShift = (line: RegionSwitchLineResult): boolean => {
|
||||||
|
if (line.outcome !== 'moved') return false
|
||||||
|
if (line.oldSlotTime == null || line.newSlotTime == null) return true
|
||||||
|
return Math.abs(dayjs(line.newSlotTime).valueOf() - dayjs(line.oldSlotTime).valueOf()) > BIG_SHIFT_MS
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AddressRegionWatcher: React.FC = () => {
|
||||||
|
const { isAuthenticated } = useAuth()
|
||||||
|
const { regionId: activeRegionId, setRegion } = useRegion()
|
||||||
|
const { selectedAddressId, setSelectedAddressId } = useAddressStore()
|
||||||
|
const { presentResults } = useRegionSwitchContext()
|
||||||
|
const utils = trpc.useUtils()
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
||||||
|
enabled: isAuthenticated,
|
||||||
|
})
|
||||||
|
const { data: regionsData } = trpc.common.getRegions.useQuery(undefined, { staleTime: Infinity })
|
||||||
|
|
||||||
|
const [preview, setPreview] = useState<AddressPreview | null>(null)
|
||||||
|
const [building, setBuilding] = useState(false)
|
||||||
|
const prevRef = useRef<{ id: number; regionId: number } | null>(null)
|
||||||
|
const dismissedRef = useRef<string | null>(null)
|
||||||
|
const seqRef = useRef(0)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isAuthenticated) return
|
||||||
|
const list = (addressesData as any)?.data ?? []
|
||||||
|
const current = list.find((a: any) => a.id === selectedAddressId) ?? null
|
||||||
|
if (!current || current.regionId == null) {
|
||||||
|
if (selectedAddressId == null) prevRef.current = null
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const prev = prevRef.current
|
||||||
|
if (prev && prev.id === current.id) {
|
||||||
|
// Same selection: only an external region switch could have misaligned
|
||||||
|
// us. The explicit region choice wins — re-anchor silently, no dialog.
|
||||||
|
prevRef.current = { id: current.id, regionId: current.regionId }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fully converged already (e.g. a dismissed no-op state)?
|
||||||
|
const dismissKey = `${current.id}|${current.regionId}|${activeRegionId}`
|
||||||
|
if (dismissedRef.current === dismissKey) {
|
||||||
|
prevRef.current = { id: current.id, regionId: current.regionId }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Aligned with the active region: anchor silently.
|
||||||
|
if (current.regionId === activeRegionId) {
|
||||||
|
prevRef.current = { id: current.id, regionId: current.regionId }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const seq = ++seqRef.current
|
||||||
|
const prevId = prev?.id ?? null
|
||||||
|
const targetName =
|
||||||
|
(regionsData as any)?.regions?.find((r: any) => r.id === current.regionId)?.name ?? 'the new region'
|
||||||
|
|
||||||
|
// Snapshot outgoing carts, then move the active region (bound unknown here,
|
||||||
|
// so the server resolves the region default). No cart edits, no dialog.
|
||||||
|
const convergeRegion = async (targetRegionId: number, targetRegionName: string) => {
|
||||||
|
setRegionSwitchInProgress(true)
|
||||||
|
try {
|
||||||
|
if (activeRegionId != null) {
|
||||||
|
for (const cartType of CART_TYPES) {
|
||||||
|
await saveCartSnapshot(activeRegionId, await getLocalCart(cartType), cartType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (targetRegionId !== activeRegionId) {
|
||||||
|
await setRegion(targetRegionId, targetRegionName)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setRegionSwitchInProgress(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const carts = await Promise.all(CART_TYPES.map((t) => getLocalCart(t)))
|
||||||
|
if (seq !== seqRef.current) return
|
||||||
|
const { names, oldSlotTimes } = snapshotCartContext()
|
||||||
|
if (carts.every((c) => c.length === 0)) {
|
||||||
|
// Nothing to reconcile: snapshot + converge silently.
|
||||||
|
prevRef.current = { id: current.id, regionId: current.regionId }
|
||||||
|
await convergeRegion(current.regionId, targetName)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setBuilding(true)
|
||||||
|
const fetched = await fetchRegionSlotMap(utils, current.regionId)
|
||||||
|
if (seq !== seqRef.current) return
|
||||||
|
const lines: PreviewLine[] = []
|
||||||
|
const linesByType: Record<string, LocalCartItem[]> = {}
|
||||||
|
CART_TYPES.forEach((cartType, i) => {
|
||||||
|
const reconciled = reconcileCartLines(carts[i], fetched.slotMap, oldSlotTimes, names)
|
||||||
|
linesByType[cartType] = reconciled.lines
|
||||||
|
for (const r of reconciled.results) {
|
||||||
|
const full: RegionSwitchLineResult = { ...r, cartType }
|
||||||
|
lines.push({ ...full, bigShift: isBigShift(full) })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if (seq !== seqRef.current) return
|
||||||
|
if (lines.every((l) => l.outcome === 'kept')) {
|
||||||
|
// Slots carry over (prices follow via region-scoped reads):
|
||||||
|
// snapshot + converge silently, no dialog.
|
||||||
|
prevRef.current = { id: current.id, regionId: current.regionId }
|
||||||
|
await convergeRegion(current.regionId, targetName)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setPreview({
|
||||||
|
currentId: current.id,
|
||||||
|
prevId,
|
||||||
|
targetId: current.regionId,
|
||||||
|
targetName,
|
||||||
|
lines,
|
||||||
|
linesByType,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Address region preview failed:', error)
|
||||||
|
} finally {
|
||||||
|
if (seq === seqRef.current) setBuilding(false)
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
}, [selectedAddressId, activeRegionId, addressesData, isAuthenticated, regionsData, utils])
|
||||||
|
|
||||||
|
const handleConfirm = async () => {
|
||||||
|
const p = preview
|
||||||
|
if (!p) return
|
||||||
|
setPreview(null)
|
||||||
|
prevRef.current = { id: p.currentId, regionId: p.targetId }
|
||||||
|
setRegionSwitchInProgress(true)
|
||||||
|
try {
|
||||||
|
if (activeRegionId != null) {
|
||||||
|
for (const cartType of CART_TYPES) {
|
||||||
|
await saveCartSnapshot(activeRegionId, await getLocalCart(cartType), cartType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const cartType of CART_TYPES) {
|
||||||
|
await saveLocalCart(p.linesByType[cartType] ?? [], cartType)
|
||||||
|
}
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['local-cart-regular'] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['local-cart-flash'] })
|
||||||
|
if (p.targetId !== activeRegionId) {
|
||||||
|
await setRegion(p.targetId, p.targetName)
|
||||||
|
}
|
||||||
|
presentResults({
|
||||||
|
regionName: p.targetName,
|
||||||
|
lines: p.lines.map(({ bigShift: _dropped, ...rest }) => rest),
|
||||||
|
error: null,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
presentResults({
|
||||||
|
regionName: p.targetName,
|
||||||
|
lines: [],
|
||||||
|
error: error instanceof Error ? error.message : 'Failed to update cart',
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
setRegionSwitchInProgress(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCancel = () => {
|
||||||
|
const p = preview
|
||||||
|
setPreview(null)
|
||||||
|
seqRef.current += 1
|
||||||
|
if (!p) return
|
||||||
|
if (p.prevId == null) {
|
||||||
|
// No previous selection to revert to: remember the dismissal so the
|
||||||
|
// effect doesn't re-prompt for this address/region combination.
|
||||||
|
dismissedRef.current = `${p.currentId}|${p.targetId}|${activeRegionId}`
|
||||||
|
prevRef.current = { id: p.currentId, regionId: p.targetId }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Reverting re-triggers the watcher effect, which anchors prevRef
|
||||||
|
// silently since the regions now match.
|
||||||
|
setSelectedAddressId(p.prevId)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<LoadingDialog open={building} message="Checking your cart…" />
|
||||||
|
<BottomDialog open={preview != null} onClose={handleCancel}>
|
||||||
|
<div className="p-6">
|
||||||
|
<p className="text-lg font-extrabold text-gray-900">Deliver to {preview?.targetName}?</p>
|
||||||
|
<p className="mt-2 text-gray-500">
|
||||||
|
This address is in a different region. Your cart will change as follows:
|
||||||
|
</p>
|
||||||
|
<div className="mt-3">
|
||||||
|
{preview?.lines.map((line, index) => (
|
||||||
|
<div key={`${line.cartType}-${line.skuId}-${index}`} className="border-b border-gray-100 py-2">
|
||||||
|
<p className="truncate font-bold text-gray-900">
|
||||||
|
{line.bigShift && line.outcome === 'moved' ? '⚠️ ' : ''}
|
||||||
|
{line.name} × {line.quantity}
|
||||||
|
</p>
|
||||||
|
{line.outcome === 'moved' && (
|
||||||
|
<p className={line.bigShift ? 'text-sm font-bold text-amber-600' : 'text-sm text-gray-500'}>
|
||||||
|
Slot moved:{' '}
|
||||||
|
{line.oldSlotTime ? dayjs(line.oldSlotTime).format('ddd h:mm A') : 'previous slot'} →{' '}
|
||||||
|
{line.newSlotTime ? dayjs(line.newSlotTime).format('ddd h:mm A') : ''}
|
||||||
|
{line.bigShift ? ' (more than 1 hour)' : ''}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{line.outcome === 'removed' && (
|
||||||
|
<p className="text-sm text-red-500">Removed{line.reason ? ` — ${line.reason}` : ''}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="mt-5 flex flex-row gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="address-region-confirm-cancel"
|
||||||
|
onClick={handleCancel}
|
||||||
|
className="flex-1 rounded-xl border border-gray-200 py-3 font-bold text-gray-900"
|
||||||
|
>
|
||||||
|
Back
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="address-region-confirm-apply"
|
||||||
|
onClick={() => void handleConfirm()}
|
||||||
|
className="flex-1 rounded-xl bg-brand-500 py-3 font-bold text-white"
|
||||||
|
>
|
||||||
|
Confirm
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</BottomDialog>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AddressRegionWatcher
|
||||||
|
|
@ -2,6 +2,9 @@ import React from 'react'
|
||||||
import { useLocation } from '@tanstack/react-router'
|
import { useLocation } from '@tanstack/react-router'
|
||||||
import { BottomNavigation } from './BottomNavigation'
|
import { BottomNavigation } from './BottomNavigation'
|
||||||
import { FloatingCartBar } from './FloatingCartBar'
|
import { FloatingCartBar } from './FloatingCartBar'
|
||||||
|
import { RegionGate } from './RegionGate'
|
||||||
|
import { RegionSwitchDialogs } from './RegionSwitchDialogs'
|
||||||
|
import { AddressRegionWatcher } from './AddressRegionWatcher'
|
||||||
import { Sidebar } from './shell/Sidebar'
|
import { Sidebar } from './shell/Sidebar'
|
||||||
import { Topbar } from './shell/Topbar'
|
import { Topbar } from './shell/Topbar'
|
||||||
|
|
||||||
|
|
@ -39,10 +42,17 @@ export function AppLayout({
|
||||||
const shouldShowCartBar = showCartBar && !shouldHideShell
|
const shouldShowCartBar = showCartBar && !shouldHideShell
|
||||||
|
|
||||||
if (shouldHideShell) {
|
if (shouldHideShell) {
|
||||||
return <main className="min-h-screen">{children}</main>
|
return (
|
||||||
|
<main className="min-h-screen">
|
||||||
|
<RegionGate>{children}</RegionGate>
|
||||||
|
<AddressRegionWatcher />
|
||||||
|
<RegionSwitchDialogs />
|
||||||
|
</main>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<RegionGate>
|
||||||
<div className="shell-grid">
|
<div className="shell-grid">
|
||||||
{/* Desktop rail */}
|
{/* Desktop rail */}
|
||||||
<Sidebar />
|
<Sidebar />
|
||||||
|
|
@ -61,5 +71,8 @@ export function AppLayout({
|
||||||
{/* Mobile bottom nav */}
|
{/* Mobile bottom nav */}
|
||||||
<BottomNavigation />
|
<BottomNavigation />
|
||||||
</div>
|
</div>
|
||||||
|
<AddressRegionWatcher />
|
||||||
|
<RegionSwitchDialogs />
|
||||||
|
</RegionGate>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -69,9 +69,10 @@ export function CheckoutAddressSelector({ onAddressSelect, onAddAddress, onEditA
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{sortedAddresses.map((address: any) => (
|
{sortedAddresses.map((address: any, index: number) => (
|
||||||
<div
|
<div
|
||||||
key={address.id}
|
key={address.id}
|
||||||
|
data-testid={`address-option-${index}`}
|
||||||
onClick={() => handleAddressSelect(address.id)}
|
onClick={() => handleAddressSelect(address.id)}
|
||||||
className={`relative cursor-pointer rounded-xl border-2 p-4 transition-all ${
|
className={`relative cursor-pointer rounded-xl border-2 p-4 transition-all ${
|
||||||
selectedAddressId === address.id
|
selectedAddressId === address.id
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,12 @@ interface PaymentAndOrderProps {
|
||||||
cartItems: any[]
|
cartItems: any[]
|
||||||
isFlashDelivery?: boolean
|
isFlashDelivery?: boolean
|
||||||
onBack?: () => void
|
onBack?: () => void
|
||||||
|
/** Coupon carried over from the cart (?coupons=) — applied to the total. */
|
||||||
|
appliedCoupon?: { code: string; amount: number } | null
|
||||||
|
/** Backend coupon id for the applied coupon (sent with placeOrder). */
|
||||||
|
couponId?: number | null
|
||||||
|
/** Delivery charge quoted by the cart — takes precedence over recomputation. */
|
||||||
|
quotedDeliveryPrice?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export function PaymentAndOrderComponent({
|
export function PaymentAndOrderComponent({
|
||||||
|
|
@ -20,6 +26,9 @@ export function PaymentAndOrderComponent({
|
||||||
cartItems,
|
cartItems,
|
||||||
isFlashDelivery = false,
|
isFlashDelivery = false,
|
||||||
onBack,
|
onBack,
|
||||||
|
appliedCoupon = null,
|
||||||
|
couponId = null,
|
||||||
|
quotedDeliveryPrice,
|
||||||
}: PaymentAndOrderProps) {
|
}: PaymentAndOrderProps) {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
|
@ -42,13 +51,17 @@ export function PaymentAndOrderComponent({
|
||||||
return sum + price * item.quantity
|
return sum + price * item.quantity
|
||||||
}, 0)
|
}, 0)
|
||||||
|
|
||||||
|
const couponDiscount = appliedCoupon?.amount || 0
|
||||||
|
const discountedTotal = Math.max(0, totalPrice - couponDiscount)
|
||||||
|
|
||||||
const deliveryCharge = useMemo(() => {
|
const deliveryCharge = useMemo(() => {
|
||||||
|
if (quotedDeliveryPrice != null && !isNaN(quotedDeliveryPrice)) return quotedDeliveryPrice
|
||||||
const threshold = isFlashDelivery ? constsData?.flashFreeDeliveryThreshold : constsData?.freeDeliveryThreshold
|
const threshold = isFlashDelivery ? constsData?.flashFreeDeliveryThreshold : constsData?.freeDeliveryThreshold
|
||||||
const charge = isFlashDelivery ? constsData?.flashDeliveryCharge : constsData?.deliveryCharge
|
const charge = isFlashDelivery ? constsData?.flashDeliveryCharge : constsData?.deliveryCharge
|
||||||
return totalPrice < threshold ? charge : 0
|
return discountedTotal < threshold ? charge : 0
|
||||||
}, [totalPrice, constsData, isFlashDelivery])
|
}, [discountedTotal, constsData, isFlashDelivery, quotedDeliveryPrice])
|
||||||
|
|
||||||
const finalTotalWithDelivery = totalPrice + deliveryCharge
|
const finalTotalWithDelivery = discountedTotal + deliveryCharge
|
||||||
|
|
||||||
const placeOrderMutation = trpc.user.order.placeOrder.useMutation({
|
const placeOrderMutation = trpc.user.order.placeOrder.useMutation({
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
|
|
@ -93,6 +106,7 @@ export function PaymentAndOrderComponent({
|
||||||
})),
|
})),
|
||||||
addressId: selectedAddress,
|
addressId: selectedAddress,
|
||||||
paymentMethod: paymentMethod,
|
paymentMethod: paymentMethod,
|
||||||
|
couponId: couponId ?? undefined,
|
||||||
userNotes: userNotes,
|
userNotes: userNotes,
|
||||||
isFlashDelivery: isFlashDelivery,
|
isFlashDelivery: isFlashDelivery,
|
||||||
}
|
}
|
||||||
|
|
@ -220,16 +234,24 @@ export function PaymentAndOrderComponent({
|
||||||
const threshold = isFlashDelivery
|
const threshold = isFlashDelivery
|
||||||
? constsData?.flashFreeDeliveryThreshold
|
? constsData?.flashFreeDeliveryThreshold
|
||||||
: constsData?.freeDeliveryThreshold
|
: constsData?.freeDeliveryThreshold
|
||||||
return threshold > 0 && totalPrice < threshold ? (
|
return threshold > 0 && discountedTotal < threshold ? (
|
||||||
<div className="mb-2 flex items-center gap-2 rounded-lg bg-blue-50 p-2.5">
|
<div className="mb-2 flex items-center gap-2 rounded-lg bg-blue-50 p-2.5">
|
||||||
<ShoppingBag className="h-4 w-4 text-blue-600" />
|
<ShoppingBag className="h-4 w-4 text-blue-600" />
|
||||||
<p className="font-medium flex-1 text-xs text-blue-700">
|
<p className="font-medium flex-1 text-xs text-blue-700">
|
||||||
Add products worth ₹{(threshold - totalPrice).toFixed(0)} for free delivery
|
Add products worth ₹{(threshold - discountedTotal).toFixed(0)} for free delivery
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : null
|
) : null
|
||||||
})()}
|
})()}
|
||||||
|
|
||||||
|
{/* Applied Coupon */}
|
||||||
|
{appliedCoupon && (
|
||||||
|
<div className="mb-2 flex items-center justify-between">
|
||||||
|
<p className="text-gray-500">Coupon Applied ({appliedCoupon.code})</p>
|
||||||
|
<p className="font-medium text-green-600">-₹{couponDiscount.toFixed(2)}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Divider */}
|
{/* Divider */}
|
||||||
<div className="my-2 h-px bg-gray-100" />
|
<div className="my-2 h-px bg-gray-100" />
|
||||||
|
|
||||||
|
|
@ -281,7 +303,7 @@ export function PaymentAndOrderComponent({
|
||||||
{/* Bottom Action Bar */}
|
{/* Bottom Action Bar */}
|
||||||
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
<div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
||||||
{!selectedAddress && (
|
{!selectedAddress && (
|
||||||
<div className="mb-3 flex items-center gap-2 rounded-lg bg-red-50 p-3">
|
<div className="mb-3 flex items-center gap-2 rounded-lg bg-red-50 p-3" data-testid="select-address-error">
|
||||||
<Info className="h-4 w-4 text-red-500" />
|
<Info className="h-4 w-4 text-red-500" />
|
||||||
<p className="font-medium text-sm text-red-600">
|
<p className="font-medium text-sm text-red-600">
|
||||||
Please select a delivery address to place order
|
Please select a delivery address to place order
|
||||||
|
|
@ -292,6 +314,7 @@ export function PaymentAndOrderComponent({
|
||||||
<MyButton
|
<MyButton
|
||||||
fullWidth
|
fullWidth
|
||||||
textContent="Place Order"
|
textContent="Place Order"
|
||||||
|
data-testid="place-order-button"
|
||||||
onClick={handlePlaceOrder}
|
onClick={handlePlaceOrder}
|
||||||
disabled={!selectedAddress || placeOrderMutation.isPending}
|
disabled={!selectedAddress || placeOrderMutation.isPending}
|
||||||
className={`py-4 text-lg ${
|
className={`py-4 text-lg ${
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ interface ProductCardProps {
|
||||||
showDeliveryInfo?: boolean
|
showDeliveryInfo?: boolean
|
||||||
miniView?: boolean
|
miniView?: boolean
|
||||||
useAddToCartDialog?: boolean
|
useAddToCartDialog?: boolean
|
||||||
|
variant?: 'default' | 'hero'
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ProductCard({
|
export function ProductCard({
|
||||||
|
|
@ -21,9 +22,11 @@ export function ProductCard({
|
||||||
showDeliveryInfo = true,
|
showDeliveryInfo = true,
|
||||||
miniView = false,
|
miniView = false,
|
||||||
useAddToCartDialog = false,
|
useAddToCartDialog = false,
|
||||||
|
variant = 'default',
|
||||||
}: ProductCardProps) {
|
}: ProductCardProps) {
|
||||||
const [imageError, setImageError] = React.useState(false)
|
const [imageError, setImageError] = React.useState(false)
|
||||||
const [imageLoading, setImageLoading] = React.useState(true)
|
const [imageLoading, setImageLoading] = React.useState(true)
|
||||||
|
const isHero = variant === 'hero'
|
||||||
|
|
||||||
const imageUri = item.images?.[0]
|
const imageUri = item.images?.[0]
|
||||||
|
|
||||||
|
|
@ -100,7 +103,7 @@ export function ProductCard({
|
||||||
{/* Image — grows to fill card height in miniView so content area stays tight */}
|
{/* Image — grows to fill card height in miniView so content area stays tight */}
|
||||||
<div
|
<div
|
||||||
className={`relative w-full overflow-hidden bg-gray-50 ${
|
className={`relative w-full overflow-hidden bg-gray-50 ${
|
||||||
miniView ? 'min-h-[110px] flex-1' : 'aspect-[4/3] shrink-0'
|
miniView ? (isHero ? 'min-h-[90px] flex-1' : 'min-h-[110px] flex-1') : 'aspect-[4/3] shrink-0'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{imageUri && !imageError ? (
|
{imageUri && !imageError ? (
|
||||||
|
|
@ -134,7 +137,7 @@ export function ProductCard({
|
||||||
*/}
|
*/}
|
||||||
|
|
||||||
{displayIsOutOfStock && (
|
{displayIsOutOfStock && (
|
||||||
<div className="absolute inset-0 flex items-center justify-center bg-gray-900/50">
|
<div className="absolute inset-0 flex items-center justify-center bg-gray-900/50" data-testid="out-of-stock-badge">
|
||||||
<div className="rounded-full bg-gray-900 px-3 py-1">
|
<div className="rounded-full bg-gray-900 px-3 py-1">
|
||||||
<p className="text-xs font-bold text-white">Out of Stock</p>
|
<p className="text-xs font-bold text-white">Out of Stock</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -142,7 +145,7 @@ export function ProductCard({
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{miniView && (
|
{miniView && (
|
||||||
<div className="absolute bottom-2 right-2">
|
<div className={`absolute ${isHero ? 'bottom-1.5 right-1.5' : 'bottom-2 right-2'}`}>
|
||||||
{quantity > 0 ? (
|
{quantity > 0 ? (
|
||||||
<MiniQuantifier
|
<MiniQuantifier
|
||||||
value={quantity}
|
value={quantity}
|
||||||
|
|
@ -151,13 +154,14 @@ export function ProductCard({
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<div
|
<div
|
||||||
className="flex h-9 w-9 items-center justify-center rounded-full bg-white shadow-md transition-colors hover:bg-brand-50"
|
data-testid="add-to-cart-icon"
|
||||||
|
className={`flex items-center justify-center rounded-full bg-white shadow-md transition-colors hover:bg-brand-50 ${isHero ? 'h-7 w-7' : 'h-9 w-9'}`}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation()
|
e.stopPropagation()
|
||||||
handleQuantityChange(1)
|
handleQuantityChange(1)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<ShoppingCart className="h-4 w-4 text-brand-600" />
|
<ShoppingCart className={`${isHero ? 'h-3.5 w-3.5' : 'h-4 w-4'} text-brand-600`} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,10 @@ export function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||||
if (isLoading) return
|
if (isLoading) return
|
||||||
if (isAuthenticated) return
|
if (isAuthenticated) return
|
||||||
|
|
||||||
sessionStorage.setItem('auth_redirect', location.pathname)
|
// Preserve full target (path + query) with a timestamp, like native AUTH_REDIRECT_KEY
|
||||||
navigate({ to: '/login', search: { redirect: location.pathname } })
|
const target = location.pathname + location.search
|
||||||
|
sessionStorage.setItem('auth_redirect', JSON.stringify({ target, at: Date.now() }))
|
||||||
|
navigate({ to: '/login', search: { redirect: target } })
|
||||||
}, [isAuthenticated, isLoading])
|
}, [isAuthenticated, isLoading])
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
|
|
|
||||||
152
apps/web-ui/src/components/QuickDeliveryAddressSelector.tsx
Normal file
152
apps/web-ui/src/components/QuickDeliveryAddressSelector.tsx
Normal file
|
|
@ -0,0 +1,152 @@
|
||||||
|
import React, { useState } from 'react'
|
||||||
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
|
import dayjs from 'dayjs'
|
||||||
|
import { ChevronLeft, ChevronDown, Zap } from 'lucide-react'
|
||||||
|
import { BottomDialog } from 'web-components'
|
||||||
|
import { useAuth } from '../lib/auth-context'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { useAddressStore } from '../lib/stores/address-store'
|
||||||
|
import { useSlots } from '../hooks/prominent-api-hooks'
|
||||||
|
|
||||||
|
interface QuickDeliveryAddressSelectorProps {
|
||||||
|
deliveryTime?: string
|
||||||
|
slotId?: number
|
||||||
|
onSlotChange?: (slotId: number) => void
|
||||||
|
isForFlashDelivery?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatTimeRange = (deliveryTime: string | Date) => {
|
||||||
|
const time = dayjs(deliveryTime)
|
||||||
|
const endTime = time.add(1, 'hour')
|
||||||
|
const startPeriod = time.format('A')
|
||||||
|
const endPeriod = endTime.format('A')
|
||||||
|
|
||||||
|
const timeRange =
|
||||||
|
startPeriod === endPeriod
|
||||||
|
? `${time.format('h')}-${endTime.format('h')} ${startPeriod}`
|
||||||
|
: `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`
|
||||||
|
|
||||||
|
return `${time.format('ddd, DD MMM ')}${timeRange}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps> = ({
|
||||||
|
deliveryTime,
|
||||||
|
slotId,
|
||||||
|
onSlotChange,
|
||||||
|
isForFlashDelivery = false,
|
||||||
|
}) => {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const [dialogOpen, setDialogOpen] = useState(false)
|
||||||
|
|
||||||
|
const { isAuthenticated } = useAuth()
|
||||||
|
const { selectedAddressId, setSelectedAddressId } = useAddressStore()
|
||||||
|
|
||||||
|
const { data: defaultAddressData } = trpc.user.address.getDefaultAddress.useQuery(undefined, {
|
||||||
|
enabled: isAuthenticated,
|
||||||
|
})
|
||||||
|
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
||||||
|
enabled: isAuthenticated,
|
||||||
|
})
|
||||||
|
const { data: slotsData } = useSlots()
|
||||||
|
|
||||||
|
const defaultAddress = (defaultAddressData as any)?.data
|
||||||
|
const addresses = ((addressesData as any)?.data || []) as any[]
|
||||||
|
|
||||||
|
const now = dayjs()
|
||||||
|
const liveSlots = ((slotsData as any)?.slots ?? []).filter(
|
||||||
|
(s: any) => dayjs(s.deliveryTime).isAfter(now) && dayjs(s.freezeTime).isAfter(now)
|
||||||
|
)
|
||||||
|
const earliestSlot = [...liveSlots].sort((a: any, b: any) => dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)))[0]
|
||||||
|
|
||||||
|
const slotOptions = liveSlots.map((slot: any) => ({
|
||||||
|
id: slot.id,
|
||||||
|
deliveryTime: formatTimeRange(slot.deliveryTime),
|
||||||
|
closeTime: dayjs(slot.freezeTime).format('h:mm A'),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const getCurrentSlotDisplay = () => {
|
||||||
|
if (isForFlashDelivery) return 'within 1 hour'
|
||||||
|
if (slotId) {
|
||||||
|
const slot = ((slotsData as any)?.slots ?? []).find((s: any) => s.id === slotId)
|
||||||
|
return slot ? formatTimeRange(slot.deliveryTime) : 'Select time'
|
||||||
|
}
|
||||||
|
if (earliestSlot) return formatTimeRange(earliestSlot.deliveryTime)
|
||||||
|
return 'Select time'
|
||||||
|
}
|
||||||
|
|
||||||
|
const getCurrentAddressDisplay = () => {
|
||||||
|
if (selectedAddressId) {
|
||||||
|
const address = addresses.find((a: any) => a.id === selectedAddressId)
|
||||||
|
if (address) return `${address.name} - ${address.addressLine1}`
|
||||||
|
}
|
||||||
|
if (defaultAddress) return `${defaultAddress.name} - ${defaultAddress.addressLine1}`
|
||||||
|
return 'Select address'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep the current address selection valid (mirrors native default-address fallback).
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (isAuthenticated && !selectedAddressId && defaultAddress) {
|
||||||
|
setSelectedAddressId(defaultAddress.id)
|
||||||
|
}
|
||||||
|
}, [isAuthenticated, selectedAddressId, defaultAddress, setSelectedAddressId])
|
||||||
|
|
||||||
|
if (isForFlashDelivery) {
|
||||||
|
return (
|
||||||
|
<div className="mb-1 flex flex-row items-center">
|
||||||
|
<button type="button" onClick={() => window.history.back()} className="-ml-2 p-2" aria-label="Back">
|
||||||
|
<ChevronLeft className="h-6 w-6 text-pink-600" />
|
||||||
|
</button>
|
||||||
|
<p className="ml-2 text-lg font-bold text-pink-600">Delivery in within 1 hour</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="flex flex-1 flex-row items-center gap-2">
|
||||||
|
<button type="button" onClick={() => window.history.back()} className="p-1" aria-label="Back">
|
||||||
|
<ChevronLeft className="h-6 w-6 text-gray-700" />
|
||||||
|
</button>
|
||||||
|
<div className="flex-1">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="quick-delivery-time"
|
||||||
|
onClick={() => setDialogOpen(true)}
|
||||||
|
className="flex w-full items-center rounded-lg border border-brand-200 bg-brand-50 px-3 py-2"
|
||||||
|
>
|
||||||
|
<div className="flex-1 text-left">
|
||||||
|
<p className="text-xs font-bold uppercase text-brand-500">Delivery Time</p>
|
||||||
|
<p className="text-sm font-bold text-brand-900">{deliveryTime ?? getCurrentSlotDisplay()}</p>
|
||||||
|
</div>
|
||||||
|
<ChevronDown className="h-5 w-5 text-brand-500" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<BottomDialog open={dialogOpen} onClose={() => setDialogOpen(false)}>
|
||||||
|
<div className="max-h-[50vh] overflow-y-auto py-6">
|
||||||
|
<p className="mb-4 text-center text-xl font-bold text-gray-900">Select Delivery Time</p>
|
||||||
|
{slotOptions.map((slot: any) => (
|
||||||
|
<button
|
||||||
|
key={slot.id}
|
||||||
|
type="button"
|
||||||
|
data-testid={`quick-delivery-slot-${slot.id}`}
|
||||||
|
onClick={() => {
|
||||||
|
onSlotChange?.(slot.id)
|
||||||
|
setDialogOpen(false)
|
||||||
|
}}
|
||||||
|
className={`mb-2 w-full rounded-lg border p-3 text-left ${
|
||||||
|
slot.id === (slotId || earliestSlot?.id) ? 'border-brand-500 bg-brand-50' : 'border-gray-200 bg-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<p className="font-medium text-gray-900">Delivery: {slot.deliveryTime}</p>
|
||||||
|
<p className="mt-1 text-xs text-gray-500">Orders Close at: {slot.closeTime}</p>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</BottomDialog>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default QuickDeliveryAddressSelector
|
||||||
57
apps/web-ui/src/components/RegionBar.tsx
Normal file
57
apps/web-ui/src/components/RegionBar.tsx
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
import React from 'react'
|
||||||
|
import { MapPin, ChevronDown } from 'lucide-react'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { useRegion } from '../contexts/RegionContext'
|
||||||
|
import { useRegionSwitchContext } from '../hooks/useRegionSwitch'
|
||||||
|
|
||||||
|
interface RegionBarProps {
|
||||||
|
testID?: string
|
||||||
|
/** Current vertical scroll offset — the bar collapses as it grows (matches native scrollY). */
|
||||||
|
scrollTop?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const BAR_HEIGHT = 34
|
||||||
|
|
||||||
|
export const RegionBar: React.FC<RegionBarProps> = ({ testID = 'region-bar', scrollTop = 0 }) => {
|
||||||
|
const { regionId, regionName } = useRegion()
|
||||||
|
const { switchRegion } = useRegionSwitchContext()
|
||||||
|
const { data: regionsData } = trpc.common.getRegions.useQuery(undefined, { staleTime: Infinity })
|
||||||
|
const regions = regionsData?.regions ?? []
|
||||||
|
|
||||||
|
const height = Math.max(0, BAR_HEIGHT - (scrollTop / 48) * BAR_HEIGHT)
|
||||||
|
const opacity = Math.max(0, 1 - scrollTop / 32)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-testid={testID}
|
||||||
|
className="overflow-hidden bg-white"
|
||||||
|
style={{ height, opacity }}
|
||||||
|
>
|
||||||
|
<div className="flex h-[34px] items-center px-4">
|
||||||
|
<MapPin className="h-4 w-4 shrink-0 text-gray-500" />
|
||||||
|
<select
|
||||||
|
data-testid={`${testID}-dropdown`}
|
||||||
|
aria-label="Region"
|
||||||
|
value={regionId ?? ''}
|
||||||
|
onChange={(e) => {
|
||||||
|
const next = regions.find((r: any) => String(r.id) === e.target.value)
|
||||||
|
if (next) void switchRegion(next.id, next.name)
|
||||||
|
}}
|
||||||
|
className="ml-1 min-w-0 flex-1 cursor-pointer appearance-none truncate bg-transparent text-sm font-medium text-gray-600 focus:outline-none"
|
||||||
|
>
|
||||||
|
<option value="" disabled>
|
||||||
|
{regionName ?? 'Detecting region…'}
|
||||||
|
</option>
|
||||||
|
{regions.map((r: any) => (
|
||||||
|
<option key={r.id} value={r.id}>
|
||||||
|
{r.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<ChevronDown className="h-4 w-4 shrink-0 text-gray-500" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default RegionBar
|
||||||
224
apps/web-ui/src/components/RegionGate.tsx
Normal file
224
apps/web-ui/src/components/RegionGate.tsx
Normal file
|
|
@ -0,0 +1,224 @@
|
||||||
|
import React, { useState, useEffect, useRef } from 'react'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { useRegion } from '../contexts/RegionContext'
|
||||||
|
|
||||||
|
type GateReason = 'denied' | 'servicesOff' | 'unserved' | 'error'
|
||||||
|
|
||||||
|
function getBrowserPosition(): Promise<{ lat: number; lng: number }> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (!navigator.geolocation) {
|
||||||
|
const err = new Error('Geolocation not supported') as any
|
||||||
|
err.code = 'UNSUPPORTED'
|
||||||
|
reject(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
navigator.geolocation.getCurrentPosition(
|
||||||
|
(pos) => resolve({ lat: pos.coords.latitude, lng: pos.coords.longitude }),
|
||||||
|
(err) => reject(err),
|
||||||
|
{ enableHighAccuracy: true, timeout: 15000 }
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export const RegionGate: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||||
|
const { regionId, regionName, isLoading: regionLoading, setRegion } = useRegion()
|
||||||
|
const [coords, setCoords] = useState<{ lat: number; lng: number } | null>(null)
|
||||||
|
const [denied, setDenied] = useState(false)
|
||||||
|
const [servicesOff, setServicesOff] = useState(false)
|
||||||
|
const [detectError, setDetectError] = useState(false)
|
||||||
|
const [detecting, setDetecting] = useState(true)
|
||||||
|
const [showPicker, setShowPicker] = useState(false)
|
||||||
|
const [picked, setPicked] = useState(false)
|
||||||
|
const [attempt, setAttempt] = useState(0)
|
||||||
|
const passedRef = useRef(false)
|
||||||
|
// Set once the first detection completes: later re-runs refresh silently
|
||||||
|
// behind the settled screen instead of flashing the full loading view.
|
||||||
|
const settledRef = useRef(false)
|
||||||
|
const lastRunRef = useRef(0)
|
||||||
|
|
||||||
|
const runDetection = async () => {
|
||||||
|
if (passedRef.current) return
|
||||||
|
lastRunRef.current = Date.now()
|
||||||
|
setDetecting(true)
|
||||||
|
if (!settledRef.current) {
|
||||||
|
setDenied(false)
|
||||||
|
setServicesOff(false)
|
||||||
|
setDetectError(false)
|
||||||
|
setCoords(null)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const pos = await getBrowserPosition()
|
||||||
|
if (passedRef.current) return
|
||||||
|
setCoords(pos)
|
||||||
|
} catch (error: any) {
|
||||||
|
if (passedRef.current) return
|
||||||
|
// 1 = PERMISSION_DENIED, 2 = POSITION_UNAVAILABLE (services off), 3 = TIMEOUT
|
||||||
|
if (error?.code === 1) setDenied(true)
|
||||||
|
else if (error?.code === 2 || error?.code === 'UNSUPPORTED') setServicesOff(true)
|
||||||
|
else setDetectError(true)
|
||||||
|
} finally {
|
||||||
|
if (!passedRef.current) {
|
||||||
|
setDetecting(false)
|
||||||
|
settledRef.current = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void runDetection()
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [attempt])
|
||||||
|
|
||||||
|
// Re-check when the tab becomes visible again (user may have changed browser site settings).
|
||||||
|
// Cooldown guards against visibility flapping; the retry button always re-runs immediately.
|
||||||
|
useEffect(() => {
|
||||||
|
const onVisible = () => {
|
||||||
|
if (document.visibilityState === 'visible' && !passedRef.current) {
|
||||||
|
if (Date.now() - lastRunRef.current > 15000) setAttempt((a) => a + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener('visibilitychange', onVisible)
|
||||||
|
window.addEventListener('focus', onVisible)
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('visibilitychange', onVisible)
|
||||||
|
window.removeEventListener('focus', onVisible)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const resolveQuery = trpc.common.resolveRegionForLocation.useQuery(
|
||||||
|
{ lat: coords?.lat ?? 0, lng: coords?.lng ?? 0 },
|
||||||
|
{ enabled: !!coords, retry: false, refetchOnWindowFocus: false, staleTime: Infinity }
|
||||||
|
)
|
||||||
|
|
||||||
|
const resolved = resolveQuery.data
|
||||||
|
const resolveFailed = resolveQuery.isError
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (resolved?.regionId != null) {
|
||||||
|
passedRef.current = true
|
||||||
|
void setRegion(resolved.regionId, resolved.regionName ?? '', resolved.boundId, resolved.boundName)
|
||||||
|
}
|
||||||
|
}, [resolved, setRegion])
|
||||||
|
|
||||||
|
const { data: regionsData, isLoading: regionsLoading } = trpc.common.getRegions.useQuery(undefined, {
|
||||||
|
staleTime: Infinity,
|
||||||
|
})
|
||||||
|
|
||||||
|
const handlePick = (id: number, name: string) => {
|
||||||
|
passedRef.current = true
|
||||||
|
setPicked(true)
|
||||||
|
void setRegion(id, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlePrimaryAction = async () => {
|
||||||
|
// No programmatic path to browser site settings — retry detection.
|
||||||
|
setAttempt((a) => a + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GPS resolved to a served region, or the user picked/continued manually.
|
||||||
|
if (resolved?.regionId != null || picked) {
|
||||||
|
return <>{children}</>
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((detecting && !settledRef.current) || regionLoading || (!!coords && !resolved && !resolveFailed)) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center bg-white" data-testid="region-gate-loading">
|
||||||
|
<div className="flex flex-col items-center">
|
||||||
|
<div className="h-10 w-10 animate-spin rounded-full border-4 border-brand-500 border-t-transparent" />
|
||||||
|
<p className="mt-3 text-gray-500">Detecting your region…</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const detectionBlocked = denied || servicesOff
|
||||||
|
const reason: GateReason = denied
|
||||||
|
? 'denied'
|
||||||
|
: servicesOff
|
||||||
|
? 'servicesOff'
|
||||||
|
: resolveFailed || detectError
|
||||||
|
? 'error'
|
||||||
|
: 'unserved'
|
||||||
|
|
||||||
|
// Hard failure (permission or location switch): message + action, picker on demand.
|
||||||
|
if ((detectionBlocked || showPicker) && reason !== 'unserved') {
|
||||||
|
if (!showPicker) {
|
||||||
|
const subheading = denied
|
||||||
|
? 'We need location permission to auto-detect your region. Allow location access for this site in your browser, or choose your region manually.'
|
||||||
|
: 'Your location is turned off. Turn it on to auto-detect your region, or choose your region manually.'
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center bg-white px-8" data-testid="region-gate-blocked">
|
||||||
|
<div className="w-full max-w-md">
|
||||||
|
<p className="text-center text-2xl font-extrabold text-gray-900">Unable to obtain location</p>
|
||||||
|
<p className="mt-3 text-center text-gray-500">{subheading}</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="region-gate-action"
|
||||||
|
onClick={handlePrimaryAction}
|
||||||
|
className="mt-8 w-full rounded-xl bg-brand-500 py-4 font-bold text-white"
|
||||||
|
>
|
||||||
|
Retry detection
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="region-gate-manual"
|
||||||
|
onClick={() => setShowPicker(true)}
|
||||||
|
className="mt-3 w-full rounded-xl border border-gray-200 py-4 font-bold text-gray-900"
|
||||||
|
>
|
||||||
|
Choose region manually
|
||||||
|
</button>
|
||||||
|
{regionId != null && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="region-gate-continue-stored"
|
||||||
|
onClick={() => handlePick(regionId, regionName ?? '')}
|
||||||
|
className="mt-3 w-full text-center text-sm text-gray-500"
|
||||||
|
>
|
||||||
|
Continue with {regionName ?? 'saved region'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Region picker: unserved GPS, resolution failure, or manual choice.
|
||||||
|
const pickerTitle = reason === 'unserved' ? 'Outside service area' : 'Choose your region'
|
||||||
|
const pickerMessage =
|
||||||
|
reason === 'unserved'
|
||||||
|
? 'Your current location is outside the areas we serve. You can still continue by picking a region below.'
|
||||||
|
: reason === 'error'
|
||||||
|
? 'We could not detect your region. Pick one below to continue.'
|
||||||
|
: 'Pick your region below to continue.'
|
||||||
|
const regions = regionsData?.regions ?? []
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-white px-6 pt-20" data-testid="region-gate-picker">
|
||||||
|
<div className="mx-auto w-full max-w-md">
|
||||||
|
<p className="text-2xl font-extrabold text-gray-900">{pickerTitle}</p>
|
||||||
|
<p className="mb-6 mt-2 text-gray-500">{pickerMessage}</p>
|
||||||
|
{regionsLoading ? (
|
||||||
|
<div className="flex justify-center">
|
||||||
|
<div className="h-10 w-10 animate-spin rounded-full border-4 border-brand-500 border-t-transparent" />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
regions.map((region: any) => (
|
||||||
|
<button
|
||||||
|
key={region.id}
|
||||||
|
type="button"
|
||||||
|
data-testid={`region-pick-${region.id}`}
|
||||||
|
onClick={() => handlePick(region.id, region.name)}
|
||||||
|
className="mb-3 w-full rounded-xl border border-gray-200 px-4 py-4 text-left"
|
||||||
|
>
|
||||||
|
<p className="text-lg font-bold text-gray-900">{region.name}</p>
|
||||||
|
{!!region.description && <p className="mt-1 text-sm text-gray-500">{region.description}</p>}
|
||||||
|
</button>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default RegionGate
|
||||||
58
apps/web-ui/src/components/RegionSwitchDialogs.tsx
Normal file
58
apps/web-ui/src/components/RegionSwitchDialogs.tsx
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
import React from 'react'
|
||||||
|
import dayjs from 'dayjs'
|
||||||
|
import { BottomDialog, LoadingDialog } from 'web-components'
|
||||||
|
import { useRegionSwitchContext } from '../hooks/useRegionSwitch'
|
||||||
|
|
||||||
|
export const RegionSwitchDialogs: React.FC = () => {
|
||||||
|
const { isSwitching, switchMessage, results, clearResults } = useRegionSwitchContext()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<LoadingDialog open={isSwitching} message={switchMessage} />
|
||||||
|
<BottomDialog open={results != null} onClose={clearResults}>
|
||||||
|
<div className="p-6">
|
||||||
|
<p className="text-lg font-extrabold text-gray-900">
|
||||||
|
{results?.error ? 'Region switch failed' : `Cart updated for ${results?.regionName ?? ''}`}
|
||||||
|
</p>
|
||||||
|
{results?.error ? (
|
||||||
|
<p className="mt-2 text-gray-500">{results.error}</p>
|
||||||
|
) : (
|
||||||
|
<div className="mt-3">
|
||||||
|
{results?.lines.length === 0 && (
|
||||||
|
<p className="text-gray-500">Your cart is empty in this region.</p>
|
||||||
|
)}
|
||||||
|
{(results?.lines ?? []).map((line, index) => (
|
||||||
|
<div key={`${line.cartType}-${line.skuId}-${index}`} className="border-b border-gray-100 py-2">
|
||||||
|
<p className="truncate font-bold text-gray-900">
|
||||||
|
{line.name} × {line.quantity}
|
||||||
|
</p>
|
||||||
|
{line.outcome === 'kept' && <p className="text-sm text-gray-500">No change</p>}
|
||||||
|
{line.outcome === 'moved' && (
|
||||||
|
<p className="text-sm text-gray-500">
|
||||||
|
Slot moved:{' '}
|
||||||
|
{line.oldSlotTime ? dayjs(line.oldSlotTime).format('ddd h:mm A') : 'previous slot'} →{' '}
|
||||||
|
{line.newSlotTime ? dayjs(line.newSlotTime).format('ddd h:mm A') : ''}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{line.outcome === 'removed' && (
|
||||||
|
<p className="text-sm text-red-500">Removed{line.reason ? ` — ${line.reason}` : ''}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="region-switch-dialog-close"
|
||||||
|
onClick={clearResults}
|
||||||
|
className="mt-5 w-full rounded-xl bg-brand-500 py-3 font-bold text-white"
|
||||||
|
>
|
||||||
|
Done
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</BottomDialog>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default RegionSwitchDialogs
|
||||||
955
apps/web-ui/src/components/cart-page.tsx
Normal file
955
apps/web-ui/src/components/cart-page.tsx
Normal file
|
|
@ -0,0 +1,955 @@
|
||||||
|
import React, { useState, useEffect, useMemo } from 'react'
|
||||||
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
|
import dayjs from 'dayjs'
|
||||||
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { Quantifier, BottomDialog, Dropdown } from 'web-components'
|
||||||
|
import { Truck, Trash2, Ticket, ChevronRight, Clock, X, Info, ShoppingBag } from 'lucide-react'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { useAuth } from '../lib/auth-context'
|
||||||
|
import { useRegion, useRegionParams } from '../contexts/RegionContext'
|
||||||
|
import { useAddressStore } from '../lib/stores/address-store'
|
||||||
|
import { AddressForm } from './AddressForm'
|
||||||
|
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
||||||
|
import { useCentralSlotStore } from '../lib/stores/central-slot-store'
|
||||||
|
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks'
|
||||||
|
import { useGetEssentialConsts } from '../hooks/prominent-api-hooks'
|
||||||
|
|
||||||
|
const formatDeliverySlot = (deliveryTime: string): string => {
|
||||||
|
const time = dayjs(deliveryTime)
|
||||||
|
const endTime = time.add(1, 'hour')
|
||||||
|
const startPeriod = time.format('A')
|
||||||
|
const endPeriod = endTime.format('A')
|
||||||
|
|
||||||
|
const range =
|
||||||
|
startPeriod === endPeriod
|
||||||
|
? `${time.format('h')}-${endTime.format('h')} ${startPeriod}`
|
||||||
|
: `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`
|
||||||
|
|
||||||
|
return `${time.format('ddd, DD MMM ')}${range}`
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DeliverySlotGroupItem {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
quantity: number
|
||||||
|
unitNotation?: string
|
||||||
|
image?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DeliverySlotGroup {
|
||||||
|
slotId: number
|
||||||
|
label: string
|
||||||
|
items: DeliverySlotGroupItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DeliverySlotMergeSuggestion {
|
||||||
|
slotId: number
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function DeliverySlotSummary({
|
||||||
|
groups,
|
||||||
|
mergeSuggestion,
|
||||||
|
onMerge,
|
||||||
|
}: {
|
||||||
|
groups: DeliverySlotGroup[]
|
||||||
|
mergeSuggestion?: DeliverySlotMergeSuggestion | null
|
||||||
|
onMerge?: () => void
|
||||||
|
}) {
|
||||||
|
const [openGroup, setOpenGroup] = useState<DeliverySlotGroup | null>(null)
|
||||||
|
|
||||||
|
if (groups.length === 0) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div data-testid="delivery-slot-summary" className="mb-4 overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm">
|
||||||
|
<div className="border-b border-gray-100 bg-gray-50 px-4 py-3">
|
||||||
|
<p className="text-base font-bold text-gray-900">Delivery Slot</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-4">
|
||||||
|
{groups.map((group, index) => (
|
||||||
|
<div
|
||||||
|
key={group.slotId}
|
||||||
|
className={`flex items-center justify-between py-2.5 ${index > 0 ? 'border-t border-gray-100' : ''}`}
|
||||||
|
>
|
||||||
|
<div className="mr-3 flex flex-1 items-center">
|
||||||
|
<Clock className="mr-2 h-4 w-4 text-gray-500" />
|
||||||
|
<p className="flex-1 text-sm text-gray-700">{group.label}</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid={`delivery-slot-items-${group.slotId}`}
|
||||||
|
onClick={() => setOpenGroup(group)}
|
||||||
|
className="flex items-center"
|
||||||
|
>
|
||||||
|
<span className="text-sm font-medium text-brand-600">
|
||||||
|
{group.items.length} {group.items.length === 1 ? 'item' : 'items'}
|
||||||
|
</span>
|
||||||
|
<ChevronRight className="h-4 w-4 text-brand-600" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{!!mergeSuggestion && (
|
||||||
|
<div
|
||||||
|
data-testid="delivery-slot-merge"
|
||||||
|
className="mt-3 flex items-center justify-between rounded-xl border border-brand-200 bg-brand-50 px-3 py-2.5"
|
||||||
|
>
|
||||||
|
<div className="mr-2 flex flex-1 items-center">
|
||||||
|
<p className="ml-2 flex-1 text-sm font-medium text-brand-700">
|
||||||
|
Deliver All items at {mergeSuggestion.label}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button type="button" data-testid="delivery-slot-merge-apply" onClick={onMerge} className="p-1">
|
||||||
|
<ChevronRight className="h-5 w-5 text-brand-600" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<BottomDialog open={!!openGroup} onClose={() => setOpenGroup(null)}>
|
||||||
|
<div className="p-6">
|
||||||
|
<div className="mb-4 flex items-start justify-between">
|
||||||
|
<div className="mr-3 flex-1">
|
||||||
|
<p className="text-lg font-bold text-gray-900">Items</p>
|
||||||
|
<p className="mt-0.5 text-xs text-gray-500">{openGroup?.label}</p>
|
||||||
|
</div>
|
||||||
|
<button type="button" onClick={() => setOpenGroup(null)} className="p-1" aria-label="Close">
|
||||||
|
<X className="h-5 w-5 text-gray-400" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{openGroup?.items.map((item) => (
|
||||||
|
<div key={item.id} className="flex items-center border-b border-gray-50 py-3">
|
||||||
|
{item.image ? (
|
||||||
|
<img src={item.image} alt="" className="mr-3 h-10 w-10 rounded-lg bg-gray-100 object-cover" />
|
||||||
|
) : (
|
||||||
|
<div className="mr-3 h-10 w-10 rounded-lg bg-gray-100" />
|
||||||
|
)}
|
||||||
|
<div className="flex-1">
|
||||||
|
<p className="truncate text-sm text-gray-900">{item.name}</p>
|
||||||
|
{!!item.unitNotation && <p className="mt-0.5 text-xs text-gray-500">{item.unitNotation}</p>}
|
||||||
|
</div>
|
||||||
|
<p className="text-sm font-bold text-gray-900">x{item.quantity}</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</BottomDialog>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CartPage({ isFlashDelivery = false }: { isFlashDelivery?: boolean }) {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const { isAuthenticated } = useAuth()
|
||||||
|
const regionParams = useRegionParams()
|
||||||
|
const { regionId: currentRegionId } = useRegion()
|
||||||
|
const { selectedAddressId, setSelectedAddressId } = useAddressStore()
|
||||||
|
const utils = trpc.useUtils()
|
||||||
|
const cartType: 'regular' | 'flash' = isFlashDelivery ? 'flash' : 'regular'
|
||||||
|
|
||||||
|
const [quantities, setQuantities] = useState<Record<number, number>>({})
|
||||||
|
const { data: cartData, isLoading, error } = useGetCart(cartType)
|
||||||
|
|
||||||
|
const productIds = cartData?.items.map((item) => item.skuId) || []
|
||||||
|
|
||||||
|
const { data: slotsData, isLoading: isSlotsLoading } = trpc.user.cart.getCartSlots.useQuery(
|
||||||
|
{ productIds, ...regionParams },
|
||||||
|
{ enabled: productIds.length > 0, refetchOnWindowFocus: false }
|
||||||
|
)
|
||||||
|
|
||||||
|
const { data: couponsRaw } = trpc.user.coupon.getEligible.useQuery(undefined, {
|
||||||
|
enabled: isAuthenticated,
|
||||||
|
})
|
||||||
|
const { data: constsData } = useGetEssentialConsts()
|
||||||
|
const products = useCentralProductStore((state) => state.products)
|
||||||
|
const productsById = useCentralProductStore((state) => state.productsById)
|
||||||
|
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap)
|
||||||
|
|
||||||
|
const cartItems = cartData?.items || []
|
||||||
|
|
||||||
|
const flashEligibleProductIds = useMemo(() => {
|
||||||
|
if (!products.length) return new Set<number>()
|
||||||
|
return new Set(products.filter((product) => productSlotsMap[product.id]?.isFlashAvailable).map((product) => product.id))
|
||||||
|
}, [products, productSlotsMap])
|
||||||
|
|
||||||
|
const baseTotalPrice = useMemo(
|
||||||
|
() =>
|
||||||
|
cartItems
|
||||||
|
.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
||||||
|
.reduce((sum, item) => {
|
||||||
|
const product = productsById[item.skuId]
|
||||||
|
const price = product?.price || 0
|
||||||
|
return sum + price * (quantities[item.id] || item.quantity)
|
||||||
|
}, 0),
|
||||||
|
[cartItems, quantities, productsById, productSlotsMap]
|
||||||
|
)
|
||||||
|
|
||||||
|
const generateCouponDescription = (coupon: any): string => {
|
||||||
|
let desc = ''
|
||||||
|
if (coupon.discountPercent) desc += `${coupon.discountPercent}% off`
|
||||||
|
else if (coupon.flatDiscount) desc += `₹${coupon.flatDiscount} off`
|
||||||
|
if (coupon.minOrder) desc += ` on orders above ₹${coupon.minOrder}`
|
||||||
|
if (coupon.maxValue) desc += ` (max discount ₹${coupon.maxValue})`
|
||||||
|
return desc
|
||||||
|
}
|
||||||
|
|
||||||
|
const eligibleCoupons = useMemo(() => {
|
||||||
|
if (!(couponsRaw as any)?.data) return []
|
||||||
|
return ((couponsRaw as any).data as any[])
|
||||||
|
.map((coupon) => {
|
||||||
|
let isEligible = true
|
||||||
|
let ineligibilityReason = ''
|
||||||
|
if (coupon.maxLimitForUser && coupon.usages.length >= coupon.maxLimitForUser) {
|
||||||
|
isEligible = false
|
||||||
|
ineligibilityReason = 'Usage limit exceeded'
|
||||||
|
}
|
||||||
|
if (coupon.minOrder && parseFloat(coupon.minOrder) > baseTotalPrice) {
|
||||||
|
isEligible = false
|
||||||
|
ineligibilityReason = `Min order ₹${coupon.minOrder}`
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: coupon.id,
|
||||||
|
code: coupon.couponCode,
|
||||||
|
discountType: coupon.discountPercent ? 'percentage' : 'flat',
|
||||||
|
discountValue: parseFloat(coupon.discountPercent || coupon.flatDiscount || '0'),
|
||||||
|
maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined,
|
||||||
|
minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined,
|
||||||
|
description: generateCouponDescription(coupon),
|
||||||
|
exclusiveApply: coupon.exclusiveApply,
|
||||||
|
isEligible,
|
||||||
|
ineligibilityReason: isEligible ? undefined : ineligibilityReason,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter((coupon) => coupon.ineligibilityReason !== 'Usage limit exceeded')
|
||||||
|
}, [couponsRaw, baseTotalPrice])
|
||||||
|
|
||||||
|
const updateCartItem = useUpdateCartItem(cartType)
|
||||||
|
const removeFromCart = useRemoveFromCart(cartType)
|
||||||
|
|
||||||
|
const [selectedSlots, setSelectedSlots] = useState<Record<number, number>>({})
|
||||||
|
const [selectedCouponId, setSelectedCouponId] = useState<number | null>(null)
|
||||||
|
const [couponDialogOpen, setCouponDialogOpen] = useState(false)
|
||||||
|
const [showAddAddress, setShowAddAddress] = useState(false)
|
||||||
|
const [regionPickOpen, setRegionPickOpen] = useState(false)
|
||||||
|
const [pendingRegionId, setPendingRegionId] = useState<number | null>(null)
|
||||||
|
const [pendingAddresses, setPendingAddresses] = useState<any[]>([])
|
||||||
|
|
||||||
|
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
||||||
|
enabled: isAuthenticated,
|
||||||
|
})
|
||||||
|
const addresses = (addressesData as any)?.data ?? []
|
||||||
|
const { data: regionsData } = trpc.common.getRegions.useQuery(undefined, { staleTime: Infinity })
|
||||||
|
const pendingRegionName = (regionsData as any)?.regions?.find((r: any) => r.id === pendingRegionId)?.name ?? ''
|
||||||
|
const selectedAddress = addresses.find((a: any) => a.id === selectedAddressId)
|
||||||
|
|
||||||
|
const handleAddressAdded = async (addressId?: number) => {
|
||||||
|
setShowAddAddress(false)
|
||||||
|
if (!addressId) return
|
||||||
|
const fresh = await utils.user.address.getUserAddresses.fetch().catch(() => null)
|
||||||
|
const created = (fresh as any)?.data?.find((a: any) => a.id === addressId)
|
||||||
|
const createdRegionId = created?.regionId ?? null
|
||||||
|
if (createdRegionId == null || currentRegionId == null || createdRegionId === currentRegionId) {
|
||||||
|
setSelectedAddressId(addressId)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const inRegion = ((fresh as any)?.data ?? []).filter((a: any) => a.regionId === createdRegionId)
|
||||||
|
setPendingAddresses(inRegion)
|
||||||
|
setPendingRegionId(createdRegionId)
|
||||||
|
setRegionPickOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getAvailableSlotsForProduct = useMemo(() => {
|
||||||
|
return (productId: number) => {
|
||||||
|
if (!slotsData || !(slotsData as any)[productId]) return []
|
||||||
|
return ((slotsData as any)[productId] as any[])
|
||||||
|
.filter((slot) => dayjs(slot.deliveryTime).isAfter(dayjs()) && dayjs(slot.freezeTime).isAfter(dayjs()))
|
||||||
|
.map((slot) => {
|
||||||
|
const time = dayjs(slot.deliveryTime)
|
||||||
|
const endTime = time.add(1, 'hour')
|
||||||
|
const startPeriod = time.format('A')
|
||||||
|
const endPeriod = endTime.format('A')
|
||||||
|
const timeRange =
|
||||||
|
startPeriod === endPeriod
|
||||||
|
? `${time.format('h')}-${endTime.format('h')} ${startPeriod}`
|
||||||
|
: `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`
|
||||||
|
return {
|
||||||
|
label: `Delivery: ${time.format('ddd, DD MMM ')}${timeRange} - Close time: ${dayjs(slot.freezeTime).format('h:mm a')}`,
|
||||||
|
value: slot.id,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}, [slotsData])
|
||||||
|
|
||||||
|
const selectedCoupons = useMemo(
|
||||||
|
() =>
|
||||||
|
selectedCouponId ? eligibleCoupons?.filter((coupon) => coupon.id === selectedCouponId && coupon.isEligible) : [],
|
||||||
|
[eligibleCoupons, selectedCouponId]
|
||||||
|
)
|
||||||
|
|
||||||
|
const totalPrice = cartItems
|
||||||
|
.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
||||||
|
.reduce((sum, item) => {
|
||||||
|
const product = productsById[item.skuId]
|
||||||
|
const quantity = quantities[item.id] || item.quantity
|
||||||
|
const price = isFlashDelivery ? (product?.flashPrice ?? product?.price ?? 0) : product?.price || 0
|
||||||
|
return sum + Number(price) * quantity
|
||||||
|
}, 0)
|
||||||
|
|
||||||
|
const totalSavings = cartItems
|
||||||
|
.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
||||||
|
.reduce((sum, item) => {
|
||||||
|
const product = productsById[item.skuId]
|
||||||
|
const quantity = quantities[item.id] || item.quantity
|
||||||
|
const marketPrice = Number(product?.marketPrice || 0)
|
||||||
|
const price = isFlashDelivery ? (product?.flashPrice ?? product?.price ?? 0) : product?.price || 0
|
||||||
|
const saving = marketPrice - Number(price)
|
||||||
|
return sum + (saving > 0 ? saving : 0) * quantity
|
||||||
|
}, 0)
|
||||||
|
|
||||||
|
const dropdownData = useMemo(
|
||||||
|
() =>
|
||||||
|
eligibleCoupons?.map((coupon) => {
|
||||||
|
const discount =
|
||||||
|
coupon.discountType === 'percentage'
|
||||||
|
? Math.min((totalPrice * coupon.discountValue) / 100, coupon.maxValue || Infinity)
|
||||||
|
: Math.min(coupon.discountValue, coupon.maxValue || totalPrice)
|
||||||
|
const saveString = !isNaN(discount) ? ` (Save ₹${discount})` : ''
|
||||||
|
const baseLabel = `${coupon.code} - ${coupon.description}${coupon.isEligible ? saveString : ''}`
|
||||||
|
const label = coupon.isEligible ? baseLabel : `${baseLabel} (${coupon.ineligibilityReason})`
|
||||||
|
return { label, value: coupon.id, disabled: !coupon.isEligible }
|
||||||
|
}) || [],
|
||||||
|
[eligibleCoupons, totalPrice]
|
||||||
|
)
|
||||||
|
|
||||||
|
const discountAmount = useMemo(
|
||||||
|
() =>
|
||||||
|
selectedCoupons?.reduce(
|
||||||
|
(sum, coupon) =>
|
||||||
|
sum +
|
||||||
|
(coupon.discountType === 'percentage'
|
||||||
|
? Math.min((totalPrice * coupon.discountValue) / 100, coupon.maxValue || Infinity)
|
||||||
|
: Math.min(coupon.discountValue, coupon.maxValue || totalPrice)),
|
||||||
|
0
|
||||||
|
) || 0,
|
||||||
|
[selectedCoupons, totalPrice]
|
||||||
|
)
|
||||||
|
|
||||||
|
const finalTotal = totalPrice - discountAmount
|
||||||
|
|
||||||
|
const deliveryCharge = useMemo(() => {
|
||||||
|
const threshold = isFlashDelivery ? (constsData as any)?.flashFreeDeliveryThreshold : (constsData as any)?.freeDeliveryThreshold
|
||||||
|
const charge = isFlashDelivery ? (constsData as any)?.flashDeliveryCharge : (constsData as any)?.deliveryCharge
|
||||||
|
return finalTotal < threshold ? charge : 0
|
||||||
|
}, [finalTotal, constsData, isFlashDelivery])
|
||||||
|
|
||||||
|
const freeDeliveryThreshold = useMemo(() => {
|
||||||
|
return isFlashDelivery ? (constsData as any)?.flashFreeDeliveryThreshold : (constsData as any)?.freeDeliveryThreshold
|
||||||
|
}, [constsData, isFlashDelivery])
|
||||||
|
|
||||||
|
const finalTotalWithDelivery = finalTotal + deliveryCharge
|
||||||
|
const hasAvailableItems = cartItems.some((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
||||||
|
|
||||||
|
const slotGroups = useMemo<DeliverySlotGroup[]>(() => {
|
||||||
|
if (isFlashDelivery || cartItems.length === 0) return []
|
||||||
|
const groupMap = new Map<number, DeliverySlotGroup>()
|
||||||
|
cartItems.forEach((item) => {
|
||||||
|
const slotId = selectedSlots[item.id]
|
||||||
|
if (slotId === undefined || slotId === null) return
|
||||||
|
if (!groupMap.has(slotId)) {
|
||||||
|
let label = ''
|
||||||
|
if (slotsData) {
|
||||||
|
for (const productId of Object.keys(slotsData as any)) {
|
||||||
|
const slot = ((slotsData as any)[Number(productId)] as any[])?.find((s) => s.id === slotId)
|
||||||
|
if (slot) {
|
||||||
|
label = formatDeliverySlot(slot.deliveryTime)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
groupMap.set(slotId, { slotId, label, items: [] })
|
||||||
|
}
|
||||||
|
const product = productsById[item.skuId]
|
||||||
|
groupMap.get(slotId)!.items.push({
|
||||||
|
id: item.id,
|
||||||
|
name: product?.name || 'Item',
|
||||||
|
quantity: quantities[item.id] || item.quantity,
|
||||||
|
unitNotation: product?.unitNotation,
|
||||||
|
image: product?.images?.[0],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return Array.from(groupMap.values()).sort((a, b) => a.slotId - b.slotId)
|
||||||
|
}, [isFlashDelivery, cartItems, selectedSlots, slotsData, productsById, quantities])
|
||||||
|
|
||||||
|
const mergeSuggestion = useMemo<DeliverySlotMergeSuggestion | null>(() => {
|
||||||
|
if (isFlashDelivery || slotGroups.length <= 1) return null
|
||||||
|
const majority = slotGroups.reduce((best, group) => (group.items.length > best.items.length ? group : best))
|
||||||
|
const inStockItems = cartItems.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
||||||
|
const now = dayjs()
|
||||||
|
const feasible =
|
||||||
|
inStockItems.length > 0 &&
|
||||||
|
inStockItems.every((item) =>
|
||||||
|
(((slotsData as any)?.[item.skuId] || []) as any[]).some(
|
||||||
|
(slot) => slot.id === majority.slotId && dayjs(slot.deliveryTime).isAfter(now) && dayjs(slot.freezeTime).isAfter(now)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if (!feasible) return null
|
||||||
|
return { slotId: majority.slotId, label: majority.label }
|
||||||
|
}, [isFlashDelivery, slotGroups, cartItems, productSlotsMap, slotsData])
|
||||||
|
|
||||||
|
const handleMergeSlots = () => {
|
||||||
|
if (!mergeSuggestion) return
|
||||||
|
setSelectedSlots((prev) => {
|
||||||
|
const next = { ...prev }
|
||||||
|
cartItems.forEach((item) => {
|
||||||
|
if (!productSlotsMap[item.skuId]?.isOutOfStock) {
|
||||||
|
next[item.id] = mergeSuggestion.slotId
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return next
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const initial: Record<number, number> = {}
|
||||||
|
cartItems.forEach((item) => {
|
||||||
|
initial[item.id] = item.quantity
|
||||||
|
})
|
||||||
|
setQuantities(initial)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [cartData])
|
||||||
|
|
||||||
|
// Auto-select delivery slots for each cart item
|
||||||
|
useEffect(() => {
|
||||||
|
if (cartItems.length === 0) return
|
||||||
|
const cartSlotIds = (cartData?.items || []).reduce((acc, item) => {
|
||||||
|
acc[item.id] = item.slotId
|
||||||
|
return acc
|
||||||
|
}, {} as Record<number, number | null | undefined>)
|
||||||
|
const next: Record<number, number> = {}
|
||||||
|
cartItems.forEach((item) => {
|
||||||
|
const existingSlotId = cartSlotIds ? cartSlotIds[item.id] : undefined
|
||||||
|
if (isFlashDelivery) {
|
||||||
|
next[item.id] = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const productSlots = (slotsData as any)?.[item.skuId]
|
||||||
|
if (!productSlots || productSlots.length === 0) return
|
||||||
|
const now = dayjs()
|
||||||
|
const upcomingSlots = (productSlots as any[])
|
||||||
|
.filter((slot) => dayjs(slot.deliveryTime).isAfter(now) && dayjs(slot.freezeTime).isAfter(now))
|
||||||
|
.sort((a, b) => dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)))
|
||||||
|
if (upcomingSlots.length === 0) return
|
||||||
|
if (existingSlotId) {
|
||||||
|
next[item.id] = upcomingSlots.some((slot) => slot.id === existingSlotId) ? existingSlotId : upcomingSlots[0].id
|
||||||
|
} else {
|
||||||
|
next[item.id] = upcomingSlots[0].id
|
||||||
|
}
|
||||||
|
})
|
||||||
|
setSelectedSlots(next)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [slotsData, cartData, isFlashDelivery])
|
||||||
|
|
||||||
|
const handleRemove = (item: any, productName?: string) => {
|
||||||
|
if (!window.confirm(`Remove ${productName ?? 'this item'} from cart?`)) return
|
||||||
|
removeFromCart.mutate(item.skuId)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCheckout = () => {
|
||||||
|
const availableItems = cartItems
|
||||||
|
.filter((item) => {
|
||||||
|
if (productSlotsMap[item.skuId]?.isOutOfStock) return false
|
||||||
|
if (isFlashDelivery) return flashEligibleProductIds.has(item.skuId)
|
||||||
|
return selectedSlots[item.id]
|
||||||
|
})
|
||||||
|
.map((item) => item.id)
|
||||||
|
|
||||||
|
if (availableItems.length === 0) {
|
||||||
|
const outOfStockItems = cartItems.filter((item) => productSlotsMap[item.skuId]?.isOutOfStock)
|
||||||
|
let errorMessage = 'Please check your cart items and try again.'
|
||||||
|
if (outOfStockItems.length === cartItems.length) {
|
||||||
|
errorMessage = 'All items in your cart are currently out of stock. Please remove them and add available items.'
|
||||||
|
} else if (isFlashDelivery) {
|
||||||
|
errorMessage =
|
||||||
|
'None of the items in your cart are available for flash delivery. Please remove ineligible items or switch to regular delivery.'
|
||||||
|
} else {
|
||||||
|
const itemsWithoutSlots = cartItems.filter(
|
||||||
|
(item) => !selectedSlots[item.id] && !productSlotsMap[item.skuId]?.isOutOfStock
|
||||||
|
)
|
||||||
|
if (itemsWithoutSlots.length > 0) {
|
||||||
|
errorMessage = `${itemsWithoutSlots.length} item(s) don't have a delivery slot. Please remove them or select a slot for each item.`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.alert(errorMessage)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isFlashDelivery && availableItems.length < cartItems.length) {
|
||||||
|
const itemsWithoutSlots = cartItems.filter(
|
||||||
|
(item) => !selectedSlots[item.id] && !productSlotsMap[item.skuId]?.isOutOfStock
|
||||||
|
)
|
||||||
|
if (itemsWithoutSlots.length > 0) {
|
||||||
|
window.alert(`${itemsWithoutSlots.length} item(s) don't have a delivery slot. Please select a slot or remove the item.`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemsBySlot: Record<number, number[]> = {}
|
||||||
|
availableItems.forEach((itemId) => {
|
||||||
|
const slotId = isFlashDelivery ? 0 : selectedSlots[itemId]
|
||||||
|
if (!itemsBySlot[slotId]) itemsBySlot[slotId] = []
|
||||||
|
itemsBySlot[slotId].push(itemId)
|
||||||
|
})
|
||||||
|
|
||||||
|
const slotParams = Object.entries(itemsBySlot)
|
||||||
|
.map(([slotId, itemIds]) => `${slotId}:${itemIds.join(',')}`)
|
||||||
|
.join(';')
|
||||||
|
|
||||||
|
navigate({
|
||||||
|
to: isFlashDelivery ? '/flash/checkout' : '/home/checkout',
|
||||||
|
search: {
|
||||||
|
slots: slotParams,
|
||||||
|
...(selectedCouponId ? { coupons: String(selectedCouponId) } : {}),
|
||||||
|
deliveryPrice: String(deliveryCharge),
|
||||||
|
},
|
||||||
|
} as any)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoading || (isSlotsLoading && !isFlashDelivery)) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-1 items-center justify-center bg-gray-50">
|
||||||
|
<p className="font-medium text-gray-500">Loading cart...</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-1 flex-col items-center justify-center bg-gray-50">
|
||||||
|
<p className="mt-4 text-lg font-bold text-gray-900">Oops!</p>
|
||||||
|
<p className="mt-2 text-gray-500">Failed to load your cart</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex-1 bg-gray-50">
|
||||||
|
<div className="border-b border-gray-100 bg-white px-4 py-3">
|
||||||
|
<div className="flex items-center">
|
||||||
|
<button type="button" onClick={() => window.history.back()} className="-ml-2 mr-1 p-2" aria-label="Back">
|
||||||
|
<ChevronRight className="h-7 w-7 rotate-180 text-gray-700" />
|
||||||
|
</button>
|
||||||
|
{isFlashDelivery ? (
|
||||||
|
<Clock className="h-6 w-6 text-pink-600" />
|
||||||
|
) : (
|
||||||
|
<Truck className="h-6 w-6 text-gray-700" />
|
||||||
|
)}
|
||||||
|
<p className={`ml-2 text-lg font-bold ${isFlashDelivery ? 'text-pink-600' : 'text-gray-700'}`}>
|
||||||
|
{isFlashDelivery ? '1 Hr Delivery Cart' : 'Scheduled Delivery Cart'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mx-auto w-full max-w-3xl px-4 pb-32">
|
||||||
|
{cartItems.length === 0 ? (
|
||||||
|
<div className="flex flex-col items-center justify-center py-12">
|
||||||
|
<div className="mb-4 flex h-20 w-20 items-center justify-center rounded-full bg-gray-100">
|
||||||
|
<Truck className="h-8 w-8 text-gray-400" />
|
||||||
|
</div>
|
||||||
|
<p className="text-lg font-bold text-gray-900">Your cart is empty</p>
|
||||||
|
<p className="mt-2 px-8 text-center text-gray-500">Looks like you haven't added anything to your cart yet.</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => navigate({ to: '/home' })}
|
||||||
|
className="mt-6 rounded-xl bg-brand-500 px-6 py-3 font-bold text-white"
|
||||||
|
>
|
||||||
|
Start Shopping
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="mb-4 rounded-2xl border border-gray-100 bg-white shadow-sm">
|
||||||
|
{cartItems.map((item, index) => {
|
||||||
|
const productSlots = getAvailableSlotsForProduct(item.skuId)
|
||||||
|
const selectedSlotForItem = selectedSlots[item.id]
|
||||||
|
const isFlashEligible = isFlashDelivery ? flashEligibleProductIds.has(item.skuId) : true
|
||||||
|
const product = productsById[item.skuId]
|
||||||
|
const productSlotInfo = productSlotsMap[item.skuId]
|
||||||
|
let isAvailable = true
|
||||||
|
if (productSlotInfo?.isOutOfStock) isAvailable = false
|
||||||
|
else if (isFlashDelivery) {
|
||||||
|
if (!isFlashEligible) isAvailable = false
|
||||||
|
} else if (productSlots.length === 0) {
|
||||||
|
isAvailable = false
|
||||||
|
}
|
||||||
|
const quantity = quantities[item.id] || item.quantity
|
||||||
|
const price = isFlashDelivery ? (product?.flashPrice ?? product?.price ?? 0) : product?.price || 0
|
||||||
|
const itemPrice = Number(price) * quantity
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={item.id}>
|
||||||
|
<div className="p-4">
|
||||||
|
<div className="mb-2 flex items-center">
|
||||||
|
<img
|
||||||
|
src={product?.images?.[0]}
|
||||||
|
alt={product?.name ?? ''}
|
||||||
|
onClick={() =>
|
||||||
|
navigate({
|
||||||
|
to: isFlashDelivery ? '/flash/product/$id' : '/home/product/$id',
|
||||||
|
params: { id: String(item.skuId) },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="mr-3 h-8 w-8 cursor-pointer rounded-lg bg-gray-100 object-cover"
|
||||||
|
/>
|
||||||
|
<p
|
||||||
|
onClick={() =>
|
||||||
|
navigate({
|
||||||
|
to: isFlashDelivery ? '/flash/product/$id' : '/home/product/$id',
|
||||||
|
params: { id: String(item.skuId) },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="mr-3 flex-1 cursor-pointer text-sm text-gray-900 line-clamp-2"
|
||||||
|
>
|
||||||
|
{product?.name}
|
||||||
|
</p>
|
||||||
|
<p className="mr-2 text-xs text-gray-500">
|
||||||
|
{product?.productType !== 'combo' ? product?.unitNotation || '' : ''}
|
||||||
|
</p>
|
||||||
|
<div className="w-[120px]">
|
||||||
|
<Quantifier
|
||||||
|
testID={`cart-item-${item.id}`}
|
||||||
|
value={quantities[item.id] || item.quantity}
|
||||||
|
setValue={(value) => {
|
||||||
|
if (value === 0) {
|
||||||
|
if (!window.confirm('Remove this item from your cart?')) {
|
||||||
|
setQuantities((prev) => ({ ...prev, [item.id]: 1 }))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
removeFromCart.mutate(item.skuId)
|
||||||
|
} else {
|
||||||
|
setQuantities((prev) => ({ ...prev, [item.id]: value }))
|
||||||
|
updateCartItem.mutate({ skuId: item.skuId, quantity: value })
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
step={product?.incrementStep}
|
||||||
|
unit={product?.unitNotation}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!isFlashDelivery && (
|
||||||
|
<div className="mt-2 flex items-center justify-between">
|
||||||
|
<div className="mr-4 flex-1">
|
||||||
|
<Dropdown
|
||||||
|
label="Select Delivery Slot"
|
||||||
|
testID={`cart-slot-picker-${item.id}`}
|
||||||
|
options={productSlots}
|
||||||
|
value={selectedSlotForItem || ''}
|
||||||
|
onValueChange={(value) =>
|
||||||
|
setSelectedSlots((prev) => ({ ...prev, [item.id]: Number(value) }))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{productSlots.length === 0 && (
|
||||||
|
<p className="mt-1 text-xs text-gray-500">No delivery slots available</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<p className="font-medium text-brand-900">₹{itemPrice}</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleRemove(item, product?.name)}
|
||||||
|
className="p-1"
|
||||||
|
aria-label={`Remove ${product?.name ?? 'item'}`}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-5 w-5 text-red-500" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isFlashDelivery && (
|
||||||
|
<div className="mt-2 flex justify-end">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<p className="font-medium text-brand-900">₹{itemPrice}</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleRemove(item, product?.name)}
|
||||||
|
className="p-1"
|
||||||
|
aria-label={`Remove ${product?.name ?? 'item'}`}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-5 w-5 text-red-500" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isAvailable && (
|
||||||
|
<div className="mt-2 self-start rounded-md bg-red-50 px-2 py-1">
|
||||||
|
<p className="text-xs font-bold text-red-600">
|
||||||
|
{productSlotInfo?.isOutOfStock
|
||||||
|
? 'Out of Stock'
|
||||||
|
: isFlashDelivery && !flashEligibleProductIds.has(item.skuId)
|
||||||
|
? 'Not available for flash delivery. Please remove'
|
||||||
|
: 'No delivery slots available'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{index < cartItems.length - 1 && <div className="mx-4 h-px bg-gray-200" />}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{cartItems.length > 0 && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => navigate({ to: isFlashDelivery ? '/flash' : '/home' })}
|
||||||
|
className="mb-4 flex items-center self-start rounded-lg bg-gray-100 px-4 py-2 font-medium text-gray-700"
|
||||||
|
>
|
||||||
|
{isFlashDelivery ? 'Go to Scheduled Delivery' : 'Go to 1 Hr Delivery'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{hasAvailableItems && (
|
||||||
|
<div className="mb-4 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
||||||
|
<div className="mb-3 flex items-center">
|
||||||
|
<div className="mr-3 flex h-8 w-8 items-center justify-center rounded-full bg-pink-50">
|
||||||
|
<Ticket className="h-4 w-4 text-pink-500" />
|
||||||
|
</div>
|
||||||
|
<p className="text-base font-bold text-gray-900">Offers & Coupons</p>
|
||||||
|
</div>
|
||||||
|
<Dropdown
|
||||||
|
label="Available Coupons"
|
||||||
|
testID="cart-coupon-dropdown"
|
||||||
|
options={dropdownData.map((d) => ({ label: d.label, value: d.value }))}
|
||||||
|
value={selectedCouponId || ''}
|
||||||
|
onValueChange={(value) => setSelectedCouponId(value ? Number(value) : null)}
|
||||||
|
/>
|
||||||
|
{eligibleCoupons.length === 0 && (
|
||||||
|
<p className="ml-1 mt-2 text-xs text-gray-400">No coupons available for this order</p>
|
||||||
|
)}
|
||||||
|
{selectedCouponId && (
|
||||||
|
<button type="button" onClick={() => setSelectedCouponId(null)} className="mt-3 self-end text-xs font-medium text-gray-400">
|
||||||
|
Remove coupon
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{!isAuthenticated && (
|
||||||
|
<button type="button" onClick={() => navigate({ to: '/login' })} className="ml-1 mt-2 text-xs">
|
||||||
|
<span className="text-blue-500 underline">Log In</span>
|
||||||
|
<span className="text-gray-400"> To find offers and coupons</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button type="button" onClick={() => navigate({ to: '/me/coupons' })} className="ml-1 mt-2 text-xs text-blue-500 underline">
|
||||||
|
Add Coupons to account
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isFlashDelivery && cartItems.length > 0 && (
|
||||||
|
<DeliverySlotSummary groups={slotGroups} mergeSuggestion={mergeSuggestion} onMerge={handleMergeSlots} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isAuthenticated && (
|
||||||
|
<div className="mb-4 overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm">
|
||||||
|
<div className="flex items-center justify-between border-b border-gray-100 bg-gray-50 px-4 py-3">
|
||||||
|
<p className="text-base font-bold text-gray-900">Delivery Address</p>
|
||||||
|
<button type="button" onClick={() => setShowAddAddress(true)} className="text-sm font-medium text-brand-600">
|
||||||
|
+ Add New
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="p-4">
|
||||||
|
{selectedAddress ? (
|
||||||
|
<div>
|
||||||
|
<p className="truncate font-bold text-gray-900">
|
||||||
|
{selectedAddress.name} • {selectedAddress.phone}
|
||||||
|
</p>
|
||||||
|
<p className="mt-0.5 text-sm text-gray-500 line-clamp-2">
|
||||||
|
{selectedAddress.addressLine1}, {selectedAddress.city} - {selectedAddress.pincode}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-gray-500">No address selected</p>
|
||||||
|
)}
|
||||||
|
{addresses
|
||||||
|
.filter((a: any) => a.id !== selectedAddressId)
|
||||||
|
.slice(0, 3)
|
||||||
|
.map((address: any) => (
|
||||||
|
<button
|
||||||
|
key={address.id}
|
||||||
|
type="button"
|
||||||
|
data-testid={`cart-address-${address.id}`}
|
||||||
|
onClick={() => setSelectedAddressId(address.id)}
|
||||||
|
className="mt-3 w-full border-t border-gray-100 pt-3 text-left"
|
||||||
|
>
|
||||||
|
<p className="truncate text-sm font-medium text-gray-900">
|
||||||
|
{address.name} • {address.phone}
|
||||||
|
</p>
|
||||||
|
<p className="mt-0.5 truncate text-xs text-gray-500">
|
||||||
|
{address.addressLine1}, {address.city} - {address.pincode}
|
||||||
|
</p>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{hasAvailableItems && (
|
||||||
|
<div className="mb-6 mt-4 overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm">
|
||||||
|
<div className="border-b border-gray-100 bg-gray-50 px-4 py-3">
|
||||||
|
<p className="text-base font-bold text-gray-900">Bill Details</p>
|
||||||
|
</div>
|
||||||
|
<div className="p-4">
|
||||||
|
<div className="mb-3 flex items-center justify-between">
|
||||||
|
<p className="text-gray-500">Item Total</p>
|
||||||
|
<p className="font-medium text-gray-900">₹{Math.trunc(totalPrice)}</p>
|
||||||
|
</div>
|
||||||
|
{totalSavings > 1 && (
|
||||||
|
<div className="mb-3 flex items-center justify-between">
|
||||||
|
<p className="text-gray-500">Total Discount</p>
|
||||||
|
<p className="font-medium text-green-600">₹{Math.trunc(totalSavings)}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{discountAmount > 0 && (
|
||||||
|
<div className="mb-3 flex items-center justify-between">
|
||||||
|
<p className="text-gray-500">Product Discount</p>
|
||||||
|
<p className="font-medium text-green-600">-₹{Math.trunc(discountAmount)}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="mb-3 flex items-center justify-between">
|
||||||
|
<p className="text-gray-500">Delivery Fee</p>
|
||||||
|
<p className={`font-medium ${deliveryCharge === 0 ? 'text-green-600' : 'text-gray-900'}`}>
|
||||||
|
{deliveryCharge === 0 ? 'Free' : `₹${deliveryCharge}`}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{deliveryCharge > 0 && (freeDeliveryThreshold || 0) > 0 && finalTotal < (freeDeliveryThreshold || 0) && (
|
||||||
|
<div className="mb-3 flex items-center rounded-lg bg-blue-50 p-2.5">
|
||||||
|
<ShoppingBag className="mr-2 h-4 w-4 text-blue-600" />
|
||||||
|
<p className="flex-1 text-xs font-medium text-blue-700">
|
||||||
|
Add products worth ₹{((freeDeliveryThreshold || 0) - finalTotal).toFixed(0)} for free delivery
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="my-2 h-px bg-gray-100" />
|
||||||
|
<div className="mt-2 flex items-center justify-between">
|
||||||
|
<p className="text-lg font-bold text-gray-900">To Pay</p>
|
||||||
|
<p className="text-xl font-bold text-gray-900">₹{Math.trunc(finalTotalWithDelivery)}</p>
|
||||||
|
</div>
|
||||||
|
{(discountAmount > 0 || deliveryCharge === 0 || totalSavings > 1) && (
|
||||||
|
<div className="mt-4 flex items-center justify-center rounded-lg bg-green-50 p-2">
|
||||||
|
<p className="text-xs font-bold text-green-700">
|
||||||
|
You saved ₹
|
||||||
|
{Math.trunc(discountAmount + totalSavings + (deliveryCharge === 0 ? (constsData as any)?.deliveryCharge || 0 : 0))} on
|
||||||
|
this order
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="border-t border-gray-100 bg-gray-50 p-4">
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => navigate({ to: isFlashDelivery ? '/flash' : '/home' })}
|
||||||
|
className="flex-1 rounded-xl border border-gray-200 bg-white py-3.5 font-bold text-gray-700 shadow-sm"
|
||||||
|
>
|
||||||
|
Shop More
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="checkout-button"
|
||||||
|
onClick={handleCheckout}
|
||||||
|
className="flex flex-1 flex-row items-center justify-center rounded-xl bg-brand-500 py-3.5 font-bold text-white shadow-md"
|
||||||
|
>
|
||||||
|
Checkout
|
||||||
|
<ChevronRight className="ml-1 h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<BottomDialog open={couponDialogOpen} onClose={() => setCouponDialogOpen(false)}>
|
||||||
|
<div className="p-6">
|
||||||
|
<div className="mb-6 flex items-center">
|
||||||
|
<div className="mr-3 flex h-10 w-10 items-center justify-center rounded-full bg-pink-50">
|
||||||
|
<Ticket className="h-5 w-5 text-pink-500" />
|
||||||
|
</div>
|
||||||
|
<p className="text-xl font-bold text-gray-900">Applied Coupons</p>
|
||||||
|
</div>
|
||||||
|
{selectedCoupons.map((coupon) => (
|
||||||
|
<div key={coupon.id} className="mb-4 rounded-xl border border-gray-100 bg-white p-4 shadow-sm">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="text-lg font-bold text-gray-900">{coupon.code}</p>
|
||||||
|
<p className="mt-1 text-sm text-gray-500">{coupon.description}</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded bg-green-50 px-2 py-1">
|
||||||
|
<p className="text-xs font-bold text-green-700">
|
||||||
|
{coupon.discountType === 'percentage' ? `${coupon.discountValue}% OFF` : `₹${coupon.discountValue} OFF`}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{coupon.maxValue && <p className="mt-2 text-xs text-gray-400">Maximum discount up to ₹{coupon.maxValue}</p>}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setCouponDialogOpen(false)}
|
||||||
|
className="mt-4 w-full rounded-xl bg-gray-900 py-3.5 font-bold text-white"
|
||||||
|
>
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</BottomDialog>
|
||||||
|
|
||||||
|
<BottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}>
|
||||||
|
<div className="p-2">
|
||||||
|
<AddressForm onSuccess={handleAddressAdded} />
|
||||||
|
</div>
|
||||||
|
</BottomDialog>
|
||||||
|
|
||||||
|
<BottomDialog open={regionPickOpen} onClose={() => setRegionPickOpen(false)}>
|
||||||
|
<div className="p-6">
|
||||||
|
<p className="text-lg font-extrabold text-gray-900">
|
||||||
|
{pendingRegionName ? `Addresses in ${pendingRegionName}` : 'Choose an address'}
|
||||||
|
</p>
|
||||||
|
<p className="mb-4 mt-1 text-sm text-gray-500">
|
||||||
|
Your new address is in a different region. Pick one of its addresses to deliver to.
|
||||||
|
</p>
|
||||||
|
{pendingAddresses.map((address: any) => (
|
||||||
|
<button
|
||||||
|
key={address.id}
|
||||||
|
type="button"
|
||||||
|
data-testid={`cart-region-address-${address.id}`}
|
||||||
|
onClick={() => {
|
||||||
|
setSelectedAddressId(address.id)
|
||||||
|
setRegionPickOpen(false)
|
||||||
|
}}
|
||||||
|
className="w-full border-b border-gray-100 py-3 text-left"
|
||||||
|
>
|
||||||
|
<p className="truncate font-bold text-gray-900">
|
||||||
|
{address.name} • {address.phone}
|
||||||
|
</p>
|
||||||
|
<p className="mt-0.5 text-sm text-gray-500 line-clamp-2">
|
||||||
|
{address.addressLine1}, {address.city} - {address.pincode}
|
||||||
|
</p>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setRegionPickOpen(false)}
|
||||||
|
className="mt-4 w-full rounded-xl bg-gray-900 py-3.5 font-bold text-white"
|
||||||
|
>
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</BottomDialog>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CartPage
|
||||||
124
apps/web-ui/src/contexts/RegionContext.tsx
Normal file
124
apps/web-ui/src/contexts/RegionContext.tsx
Normal file
|
|
@ -0,0 +1,124 @@
|
||||||
|
import React, { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react'
|
||||||
|
import type { ReactParentComponent } from '@packages/shared'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
|
||||||
|
export const ACTIVE_REGION_KEY = 'active_region'
|
||||||
|
|
||||||
|
interface RegionState {
|
||||||
|
regionId: number | null
|
||||||
|
regionName: string | null
|
||||||
|
boundId: number | null
|
||||||
|
boundName: string | null
|
||||||
|
isLoading: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RegionContextType extends RegionState {
|
||||||
|
setRegion: (regionId: number, regionName: string, boundId?: number | null, boundName?: string | null) => Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
const RegionContext = createContext<RegionContextType | undefined>(undefined)
|
||||||
|
|
||||||
|
interface StoredRegion {
|
||||||
|
regionId: number
|
||||||
|
regionName: string | null
|
||||||
|
boundId: number | null
|
||||||
|
boundName: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
function readStoredRegion(): StoredRegion | null {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(ACTIVE_REGION_KEY)
|
||||||
|
if (!raw) return null
|
||||||
|
const parsed = JSON.parse(raw)
|
||||||
|
if (typeof parsed?.regionId !== 'number') return null
|
||||||
|
return {
|
||||||
|
regionId: parsed.regionId,
|
||||||
|
regionName: typeof parsed.regionName === 'string' ? parsed.regionName : null,
|
||||||
|
boundId: typeof parsed?.boundId === 'number' ? parsed.boundId : null,
|
||||||
|
boundName: typeof parsed?.boundName === 'string' ? parsed.boundName : null,
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const RegionProvider: React.FC<ReactParentComponent> = ({ children }) => {
|
||||||
|
const [state, setState] = useState<RegionState>({
|
||||||
|
regionId: null,
|
||||||
|
regionName: null,
|
||||||
|
boundId: null,
|
||||||
|
boundName: null,
|
||||||
|
isLoading: true,
|
||||||
|
})
|
||||||
|
const [stored, setStored] = useState<{ loaded: boolean; value: StoredRegion | null }>({
|
||||||
|
loaded: false,
|
||||||
|
value: null,
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setStored({ loaded: true, value: readStoredRegion() })
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
// Validate the persisted region still exists backend-side. Unknown ids reset
|
||||||
|
// so the gate re-prompts instead of serving a ghost region. A stale boundId
|
||||||
|
// needs no reset: server merge degrades gracefully to region rows.
|
||||||
|
const { data: regionsData } = trpc.common.getRegions.useQuery(undefined, { staleTime: Infinity })
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!stored.loaded || regionsData === undefined) return
|
||||||
|
const valid = stored.value != null && regionsData.regions.some((r) => r.id === stored.value!.regionId)
|
||||||
|
if (valid && stored.value != null) {
|
||||||
|
setState({ ...stored.value, isLoading: false })
|
||||||
|
} else {
|
||||||
|
if (stored.value != null) {
|
||||||
|
try {
|
||||||
|
localStorage.removeItem(ACTIVE_REGION_KEY)
|
||||||
|
} catch {
|
||||||
|
// ignore storage errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setState({ regionId: null, regionName: null, boundId: null, boundName: null, isLoading: false })
|
||||||
|
}
|
||||||
|
}, [stored, regionsData])
|
||||||
|
|
||||||
|
const setRegion = useCallback(
|
||||||
|
async (regionId: number, regionName: string, boundId?: number | null, boundName?: string | null) => {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(
|
||||||
|
ACTIVE_REGION_KEY,
|
||||||
|
JSON.stringify({ regionId, regionName, boundId: boundId ?? null, boundName: boundName ?? null })
|
||||||
|
)
|
||||||
|
} catch {
|
||||||
|
// ignore storage errors (private mode etc.)
|
||||||
|
}
|
||||||
|
setState({ regionId, regionName, boundId: boundId ?? null, boundName: boundName ?? null, isLoading: false })
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
)
|
||||||
|
|
||||||
|
const value = useMemo(() => ({ ...state, setRegion }), [state, setRegion])
|
||||||
|
|
||||||
|
return <RegionContext.Provider value={value}>{children}</RegionContext.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useRegion = (): RegionContextType => {
|
||||||
|
const context = useContext(RegionContext)
|
||||||
|
if (context === undefined) {
|
||||||
|
throw new Error('useRegion must be used within a RegionProvider')
|
||||||
|
}
|
||||||
|
return context
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Spread into user-facing trpc query/mutation inputs so the backend scopes
|
||||||
|
* to the active region (and bound, when known). Empty object when no region
|
||||||
|
* is set yet (backend keeps its default-region behaviour in that case). */
|
||||||
|
export const useRegionParams = (): { regionId?: number; boundId?: number } => {
|
||||||
|
const { regionId, boundId } = useRegion()
|
||||||
|
return useMemo(
|
||||||
|
() => ({
|
||||||
|
...(regionId != null ? { regionId } : {}),
|
||||||
|
...(boundId != null ? { boundId } : {}),
|
||||||
|
}),
|
||||||
|
[regionId, boundId]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -3,6 +3,8 @@ import type { CartData as SharedCartData } from '@packages/shared'
|
||||||
|
|
||||||
type CartType = 'regular' | 'flash'
|
type CartType = 'regular' | 'flash'
|
||||||
|
|
||||||
|
export type { CartType }
|
||||||
|
|
||||||
interface CartItem {
|
interface CartItem {
|
||||||
id: number
|
id: number
|
||||||
skuId: number
|
skuId: number
|
||||||
|
|
@ -13,6 +15,8 @@ interface CartItem {
|
||||||
deliveryDate?: string | null
|
deliveryDate?: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type LocalCartItem = CartItem
|
||||||
|
|
||||||
type CartData = SharedCartData<CartItem>
|
type CartData = SharedCartData<CartItem>
|
||||||
|
|
||||||
function getCartKey(cartType: CartType): string {
|
function getCartKey(cartType: CartType): string {
|
||||||
|
|
@ -144,3 +148,46 @@ export function useRemoveFromCart(cartType: CartType = 'regular') {
|
||||||
export function clearLocalCart(cartType: CartType = 'regular') {
|
export function clearLocalCart(cartType: CartType = 'regular') {
|
||||||
localStorage.removeItem(getCartKey(cartType))
|
localStorage.removeItem(getCartKey(cartType))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Region-switch support (mirrors user-ui cart-query-hooks)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Async read/write wrappers so switch logic matches the native call sites. */
|
||||||
|
export const getLocalCart = async (cartType: CartType = 'regular'): Promise<LocalCartItem[]> => {
|
||||||
|
return readCart(cartType)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const saveLocalCart = async (items: LocalCartItem[], cartType: CartType = 'regular'): Promise<void> => {
|
||||||
|
writeCart(cartType, items)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Storage key for a region's cart snapshot (full lines incl. quantity). */
|
||||||
|
export const getCartSnapshotKey = (regionId: number, cartType: CartType = 'regular'): string => {
|
||||||
|
return `cart_snapshot_${regionId}_${cartType}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getCartSnapshot = async (regionId: number, cartType: CartType = 'regular'): Promise<LocalCartItem[] | null> => {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(getCartSnapshotKey(regionId, cartType))
|
||||||
|
return raw ? (JSON.parse(raw) as LocalCartItem[]) : null
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const saveCartSnapshot = async (regionId: number, items: LocalCartItem[], cartType: CartType = 'regular'): Promise<void> => {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(getCartSnapshotKey(regionId, cartType), JSON.stringify(items))
|
||||||
|
} catch {
|
||||||
|
// ignore storage errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// While a region switch is reconciling explicitly, background cart passes
|
||||||
|
// must stay out of the way.
|
||||||
|
let regionSwitchInProgress = false
|
||||||
|
export const setRegionSwitchInProgress = (value: boolean): void => {
|
||||||
|
regionSwitchInProgress = value
|
||||||
|
}
|
||||||
|
export const isRegionSwitchInProgress = (): boolean => regionSwitchInProgress
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ import { useMemo, useEffect, useState } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import axios from 'axios'
|
import axios from 'axios'
|
||||||
import { trpc } from '../lib/trpc-client'
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { useRegion } from '../contexts/RegionContext'
|
||||||
import type { ProductPriceFlags } from '@packages/shared'
|
import type { ProductPriceFlags } from '@packages/shared'
|
||||||
import type {
|
import type {
|
||||||
AllProductsApiType,
|
AllProductsApiType,
|
||||||
|
|
@ -14,10 +15,48 @@ import type {
|
||||||
} from '@backend/trpc/router'
|
} from '@backend/trpc/router'
|
||||||
import { CACHE_FILENAMES } from '@packages/shared'
|
import { CACHE_FILENAMES } from '@packages/shared'
|
||||||
|
|
||||||
|
// The only persisted config payload: the small essential-consts object
|
||||||
|
// (assetsDomain, cache versions, etc.).
|
||||||
|
const ESSENTIAL_CONSTS_KEY = 'essential_consts'
|
||||||
|
|
||||||
export const useGetEssentialConsts = () => {
|
export const useGetEssentialConsts = () => {
|
||||||
const query = trpc.common.essentialConsts.useQuery(undefined, {
|
const { regionId, boundId } = useRegion()
|
||||||
|
const [initialData, setInitialData] = useState<EssentialConstsApiType | undefined>(undefined)
|
||||||
|
const [isReady, setIsReady] = useState(false)
|
||||||
|
|
||||||
|
// Load the last persisted response so config is available immediately.
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(ESSENTIAL_CONSTS_KEY)
|
||||||
|
if (raw) setInitialData(JSON.parse(raw))
|
||||||
|
} catch {
|
||||||
|
// ignore corrupt cache
|
||||||
|
}
|
||||||
|
if (!cancelled) setIsReady(true)
|
||||||
|
return () => { cancelled = true }
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const query = trpc.common.essentialConsts.useQuery(
|
||||||
|
regionId != null ? { regionId, ...(boundId != null ? { boundId } : {}) } : undefined,
|
||||||
|
{
|
||||||
refetchInterval: 60000,
|
refetchInterval: 60000,
|
||||||
})
|
enabled: isReady,
|
||||||
|
placeholderData: initialData,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Persist the latest response.
|
||||||
|
useEffect(() => {
|
||||||
|
if (query.data) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(ESSENTIAL_CONSTS_KEY, JSON.stringify(query.data))
|
||||||
|
} catch {
|
||||||
|
// ignore storage errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [query.data])
|
||||||
|
|
||||||
return { ...query, refetch: query.refetch }
|
return { ...query, refetch: query.refetch }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -91,53 +130,81 @@ type StoreWithProductsResponse = StoreWithProductsApiType
|
||||||
type AvailabilityResponse = AvailabilityApiType
|
type AvailabilityResponse = AvailabilityApiType
|
||||||
|
|
||||||
type BaseProduct = AllProductsApiType['products'][number]
|
type BaseProduct = AllProductsApiType['products'][number]
|
||||||
type AvailabilityEntry = AvailabilityApiType['availability'][number]
|
export type AvailabilityEntry = AvailabilityApiType['availability'][number]
|
||||||
|
|
||||||
export type MergedProduct = BaseProduct & ProductPriceFlags
|
export type MergedProduct = BaseProduct & ProductPriceFlags
|
||||||
|
|
||||||
function useCacheUrl(filename: string): string | null {
|
/** Minimal consts surface needed to build CDN cache URLs (both the scaffold
|
||||||
const { data: essentialConsts } = useGetEssentialConsts()
|
* type and the router-enriched response satisfy this). */
|
||||||
|
export interface CacheUrlConsts {
|
||||||
|
assetsDomain?: string | null
|
||||||
|
apiCacheKey?: string | null
|
||||||
|
cacheVersion?: number | null
|
||||||
|
availabilityVersionNum?: number | null
|
||||||
|
slotsVersionNum?: number | null
|
||||||
|
cachePathPrefix?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildProductsCacheUrl(
|
||||||
|
essentialConsts: CacheUrlConsts | null | undefined,
|
||||||
|
filename: string = CACHE_FILENAMES.products
|
||||||
|
): string | null {
|
||||||
const assetsDomain = essentialConsts?.assetsDomain
|
const assetsDomain = essentialConsts?.assetsDomain
|
||||||
const apiCacheKey = essentialConsts?.apiCacheKey
|
const apiCacheKey = essentialConsts?.apiCacheKey
|
||||||
const cacheVersion = essentialConsts?.cacheVersion
|
const cacheVersion = essentialConsts?.cacheVersion
|
||||||
|
const cachePathPrefix = essentialConsts?.cachePathPrefix ?? ''
|
||||||
|
|
||||||
if (
|
if (!assetsDomain || !apiCacheKey || cacheVersion === undefined || cacheVersion === null) {
|
||||||
!assetsDomain ||
|
|
||||||
!apiCacheKey ||
|
|
||||||
cacheVersion === undefined ||
|
|
||||||
cacheVersion === null
|
|
||||||
) {
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${assetsDomain}${apiCacheKey}/v-${cacheVersion}/${filename}`
|
return `${assetsDomain}${apiCacheKey}/${cachePathPrefix}v-${cacheVersion}/${filename}`
|
||||||
}
|
}
|
||||||
|
|
||||||
function useAvailabilityCacheUrl(): string | null {
|
export function buildAvailabilityCacheUrl(
|
||||||
const { data: essentialConsts } = useGetEssentialConsts()
|
essentialConsts: CacheUrlConsts | null | undefined
|
||||||
|
): string | null {
|
||||||
const assetsDomain = essentialConsts?.assetsDomain
|
const assetsDomain = essentialConsts?.assetsDomain
|
||||||
const availabilityVersionNum = essentialConsts?.availabilityVersionNum
|
const availabilityVersionNum = essentialConsts?.availabilityVersionNum
|
||||||
|
const cachePathPrefix = essentialConsts?.cachePathPrefix ?? ''
|
||||||
|
|
||||||
if (!assetsDomain || availabilityVersionNum === undefined || availabilityVersionNum === null) {
|
if (!assetsDomain || availabilityVersionNum === undefined || availabilityVersionNum === null) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${assetsDomain}av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}`
|
return `${assetsDomain}${cachePathPrefix}av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}`
|
||||||
}
|
}
|
||||||
|
|
||||||
function useSlotsCacheUrl(): string | null {
|
export function buildSlotsCacheUrl(
|
||||||
const { data: essentialConsts } = useGetEssentialConsts()
|
essentialConsts: CacheUrlConsts | null | undefined
|
||||||
|
): string | null {
|
||||||
const assetsDomain = essentialConsts?.assetsDomain
|
const assetsDomain = essentialConsts?.assetsDomain
|
||||||
const slotsVersionNum = essentialConsts?.slotsVersionNum
|
const slotsVersionNum = essentialConsts?.slotsVersionNum
|
||||||
|
const cachePathPrefix = essentialConsts?.cachePathPrefix ?? ''
|
||||||
|
|
||||||
if (!assetsDomain || slotsVersionNum === undefined || slotsVersionNum === null) {
|
if (!assetsDomain || slotsVersionNum === undefined || slotsVersionNum === null) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${assetsDomain}slots/v-${slotsVersionNum}/${CACHE_FILENAMES.slots}`
|
return `${assetsDomain}${cachePathPrefix}slots/v-${slotsVersionNum}/${CACHE_FILENAMES.slots}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function useCacheUrl(filename: string): string | null {
|
||||||
|
const { data: essentialConsts } = useGetEssentialConsts()
|
||||||
|
|
||||||
|
return buildProductsCacheUrl(essentialConsts, filename)
|
||||||
|
}
|
||||||
|
|
||||||
|
function useAvailabilityCacheUrl(): string | null {
|
||||||
|
const { data: essentialConsts } = useGetEssentialConsts()
|
||||||
|
|
||||||
|
return buildAvailabilityCacheUrl(essentialConsts)
|
||||||
|
}
|
||||||
|
|
||||||
|
function useSlotsCacheUrl(): string | null {
|
||||||
|
const { data: essentialConsts } = useGetEssentialConsts()
|
||||||
|
|
||||||
|
return buildSlotsCacheUrl(essentialConsts)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAllProducts() {
|
export function useAllProducts() {
|
||||||
|
|
@ -289,10 +356,11 @@ export function useStoreWithProducts(storeId: number) {
|
||||||
const assetsDomain = essentialConsts?.assetsDomain
|
const assetsDomain = essentialConsts?.assetsDomain
|
||||||
const apiCacheKey = essentialConsts?.apiCacheKey
|
const apiCacheKey = essentialConsts?.apiCacheKey
|
||||||
const cacheVersion = essentialConsts?.cacheVersion
|
const cacheVersion = essentialConsts?.cacheVersion
|
||||||
|
const cachePathPrefix = essentialConsts?.cachePathPrefix ?? ''
|
||||||
|
|
||||||
const cacheUrl =
|
const cacheUrl =
|
||||||
assetsDomain && apiCacheKey
|
assetsDomain && apiCacheKey
|
||||||
? `${assetsDomain}${apiCacheKey}/v-${cacheVersion}/stores/${storeId}.json`
|
? `${assetsDomain}${apiCacheKey}/${cachePathPrefix}v-${cacheVersion}/stores/${storeId}.json`
|
||||||
: null
|
: null
|
||||||
const version = cacheUrl ?? ''
|
const version = cacheUrl ?? ''
|
||||||
const { initialData, isReady } = usePersistedCache<StoreWithProductsResponse>(CACHE_STORAGE_KEYS.storeProducts(storeId), version)
|
const { initialData, isReady } = usePersistedCache<StoreWithProductsResponse>(CACHE_STORAGE_KEYS.storeProducts(storeId), version)
|
||||||
|
|
|
||||||
271
apps/web-ui/src/hooks/useRegionSwitch.tsx
Normal file
271
apps/web-ui/src/hooks/useRegionSwitch.tsx
Normal file
|
|
@ -0,0 +1,271 @@
|
||||||
|
import { useCallback, useRef, useState, createContext, useContext, useMemo } from 'react'
|
||||||
|
import type { FC, ReactNode } from 'react'
|
||||||
|
import axios from 'axios'
|
||||||
|
import dayjs from 'dayjs'
|
||||||
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { useRegion } from '../contexts/RegionContext'
|
||||||
|
import {
|
||||||
|
getLocalCart,
|
||||||
|
saveLocalCart,
|
||||||
|
getCartSnapshot,
|
||||||
|
saveCartSnapshot,
|
||||||
|
setRegionSwitchInProgress,
|
||||||
|
type CartType,
|
||||||
|
type LocalCartItem,
|
||||||
|
} from './cart-query-hooks'
|
||||||
|
import { buildSlotsCacheUrl, buildAvailabilityCacheUrl, type AvailabilityEntry } from './prominent-api-hooks'
|
||||||
|
import { useCentralSlotStore } from '../lib/stores/central-slot-store'
|
||||||
|
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
||||||
|
import type { SlotsApiType } from '@backend/trpc/router'
|
||||||
|
|
||||||
|
type SwitchSlot = SlotsApiType['slots'][number]
|
||||||
|
type SlotMap = Record<number, { slots: SwitchSlot[]; isOutOfStock: boolean; isSuspended: boolean }>
|
||||||
|
|
||||||
|
export interface RegionSwitchLineResult {
|
||||||
|
cartType: CartType
|
||||||
|
skuId: number
|
||||||
|
name: string
|
||||||
|
quantity: number
|
||||||
|
outcome: 'kept' | 'moved' | 'removed'
|
||||||
|
oldSlotTime: string | null
|
||||||
|
newSlotTime: string | null
|
||||||
|
reason: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RegionSwitchResults {
|
||||||
|
regionName: string
|
||||||
|
lines: RegionSwitchLineResult[]
|
||||||
|
error: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pure reconcile: remap each line onto the new region's slot map. */
|
||||||
|
export function reconcileCartLines(
|
||||||
|
items: LocalCartItem[],
|
||||||
|
slotMap: SlotMap,
|
||||||
|
oldSlotTimes: Record<number, string>,
|
||||||
|
names: Record<number, string>,
|
||||||
|
now: Date = new Date()
|
||||||
|
): { lines: LocalCartItem[]; results: Omit<RegionSwitchLineResult, 'cartType'>[] } {
|
||||||
|
const lines: LocalCartItem[] = []
|
||||||
|
const results: Omit<RegionSwitchLineResult, 'cartType'>[] = []
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
const name = names[item.skuId] ?? `Item ${item.skuId}`
|
||||||
|
const base = {
|
||||||
|
skuId: item.skuId,
|
||||||
|
name,
|
||||||
|
quantity: item.quantity,
|
||||||
|
oldSlotTime: item.slotId != null ? (oldSlotTimes[item.slotId] ?? null) : null,
|
||||||
|
}
|
||||||
|
const info = slotMap[item.skuId]
|
||||||
|
|
||||||
|
if (!info || info.isSuspended) {
|
||||||
|
results.push({ ...base, outcome: 'removed', newSlotTime: null, reason: 'Not available in this region' })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const valid = info.slots.filter(
|
||||||
|
(s) => dayjs((s as any).freezeTime).isAfter(now) && dayjs((s as any).deliveryTime).isAfter(now)
|
||||||
|
)
|
||||||
|
|
||||||
|
if (valid.some((s) => s.id === item.slotId)) {
|
||||||
|
lines.push(item)
|
||||||
|
const kept = valid.find((s) => s.id === item.slotId)!
|
||||||
|
results.push({ ...base, outcome: 'kept', newSlotTime: String((kept as any).deliveryTime), reason: null })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (valid.length === 0) {
|
||||||
|
results.push({ ...base, outcome: 'removed', newSlotTime: null, reason: 'No delivery slots in this region' })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldTime = base.oldSlotTime != null ? dayjs(base.oldSlotTime).valueOf() : null
|
||||||
|
const nearest = [...valid].sort((a, b) => {
|
||||||
|
if (oldTime == null)
|
||||||
|
return dayjs((a as any).deliveryTime).valueOf() - dayjs((b as any).deliveryTime).valueOf()
|
||||||
|
return (
|
||||||
|
Math.abs(dayjs((a as any).deliveryTime).valueOf() - oldTime) -
|
||||||
|
Math.abs(dayjs((b as any).deliveryTime).valueOf() - oldTime)
|
||||||
|
)
|
||||||
|
})[0]
|
||||||
|
|
||||||
|
lines.push({ ...item, slotId: nearest.id })
|
||||||
|
results.push({
|
||||||
|
...base,
|
||||||
|
outcome: 'moved',
|
||||||
|
newSlotTime: String((nearest as any).deliveryTime),
|
||||||
|
reason: null,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return { lines, results }
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CART_TYPES: CartType[] = ['regular', 'flash']
|
||||||
|
|
||||||
|
type TrpcUtils = ReturnType<typeof trpc.useUtils>
|
||||||
|
|
||||||
|
/** Fetch a region's slot payloads and build its slot map WITHOUT touching
|
||||||
|
* the central store (for previews before the user confirms). */
|
||||||
|
export async function fetchRegionSlotMap(
|
||||||
|
utils: TrpcUtils,
|
||||||
|
regionId: number
|
||||||
|
): Promise<{
|
||||||
|
slotMap: SlotMap
|
||||||
|
slots: SlotsApiType['slots']
|
||||||
|
availability: AvailabilityEntry[]
|
||||||
|
}> {
|
||||||
|
const consts = await utils.common.essentialConsts.fetch({ regionId })
|
||||||
|
const slotsUrl = buildSlotsCacheUrl(consts)
|
||||||
|
const availabilityUrl = buildAvailabilityCacheUrl(consts)
|
||||||
|
if (!slotsUrl || !availabilityUrl) {
|
||||||
|
throw new Error('Region data is not available yet')
|
||||||
|
}
|
||||||
|
const [slotsRes, availabilityRes] = await Promise.all([
|
||||||
|
axios.get<SlotsApiType>(slotsUrl),
|
||||||
|
axios.get<{ availability: AvailabilityEntry[] }>(availabilityUrl),
|
||||||
|
])
|
||||||
|
const slots = slotsRes.data.slots ?? []
|
||||||
|
const availability = availabilityRes.data.availability ?? []
|
||||||
|
const availabilityById: Record<number, AvailabilityEntry> = {}
|
||||||
|
for (const entry of availability) availabilityById[(entry as any).id] = entry
|
||||||
|
const slotMap: SlotMap = {}
|
||||||
|
for (const slot of slots) {
|
||||||
|
for (const p of ((slot as any).products ?? []) as { id: number }[]) {
|
||||||
|
if (!slotMap[p.id]) {
|
||||||
|
const a = availabilityById[p.id] as any
|
||||||
|
slotMap[p.id] = {
|
||||||
|
slots: [],
|
||||||
|
isOutOfStock: a?.isOutOfStock ?? false,
|
||||||
|
isSuspended: a?.isSuspended ?? false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
slotMap[p.id].slots.push(slot)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { slotMap, slots, availability }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Names + old slot times snapshot for reconcile previews/results. */
|
||||||
|
export function snapshotCartContext(): { names: Record<number, string>; oldSlotTimes: Record<number, string> } {
|
||||||
|
const names: Record<number, string> = {}
|
||||||
|
for (const [key, product] of Object.entries(useCentralProductStore.getState().productsById)) {
|
||||||
|
names[Number(key)] = (product as { name?: string })?.name ?? `Item ${key}`
|
||||||
|
}
|
||||||
|
const oldSlotTimes: Record<number, string> = {}
|
||||||
|
for (const slot of useCentralSlotStore.getState().slots) {
|
||||||
|
oldSlotTimes[slot.id] = String((slot as any).deliveryTime)
|
||||||
|
}
|
||||||
|
return { names, oldSlotTimes }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRegionSwitch() {
|
||||||
|
const { regionId, setRegion } = useRegion()
|
||||||
|
const utils = trpc.useUtils()
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const [isSwitching, setIsSwitching] = useState(false)
|
||||||
|
const [switchMessage, setSwitchMessage] = useState('Switching region…')
|
||||||
|
const [results, setResults] = useState<RegionSwitchResults | null>(null)
|
||||||
|
const runningRef = useRef(false)
|
||||||
|
|
||||||
|
const switchRegion = useCallback(
|
||||||
|
async (nextId: number, nextName: string) => {
|
||||||
|
if (runningRef.current || nextId === regionId) return
|
||||||
|
runningRef.current = true
|
||||||
|
setResults(null)
|
||||||
|
setSwitchMessage(`Switching to ${nextName}…`)
|
||||||
|
setIsSwitching(true)
|
||||||
|
setRegionSwitchInProgress(true)
|
||||||
|
|
||||||
|
const lines: RegionSwitchLineResult[] = []
|
||||||
|
let error: string | null = null
|
||||||
|
|
||||||
|
try {
|
||||||
|
const currentId = regionId
|
||||||
|
|
||||||
|
// Snapshot names + old slot times before the stores are overwritten.
|
||||||
|
const { names, oldSlotTimes } = snapshotCartContext()
|
||||||
|
|
||||||
|
// Snapshot both current carts under the outgoing region.
|
||||||
|
for (const cartType of CART_TYPES) {
|
||||||
|
const items = await getLocalCart(cartType)
|
||||||
|
if (currentId != null) {
|
||||||
|
await saveCartSnapshot(currentId, items, cartType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await setRegion(nextId, nextName)
|
||||||
|
|
||||||
|
// Fetch the new region's cache payloads directly so reconcile
|
||||||
|
// doesn't race the central-store effects.
|
||||||
|
setSwitchMessage(`Loading ${nextName}…`)
|
||||||
|
const fetched = await fetchRegionSlotMap(utils, nextId)
|
||||||
|
const slotMap = fetched.slotMap
|
||||||
|
|
||||||
|
// Restore-or-carry, then reconcile each cart.
|
||||||
|
setSwitchMessage('Updating your cart…')
|
||||||
|
for (const cartType of CART_TYPES) {
|
||||||
|
const base = (await getCartSnapshot(nextId, cartType)) ?? (await getLocalCart(cartType))
|
||||||
|
const reconciled = reconcileCartLines(base, slotMap, oldSlotTimes, names)
|
||||||
|
await saveLocalCart(reconciled.lines, cartType)
|
||||||
|
for (const r of reconciled.results) {
|
||||||
|
lines.push({ ...r, cartType })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['local-cart-regular'] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['local-cart-flash'] })
|
||||||
|
// Region-scoped cache URLs change with the region — refetch catalog data.
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['all-products'] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['slots'] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['availability'] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['stores'] })
|
||||||
|
|
||||||
|
setResults({ regionName: nextName, lines, error: null })
|
||||||
|
} catch (e) {
|
||||||
|
error = e instanceof Error ? e.message : 'Region switch failed'
|
||||||
|
setResults({ regionName: nextName, lines, error })
|
||||||
|
} finally {
|
||||||
|
setRegionSwitchInProgress(false)
|
||||||
|
setIsSwitching(false)
|
||||||
|
runningRef.current = false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[regionId, setRegion, utils, queryClient]
|
||||||
|
)
|
||||||
|
|
||||||
|
const clearResults = useCallback(() => setResults(null), [])
|
||||||
|
|
||||||
|
const presentResults = useCallback((next: RegionSwitchResults) => setResults(next), [])
|
||||||
|
|
||||||
|
return { switchRegion, isSwitching, switchMessage, results, clearResults, presentResults }
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RegionSwitchContextValue {
|
||||||
|
switchRegion: (nextId: number, nextName: string) => Promise<void>
|
||||||
|
isSwitching: boolean
|
||||||
|
switchMessage: string
|
||||||
|
results: RegionSwitchResults | null
|
||||||
|
clearResults: () => void
|
||||||
|
presentResults: (next: RegionSwitchResults) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const RegionSwitchContext = createContext<RegionSwitchContextValue | undefined>(undefined)
|
||||||
|
|
||||||
|
export const RegionSwitchProvider: FC<{ children: ReactNode }> = ({ children }) => {
|
||||||
|
const { switchRegion, isSwitching, switchMessage, results, clearResults, presentResults } = useRegionSwitch()
|
||||||
|
const value = useMemo(
|
||||||
|
() => ({ switchRegion, isSwitching, switchMessage, results, clearResults, presentResults }),
|
||||||
|
[switchRegion, isSwitching, switchMessage, results, clearResults, presentResults]
|
||||||
|
)
|
||||||
|
return <RegionSwitchContext.Provider value={value}>{children}</RegionSwitchContext.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useRegionSwitchContext = (): RegionSwitchContextValue => {
|
||||||
|
const context = useContext(RegionSwitchContext)
|
||||||
|
if (context === undefined) {
|
||||||
|
throw new Error('useRegionSwitchContext must be used within a RegionSwitchProvider')
|
||||||
|
}
|
||||||
|
return context
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'
|
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'
|
||||||
import { trpc } from './trpc-client'
|
import { trpc } from './trpc-client'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
import type { User as SharedUser, AuthStateCore } from '@packages/shared'
|
import type { User as SharedUser, AuthStateCore } from '@packages/shared'
|
||||||
|
|
||||||
// Auth user — serialized view of the shared User (optional name, no createdAt)
|
// Auth user — serialized view of the shared User (optional name, no createdAt)
|
||||||
|
|
@ -35,6 +36,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
token: null,
|
token: null,
|
||||||
})
|
})
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
// On mount, check for stored token
|
// On mount, check for stored token
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -51,10 +53,12 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
// Fetch user data when token is available
|
// Fetch user data when token is available (mirrors native: no retry, fresh on mount)
|
||||||
const { data: selfData } = trpc.user.user.getSelfData.useQuery(undefined, {
|
const { data: selfData, isError: selfError } = trpc.user.user.getSelfData.useQuery(undefined, {
|
||||||
enabled: !!state.token && state.isAuthenticated,
|
enabled: !!state.token && state.isAuthenticated,
|
||||||
retry: 1,
|
retry: false,
|
||||||
|
staleTime: 0,
|
||||||
|
refetchOnMount: true,
|
||||||
})
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -65,10 +69,20 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
userDetails: selfData.data.user,
|
userDetails: selfData.data.user,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
}))
|
}))
|
||||||
} else if (selfData === undefined && state.token) {
|
} else if (selfError && state.token) {
|
||||||
// Token might be invalid
|
// Token invalid — force logout like native
|
||||||
|
localStorage.removeItem('auth_token')
|
||||||
|
localStorage.removeItem('user_id')
|
||||||
|
queryClient.clear()
|
||||||
|
setState({
|
||||||
|
user: null,
|
||||||
|
userDetails: null,
|
||||||
|
isAuthenticated: false,
|
||||||
|
isLoading: false,
|
||||||
|
token: null,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}, [selfData, state.token])
|
}, [selfData, selfError, state.token, queryClient])
|
||||||
|
|
||||||
const login = useCallback((token: string, user: User) => {
|
const login = useCallback((token: string, user: User) => {
|
||||||
localStorage.setItem('auth_token', token)
|
localStorage.setItem('auth_token', token)
|
||||||
|
|
@ -93,6 +107,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
const logout = useCallback(() => {
|
const logout = useCallback(() => {
|
||||||
localStorage.removeItem('auth_token')
|
localStorage.removeItem('auth_token')
|
||||||
localStorage.removeItem('user_id')
|
localStorage.removeItem('user_id')
|
||||||
|
queryClient.clear()
|
||||||
setState({
|
setState({
|
||||||
user: null,
|
user: null,
|
||||||
userDetails: null,
|
userDetails: null,
|
||||||
|
|
@ -101,7 +116,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
token: null,
|
token: null,
|
||||||
})
|
})
|
||||||
navigate({ to: '/login' })
|
navigate({ to: '/login' })
|
||||||
}, [navigate])
|
}, [navigate, queryClient])
|
||||||
|
|
||||||
const updateUser = useCallback((user: User) => {
|
const updateUser = useCallback((user: User) => {
|
||||||
setState((prev) => ({ ...prev, user }))
|
setState((prev) => ({ ...prev, user }))
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,8 @@ import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
|
||||||
import { trpc, getTrpcClient } from '../lib/trpc-client'
|
import { trpc, getTrpcClient } from '../lib/trpc-client'
|
||||||
import { getQueryClient } from '../lib/query-client'
|
import { getQueryClient } from '../lib/query-client'
|
||||||
import { AuthProvider } from '../lib/auth-context'
|
import { AuthProvider } from '../lib/auth-context'
|
||||||
|
import { RegionProvider } from '../contexts/RegionContext'
|
||||||
|
import { RegionSwitchProvider } from '../hooks/useRegionSwitch'
|
||||||
import appCss from '../styles.css?url'
|
import appCss from '../styles.css?url'
|
||||||
|
|
||||||
const queryClient = getQueryClient()
|
const queryClient = getQueryClient()
|
||||||
|
|
@ -38,10 +40,14 @@ function RootDocument({ children }: { children: React.ReactNode }) {
|
||||||
<body>
|
<body>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<trpc.Provider client={trpcClient} queryClient={queryClient}>
|
<trpc.Provider client={trpcClient} queryClient={queryClient}>
|
||||||
|
<RegionProvider>
|
||||||
|
<RegionSwitchProvider>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<div id="app">{children}</div>
|
<div id="app">{children}</div>
|
||||||
<ReactQueryDevtools />
|
<ReactQueryDevtools />
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
|
</RegionSwitchProvider>
|
||||||
|
</RegionProvider>
|
||||||
</trpc.Provider>
|
</trpc.Provider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
<TanStackDevtools
|
<TanStackDevtools
|
||||||
|
|
|
||||||
|
|
@ -1,154 +1,13 @@
|
||||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks'
|
|
||||||
import { useAllProducts } from '../hooks/prominent-api-hooks'
|
|
||||||
import { Quantifier } from 'web-components'
|
|
||||||
import { AppLayout } from '../components/AppLayout'
|
import { AppLayout } from '../components/AppLayout'
|
||||||
import { Trash2, ShoppingCart, Ticket, ChevronRight } from 'lucide-react'
|
import { CartPage } from '../components/cart-page'
|
||||||
|
|
||||||
export const Route = createFileRoute('/cart')({ component: CartPage })
|
export const Route = createFileRoute('/cart')({ component: GenericCartRoute })
|
||||||
|
|
||||||
function CartPage() {
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const { data: cart } = useGetCart('regular')
|
|
||||||
const { data: productsData } = useAllProducts()
|
|
||||||
const updateItem = useUpdateCartItem('regular')
|
|
||||||
const removeItem = useRemoveFromCart('regular')
|
|
||||||
|
|
||||||
const products = productsData?.products || []
|
|
||||||
const productsById: Record<number, any> = {}
|
|
||||||
products.forEach((p: any) => { productsById[p.id] = p })
|
|
||||||
|
|
||||||
const cartItems = (cart?.items || []).filter((item) => productsById[item.skuId])
|
|
||||||
|
|
||||||
let total = 0
|
|
||||||
cartItems.forEach((item) => {
|
|
||||||
const product = productsById[item.skuId]
|
|
||||||
if (product) {
|
|
||||||
total += product.price * item.quantity
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
|
function GenericCartRoute() {
|
||||||
return (
|
return (
|
||||||
<AppLayout>
|
<AppLayout>
|
||||||
<div className="mx-auto w-full max-w-7xl px-4 py-6 pb-24 md:px-8 md:pb-12">
|
<CartPage isFlashDelivery={false} />
|
||||||
<div className="mb-6">
|
|
||||||
<p className="text-[11px] font-black uppercase tracking-[0.22em] text-brand-600">
|
|
||||||
Review Before Delivery
|
|
||||||
</p>
|
|
||||||
<h1 className="display-2 mt-1 text-gray-900">Your Cart</h1>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{cartItems.length === 0 ? (
|
|
||||||
<div className="flex flex-col items-center gap-4 rounded-xl border border-dashed border-gray-300 bg-white py-24">
|
|
||||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gray-50">
|
|
||||||
<ShoppingCart className="h-7 w-7 text-gray-400" />
|
|
||||||
</div>
|
|
||||||
<p className="font-bold text-gray-800">Your cart is empty</p>
|
|
||||||
<p className="text-sm text-gray-500">Fresh cuts are waiting at the counter</p>
|
|
||||||
<button
|
|
||||||
onClick={() => navigate({ to: '/home' })}
|
|
||||||
className="mt-2 rounded-lg bg-brand-600 px-6 py-2.5 text-sm font-bold text-white transition-colors hover:bg-brand-700"
|
|
||||||
>
|
|
||||||
Browse Products
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_360px]">
|
|
||||||
{/* Items */}
|
|
||||||
<div className="flex flex-col gap-3">
|
|
||||||
{cartItems.map((item) => {
|
|
||||||
const product = productsById[item.skuId]
|
|
||||||
const price = product.price
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={item.skuId}
|
|
||||||
className="flex items-center gap-4 rounded-xl border border-gray-200 bg-white p-4"
|
|
||||||
>
|
|
||||||
<img
|
|
||||||
src={product.images?.[0]}
|
|
||||||
alt={product.name}
|
|
||||||
className="h-20 w-20 shrink-0 rounded-lg object-cover"
|
|
||||||
/>
|
|
||||||
<div className="min-w-0 flex-1">
|
|
||||||
<p className="text-sm font-bold text-gray-900">{product.name}</p>
|
|
||||||
<p className="mt-0.5 text-xs text-gray-500">
|
|
||||||
{product.unitNotation || ''} per unit
|
|
||||||
</p>
|
|
||||||
<div className="mt-2 flex items-center gap-3">
|
|
||||||
<Quantifier
|
|
||||||
value={item.quantity}
|
|
||||||
setValue={(q) => updateItem.mutate({ skuId: item.skuId, quantity: q })}
|
|
||||||
/>
|
|
||||||
<p className="text-sm font-bold text-gray-900">₹{price}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-col items-end gap-2">
|
|
||||||
<p className="text-sm font-extrabold text-brand-600 sm:text-base">₹{price * item.quantity}</p>
|
|
||||||
<button
|
|
||||||
onClick={() => removeItem.mutate(item.skuId)}
|
|
||||||
className="flex h-9 w-9 items-center justify-center rounded-lg text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
|
|
||||||
aria-label={`Remove ${product.name}`}
|
|
||||||
>
|
|
||||||
<Trash2 className="h-4 w-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Coupons card */}
|
|
||||||
<div className="rounded-xl border border-gray-200 bg-white p-4">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-pink-50">
|
|
||||||
<Ticket className="h-4 w-4 text-pink-500" />
|
|
||||||
</div>
|
|
||||||
<p className="text-base font-bold text-gray-900">Offers & Coupons</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
onClick={() => navigate({ to: '/me/coupons' })}
|
|
||||||
className="mt-2 flex items-center gap-0.5 text-sm font-bold text-brand-600 hover:text-brand-700"
|
|
||||||
>
|
|
||||||
Add Coupons to account
|
|
||||||
<ChevronRight className="h-4 w-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Summary */}
|
|
||||||
<div className="lg:sticky lg:top-24 lg:self-start">
|
|
||||||
<div className="rounded-xl border border-gray-200 bg-white p-6">
|
|
||||||
<p className="font-display text-lg font-extrabold text-gray-900">Bill Summary</p>
|
|
||||||
<div className="mt-4 space-y-2 border-b border-gray-100 pb-4">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<p className="text-sm text-gray-600">Item Total</p>
|
|
||||||
<p className="text-sm font-bold text-gray-900">₹{total}</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<p className="text-sm text-gray-600">Delivery Fee</p>
|
|
||||||
<p className="text-sm font-semibold text-green-600">Calculated at checkout</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between py-4">
|
|
||||||
<p className="font-bold text-gray-900">Total</p>
|
|
||||||
<p className="font-display text-xl font-extrabold text-gray-900">₹{total}</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
onClick={() => navigate({ to: '/checkout' })}
|
|
||||||
className="w-full rounded-lg bg-brand-600 py-3.5 text-sm font-bold text-white transition-colors hover:bg-brand-700"
|
|
||||||
>
|
|
||||||
Proceed to Checkout
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => navigate({ to: '/home' })}
|
|
||||||
className="mt-3 w-full rounded-lg border border-gray-200 py-3 text-sm font-bold text-gray-700 transition-colors hover:bg-gray-50"
|
|
||||||
>
|
|
||||||
Continue Shopping
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</AppLayout>
|
</AppLayout>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,136 +1,13 @@
|
||||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks'
|
|
||||||
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
|
||||||
import { Quantifier } from 'web-components'
|
|
||||||
import { AppLayout } from '../components/AppLayout'
|
import { AppLayout } from '../components/AppLayout'
|
||||||
import { Trash2, Zap, ShoppingCart } from 'lucide-react'
|
import { CartPage } from '../components/cart-page'
|
||||||
|
|
||||||
export const Route = createFileRoute('/flash/cart')({ component: FlashCartPage })
|
export const Route = createFileRoute('/flash/cart')({ component: FlashCartRoute })
|
||||||
|
|
||||||
function FlashCartPage() {
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const { data: cart } = useGetCart('flash')
|
|
||||||
const updateItem = useUpdateCartItem('flash')
|
|
||||||
const removeItem = useRemoveFromCart('flash')
|
|
||||||
const productsById = useCentralProductStore((s) => s.productsById)
|
|
||||||
|
|
||||||
const cartItems = (cart?.items || []).filter((item) => productsById[item.skuId])
|
|
||||||
|
|
||||||
let total = 0
|
|
||||||
cartItems.forEach((item) => {
|
|
||||||
const product = productsById[item.skuId]
|
|
||||||
if (product) {
|
|
||||||
total += product.price * item.quantity
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
|
function FlashCartRoute() {
|
||||||
return (
|
return (
|
||||||
<AppLayout isFlashDelivery={true}>
|
<AppLayout>
|
||||||
<div className="mx-auto w-full max-w-7xl px-4 py-6 pb-24 md:px-8 md:pb-12">
|
<CartPage isFlashDelivery={true} />
|
||||||
<div className="mb-6">
|
|
||||||
<p className="text-[11px] font-black uppercase tracking-[0.22em] text-flash-500">
|
|
||||||
1 Hr Delivery
|
|
||||||
</p>
|
|
||||||
<h1 className="display-2 mt-1 flex items-center gap-2 text-gray-900">
|
|
||||||
<Zap className="h-6 w-6 text-flash-500" fill="currentColor" />
|
|
||||||
Flash Cart
|
|
||||||
</h1>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{cartItems.length === 0 ? (
|
|
||||||
<div className="flex flex-col items-center gap-4 rounded-xl border border-dashed border-gray-300 bg-white py-24">
|
|
||||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-flash-25">
|
|
||||||
<ShoppingCart className="h-7 w-7 text-flash-500" />
|
|
||||||
</div>
|
|
||||||
<p className="font-bold text-gray-800">Your flash cart is empty</p>
|
|
||||||
<p className="text-sm text-gray-500">Pick something from 1 hr delivery</p>
|
|
||||||
<button
|
|
||||||
onClick={() => navigate({ to: '/flash' })}
|
|
||||||
className="mt-2 rounded-lg bg-flash-500 px-6 py-2.5 text-sm font-bold text-white transition-colors hover:bg-flash-600"
|
|
||||||
>
|
|
||||||
Browse Flash Products
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_360px]">
|
|
||||||
{/* Items */}
|
|
||||||
<div className="flex flex-col gap-3">
|
|
||||||
{cartItems.map((item) => {
|
|
||||||
const product = productsById[item.skuId]
|
|
||||||
const price = product.price
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={item.skuId}
|
|
||||||
className="flex items-center gap-4 rounded-xl border border-gray-200 bg-white p-4"
|
|
||||||
>
|
|
||||||
<img
|
|
||||||
src={product.images?.[0] ?? ''}
|
|
||||||
alt={product.name}
|
|
||||||
className="h-20 w-20 shrink-0 rounded-lg object-cover"
|
|
||||||
/>
|
|
||||||
<div className="min-w-0 flex-1">
|
|
||||||
<p className="text-sm font-bold text-gray-900">{product.name}</p>
|
|
||||||
<p className="mt-0.5 text-xs text-gray-500">
|
|
||||||
{product.unitNotation || ''} per unit
|
|
||||||
</p>
|
|
||||||
<div className="mt-2 flex items-center gap-3">
|
|
||||||
<Quantifier
|
|
||||||
value={item.quantity}
|
|
||||||
setValue={(q) => updateItem.mutate({ skuId: item.skuId, quantity: q })}
|
|
||||||
/>
|
|
||||||
<p className="text-sm font-bold text-gray-900">₹{price}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-col items-end gap-2">
|
|
||||||
<p className="text-base font-extrabold text-flash-500">₹{price * item.quantity}</p>
|
|
||||||
<button
|
|
||||||
onClick={() => removeItem.mutate(item.skuId)}
|
|
||||||
className="flex h-9 w-9 items-center justify-center rounded-lg text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
|
|
||||||
aria-label={`Remove ${product.name}`}
|
|
||||||
>
|
|
||||||
<Trash2 className="h-4 w-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Summary */}
|
|
||||||
<div className="lg:sticky lg:top-24 lg:self-start">
|
|
||||||
<div className="rounded-xl border border-gray-200 bg-white p-6">
|
|
||||||
<p className="font-display text-lg font-extrabold text-gray-900">Bill Summary</p>
|
|
||||||
<div className="mt-4 space-y-2 border-b border-gray-100 pb-4">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<p className="text-sm text-gray-600">Item Total</p>
|
|
||||||
<p className="text-sm font-bold text-gray-900">₹{total}</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<p className="text-sm text-gray-600">Delivery Fee</p>
|
|
||||||
<p className="text-sm font-semibold text-green-600">Calculated at checkout</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between py-4">
|
|
||||||
<p className="font-bold text-gray-900">Total</p>
|
|
||||||
<p className="font-display text-xl font-extrabold text-gray-900">₹{total}</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
onClick={() => navigate({ to: '/flash/checkout' })}
|
|
||||||
className="w-full rounded-lg bg-flash-500 py-3.5 text-sm font-bold text-white transition-colors hover:bg-flash-600"
|
|
||||||
>
|
|
||||||
Proceed to Checkout
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => navigate({ to: '/flash' })}
|
|
||||||
className="mt-3 w-full rounded-lg border border-gray-200 py-3 text-sm font-bold text-gray-700 transition-colors hover:bg-gray-50"
|
|
||||||
>
|
|
||||||
Continue Shopping
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</AppLayout>
|
</AppLayout>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,132 +1,162 @@
|
||||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||||
import { useState } from 'react'
|
import { useState, useMemo, useEffect } from 'react'
|
||||||
import { useAuth } from '../lib/auth-context'
|
import { useAuth } from '../lib/auth-context'
|
||||||
import { useGetCart } from '../hooks/cart-query-hooks'
|
import { useGetCart } from '../hooks/cart-query-hooks'
|
||||||
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
||||||
|
import { useCentralSlotStore } from '../lib/stores/central-slot-store'
|
||||||
import { trpc } from '../lib/trpc-client'
|
import { trpc } from '../lib/trpc-client'
|
||||||
import { clearLocalCart } from '../hooks/cart-query-hooks'
|
import { ProtectedRoute } from '../components/ProtectedRoute'
|
||||||
import { p, MyButton, LoadingDialog, AppContainer } from 'web-components'
|
import { CheckoutAddressSelector } from '../components/CheckoutAddressSelector'
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
import { PaymentAndOrderComponent } from '../components/PaymentAndOrderComponent'
|
||||||
|
import { useAddressStore } from '../lib/stores/address-store'
|
||||||
|
import { AppContainer } from 'web-components'
|
||||||
|
import { ShoppingCart, ChevronLeft } from 'lucide-react'
|
||||||
|
|
||||||
export const Route = createFileRoute('/flash/checkout')({ component: FlashCheckoutPage })
|
export const Route = createFileRoute('/flash/checkout')({
|
||||||
|
component: FlashCheckoutPage,
|
||||||
|
validateSearch: (search: Record<string, unknown>): { slots?: string; coupons?: string; deliveryPrice?: string } => ({
|
||||||
|
slots: typeof search.slots === 'string' ? search.slots : undefined,
|
||||||
|
coupons: typeof search.coupons === 'string' ? search.coupons : undefined,
|
||||||
|
deliveryPrice: typeof search.deliveryPrice === 'string' ? search.deliveryPrice : undefined,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
function FlashCheckoutPage() {
|
function FlashCheckoutPage() {
|
||||||
const navigate = useNavigate()
|
return (
|
||||||
const queryClient = useQueryClient()
|
<ProtectedRoute>
|
||||||
const { isAuthenticated } = useAuth()
|
<FlashCheckoutContent />
|
||||||
const { data: cart } = useGetCart('flash')
|
</ProtectedRoute>
|
||||||
const productsById = useCentralProductStore((s) => s.productsById)
|
)
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
}
|
||||||
|
|
||||||
const { data: addresses } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
function FlashCheckoutContent() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const { slots, coupons, deliveryPrice } = Route.useSearch()
|
||||||
|
const { isAuthenticated } = useAuth()
|
||||||
|
const { selectedAddressId } = useAddressStore()
|
||||||
|
const { data: cartData } = useGetCart('flash')
|
||||||
|
const products = useCentralProductStore((s) => s.products)
|
||||||
|
const productsById = useCentralProductStore((s) => s.productsById)
|
||||||
|
const productSlotsMap = useCentralSlotStore((s) => s.productSlotsMap)
|
||||||
|
const [selectedCouponId, setSelectedCouponId] = useState<number | null>(null)
|
||||||
|
|
||||||
|
const cartItems = cartData?.items || []
|
||||||
|
|
||||||
|
const flashEligibleProductIds = useMemo(() => {
|
||||||
|
if (!products.length) return new Set<number>()
|
||||||
|
return new Set(products.filter((product) => productSlotsMap[product.id]?.isFlashAvailable).map((product) => product.id))
|
||||||
|
}, [products, productSlotsMap])
|
||||||
|
|
||||||
|
// Parse slots parameter from URL (format: "0:1,2,3")
|
||||||
|
const selectedSlots = useMemo(() => {
|
||||||
|
const parsed: Record<number, number> = {}
|
||||||
|
if (slots) {
|
||||||
|
slots.split(';').forEach((group) => {
|
||||||
|
const [slotIdStr, itemIdsStr] = group.split(':')
|
||||||
|
const slotId = Number(slotIdStr)
|
||||||
|
if (!slotIdStr || !itemIdsStr) return
|
||||||
|
itemIdsStr.split(',').map(Number).forEach((itemId) => {
|
||||||
|
parsed[itemId] = slotId
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}, [slots])
|
||||||
|
|
||||||
|
// Flash checkout only includes flash-eligible items (slot group 0 from the cart).
|
||||||
|
const selectedItems = cartItems.filter(
|
||||||
|
(item) => flashEligibleProductIds.has(item.skuId) && (Object.keys(selectedSlots).length === 0 || selectedSlots[item.id] != null)
|
||||||
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (coupons) {
|
||||||
|
const couponId = Number(coupons)
|
||||||
|
if (!isNaN(couponId)) setSelectedCouponId(couponId)
|
||||||
|
}
|
||||||
|
}, [coupons])
|
||||||
|
|
||||||
|
const { data: couponsRaw } = trpc.user.coupon.getEligible.useQuery(undefined, {
|
||||||
enabled: isAuthenticated,
|
enabled: isAuthenticated,
|
||||||
})
|
})
|
||||||
const [selectedAddressId, setSelectedAddressId] = useState<number | null>(null)
|
|
||||||
|
|
||||||
const placeOrderMutation = trpc.user.order.placeOrder.useMutation({
|
const totalPrice = selectedItems
|
||||||
onSuccess: (data) => {
|
.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
||||||
const order = data.data?.[0]
|
.reduce((sum, item) => {
|
||||||
clearLocalCart('flash')
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['local-cart-flash'] })
|
|
||||||
navigate({
|
|
||||||
to: '/flash/order-success',
|
|
||||||
search: { orderId: String(order?.id), totalAmount: String(total) },
|
|
||||||
})
|
|
||||||
},
|
|
||||||
onSettled: () => setIsLoading(false),
|
|
||||||
})
|
|
||||||
|
|
||||||
const cartItems = (cart?.items || []).filter((item) => productsById[item.skuId])
|
|
||||||
|
|
||||||
let total = 0
|
|
||||||
cartItems.forEach((item) => {
|
|
||||||
const product = productsById[item.skuId]
|
const product = productsById[item.skuId]
|
||||||
if (product) {
|
return sum + (product?.flashPrice ?? product?.price ?? 0) * item.quantity
|
||||||
total += product.price * item.quantity
|
}, 0)
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const handlePlaceOrder = () => {
|
const appliedCoupon = useMemo(() => {
|
||||||
if (!selectedAddressId) return
|
if (!selectedCouponId || !(couponsRaw as any)?.data) return null
|
||||||
setIsLoading(true)
|
const coupon = ((couponsRaw as any).data as any[]).find((c) => c.id === selectedCouponId)
|
||||||
placeOrderMutation.mutate({
|
if (!coupon) return null
|
||||||
selectedItems: cartItems.map((item) => ({
|
if (coupon.maxLimitForUser && coupon.usages.length >= coupon.maxLimitForUser) return null
|
||||||
skuId: item.skuId,
|
if (coupon.minOrder && parseFloat(coupon.minOrder) > totalPrice) return null
|
||||||
quantity: item.quantity,
|
const amount = coupon.discountPercent
|
||||||
slotId: null,
|
? Math.min((totalPrice * parseFloat(coupon.discountPercent)) / 100, coupon.maxValue ? parseFloat(coupon.maxValue) : Infinity)
|
||||||
})),
|
: Math.min(parseFloat(coupon.flatDiscount || '0'), coupon.maxValue ? parseFloat(coupon.maxValue) : totalPrice)
|
||||||
addressId: selectedAddressId,
|
return { code: coupon.couponCode, amount }
|
||||||
paymentMethod: 'cod',
|
}, [selectedCouponId, couponsRaw, totalPrice])
|
||||||
isFlashDelivery: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
|
const quoteDeliveryPrice = deliveryPrice != null && !isNaN(Number(deliveryPrice)) ? Number(deliveryPrice) : undefined
|
||||||
|
|
||||||
|
if (selectedItems.length === 0) {
|
||||||
return (
|
return (
|
||||||
<AppContainer>
|
<AppContainer>
|
||||||
<p className="font-bold mb-4 text-xl">
|
<div className="flex min-h-screen flex-col items-center justify-center bg-gray-50 p-6">
|
||||||
Flash Checkout
|
<div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-white">
|
||||||
|
<ShoppingCart className="h-9 w-9 text-gray-400" />
|
||||||
|
</div>
|
||||||
|
<p className="mt-6 text-xl font-bold text-gray-900">
|
||||||
|
{cartItems.length === 0 ? 'Your cart is empty' : 'No items to checkout'}
|
||||||
</p>
|
</p>
|
||||||
|
<p className="mb-6 mt-1 text-gray-500">
|
||||||
<div className="mb-6">
|
{cartItems.length === 0
|
||||||
<p className="font-semibold mb-2">
|
? 'Add some delicious items to your cart before checking out'
|
||||||
Delivery Address
|
: "None of your cart items are available for flash delivery"}
|
||||||
</p>
|
</p>
|
||||||
{addresses?.data?.map((addr: any) => (
|
|
||||||
<button
|
<button
|
||||||
key={addr.id}
|
onClick={() => navigate({ to: '/flash/cart' })}
|
||||||
onClick={() => setSelectedAddressId(addr.id)}
|
className="rounded-lg bg-brand-600 px-6 py-3 text-sm font-bold text-white transition-colors hover:bg-brand-700"
|
||||||
className={`mb-2 w-full rounded-xl border p-3 text-left ${
|
|
||||||
selectedAddressId === addr.id
|
|
||||||
? 'border-brand-500 bg-brand-50'
|
|
||||||
: 'border-gray-200'
|
|
||||||
}`}
|
|
||||||
>
|
>
|
||||||
<p className="font-semibold">{addr.name}</p>
|
Back to Cart
|
||||||
<p className="text-sm text-gray-600">
|
|
||||||
{addr.addressLine1}, {addr.city}
|
|
||||||
</p>
|
|
||||||
<p className="text-sm text-gray-500">{addr.phone}</p>
|
|
||||||
</button>
|
</button>
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mb-6">
|
|
||||||
<p className="font-semibold mb-2">
|
|
||||||
Order Summary
|
|
||||||
</p>
|
|
||||||
{cartItems.map((item) => {
|
|
||||||
const product = productsById[item.skuId]
|
|
||||||
if (!product) return null
|
|
||||||
return (
|
|
||||||
<div key={item.skuId} className="flex items-center justify-between py-2">
|
|
||||||
<p className="text-sm">
|
|
||||||
{product.name} x{item.quantity}
|
|
||||||
</p>
|
|
||||||
<p className="text-sm font-bold">
|
|
||||||
₹{product.price * item.quantity}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
<div className="mt-2 border-t border-gray-200 pt-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<p className="font-bold">Total</p>
|
|
||||||
<p className="font-bold text-brand-600">
|
|
||||||
₹{total}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<MyButton
|
|
||||||
fullWidth
|
|
||||||
textContent="Place Flash Order (COD)"
|
|
||||||
onClick={handlePlaceOrder}
|
|
||||||
disabled={!selectedAddressId || placeOrderMutation.isPending}
|
|
||||||
className="bg-brand-500 text-white"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<LoadingDialog open={isLoading} message="Placing flash order..." />
|
|
||||||
</AppContainer>
|
</AppContainer>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-50">
|
||||||
|
<div className="sticky top-0 z-20 border-b border-gray-200 bg-white">
|
||||||
|
<div className="mx-auto flex h-16 w-full max-w-7xl items-center gap-3 px-4 md:px-8">
|
||||||
|
<button
|
||||||
|
onClick={() => navigate({ to: '/flash/cart' })}
|
||||||
|
className="flex h-9 w-9 items-center justify-center rounded-lg text-gray-600 transition-colors hover:bg-gray-50"
|
||||||
|
aria-label="Back to cart"
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
<p className="font-display text-lg font-extrabold text-gray-900">1 Hr Delivery Checkout</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mx-auto grid w-full max-w-7xl gap-8 px-4 py-6 md:px-8 lg:grid-cols-[minmax(0,1fr)_420px]">
|
||||||
|
<div>
|
||||||
|
<CheckoutAddressSelector />
|
||||||
|
</div>
|
||||||
|
<div className="lg:sticky lg:top-24 lg:self-start">
|
||||||
|
<PaymentAndOrderComponent
|
||||||
|
selectedAddress={selectedAddressId}
|
||||||
|
cartItems={selectedItems}
|
||||||
|
isFlashDelivery={true}
|
||||||
|
appliedCoupon={appliedCoupon}
|
||||||
|
couponId={selectedCouponId}
|
||||||
|
quotedDeliveryPrice={quoteDeliveryPrice}
|
||||||
|
onBack={() => navigate({ to: '/flash/cart' })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||||
import { Zap } from 'lucide-react'
|
import { Zap } from 'lucide-react'
|
||||||
|
import { NextOrderGlimpse } from '../components/me/NextOrderGlimpse'
|
||||||
|
|
||||||
export const Route = createFileRoute('/flash/order-success')({
|
export const Route = createFileRoute('/flash/order-success')({
|
||||||
component: FlashOrderSuccessPage,
|
component: FlashOrderSuccessPage,
|
||||||
|
|
@ -35,6 +36,10 @@ function FlashOrderSuccessPage() {
|
||||||
>
|
>
|
||||||
View My Orders
|
View My Orders
|
||||||
</button>
|
</button>
|
||||||
|
{/* Upcoming-order glimpse (matches user-ui order-success flow) */}
|
||||||
|
<div className="mt-8 w-full max-w-md">
|
||||||
|
<NextOrderGlimpse />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,137 +1,13 @@
|
||||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks'
|
|
||||||
import { useAllProducts } from '../hooks/prominent-api-hooks'
|
|
||||||
import { Quantifier } from 'web-components'
|
|
||||||
import { AppLayout } from '../components/AppLayout'
|
import { AppLayout } from '../components/AppLayout'
|
||||||
import { Trash2, ShoppingCart } from 'lucide-react'
|
import { CartPage } from '../components/cart-page'
|
||||||
|
|
||||||
export const Route = createFileRoute('/home/cart')({ component: CartPage })
|
export const Route = createFileRoute('/home/cart')({ component: HomeCartRoute })
|
||||||
|
|
||||||
function CartPage() {
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const { data: cart } = useGetCart('regular')
|
|
||||||
const { data: productsData } = useAllProducts()
|
|
||||||
const updateItem = useUpdateCartItem('regular')
|
|
||||||
const removeItem = useRemoveFromCart('regular')
|
|
||||||
|
|
||||||
const products = productsData?.products || []
|
|
||||||
const productsById: Record<number, any> = {}
|
|
||||||
products.forEach((p: any) => { productsById[p.id] = p })
|
|
||||||
|
|
||||||
const cartItems = (cart?.items || []).filter((item) => productsById[item.skuId])
|
|
||||||
|
|
||||||
let total = 0
|
|
||||||
cartItems.forEach((item) => {
|
|
||||||
const product = productsById[item.skuId]
|
|
||||||
if (product) {
|
|
||||||
total += product.price * item.quantity
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
|
function HomeCartRoute() {
|
||||||
return (
|
return (
|
||||||
<AppLayout>
|
<AppLayout>
|
||||||
<div className="mx-auto w-full max-w-7xl px-4 py-6 pb-24 md:px-8 md:pb-12">
|
<CartPage isFlashDelivery={false} />
|
||||||
<div className="mb-6">
|
|
||||||
<p className="text-[11px] font-black uppercase tracking-[0.22em] text-brand-600">
|
|
||||||
Review Before Delivery
|
|
||||||
</p>
|
|
||||||
<h1 className="display-2 mt-1 text-gray-900">Your Cart</h1>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{cartItems.length === 0 ? (
|
|
||||||
<div className="flex flex-col items-center gap-4 rounded-xl border border-dashed border-gray-300 bg-white py-24">
|
|
||||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gray-50">
|
|
||||||
<ShoppingCart className="h-7 w-7 text-gray-400" />
|
|
||||||
</div>
|
|
||||||
<p className="font-bold text-gray-800">Your cart is empty</p>
|
|
||||||
<p className="text-sm text-gray-500">Fresh cuts are waiting at the counter</p>
|
|
||||||
<button
|
|
||||||
onClick={() => navigate({ to: '/home' })}
|
|
||||||
className="mt-2 rounded-lg bg-brand-600 px-6 py-2.5 text-sm font-bold text-white transition-colors hover:bg-brand-700"
|
|
||||||
>
|
|
||||||
Browse Products
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_360px]">
|
|
||||||
{/* Items */}
|
|
||||||
<div className="flex flex-col gap-3">
|
|
||||||
{cartItems.map((item) => {
|
|
||||||
const product = productsById[item.skuId]
|
|
||||||
const price = product.price
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={item.skuId}
|
|
||||||
className="flex items-center gap-4 rounded-xl border border-gray-200 bg-white p-4"
|
|
||||||
>
|
|
||||||
<img
|
|
||||||
src={product.images?.[0]}
|
|
||||||
alt={product.name}
|
|
||||||
className="h-20 w-20 shrink-0 rounded-lg object-cover"
|
|
||||||
/>
|
|
||||||
<div className="min-w-0 flex-1">
|
|
||||||
<p className="text-sm font-bold text-gray-900">{product.name}</p>
|
|
||||||
<p className="mt-0.5 text-xs text-gray-500">
|
|
||||||
{product.unitNotation || ''} per unit
|
|
||||||
</p>
|
|
||||||
<div className="mt-2 flex items-center gap-3">
|
|
||||||
<Quantifier
|
|
||||||
value={item.quantity}
|
|
||||||
setValue={(q) => updateItem.mutate({ skuId: item.skuId, quantity: q })}
|
|
||||||
/>
|
|
||||||
<p className="text-sm font-bold text-gray-900">₹{price}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-col items-end gap-2">
|
|
||||||
<p className="text-sm font-extrabold text-brand-600 sm:text-base">₹{price * item.quantity}</p>
|
|
||||||
<button
|
|
||||||
onClick={() => removeItem.mutate(item.skuId)}
|
|
||||||
className="flex h-9 w-9 items-center justify-center rounded-lg text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
|
|
||||||
aria-label={`Remove ${product.name}`}
|
|
||||||
>
|
|
||||||
<Trash2 className="h-4 w-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Summary */}
|
|
||||||
<div className="lg:sticky lg:top-24 lg:self-start">
|
|
||||||
<div className="rounded-xl border border-gray-200 bg-white p-6">
|
|
||||||
<p className="font-display text-lg font-extrabold text-gray-900">Bill Summary</p>
|
|
||||||
<div className="mt-4 space-y-2 border-b border-gray-100 pb-4">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<p className="text-sm text-gray-600">Item Total</p>
|
|
||||||
<p className="text-sm font-bold text-gray-900">₹{total}</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<p className="text-sm text-gray-600">Delivery Fee</p>
|
|
||||||
<p className="text-sm font-semibold text-green-600">Calculated at checkout</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between py-4">
|
|
||||||
<p className="font-bold text-gray-900">Total</p>
|
|
||||||
<p className="font-display text-xl font-extrabold text-gray-900">₹{total}</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
onClick={() => navigate({ to: '/home/checkout' })}
|
|
||||||
className="w-full rounded-lg bg-brand-600 py-3.5 text-sm font-bold text-white transition-colors hover:bg-brand-700"
|
|
||||||
>
|
|
||||||
Proceed to Checkout
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => navigate({ to: '/home' })}
|
|
||||||
className="mt-3 w-full rounded-lg border border-gray-200 py-3 text-sm font-bold text-gray-700 transition-colors hover:bg-gray-50"
|
|
||||||
>
|
|
||||||
Continue Shopping
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</AppLayout>
|
</AppLayout>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,134 +1,157 @@
|
||||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||||
import { useState } from 'react'
|
import { useState, useMemo, useEffect } from 'react'
|
||||||
import { useAuth } from '../lib/auth-context'
|
import { useAuth } from '../lib/auth-context'
|
||||||
import { useGetCart } from '../hooks/cart-query-hooks'
|
import { useGetCart } from '../hooks/cart-query-hooks'
|
||||||
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
||||||
|
import { useCentralSlotStore } from '../lib/stores/central-slot-store'
|
||||||
import { trpc } from '../lib/trpc-client'
|
import { trpc } from '../lib/trpc-client'
|
||||||
import { clearLocalCart } from '../hooks/cart-query-hooks'
|
|
||||||
import { p, MyButton, LoadingDialog, AppContainer, div } from 'web-components'
|
import { p, MyButton, LoadingDialog, AppContainer, div } from 'web-components'
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { ProtectedRoute } from '../components/ProtectedRoute'
|
||||||
|
import { CheckoutAddressSelector } from '../components/CheckoutAddressSelector'
|
||||||
|
import { PaymentAndOrderComponent } from '../components/PaymentAndOrderComponent'
|
||||||
|
import { useAddressStore } from '../lib/stores/address-store'
|
||||||
|
import { useRegionParams } from '../contexts/RegionContext'
|
||||||
|
import { ShoppingCart, ChevronLeft } from 'lucide-react'
|
||||||
|
|
||||||
export const Route = createFileRoute('/home/checkout')({ component: CheckoutPage })
|
export const Route = createFileRoute('/home/checkout')({
|
||||||
|
component: CheckoutPage,
|
||||||
|
validateSearch: (search: Record<string, unknown>): { slots?: string; coupons?: string; deliveryPrice?: string } => ({
|
||||||
|
slots: typeof search.slots === 'string' ? search.slots : undefined,
|
||||||
|
coupons: typeof search.coupons === 'string' ? search.coupons : undefined,
|
||||||
|
deliveryPrice: typeof search.deliveryPrice === 'string' ? search.deliveryPrice : undefined,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
function CheckoutPage() {
|
function CheckoutPage() {
|
||||||
const navigate = useNavigate()
|
return (
|
||||||
const queryClient = useQueryClient()
|
<ProtectedRoute>
|
||||||
const { isAuthenticated } = useAuth()
|
<CheckoutContent />
|
||||||
const { data: cart } = useGetCart('regular')
|
</ProtectedRoute>
|
||||||
const productsById = useCentralProductStore((s) => s.productsById)
|
)
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
}
|
||||||
|
|
||||||
const { data: addresses } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
function CheckoutContent() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const { slots, coupons, deliveryPrice } = Route.useSearch()
|
||||||
|
const { isAuthenticated } = useAuth()
|
||||||
|
const regionParams = useRegionParams()
|
||||||
|
const { selectedAddressId } = useAddressStore()
|
||||||
|
const { data: cartData } = useGetCart('regular')
|
||||||
|
const productsById = useCentralProductStore((s) => s.productsById)
|
||||||
|
const products = useCentralProductStore((s) => s.products)
|
||||||
|
const productSlotsMap = useCentralSlotStore((s) => s.productSlotsMap)
|
||||||
|
const [selectedCouponId, setSelectedCouponId] = useState<number | null>(null)
|
||||||
|
|
||||||
|
const cartItems = cartData?.items || []
|
||||||
|
|
||||||
|
// Parse slots parameter from URL (format: "1:1,2,3;2:4,5")
|
||||||
|
const selectedSlots = useMemo(() => {
|
||||||
|
const parsed: Record<number, number> = {}
|
||||||
|
if (slots) {
|
||||||
|
slots.split(';').forEach((group) => {
|
||||||
|
const [slotIdStr, itemIdsStr] = group.split(':')
|
||||||
|
const slotId = Number(slotIdStr)
|
||||||
|
if (!slotIdStr || !itemIdsStr) return
|
||||||
|
itemIdsStr.split(',').map(Number).forEach((itemId) => {
|
||||||
|
parsed[itemId] = slotId
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}, [slots])
|
||||||
|
|
||||||
|
const selectedItems = cartItems.filter((item) => selectedSlots[item.id])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (coupons) {
|
||||||
|
const couponId = Number(coupons)
|
||||||
|
if (!isNaN(couponId)) setSelectedCouponId(couponId)
|
||||||
|
}
|
||||||
|
}, [coupons])
|
||||||
|
|
||||||
|
const { data: couponsRaw } = trpc.user.coupon.getEligible.useQuery(undefined, {
|
||||||
enabled: isAuthenticated,
|
enabled: isAuthenticated,
|
||||||
})
|
})
|
||||||
const [selectedAddressId, setSelectedAddressId] = useState<number | null>(null)
|
|
||||||
|
|
||||||
const placeOrderMutation = trpc.user.order.placeOrder.useMutation({
|
const totalPrice = selectedItems
|
||||||
onSuccess: (data) => {
|
.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
||||||
const order = data.data?.[0]
|
.reduce((sum, item) => {
|
||||||
clearLocalCart('regular')
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['local-cart-regular'] })
|
|
||||||
navigate({
|
|
||||||
to: '/home/order-success',
|
|
||||||
search: { orderId: String(order?.id), totalAmount: String(total) },
|
|
||||||
})
|
|
||||||
},
|
|
||||||
onSettled: () => setIsLoading(false),
|
|
||||||
})
|
|
||||||
|
|
||||||
const cartItems = (cart?.items || []).filter((item) => productsById[item.skuId])
|
|
||||||
|
|
||||||
let total = 0
|
|
||||||
cartItems.forEach((item) => {
|
|
||||||
const product = productsById[item.skuId]
|
const product = productsById[item.skuId]
|
||||||
if (product) {
|
return sum + (product?.price || 0) * item.quantity
|
||||||
total += product.price * item.quantity
|
}, 0)
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const handlePlaceOrder = () => {
|
const appliedCoupon = useMemo(() => {
|
||||||
if (!selectedAddressId) return
|
if (!selectedCouponId || !(couponsRaw as any)?.data) return null
|
||||||
setIsLoading(true)
|
const coupon = ((couponsRaw as any).data as any[]).find((c) => c.id === selectedCouponId)
|
||||||
placeOrderMutation.mutate({
|
if (!coupon) return null
|
||||||
selectedItems: cartItems.map((item) => ({
|
if (coupon.maxLimitForUser && coupon.usages.length >= coupon.maxLimitForUser) return null
|
||||||
skuId: item.skuId,
|
if (coupon.minOrder && parseFloat(coupon.minOrder) > totalPrice) return null
|
||||||
quantity: item.quantity,
|
const amount = coupon.discountPercent
|
||||||
slotId: null,
|
? Math.min((totalPrice * parseFloat(coupon.discountPercent)) / 100, coupon.maxValue ? parseFloat(coupon.maxValue) : Infinity)
|
||||||
})),
|
: Math.min(parseFloat(coupon.flatDiscount || '0'), coupon.maxValue ? parseFloat(coupon.maxValue) : totalPrice)
|
||||||
addressId: selectedAddressId,
|
return { code: coupon.couponCode, amount }
|
||||||
paymentMethod: 'cod',
|
}, [selectedCouponId, couponsRaw, totalPrice])
|
||||||
isFlashDelivery: false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
|
const quoteDeliveryPrice = deliveryPrice != null && !isNaN(Number(deliveryPrice)) ? Number(deliveryPrice) : undefined
|
||||||
|
|
||||||
|
if (selectedItems.length === 0) {
|
||||||
return (
|
return (
|
||||||
<AppContainer>
|
<AppContainer>
|
||||||
<p className="font-bold mb-4 text-xl">
|
<div className="flex min-h-screen flex-col items-center justify-center bg-gray-50 p-6">
|
||||||
Checkout
|
<div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-white">
|
||||||
|
<ShoppingCart className="h-9 w-9 text-gray-400" />
|
||||||
|
</div>
|
||||||
|
<p className="mt-6 text-xl font-bold text-gray-900">
|
||||||
|
{cartItems.length === 0 ? 'Your cart is empty' : 'No items to checkout'}
|
||||||
</p>
|
</p>
|
||||||
|
<p className="mb-6 mt-1 text-gray-500">
|
||||||
{/* Address Selection */}
|
{cartItems.length === 0
|
||||||
<div className="mb-6">
|
? 'Add some delicious items to your cart before checking out'
|
||||||
<p className="font-semibold mb-2">
|
: 'Please select delivery slots for your items'}
|
||||||
Delivery Address
|
|
||||||
</p>
|
</p>
|
||||||
{addresses?.data?.map((addr: any) => (
|
<button
|
||||||
<div
|
onClick={() => navigate({ to: '/home/cart' })}
|
||||||
key={addr.id}
|
className="rounded-lg bg-brand-600 px-6 py-3 text-sm font-bold text-white transition-colors hover:bg-brand-700"
|
||||||
onClick={() => setSelectedAddressId(addr.id)}
|
|
||||||
className={`mb-2 rounded-xl border p-3 ${
|
|
||||||
selectedAddressId === addr.id
|
|
||||||
? 'border-brand-500 bg-brand-50'
|
|
||||||
: 'border-gray-200'
|
|
||||||
}`}
|
|
||||||
>
|
>
|
||||||
<p className="font-semibold">{addr.name}</p>
|
Back to Cart
|
||||||
<p className="text-sm text-gray-600">
|
</button>
|
||||||
{addr.addressLine1}, {addr.city}
|
|
||||||
</p>
|
|
||||||
<p className="text-sm text-gray-500">{addr.phone}</p>
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Order Summary */}
|
|
||||||
<div className="mb-6">
|
|
||||||
<p className="font-semibold mb-2">
|
|
||||||
Order Summary
|
|
||||||
</p>
|
|
||||||
{cartItems.map((item) => {
|
|
||||||
const product = productsById[item.skuId]
|
|
||||||
if (!product) return null
|
|
||||||
return (
|
|
||||||
<div key={item.skuId} className="flex items-center justify-between py-2">
|
|
||||||
<p className="text-sm">
|
|
||||||
{product.name} x{item.quantity}
|
|
||||||
</p>
|
|
||||||
<p className="text-sm font-bold">
|
|
||||||
₹{product.price * item.quantity}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
<div className="mt-2 border-t border-gray-200 pt-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<p className="font-bold">Total</p>
|
|
||||||
<p className="font-bold text-brand-600">
|
|
||||||
₹{total}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<MyButton
|
|
||||||
fullWidth
|
|
||||||
textContent="Place Order (COD)"
|
|
||||||
onClick={handlePlaceOrder}
|
|
||||||
disabled={!selectedAddressId || placeOrderMutation.isPending}
|
|
||||||
className="bg-brand-500 text-white"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<LoadingDialog open={isLoading} message="Placing your order..." />
|
|
||||||
</AppContainer>
|
</AppContainer>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-50">
|
||||||
|
<div className="sticky top-0 z-20 border-b border-gray-200 bg-white">
|
||||||
|
<div className="mx-auto flex h-16 w-full max-w-7xl items-center gap-3 px-4 md:px-8">
|
||||||
|
<button
|
||||||
|
onClick={() => navigate({ to: '/home/cart' })}
|
||||||
|
className="flex h-9 w-9 items-center justify-center rounded-lg text-gray-600 transition-colors hover:bg-gray-50"
|
||||||
|
aria-label="Back to cart"
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
<p className="font-display text-lg font-extrabold text-gray-900">Scheduled Delivery Checkout</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mx-auto grid w-full max-w-7xl gap-8 px-4 py-6 md:px-8 lg:grid-cols-[minmax(0,1fr)_420px]">
|
||||||
|
<div>
|
||||||
|
<CheckoutAddressSelector />
|
||||||
|
</div>
|
||||||
|
<div className="lg:sticky lg:top-24 lg:self-start">
|
||||||
|
<PaymentAndOrderComponent
|
||||||
|
selectedAddress={selectedAddressId}
|
||||||
|
cartItems={selectedItems}
|
||||||
|
isFlashDelivery={false}
|
||||||
|
appliedCoupon={appliedCoupon}
|
||||||
|
couponId={selectedCouponId}
|
||||||
|
quotedDeliveryPrice={quoteDeliveryPrice}
|
||||||
|
onBack={() => navigate({ to: '/home/cart' })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,8 @@ import { useCentralSlotStore } from '../lib/stores/central-slot-store'
|
||||||
import { AppLayout } from '../components/AppLayout'
|
import { AppLayout } from '../components/AppLayout'
|
||||||
import { ProductCard } from '../components/ProductCard'
|
import { ProductCard } from '../components/ProductCard'
|
||||||
import AddToCartDialog from '../components/AddToCartDialog'
|
import AddToCartDialog from '../components/AddToCartDialog'
|
||||||
|
import { NextOrderGlimpse } from '../components/me/NextOrderGlimpse'
|
||||||
|
import { RegionBar } from '../components/RegionBar'
|
||||||
import { useProductSlotIdentifier } from '../hooks/useProductSlotIdentifier'
|
import { useProductSlotIdentifier } from '../hooks/useProductSlotIdentifier'
|
||||||
import { usePopulateCentralStores } from '../hooks/usePopulateCentralStores'
|
import { usePopulateCentralStores } from '../hooks/usePopulateCentralStores'
|
||||||
import { Store, ImageOff, Loader2, Clock, Truck } from 'lucide-react'
|
import { Store, ImageOff, Loader2, Clock, Truck } from 'lucide-react'
|
||||||
|
|
@ -97,6 +99,14 @@ function HomePage() {
|
||||||
// Refs for scrollable sections
|
// Refs for scrollable sections
|
||||||
const slotsScrollRef = useRef<HTMLDivElement>(null)
|
const slotsScrollRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
|
// Region bar collapse offset (matches native scrollY behavior)
|
||||||
|
const [scrollTop, setScrollTop] = useState(0)
|
||||||
|
useEffect(() => {
|
||||||
|
const onScroll = () => setScrollTop(window.scrollY)
|
||||||
|
window.addEventListener('scroll', onScroll, { passive: true })
|
||||||
|
return () => window.removeEventListener('scroll', onScroll)
|
||||||
|
}, [])
|
||||||
|
|
||||||
// Populate central stores with slots and product data
|
// Populate central stores with slots and product data
|
||||||
usePopulateCentralStores()
|
usePopulateCentralStores()
|
||||||
|
|
||||||
|
|
@ -104,6 +114,8 @@ function HomePage() {
|
||||||
// const banners = bannersData?.banners || []
|
// const banners = bannersData?.banners || []
|
||||||
const allProducts = productsData?.products || []
|
const allProducts = productsData?.products || []
|
||||||
const slots = slotsData?.slots || []
|
const slots = slotsData?.slots || []
|
||||||
|
// Until slots load, missing slot data must not mark products out of stock (matches user-ui).
|
||||||
|
const slotsReady = !isSlotsLoading
|
||||||
|
|
||||||
// Explore Products tabs — tags in tagsOrder, products in per-tag sortOrder
|
// Explore Products tabs — tags in tagsOrder, products in per-tag sortOrder
|
||||||
const dashboardTags = productsData?.tags || []
|
const dashboardTags = productsData?.tags || []
|
||||||
|
|
@ -143,7 +155,7 @@ function HomePage() {
|
||||||
const rest: any[] = []
|
const rest: any[] = []
|
||||||
for (const id of orderedIds) {
|
for (const id of orderedIds) {
|
||||||
const product = productById.get(id)
|
const product = productById.get(id)
|
||||||
const isOutOfStock = Boolean(productSlotsMap[id]?.isOutOfStock) || !getQuickestSlot(id)
|
const isOutOfStock = Boolean(productSlotsMap[id]?.isOutOfStock) || (slotsReady && !getQuickestSlot(id))
|
||||||
if (isOutOfStock) rest.push(product)
|
if (isOutOfStock) rest.push(product)
|
||||||
else ordered.push(product)
|
else ordered.push(product)
|
||||||
}
|
}
|
||||||
|
|
@ -155,8 +167,8 @@ function HomePage() {
|
||||||
.sort((a: any, b: any) => {
|
.sort((a: any, b: any) => {
|
||||||
const slotA = getQuickestSlot(a.id)
|
const slotA = getQuickestSlot(a.id)
|
||||||
const slotB = getQuickestSlot(b.id)
|
const slotB = getQuickestSlot(b.id)
|
||||||
const aOutOfStock = Boolean(productSlotsMap[a.id]?.isOutOfStock) || !slotA
|
const aOutOfStock = Boolean(productSlotsMap[a.id]?.isOutOfStock) || (slotsReady && !slotA)
|
||||||
const bOutOfStock = Boolean(productSlotsMap[b.id]?.isOutOfStock) || !slotB
|
const bOutOfStock = Boolean(productSlotsMap[b.id]?.isOutOfStock) || (slotsReady && !slotB)
|
||||||
if (aOutOfStock && !bOutOfStock) return 1
|
if (aOutOfStock && !bOutOfStock) return 1
|
||||||
if (!aOutOfStock && bOutOfStock) return -1
|
if (!aOutOfStock && bOutOfStock) return -1
|
||||||
return 0
|
return 0
|
||||||
|
|
@ -165,7 +177,7 @@ function HomePage() {
|
||||||
map[tag.id] = [...ordered, ...rest, ...extra]
|
map[tag.id] = [...ordered, ...rest, ...extra]
|
||||||
}
|
}
|
||||||
return map
|
return map
|
||||||
}, [dashboardTags, allProducts, getQuickestSlot, productSlotsMap])
|
}, [dashboardTags, allProducts, getQuickestSlot, productSlotsMap, slotsReady])
|
||||||
|
|
||||||
const activeTagProducts = activeTagId != null ? (productsByTagId[activeTagId] || []) : []
|
const activeTagProducts = activeTagId != null ? (productsByTagId[activeTagId] || []) : []
|
||||||
|
|
||||||
|
|
@ -177,14 +189,14 @@ function HomePage() {
|
||||||
const slotA = getQuickestSlot(a.id)
|
const slotA = getQuickestSlot(a.id)
|
||||||
const slotB = getQuickestSlot(b.id)
|
const slotB = getQuickestSlot(b.id)
|
||||||
|
|
||||||
const aOutOfStock = Boolean(productSlotsMap[a.id]?.isOutOfStock) || !slotA
|
const aOutOfStock = Boolean(productSlotsMap[a.id]?.isOutOfStock) || (slotsReady && !slotA)
|
||||||
const bOutOfStock = Boolean(productSlotsMap[b.id]?.isOutOfStock) || !slotB
|
const bOutOfStock = Boolean(productSlotsMap[b.id]?.isOutOfStock) || (slotsReady && !slotB)
|
||||||
|
|
||||||
if (aOutOfStock && !bOutOfStock) return 1
|
if (aOutOfStock && !bOutOfStock) return 1
|
||||||
if (!aOutOfStock && bOutOfStock) return -1
|
if (!aOutOfStock && bOutOfStock) return -1
|
||||||
return 0
|
return 0
|
||||||
})
|
})
|
||||||
}, [productsData, productSlotsMap])
|
}, [productsData, productSlotsMap, getQuickestSlot, slotsReady])
|
||||||
|
|
||||||
// Load-more model for All Products (matches user-ui: 21 at a time)
|
// Load-more model for All Products (matches user-ui: 21 at a time)
|
||||||
const [visibleCount, setVisibleCount] = useState(21)
|
const [visibleCount, setVisibleCount] = useState(21)
|
||||||
|
|
@ -203,11 +215,11 @@ function HomePage() {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sort slots by delivery time
|
// Sort slots by delivery time — drop anything past freeze (matches user-ui)
|
||||||
const sortedSlots = useMemo(() => {
|
const sortedSlots = useMemo(() => {
|
||||||
const now = dayjs()
|
const now = dayjs()
|
||||||
return [...slots]
|
return [...slots]
|
||||||
.filter((slot) => dayjs(slot.deliveryTime).isAfter(now))
|
.filter((slot) => dayjs(slot.deliveryTime).isAfter(now) && dayjs(slot.freezeTime).isAfter(now))
|
||||||
.sort((a, b) => {
|
.sort((a, b) => {
|
||||||
const deliveryDiff = dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime))
|
const deliveryDiff = dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime))
|
||||||
if (deliveryDiff !== 0) return deliveryDiff
|
if (deliveryDiff !== 0) return deliveryDiff
|
||||||
|
|
@ -271,6 +283,13 @@ function HomePage() {
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Upcoming order glimpse (matches user-ui home ListHeader) */}
|
||||||
|
<div className="mb-8">
|
||||||
|
<NextOrderGlimpse />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<RegionBar scrollTop={scrollTop} />
|
||||||
|
|
||||||
{/* Explore Products Section — first, matching user-ui home order */}
|
{/* Explore Products Section — first, matching user-ui home order */}
|
||||||
{dashboardTags.length > 0 && (
|
{dashboardTags.length > 0 && (
|
||||||
<section className="mb-10">
|
<section className="mb-10">
|
||||||
|
|
@ -293,6 +312,7 @@ function HomePage() {
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={tag.id}
|
key={tag.id}
|
||||||
|
data-testid={`tag-tab-${tag.id}`}
|
||||||
ref={(el) => {
|
ref={(el) => {
|
||||||
tabPositions.current[i] = el?.offsetLeft ?? 0
|
tabPositions.current[i] = el?.offsetLeft ?? 0
|
||||||
}}
|
}}
|
||||||
|
|
@ -317,26 +337,28 @@ function HomePage() {
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Active tag products — brand-tinted container (matches user-ui) */}
|
{/* Active tag products — brand-tinted container (matches user-ui) */}
|
||||||
<div className="mb-2 rounded-[28px] border border-brand-100 bg-brand-25 px-3 pb-4 pt-3">
|
<div className="mb-2 rounded-[28px] border border-brand-100 bg-brand-25 px-3 pb-4 pt-3" data-testid={`tag-grid-${activeTagId}`}>
|
||||||
{activeTagProducts.length > 0 ? (
|
{activeTagProducts.length > 0 ? (
|
||||||
<>
|
<>
|
||||||
<div className="grid grid-cols-3 gap-3 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
|
<div className="grid grid-cols-3 gap-3 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
|
||||||
{activeTagProducts
|
{activeTagProducts
|
||||||
.slice(0, expandedByTagId[activeTagId] ? undefined : 6)
|
.slice(0, expandedByTagId[activeTagId] ? undefined : 6)
|
||||||
.map((product: any) => (
|
.map((product: any) => (
|
||||||
|
<div key={product.id} data-testid={`tag-product-${product.id}`}>
|
||||||
<ProductCard
|
<ProductCard
|
||||||
key={product.id}
|
|
||||||
item={product}
|
item={product}
|
||||||
onPress={() => handleProductPress(product.id)}
|
onPress={() => handleProductPress(product.id)}
|
||||||
showDeliveryInfo={false}
|
showDeliveryInfo={false}
|
||||||
miniView={true}
|
miniView={true}
|
||||||
useAddToCartDialog={true}
|
useAddToCartDialog={true}
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
{activeTagProducts.length > 6 && !expandedByTagId[activeTagId] && (
|
{activeTagProducts.length > 6 && !expandedByTagId[activeTagId] && (
|
||||||
<div className="mt-4 flex justify-center">
|
<div className="mt-4 flex justify-center">
|
||||||
<button
|
<button
|
||||||
|
data-testid={`tag-show-more-${activeTagId}`}
|
||||||
onClick={() => handleToggleExpand(activeTagId)}
|
onClick={() => handleToggleExpand(activeTagId)}
|
||||||
className="rounded-full bg-brand-500 px-6 py-2.5 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-brand-600"
|
className="rounded-full bg-brand-500 px-6 py-2.5 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-brand-600"
|
||||||
>
|
>
|
||||||
|
|
@ -439,14 +461,15 @@ function HomePage() {
|
||||||
<>
|
<>
|
||||||
<div className="grid grid-cols-3 gap-3 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
|
<div className="grid grid-cols-3 gap-3 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
|
||||||
{sortedProducts.slice(0, visibleCount).map((product) => (
|
{sortedProducts.slice(0, visibleCount).map((product) => (
|
||||||
|
<div key={product.id} data-testid={`product-item-${product.id}`}>
|
||||||
<ProductCard
|
<ProductCard
|
||||||
key={product.id}
|
|
||||||
item={product}
|
item={product}
|
||||||
onPress={() => handleProductPress(product.id)}
|
onPress={() => handleProductPress(product.id)}
|
||||||
showDeliveryInfo={true}
|
showDeliveryInfo={true}
|
||||||
miniView={true}
|
miniView={true}
|
||||||
useAddToCartDialog={true}
|
useAddToCartDialog={true}
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
{hasMore && (
|
{hasMore && (
|
||||||
|
|
@ -573,6 +596,7 @@ function SlotCard({ slot }: { slot: any }) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
onClick={() => navigate({ to: '/slot-view', search: { slotId: slot.id } })}
|
onClick={() => navigate({ to: '/slot-view', search: { slotId: slot.id } })}
|
||||||
|
data-testid={`slot-card-${slot.id}`}
|
||||||
className={`min-w-70 shrink-0 cursor-pointer rounded-xl border bg-white p-5 shadow-sm transition-all hover:shadow-md ${
|
className={`min-w-70 shrink-0 cursor-pointer rounded-xl border bg-white p-5 shadow-sm transition-all hover:shadow-md ${
|
||||||
isClosingSoon ? 'border-l-4 border-l-amber-400' : 'border-l-4 border-l-brand-600'
|
isClosingSoon ? 'border-l-4 border-l-amber-400' : 'border-l-4 border-l-brand-600'
|
||||||
}`}
|
}`}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||||
import { CheckCircle2 } from 'lucide-react'
|
import { CheckCircle2 } from 'lucide-react'
|
||||||
|
import { NextOrderGlimpse } from '../components/me/NextOrderGlimpse'
|
||||||
|
|
||||||
export const Route = createFileRoute('/home/order-success')({
|
export const Route = createFileRoute('/home/order-success')({
|
||||||
component: OrderSuccessPage,
|
component: OrderSuccessPage,
|
||||||
|
|
@ -39,6 +40,10 @@ function OrderSuccessPage() {
|
||||||
>
|
>
|
||||||
View My Orders
|
View My Orders
|
||||||
</button>
|
</button>
|
||||||
|
{/* Upcoming-order glimpse (matches user-ui order-success flow) */}
|
||||||
|
<div className="mt-8 w-full max-w-md">
|
||||||
|
<NextOrderGlimpse />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -136,6 +136,7 @@ function SearchPage() {
|
||||||
value={inputQuery}
|
value={inputQuery}
|
||||||
onChange={setInputQuery}
|
onChange={setInputQuery}
|
||||||
onSearch={handleSearch}
|
onSearch={handleSearch}
|
||||||
|
testID="search-input"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -7,11 +7,50 @@ import { useGetEssentialConsts } from '../hooks/prominent-api-hooks'
|
||||||
import { MyButton, pInput as PInput } from 'web-components'
|
import { MyButton, pInput as PInput } from 'web-components'
|
||||||
import type { LoginFormInputs } from '@packages/shared'
|
import type { LoginFormInputs } from '@packages/shared'
|
||||||
|
|
||||||
export const Route = createFileRoute('/login')({ component: LoginPage })
|
export const Route = createFileRoute('/login')({
|
||||||
|
component: LoginPage,
|
||||||
|
validateSearch: (search: Record<string, unknown>): { redirect?: string } => ({
|
||||||
|
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
const AUTH_REDIRECT_TTL_MS = 15 * 60 * 1000
|
||||||
|
|
||||||
|
function consumeRedirect(fallback?: string): { to: string; search?: Record<string, string> } {
|
||||||
|
try {
|
||||||
|
const raw = sessionStorage.getItem('auth_redirect')
|
||||||
|
if (raw) {
|
||||||
|
sessionStorage.removeItem('auth_redirect')
|
||||||
|
const { target, at } = JSON.parse(raw)
|
||||||
|
if (typeof target === 'string' && target.startsWith('/') && Date.now() - at < AUTH_REDIRECT_TTL_MS) {
|
||||||
|
const url = new URL(target, window.location.origin)
|
||||||
|
const search = Object.fromEntries(url.searchParams.entries())
|
||||||
|
return { to: url.pathname, search: Object.keys(search).length > 0 ? search : undefined }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// fall through to fallback
|
||||||
|
}
|
||||||
|
if (fallback && fallback.startsWith('/')) {
|
||||||
|
try {
|
||||||
|
const url = new URL(fallback, window.location.origin)
|
||||||
|
const search = Object.fromEntries(url.searchParams.entries())
|
||||||
|
return { to: url.pathname, search: Object.keys(search).length > 0 ? search : undefined }
|
||||||
|
} catch {
|
||||||
|
// fall through
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { to: '/home' }
|
||||||
|
}
|
||||||
|
|
||||||
function LoginPage() {
|
function LoginPage() {
|
||||||
const { loginWithToken } = useAuth()
|
const { loginWithToken } = useAuth()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { redirect } = Route.useSearch()
|
||||||
|
const navigateAfterLogin = () => {
|
||||||
|
const dest = consumeRedirect(redirect)
|
||||||
|
navigate(dest as any)
|
||||||
|
}
|
||||||
const { data: constsData } = useGetEssentialConsts()
|
const { data: constsData } = useGetEssentialConsts()
|
||||||
const [step, setStep] = useState<'mobile' | 'choice' | 'otp' | 'password'>('mobile')
|
const [step, setStep] = useState<'mobile' | 'choice' | 'otp' | 'password'>('mobile')
|
||||||
const [selectedMobile, setSelectedMobile] = useState('')
|
const [selectedMobile, setSelectedMobile] = useState('')
|
||||||
|
|
@ -35,7 +74,7 @@ function LoginPage() {
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
if (data.success && data.token && data.user) {
|
if (data.success && data.token && data.user) {
|
||||||
loginWithToken(data.token, data.user)
|
loginWithToken(data.token, data.user)
|
||||||
navigate({ to: '/home' })
|
navigateAfterLogin()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
@ -113,7 +152,7 @@ function LoginPage() {
|
||||||
{
|
{
|
||||||
onSuccess: (res) => {
|
onSuccess: (res) => {
|
||||||
loginWithToken(res.data.token, res.data.user)
|
loginWithToken(res.data.token, res.data.user)
|
||||||
navigate({ to: '/home' })
|
navigateAfterLogin()
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
@ -195,6 +234,7 @@ function LoginPage() {
|
||||||
if (clean.length <= 10) onChange(clean)
|
if (clean.length <= 10) onChange(clean)
|
||||||
}}
|
}}
|
||||||
className="bg-gray-50"
|
className="bg-gray-50"
|
||||||
|
data-testid="user-login-mobile"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
@ -209,6 +249,7 @@ function LoginPage() {
|
||||||
{[0, 1, 2, 3].map((i) => (
|
{[0, 1, 2, 3].map((i) => (
|
||||||
<input
|
<input
|
||||||
key={i}
|
key={i}
|
||||||
|
data-testid={`user-login-otp-${i}`}
|
||||||
ref={(el) => { inputRefs.current[i] = el }}
|
ref={(el) => { inputRefs.current[i] = el }}
|
||||||
className="h-14 w-14 rounded-xl border-2 text-center text-2xl font-bold"
|
className="h-14 w-14 rounded-xl border-2 text-center text-2xl font-bold"
|
||||||
style={{
|
style={{
|
||||||
|
|
@ -254,6 +295,7 @@ function LoginPage() {
|
||||||
onChange={(e) => onChange(e.target.value)}
|
onChange={(e) => onChange(e.target.value)}
|
||||||
type="password"
|
type="password"
|
||||||
className="bg-gray-50"
|
className="bg-gray-50"
|
||||||
|
data-testid="user-login-password"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
@ -263,6 +305,7 @@ function LoginPage() {
|
||||||
<MyButton
|
<MyButton
|
||||||
type="submit"
|
type="submit"
|
||||||
fullWidth
|
fullWidth
|
||||||
|
data-testid="user-login-submit"
|
||||||
className="h-12 rounded-lg bg-brand-600 text-white shadow-md transition-colors hover:bg-brand-700"
|
className="h-12 rounded-lg bg-brand-600 text-white shadow-md transition-colors hover:bg-brand-700"
|
||||||
disabled={
|
disabled={
|
||||||
sendOtpMutation.isPending ||
|
sendOtpMutation.isPending ||
|
||||||
|
|
@ -282,6 +325,7 @@ function LoginPage() {
|
||||||
|
|
||||||
{step === 'otp' && (
|
{step === 'otp' && (
|
||||||
<div
|
<div
|
||||||
|
data-testid="user-login-other-ways"
|
||||||
onClick={() => { setStep('password'); setOtpCells(['', '', '', '']) }}
|
onClick={() => { setStep('password'); setOtpCells(['', '', '', '']) }}
|
||||||
className="mt-4 block text-center"
|
className="mt-4 block text-center"
|
||||||
>
|
>
|
||||||
|
|
|
||||||
|
|
@ -45,12 +45,14 @@ function RegisterPage() {
|
||||||
value={name}
|
value={name}
|
||||||
onChange={(e) => setName(e.target.value)}
|
onChange={(e) => setName(e.target.value)}
|
||||||
required
|
required
|
||||||
|
data-testid="user-register-name"
|
||||||
/>
|
/>
|
||||||
<PInput
|
<PInput
|
||||||
placeholder="Email"
|
placeholder="Email"
|
||||||
type="email"
|
type="email"
|
||||||
value={email}
|
value={email}
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
data-testid="user-register-email"
|
||||||
/>
|
/>
|
||||||
<PInput
|
<PInput
|
||||||
placeholder="Mobile Number"
|
placeholder="Mobile Number"
|
||||||
|
|
@ -60,6 +62,7 @@ function RegisterPage() {
|
||||||
if (clean.length <= 10) setMobile(clean)
|
if (clean.length <= 10) setMobile(clean)
|
||||||
}}
|
}}
|
||||||
required
|
required
|
||||||
|
data-testid="user-register-mobile"
|
||||||
/>
|
/>
|
||||||
<PInput
|
<PInput
|
||||||
placeholder="Password"
|
placeholder="Password"
|
||||||
|
|
@ -67,6 +70,7 @@ function RegisterPage() {
|
||||||
value={password}
|
value={password}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
required
|
required
|
||||||
|
data-testid="user-register-password"
|
||||||
/>
|
/>
|
||||||
<MyButton
|
<MyButton
|
||||||
type="submit"
|
type="submit"
|
||||||
|
|
@ -74,6 +78,7 @@ function RegisterPage() {
|
||||||
className="mt-2 h-12 rounded-xl bg-brand-600 text-white shadow-lg"
|
className="mt-2 h-12 rounded-xl bg-brand-600 text-white shadow-lg"
|
||||||
disabled={registerMutation.isPending}
|
disabled={registerMutation.isPending}
|
||||||
textContent={registerMutation.isPending ? 'Creating...' : 'Register'}
|
textContent={registerMutation.isPending ? 'Creating...' : 'Register'}
|
||||||
|
data-testid="user-register-submit"
|
||||||
/>
|
/>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -26,8 +26,8 @@ import {
|
||||||
} from "../hooks/cart-query-hooks";
|
} from "../hooks/cart-query-hooks";
|
||||||
import { usePopulateCentralProductStore } from "../hooks/usePopulateCentralProductStore";
|
import { usePopulateCentralProductStore } from "../hooks/usePopulateCentralProductStore";
|
||||||
import { AppLayout } from "../components/AppLayout";
|
import { AppLayout } from "../components/AppLayout";
|
||||||
import { Truck, Store, Grid3X3, ChevronLeft, ShoppingCart, Clock, ChevronDown } from "lucide-react";
|
import { Truck, Store, Grid3X3, ShoppingCart, Clock } from "lucide-react";
|
||||||
import { Dialog } from "../components/Dialog";
|
import { QuickDeliveryAddressSelector } from "../components/QuickDeliveryAddressSelector";
|
||||||
import type { CompactProductCardProps } from '@packages/shared';
|
import type { CompactProductCardProps } from '@packages/shared';
|
||||||
|
|
||||||
export const Route = createFileRoute("/slot-view")({
|
export const Route = createFileRoute("/slot-view")({
|
||||||
|
|
@ -47,7 +47,6 @@ function SlotViewPage() {
|
||||||
const { productsById } = useCentralProductStore();
|
const { productsById } = useCentralProductStore();
|
||||||
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
||||||
const { data: storesData } = useStores();
|
const { data: storesData } = useStores();
|
||||||
const [showSlotDialog, setShowSlotDialog] = useState(false);
|
|
||||||
|
|
||||||
// Populate central product store with products data
|
// Populate central product store with products data
|
||||||
usePopulateCentralProductStore();
|
usePopulateCentralProductStore();
|
||||||
|
|
@ -57,55 +56,9 @@ function SlotViewPage() {
|
||||||
// Find the specific slot from cached data
|
// Find the specific slot from cached data
|
||||||
const slot = slotsData?.slots?.find((s: any) => s.id === slotId);
|
const slot = slotsData?.slots?.find((s: any) => s.id === slotId);
|
||||||
|
|
||||||
// Find earliest slot for pre-selection
|
|
||||||
const earliestSlot = slotsData?.slots
|
|
||||||
?.filter((s: any) => dayjs(s.deliveryTime).isAfter(dayjs()))
|
|
||||||
.sort((a: any, b: any) => dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)))[0];
|
|
||||||
|
|
||||||
const addToCart = useAddToCart("regular");
|
const addToCart = useAddToCart("regular");
|
||||||
const { data: cartData } = useGetCart("regular");
|
const { data: cartData } = useGetCart("regular");
|
||||||
|
|
||||||
const formatTimeRange = (deliveryTime: string) => {
|
|
||||||
const time = dayjs(deliveryTime);
|
|
||||||
const endTime = time.add(1, "hour");
|
|
||||||
const startPeriod = time.format("A");
|
|
||||||
const endPeriod = endTime.format("A");
|
|
||||||
|
|
||||||
if (startPeriod === endPeriod) {
|
|
||||||
return `${time.format("h")}-${endTime.format("h")} ${startPeriod}`;
|
|
||||||
} else {
|
|
||||||
return `${time.format("h:mm")} ${startPeriod} - ${endTime.format("h:mm")} ${endPeriod}`;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatFullDisplay = (deliveryTime: string) => {
|
|
||||||
const time = dayjs(deliveryTime);
|
|
||||||
const endTime = time.add(1, "hour");
|
|
||||||
const startPeriod = time.format("A");
|
|
||||||
const endPeriod = endTime.format("A");
|
|
||||||
|
|
||||||
let timeRange;
|
|
||||||
if (startPeriod === endPeriod) {
|
|
||||||
timeRange = `${time.format("h")}-${endTime.format("h")} ${startPeriod}`;
|
|
||||||
} else {
|
|
||||||
timeRange = `${time.format("h:mm")} ${startPeriod} - ${endTime.format("h:mm")} ${endPeriod}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return `${time.format("ddd, DD MMM ")}${timeRange}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Get current selected slot display
|
|
||||||
const getCurrentSlotDisplay = () => {
|
|
||||||
if (slotId) {
|
|
||||||
const s = slotsData?.slots?.find((s: any) => s.id === slotId);
|
|
||||||
return s ? formatFullDisplay(s.deliveryTime as any) : 'Select time';
|
|
||||||
}
|
|
||||||
if (earliestSlot) {
|
|
||||||
return formatFullDisplay(earliestSlot.deliveryTime as any);
|
|
||||||
}
|
|
||||||
return 'Select time';
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleAddToCart = (productId: number) => {
|
const handleAddToCart = (productId: number) => {
|
||||||
const item = filteredProducts.find((p) => p.id === productId);
|
const item = filteredProducts.find((p) => p.id === productId);
|
||||||
const deliveryTime = slot?.deliveryTime
|
const deliveryTime = slot?.deliveryTime
|
||||||
|
|
@ -123,14 +76,6 @@ function SlotViewPage() {
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSlotChange = (newSlotId: number) => {
|
|
||||||
navigate({
|
|
||||||
to: "/slot-view",
|
|
||||||
search: { slotId: newSlotId, storeId },
|
|
||||||
});
|
|
||||||
setShowSlotDialog(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Get product details from central store using slot product IDs
|
// Get product details from central store using slot product IDs
|
||||||
const slotProducts =
|
const slotProducts =
|
||||||
slot?.products
|
slot?.products
|
||||||
|
|
@ -146,16 +91,6 @@ function SlotViewPage() {
|
||||||
? slotProducts.filter((p: any) => p.storeId === storeId)
|
? slotProducts.filter((p: any) => p.storeId === storeId)
|
||||||
: slotProducts;
|
: slotProducts;
|
||||||
|
|
||||||
// Transform slots for display
|
|
||||||
const slotOptions = slotsData?.slots
|
|
||||||
?.filter((s: any) => dayjs(s.deliveryTime).isAfter(dayjs()))
|
|
||||||
.sort((a: any, b: any) => dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)))
|
|
||||||
.map((s: any) => ({
|
|
||||||
id: s.id,
|
|
||||||
deliveryTime: formatFullDisplay(s.deliveryTime),
|
|
||||||
closeTime: dayjs(s.freezeTime).format("h:mm A"),
|
|
||||||
})) || [];
|
|
||||||
|
|
||||||
if (!slot) {
|
if (!slot) {
|
||||||
return (
|
return (
|
||||||
<AppLayout>
|
<AppLayout>
|
||||||
|
|
@ -175,28 +110,16 @@ function SlotViewPage() {
|
||||||
{/* Header with Dropdown - Matching Mobile App */}
|
{/* Header with Dropdown - Matching Mobile App */}
|
||||||
<div className="sticky top-0 z-20 border-b border-gray-200 bg-white px-4 py-3">
|
<div className="sticky top-0 z-20 border-b border-gray-200 bg-white px-4 py-3">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{/* Back Button */}
|
|
||||||
<button
|
|
||||||
onClick={() => navigate({ to: "/home" })}
|
|
||||||
className="p-1 hover:bg-gray-100 rounded-full"
|
|
||||||
>
|
|
||||||
<ChevronLeft className="h-6 w-6 text-gray-700" />
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{/* Delivery Time Dropdown */}
|
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
<button
|
<QuickDeliveryAddressSelector
|
||||||
onClick={() => setShowSlotDialog(true)}
|
slotId={slotId}
|
||||||
className="flex w-full items-center justify-between rounded-lg border border-brand-200 bg-brand-50 px-3 py-2"
|
onSlotChange={(newSlotId) =>
|
||||||
>
|
navigate({
|
||||||
<div className="flex-1 text-left">
|
to: '/slot-view',
|
||||||
<p className="text-xs font-bold uppercase text-brand-500">Delivery Time</p>
|
search: { slotId: newSlotId, storeId },
|
||||||
<p className="text-sm font-bold text-brand-900">
|
})
|
||||||
{getCurrentSlotDisplay()}
|
}
|
||||||
</p>
|
/>
|
||||||
</div>
|
|
||||||
<ChevronDown className="h-5 w-5 text-brand-500" />
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -262,32 +185,9 @@ function SlotViewPage() {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Slot Selection Dialog */}
|
|
||||||
<Dialog open={showSlotDialog} onClose={() => setShowSlotDialog(false)} title="Select Delivery Time">
|
|
||||||
<div className="max-h-[60vh] overflow-y-auto p-4">
|
|
||||||
{slotOptions.map((slotOption) => (
|
|
||||||
<button
|
|
||||||
key={slotOption.id}
|
|
||||||
onClick={() => handleSlotChange(slotOption.id)}
|
|
||||||
className={`mb-2 w-full rounded-lg border p-3 text-left transition-colors ${
|
|
||||||
slotOption.id === (slotId || earliestSlot?.id)
|
|
||||||
? 'border-brand-500 bg-brand-50'
|
|
||||||
: 'border-gray-200 bg-white hover:bg-gray-50'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<p className="font-medium text-gray-900">
|
|
||||||
Delivery: {slotOption.deliveryTime}
|
|
||||||
</p>
|
|
||||||
<p className="mt-1 text-xs text-gray-500">
|
|
||||||
Orders Close at: {slotOption.closeTime}
|
|
||||||
</p>
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
</div>
|
||||||
</AppLayout>
|
</AppLayout>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
interface StoreSidebarProps {
|
interface StoreSidebarProps {
|
||||||
|
|
|
||||||
|
|
@ -668,3 +668,92 @@ Left untouched: 4 stale DROPs still in script but absent from schema (address_ar
|
||||||
[2026-10-05T19:39+05:30] drizzle/0007_region_scoping.sql step 4 rewritten: DROP TABLE product_info fails on D1 (dashboard AND cli) with FK constraint — D1 enforces FKs and neuters defer_foreign_keys/foreign_keys=OFF pragmas, so the create-copy-drop-rename pattern dies at DROP while product_skus/product_reviews hold rows. Verified in-memory: DROP TABLE parent fails (exit 19), DROP COLUMN on FK-child col succeeds, ADD..REFERENCES..NOT NULL DEFAULT rejected, no ALTER COLUMN in SQLite. New approach (user-designed, extended one level): rebuild the full 13-table FK subgraph with NOT NULL preserved — __new_product_info, __new_product_skus, __new_product_reviews, 9 sku-children, plus coupon_usage (found via schema.ts audit: coupon_usage.order_item_id refs order_items, so order_items is not a leaf). Leaves drop freely; mids drop once unreferenced; renames auto-rewrite child FK clauses (verified). Two deviations from drizzle-kit rendering, both required: rating_check CHECK written unqualified (RENAME does not rewrite CHECK exprs — qualified name would dangle), __new_ FKs point at __new_ names (rewritten to final on rename). Index creation moved after renames (names freed by drops). Old step 5 (market_stats unique swap) removed — subsumed by the rebuild. PRE-FLIGHT REQUIRED on live target before apply: SELECT type,name FROM sqlite_master WHERE (sql LIKE '%product_skus%' OR sql LIKE '%product_info%') AND name NOT LIKE 'sqlite_%' must show only known tables+indexes (no legacy/views/triggers).
|
[2026-10-05T19:39+05:30] drizzle/0007_region_scoping.sql step 4 rewritten: DROP TABLE product_info fails on D1 (dashboard AND cli) with FK constraint — D1 enforces FKs and neuters defer_foreign_keys/foreign_keys=OFF pragmas, so the create-copy-drop-rename pattern dies at DROP while product_skus/product_reviews hold rows. Verified in-memory: DROP TABLE parent fails (exit 19), DROP COLUMN on FK-child col succeeds, ADD..REFERENCES..NOT NULL DEFAULT rejected, no ALTER COLUMN in SQLite. New approach (user-designed, extended one level): rebuild the full 13-table FK subgraph with NOT NULL preserved — __new_product_info, __new_product_skus, __new_product_reviews, 9 sku-children, plus coupon_usage (found via schema.ts audit: coupon_usage.order_item_id refs order_items, so order_items is not a leaf). Leaves drop freely; mids drop once unreferenced; renames auto-rewrite child FK clauses (verified). Two deviations from drizzle-kit rendering, both required: rating_check CHECK written unqualified (RENAME does not rewrite CHECK exprs — qualified name would dangle), __new_ FKs point at __new_ names (rewritten to final on rename). Index creation moved after renames (names freed by drops). Old step 5 (market_stats unique swap) removed — subsumed by the rebuild. PRE-FLIGHT REQUIRED on live target before apply: SELECT type,name FROM sqlite_master WHERE (sql LIKE '%product_skus%' OR sql LIKE '%product_info%') AND name NOT LIKE 'sqlite_%' must show only known tables+indexes (no legacy/views/triggers).
|
||||||
|
|
||||||
[2026-10-05T19:52+05:30] docs/recreate-referenced-table.md: new doc capturing the D1 FK-rebuild pattern (why DROP dies on D1, leaves-first subgraph rebuild, pre-flight query, CHECK/index/rename pitfalls, proof harness). Written for reuse the next time a referenced table must be re-created.
|
[2026-10-05T19:52+05:30] docs/recreate-referenced-table.md: new doc capturing the D1 FK-rebuild pattern (why DROP dies on D1, leaves-first subgraph rebuild, pre-flight query, CHECK/index/rename pitfalls, proof harness). Written for reuse the next time a referenced table must be re-created.
|
||||||
|
|
||||||
|
[2026-10-05T20:05+05:30] Phase A1 web parity: testID support in select primitives, mirroring native BottomDropdown convention ({testID}, {testID}-search, {testID}-option-{value}, {testID}-done). web-components Dropdown gains testID prop (wrapper data-testid + per-option IDs); SearchBar gains testID + autoCorrect/autoCapitalize passthrough (defaults off/none, as native); admin-web SearchableSelect/MultiSelect thread {testID}-search/option/done IDs (replacing generic multiselect-option).
|
||||||
|
|
||||||
|
[2026-10-05T20:18+05:30] Phase A2 web parity: admin-web customize-app hub gains bound scoping identical to admin-ui (getMyRegionBounds + activeBoundId/boundsReady, enabled-gated getConstants({boundId}), updateConstants({boundId}), const-bound-tabs/tab-{id} testIDs, Formik key remount). CONST_LABELS/VISIBILITY aligned to native canonical set (adds internalAppVersion label; platformFeePercent/minOrderAmountForCoupon/flashDeliverySlotId/versionNum/playStoreUrl/appStoreUrl/popularItems hidden as on native). popular/ordering sub-screens left unscoped on both apps (native navigates without bound param).
|
||||||
|
|
||||||
|
[2026-10-05T20:27+05:30] Phase A3 web parity: data-testid hooks mirroring native testIDs — StoreForm (store-name-input/description-input/owner-dropdown/products-selector/submit-button), TagForm (7 IDs), ProductForm (native names incl. -dropdown/create-product-button renames), SlotForm snippet selector, const-bound-style tabs n/a; OrderOptionsMenu welcome row (welcomeMessage + isFirstOrder send-welcome-msg); BannerForm autoCapitalize/autoCorrect; add-product-button + edit-slot-fab IDs on index/detail routes.
|
||||||
|
|
||||||
|
[2026-10-05T20:45+05:30] Phase B web parity (web-ui): data-testid hooks mirroring native (tag-tab-/tag-grid-/tag-show-more-/tag-product-/slot-card-/search-input, ProductCard variant+badges, address-option-, select-address-error/place-order-button, login/register IDs); behavior fixes — freezeTime slot filtering (home sortedSlots + AddToCartDialog), slots-load guard on product sort, NextOrderGlimpse on home, logout clears query cache, ProtectedRoute preserves query params + covers /home/checkout.
|
||||||
|
|
||||||
|
[2026-10-05T21:10+05:30] Phase C1 web parity: RegionContext port (localStorage-backed active_region, getRegions ghost validation, useRegion/useRegionParams) + wire into __root above AuthProvider; prominent-api-hooks useGetEssentialConsts scoped to {regionId,boundId} with cachePathPrefix + build*CacheUrl helpers.
|
||||||
|
|
||||||
|
[2026-10-05T21:28+05:30] Phase C2 web parity: RegionGate port (browser geolocation + visibilitychange re-check, resolveRegionForLocation auto-pass, region-gate-*/region-pick-* testIDs, stored-region continue) mounted in AppLayout; RegionBar port (region-bar testID, collapsible) placed on home above Explore Products.
|
||||||
|
|
||||||
|
[2026-10-05T22:10+05:30] Phase D web parity start: cart/checkout depth (slot grouping + per-item pickers, cart address section, slot-grouped checkout URLs, coupon/threshold logic, QuickDeliveryAddressSelector, order-success glimpse).
|
||||||
|
|
||||||
|
[2026-10-05T22:40+05:30] RegionGate infinite-loading fix (user-ui + web-ui): full-screen spinner reflashed on every re-detection because render had no settled memory. Gate now tracks settledRef (first detection completion) — background re-runs keep the current blocked/picker screen instead of flashing loading; flags only reset on the initial run. AppState/visibility-triggered re-runs gain a 15s cooldown; settings-return bypasses it via expectReturnRef so the grant-permission flow still re-checks immediately.
|
||||||
|
|
||||||
|
[2026-10-06T00:01+05:30] superadmin scope work: new superadmins table (id autoincrement PK, name UNIQUE NOT NULL, password NOT NULL, created_at; no region_id/role — global by definition) in db_helper_sqlite + db_helper_postgres schemas; drizzle migration 0008 (CREATE TABLE only); backend ctx.superadmin ({superadminId} JWT claim) + superadminProcedure + src/trpc/apis/superadmin-apis/ (auth.login + thin wrappers for the 9 other procedures superadmin-ui uses, unscoped) merged as superadmin router; superadmin-ui client switched admin.* -> superadmin.*. admin.* untouched. Bootstrap: manual SQL INSERT with bcryptjs hash (cost 10).
|
||||||
|
|
||||||
|
[2026-10-06T00:20+05:30] all-region stores work: E2E audit — full-suite gen_flows.py product_flow asserts product-all-regions-checkbox visible+unchecked (E2E admin role is 'admin', so hiding the checkbox requires dropping those generator steps; gen/*.yaml regenerate per run.sh so only the generator changes). regions/admin-product-search.yaml only needs an all-regions product to EXIST (no checkbox interaction — safe). Plan: hide flag in admin-ui/admin-web ProductForm for all roles, gen_flows.py steps removed, admin.product 403 on flag=true (superadmin scope only).
|
||||||
|
|
||||||
|
[2026-10-06T00:35+05:30] all-region stores Phase 1+2: proof_0009 passes; schema storeInfo regionId nullable + availableInAllRegions; migration 0009 (2-table rebuild, verified verbatim, 9 statements); shared CreateStoreInput/UpdateStoreInput gain availableInAllRegions?; read-path OR-flag: getAllStores scoped branch, getAllStoresForCache, getStoreSummaries, getStoreDetail; createStore/updateStore accept nullable region + flag, market-stats product assignment spans all regions for regionless stores.
|
||||||
|
|
||||||
|
[2026-10-06T01:10+05:30] all-region stores Phase 3-5: superadmin.store/product/staffUser.getStaff/upload procs (product create requires creator regionId; update/delete/toggle mirrored; getAllSkusSummary unscoped); admin.store/admin.product 403 on all-regions flag create/flip/delete (superadmin scope only); per-region ops (OOS/suspend/prices) untouched. superadmin-ui stores+products sections (list/new/edit, AppShell nav, copied+adapted StoreForm/ProductForm/ProductsSelector/MultiSelect/SearchableSelect/upload hook; routeTree regenerated via vite dev). Admin-ui/admin-web ProductForm flag hidden for all roles (all-region edits read-only banner + disabled save); gen_flows.py checkbox steps removed (gen YAMLs regenerate per run.sh). tsc clean: backend, superadmin-ui, admin-web, admin-ui, web-ui. NOTE: postgres skipped per user.
|
||||||
|
[2026-10-05 23:58:50] Add scripts/delete-orders-before.sql (apps/backend/scripts).
|
||||||
|
|
||||||
|
New file apps/backend/scripts/delete-orders-before.sql:
|
||||||
|
- Deletes orders with created_at < a single editable cutoff (helper table
|
||||||
|
_old_orders holds {id, payment_info_id}; dropped at start and end so re-runs
|
||||||
|
are fresh), plus dependent rows child-first because D1 enforces FKs without
|
||||||
|
defer: coupon_usage (order_id OR order_item_id subselect), complaints,
|
||||||
|
user_incidents, payments, refunds, order_status, order_items, orders;
|
||||||
|
optional orphaned payment_info cleanup (step 5, kept on by default).
|
||||||
|
- Header documents date formats (ISO '2026-01-01' recommended; full
|
||||||
|
'T...Z' timestamp also accepted), run command, and backup warning.
|
||||||
|
|
||||||
|
[2026-10-06T01:30+05:30] superadmin-ui tabbed sections: products + stores lists gain Global-first tab strips (global = availableInAllRegions only; region tabs = that region's exclusive products/stores); regions via getRegions; *-tab-*/grid testIDs.
|
||||||
|
[2026-10-06 00:04:56] Spell out the ordered date components in delete-orders-before.sql header.
|
||||||
|
|
||||||
|
apps/backend/scripts/delete-orders-before.sql:
|
||||||
|
- DATE FORMAT comment now explains each placeholder position explicitly:
|
||||||
|
'YYYY(=2026)-MM(=01 month)-DD(=01 day)' with an example mapping
|
||||||
|
25 Mar 2024 -> '2024-03-25'.
|
||||||
|
|
||||||
|
[2026-10-06T01:45+05:30] superadmin-ui products edit: global-product price edits threw 'regionId is required' (db scopes writes to one creatorRegionId row; all-regions mode sends regionId null). Edit route now falls back to first region, matching create-route rule; other regions' rows untouched.
|
||||||
|
|
||||||
|
[2026-10-06T02:05+05:30] admin-ui ProductForm regional global-edit: removed create-global traces already; now regional staff CAN edit global products scoped to own region (banner reworded, per-region store UI collapsed to staff region only with name-match prefill, validation scoped to own region, save re-enabled). super_admin role keeps full per-region UI. Backend already scopes writes via writeRegion (no change). all-region stores included in region store lists.
|
||||||
|
|
||||||
|
[2026-10-06T02:20+05:30] admin-ui product edit fix: global-product save crashed zod (regionId null vs optional number). Route now sends regionId ?? undefined; backend writeRegion falls back to staffer region = desired regional scoping.
|
||||||
|
|
||||||
|
[2026-10-06T02:35+05:30] user-ui: console.log constructed cache URLs in buildProductsCacheUrl/buildAvailabilityCacheUrl/buildSlotsCacheUrl (single choke point for all callers).
|
||||||
|
|
||||||
|
[2026-10-06T01:05+05:30] cache URL segment swap fix: client built {region}{key}/v-... but writer/R2 use {key}/{region}v-... (proven live: writer path 200, client path 404; invisible on region 1 where prefix is empty). Fixed buildProductsCacheUrl + store-products URL in user-ui and web-ui builders; availability/slots were already correct.
|
||||||
|
|
||||||
|
[2026-10-06T02:00+05:30] superadmin product form restructure: RegionSkuStats type + db create/update per-region overlay + superadmin zod; form split into product-info section, stat-less variant cards, and region-tabbed pricing/availability with match-for-all (default checked on create).
|
||||||
|
|
||||||
|
[2026-10-06T09:30+05:30] neo-tests/e2e scaffold (new tests, tests/ untouched): Maestro MCP (stdio, device chromium) web flows for superadmin-ui region check. MBNR verified pre-existing via API (region 1 Mahabubnagar, bounds Mbnr-1 p1 + Mbnr-2 p2, coordinates match map-assets exactly) so UI flow is verify-only; create branch runs only if Mahabubnagar card missing.
|
||||||
|
|
||||||
|
neo-tests/e2e/mbnr-region-verify.yaml:
|
||||||
|
- url header http://localhost:4175/login + launchApp clearState, tapOn placeholder fields (Enter your name / Enter your password), inputText creds, tapOn Login, assert Regions, openLink /regions, assert Mahabubnagar.
|
||||||
|
|
||||||
|
neo-tests/e2e/mbnr-region-create.yaml:
|
||||||
|
- Same login, then /regions/new: name Mahabubnagar, description, 2 bounds (Mbnr-1 p1 / Mbnr-2 p2, compact Polygon geojson from map-assets), Add Bound for second, telegram cred from env TG_TOKEN/TG_CHAT, Create Region, assert Mahabubnagar card.
|
||||||
|
|
||||||
|
[2026-10-06T09:45+05:30] neo-tests/e2e: assertVisible timeout property rejected by Maestro 2.7.0 schema (Unknown Property: timeout); reverted to plain string asserts in both flows.
|
||||||
|
|
||||||
|
[2026-10-06T09:50+05:30] superadmin-ui admins: Create Admin becomes full admin management (list + new + edit + delete). Backend staff-user.ts gains updateStaffUserInfo (rename unique-checked, role, region, optional bcrypt-12 password reset) + deleteStaffUser (deletes staff_notif_creds; 409 blocks when staff owns stores / created coupons+reserved / filed incidents). Router: getStaff enriched with role+region names; new updateStaffUser/deleteStaffUser procs. UI: /admins list cards (name, role, region, Edit/Delete), /admins/new (moved form), /admins/$id/edit (prefill + optional new-password), nav renamed Admins, routeTree regen.
|
||||||
|
|
||||||
|
[2026-10-06T10:05+05:30] admins CRUD verified: local backend (wrangler dev, dev D1) getStaff returns roleId/roleName/regionName; create temp id 8, update rename+region+password, staff login with new password OK, delete qusham blocked 'they own 1 store...', temp deleted and gone. UI via Maestro MCP Chrome: list + edit prefill render (role/region names blank until backend deploy since devapi runs old code). Fixed double AppShell on /admins/new + /admins/$id/edit (parent layout already wraps; matches regions convention).
|
||||||
|
|
||||||
|
[2026-10-06T10:20+05:30] neo-tests/e2e/ensure-init-regions.yaml (new, Maestro flow per user): login via SUPERADMIN_NAME/PASSWORD env, guarded region blocks (Mahabubnagar Mbnr-1 p1 + Mbnr-2 p2 compact geometry embedded; Jadcherla single bound from jcl.geojson; TG_TOKEN/TG_CHAT env only on create path), guarded admin blocks (mbnradmin/mbnradmiN123 admin+Mahabubnagar, jcladmin/jcladmiN123 admin+Jadcherla; existing left untouched). Targets whatever backend superadmin-ui points at (now local http://192.168.1.5:8787 via shared default).
|
||||||
|
|
||||||
|
[2026-10-06T10:35+05:30] Maestro web inputText bug root-caused: inputText resolves target via createXPathFromElement, which uses id else class. Add-admin inputs had no id and shared wrapper class 'mb-4' + same input class, so xpath was ambiguous and typed password into the Name field (login worked only because its wrappers were classless/positional). Fix: add stable ids to superadmin-ui admin + region create/edit form controls and tap by id in neo-tests/e2e/ensure-init-regions.yaml. Files: apps/superadmin-ui/src/routes/admins.new.tsx, admins.$id.edit.tsx, regions.new.tsx, regions.$id.edit.tsx; neo-tests/e2e/ensure-init-regions.yaml.
|
||||||
|
|
||||||
|
[2026-10-06T10:50+05:30] neo-tests/e2e/create-mbnr-admin.yaml (new): dedicated flow to create an admin in Mahabubnagar via id-based field targeting, then verify the card on /admins. Note: reuse of a single MCP server session keeps one Chrome window alive across tools/call; spawning a new `maestro mcp` per call creates a fresh Chrome/profile.
|
||||||
|
|
||||||
|
[2026-10-06T11:00+05:30] Maestro web native <select> selection fix: tapping synthetic <option> resolves by index-in-parent synthetic coordinates, so role 'admin' (idx1) and region 'Mahabubnagar' (idx1) collided and the region tap re-selected role. Fixed by focusing the select by id then type-to-select via inputText (native select type-ahead) in create-mbnr-admin.yaml + ensure-init-regions.yaml. Verified: created mbnradmin (admin, Mahabubnagar) end-to-end via MCP Chrome; staff API now lists id 8 mbnradmin. Screenshot confirms card.
|
||||||
|
|
||||||
|
[2026-10-06T11:20+05:30] neo-tests subflow refactor (arg-driven): superadmin-ui submit buttons + add-bound get ids (create-region-submit, create-admin-submit, add-bound-button) in regions.new.tsx/admins.new.tsx. New subflows/e2e subflows: login.yaml, add-bound.yaml (args BOUND_INDEX/NAME/DESCRIPTION/GEOJSON; self-taps Add Bound when row absent), add-region.yaml (args REGION_NAME/DESCRIPTION/BOUND_COUNT + BOUND_0_*/BOUND_1_*; conditional 2nd bound via when true ${Number(BOUND_COUNT)>1}; creds; submit by id), add-admin.yaml (args ADMIN_*; submit by id). ensure-init-regions.yaml + create-mbnr-admin.yaml rewritten to orchestrate subflows; guard race fixed by waiting page subtitle + waitForAnimationEnd.
|
||||||
|
|
||||||
|
[2026-10-06T11:40+05:30] neo-tests region subflows: add-bound.yaml and add-region.yaml now scrollUntilVisible (direction DOWN) before tapping each field/button, so off-screen bound rows, creds and the submit button are reachable. Fixes 'Element not found: id bound-1-description' when a second bound is added below the fold.
|
||||||
|
|
||||||
|
[2026-10-06T11:42+05:30] add-bound.yaml: Add Bound button scrolls direction UP (it sits in the Bounds header above the bound cards); bound name/description/geojson scroll DOWN.
|
||||||
|
|
||||||
|
[2026-10-06T11:50+05:30] neo-tests/e2e/add-region.yaml (new): standalone entry script to create one region, reusing subflows/login.yaml + subflows/add-region.yaml. Demo env defaults (Demo Region, Demo-1 bound, BOUND_COUNT 1, demo TG creds) all overridable via env; TG_TOKEN/TG_CHAT inherited by the subflow.
|
||||||
|
|
||||||
|
[2026-10-06T12:00+05:30] ensure-init-regions.yaml verified via CLI (maestro test -e ...): local DB had been reset so create paths ran. add-region subflow created Mahabubnagar (Mbnr-1+Mbnr-2) and Jadcherla (1 bound) with scrollUntilVisible + BOUND_COUNT conditional; add-admin created mbnradmin + jcladmin. Verified no duplicate regions/admins via API.
|
||||||
|
|
||||||
|
[2026-10-06T12:10+05:30] Removed superseded neo-tests/e2e flows: mbnr-region-create.yaml (obsolete/broken placeholder stubs), mbnr-region-verify.yaml, create-mbnr-admin.yaml. None referenced by any flow (verified via grep); functionality covered by ensure-init-regions.yaml + subflows/{login,add-bound,add-region,add-admin}.yaml and add-region.yaml.
|
||||||
|
|
|
||||||
6
change-logs/maestro-upgrade.txt
Normal file
6
change-logs/maestro-upgrade.txt
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
[2026-10-06T09:31:59+05:30] User-requested Maestro upgrade and MCP browser verification.
|
||||||
|
Installed tool change (outside application source):
|
||||||
|
- ~/.maestro/bin and ~/.maestro/lib: Maestro 2.7.0 distribution
|
||||||
|
+ ~/.maestro/bin and ~/.maestro/lib: official Maestro 2.11.0 distribution
|
||||||
|
Preserve existing Maestro state and use the official installer with MAESTRO_VERSION=2.11.0.
|
||||||
|
Verify Chrome navigation, hierarchy inspection, and superadmin login via MCP tools/call in one server session.
|
||||||
39
neo-tests/e2e/add-region.yaml
Normal file
39
neo-tests/e2e/add-region.yaml
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
# add-region.yaml: create one region, with demo defaults you can override via env.
|
||||||
|
# Entry-point script that reuses the login + add-region subflows.
|
||||||
|
# Run via Maestro MCP run tool, device_id chromium. Override any value, e.g.:
|
||||||
|
# env: { REGION_NAME: "Mahabubnagar", BOUND_COUNT: "2", BOUND_1_GEOJSON: '<...>' }
|
||||||
|
url: http://localhost:4175/login
|
||||||
|
env:
|
||||||
|
SUPERADMIN_NAME: ${SUPERADMIN_NAME || "superadmin"}
|
||||||
|
SUPERADMIN_PASSWORD: ${SUPERADMIN_PASSWORD || "superadmiN123"}
|
||||||
|
REGION_NAME: ${REGION_NAME || "Demo Region"}
|
||||||
|
REGION_DESCRIPTION: ${REGION_DESCRIPTION || "Demo region created by add-region.yaml"}
|
||||||
|
BOUND_COUNT: ${BOUND_COUNT || "1"}
|
||||||
|
BOUND_0_NAME: ${BOUND_0_NAME || "Demo-1"}
|
||||||
|
BOUND_0_DESCRIPTION: ${BOUND_0_DESCRIPTION || "Demo bound one"}
|
||||||
|
BOUND_0_GEOJSON: '${BOUND_0_GEOJSON || "{\"type\":\"Polygon\",\"coordinates\":[[[78.0,16.7],[78.01,16.7],[78.01,16.71],[78.0,16.71],[78.0,16.7]]]}"}'
|
||||||
|
BOUND_1_NAME: ${BOUND_1_NAME || "Demo-2"}
|
||||||
|
BOUND_1_DESCRIPTION: ${BOUND_1_DESCRIPTION || "Demo bound two"}
|
||||||
|
BOUND_1_GEOJSON: '${BOUND_1_GEOJSON || "{\"type\":\"Polygon\",\"coordinates\":[[[78.02,16.7],[78.03,16.7],[78.03,16.71],[78.02,16.71],[78.02,16.7]]]}"}'
|
||||||
|
TG_TOKEN: ${TG_TOKEN || "demo-bot-token"}
|
||||||
|
TG_CHAT: ${TG_CHAT || "demo-chat-id"}
|
||||||
|
---
|
||||||
|
- launchApp
|
||||||
|
- runFlow: subflows/login.yaml
|
||||||
|
- openLink: http://localhost:4175/regions
|
||||||
|
- extendedWaitUntil:
|
||||||
|
visible: "Group delivery areas.*"
|
||||||
|
timeout: 30000
|
||||||
|
- waitForAnimationToEnd
|
||||||
|
- runFlow:
|
||||||
|
file: subflows/add-region.yaml
|
||||||
|
env:
|
||||||
|
REGION_NAME: ${REGION_NAME}
|
||||||
|
REGION_DESCRIPTION: ${REGION_DESCRIPTION}
|
||||||
|
BOUND_COUNT: ${BOUND_COUNT}
|
||||||
|
BOUND_0_NAME: ${BOUND_0_NAME}
|
||||||
|
BOUND_0_DESCRIPTION: ${BOUND_0_DESCRIPTION}
|
||||||
|
BOUND_0_GEOJSON: ${BOUND_0_GEOJSON}
|
||||||
|
BOUND_1_NAME: ${BOUND_1_NAME}
|
||||||
|
BOUND_1_DESCRIPTION: ${BOUND_1_DESCRIPTION}
|
||||||
|
BOUND_1_GEOJSON: ${BOUND_1_GEOJSON}
|
||||||
94
neo-tests/e2e/ensure-init-regions.yaml
Normal file
94
neo-tests/e2e/ensure-init-regions.yaml
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
# ensure-init-regions: guarantee the two init regions + their admins exist.
|
||||||
|
# Orchestration only - all creation lives in argument-driven subflows.
|
||||||
|
# Idempotent: each create block is guarded by a notVisible check on the list.
|
||||||
|
# Run via Maestro MCP run tool, device_id chromium, env:
|
||||||
|
# SUPERADMIN_NAME, SUPERADMIN_PASSWORD (required)
|
||||||
|
# TG_TOKEN, TG_CHAT (required only when a region must be created)
|
||||||
|
url: http://localhost:4175/login
|
||||||
|
env:
|
||||||
|
SUPERADMIN_NAME: ${SUPERADMIN_NAME || ""}
|
||||||
|
SUPERADMIN_PASSWORD: ${SUPERADMIN_PASSWORD || ""}
|
||||||
|
TG_TOKEN: ${TG_TOKEN || ""}
|
||||||
|
TG_CHAT: ${TG_CHAT || ""}
|
||||||
|
---
|
||||||
|
- launchApp
|
||||||
|
- runFlow: subflows/login.yaml
|
||||||
|
|
||||||
|
# ---- Mahabubnagar (Mbnr-1 p1 + Mbnr-2 p2) ----
|
||||||
|
- openLink: http://localhost:4175/regions
|
||||||
|
- extendedWaitUntil:
|
||||||
|
visible: "Group delivery areas.*"
|
||||||
|
timeout: 30000
|
||||||
|
- waitForAnimationToEnd
|
||||||
|
- runFlow:
|
||||||
|
when:
|
||||||
|
notVisible: Mahabubnagar
|
||||||
|
commands:
|
||||||
|
- runFlow:
|
||||||
|
file: subflows/add-region.yaml
|
||||||
|
env:
|
||||||
|
REGION_NAME: Mahabubnagar
|
||||||
|
REGION_DESCRIPTION: Mahabubnagar town and surrounding areas
|
||||||
|
BOUND_COUNT: "2"
|
||||||
|
BOUND_0_NAME: Mbnr-1
|
||||||
|
BOUND_0_DESCRIPTION: Town core coverage area
|
||||||
|
BOUND_0_GEOJSON: '{"type":"Polygon","coordinates":[[[77.9802307,16.7224827],[77.9832452,16.7186281],[77.9885003,16.7191643],[78.0027771,16.7184524],[78.0167635,16.717821],[78.0176657,16.7225884],[78.0245685,16.7301059],[78.0346065,16.7366045],[78.0483126,16.7469324],[78.0558892,16.7506815],[78.0533183,16.7547082],[78.0497798,16.7596596],[78.0456892,16.7640471],[78.0383339,16.7641426],[78.0343234,16.758687],[78.021375,16.7570244],[78.0163704,16.758279],[78.0128516,16.7590231],[78.0120219,16.7648881],[78.0095524,16.7664414],[77.99363,16.7660548],[77.9720422,16.7596124],[77.9679337,16.7449906],[77.9802307,16.7224827]]]}'
|
||||||
|
BOUND_1_NAME: Mbnr-2
|
||||||
|
BOUND_1_DESCRIPTION: Extended coverage area
|
||||||
|
BOUND_1_GEOJSON: '{"type":"Polygon","coordinates":[[[77.9773739,16.7127921],[77.9950359,16.7080928],[78.0187929,16.70999],[78.0289444,16.7211582],[78.0570875,16.7502883],[78.0662922,16.7519867],[78.0652719,16.7684088],[78.0204341,16.7689639],[78.0023161,16.770186],[77.9984809,16.7850848],[77.983305,16.782843],[77.971574,16.7646028],[77.9686551,16.7454905],[77.9773739,16.7127921]]]}'
|
||||||
|
|
||||||
|
# ---- Jadcherla (single bound) ----
|
||||||
|
- openLink: http://localhost:4175/regions
|
||||||
|
- extendedWaitUntil:
|
||||||
|
visible: "Group delivery areas.*"
|
||||||
|
timeout: 30000
|
||||||
|
- waitForAnimationToEnd
|
||||||
|
- runFlow:
|
||||||
|
when:
|
||||||
|
notVisible: Jadcherla
|
||||||
|
commands:
|
||||||
|
- runFlow:
|
||||||
|
file: subflows/add-region.yaml
|
||||||
|
env:
|
||||||
|
REGION_NAME: Jadcherla
|
||||||
|
REGION_DESCRIPTION: Jadcherla town
|
||||||
|
BOUND_COUNT: "1"
|
||||||
|
BOUND_0_NAME: Jadcherla
|
||||||
|
BOUND_0_DESCRIPTION: Jadcherla town coverage area
|
||||||
|
BOUND_0_GEOJSON: '{"type":"Polygon","coordinates":[[[78.1403916,16.744066],[78.1548681,16.7415277],[78.1593669,16.7523755],[78.1621315,16.7630654],[78.1620705,16.7692272],[78.1564687,16.7758419],[78.1513873,16.7783785],[78.1455877,16.7796921],[78.1326433,16.781202],[78.123043,16.7805196],[78.118775,16.7757046],[78.1173809,16.7685992],[78.1205895,16.7633171],[78.1403916,16.744066]]]}'
|
||||||
|
|
||||||
|
# ---- mbnradmin (admin role, Mahabubnagar) ----
|
||||||
|
- openLink: http://localhost:4175/admins
|
||||||
|
- extendedWaitUntil:
|
||||||
|
visible: "Staff users and the region each one manages.*"
|
||||||
|
timeout: 30000
|
||||||
|
- waitForAnimationToEnd
|
||||||
|
- runFlow:
|
||||||
|
when:
|
||||||
|
notVisible: mbnradmin
|
||||||
|
commands:
|
||||||
|
- runFlow:
|
||||||
|
file: subflows/add-admin.yaml
|
||||||
|
env:
|
||||||
|
ADMIN_NAME: mbnradmin
|
||||||
|
ADMIN_PASSWORD: mbnradmiN123
|
||||||
|
ADMIN_ROLE: admin
|
||||||
|
ADMIN_REGION: Mahabubnagar
|
||||||
|
|
||||||
|
# ---- jcladmin (admin role, Jadcherla) ----
|
||||||
|
- openLink: http://localhost:4175/admins
|
||||||
|
- extendedWaitUntil:
|
||||||
|
visible: "Staff users and the region each one manages.*"
|
||||||
|
timeout: 30000
|
||||||
|
- waitForAnimationToEnd
|
||||||
|
- runFlow:
|
||||||
|
when:
|
||||||
|
notVisible: jcladmin
|
||||||
|
commands:
|
||||||
|
- runFlow:
|
||||||
|
file: subflows/add-admin.yaml
|
||||||
|
env:
|
||||||
|
ADMIN_NAME: jcladmin
|
||||||
|
ADMIN_PASSWORD: jcladmiN123
|
||||||
|
ADMIN_ROLE: admin
|
||||||
|
ADMIN_REGION: Jadcherla
|
||||||
32
neo-tests/e2e/subflows/add-admin.yaml
Normal file
32
neo-tests/e2e/subflows/add-admin.yaml
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
# add-admin.yaml: create a staff admin and verify the card appears.
|
||||||
|
# Args: ADMIN_NAME, ADMIN_PASSWORD, ADMIN_ROLE, ADMIN_REGION.
|
||||||
|
# Role/region are native <select>s; select by focusing the id then typing the
|
||||||
|
# option label (Maestro's synthetic-option tap collides across selects).
|
||||||
|
url: http://localhost:4175/admins/new
|
||||||
|
env:
|
||||||
|
ADMIN_NAME: ${ADMIN_NAME || ""}
|
||||||
|
ADMIN_PASSWORD: ${ADMIN_PASSWORD || ""}
|
||||||
|
ADMIN_ROLE: ${ADMIN_ROLE || "admin"}
|
||||||
|
ADMIN_REGION: ${ADMIN_REGION || ""}
|
||||||
|
---
|
||||||
|
- openLink: http://localhost:4175/admins/new
|
||||||
|
- extendedWaitUntil:
|
||||||
|
visible: Region
|
||||||
|
timeout: 30000
|
||||||
|
- tapOn:
|
||||||
|
id: admin-name
|
||||||
|
- inputText: ${ADMIN_NAME}
|
||||||
|
- tapOn:
|
||||||
|
id: admin-password
|
||||||
|
- inputText: ${ADMIN_PASSWORD}
|
||||||
|
- tapOn:
|
||||||
|
id: admin-role
|
||||||
|
- inputText: ${ADMIN_ROLE}
|
||||||
|
- tapOn:
|
||||||
|
id: admin-region
|
||||||
|
- inputText: ${ADMIN_REGION}
|
||||||
|
- tapOn:
|
||||||
|
id: create-admin-submit
|
||||||
|
- extendedWaitUntil:
|
||||||
|
visible: ${ADMIN_NAME}
|
||||||
|
timeout: 60000
|
||||||
64
neo-tests/e2e/subflows/add-bound.yaml
Normal file
64
neo-tests/e2e/subflows/add-bound.yaml
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
# add-bound.yaml: fill one bound row on the Add Region form.
|
||||||
|
# Args: BOUND_INDEX, BOUND_NAME, BOUND_DESCRIPTION, BOUND_GEOJSON.
|
||||||
|
# Assumes the caller is already on /regions/new. Adds the row (via the
|
||||||
|
# Add Bound button) when it does not exist yet, then scrolls to and fills it
|
||||||
|
# by id. Bound rows can sit below the fold, so every target is scrolled to
|
||||||
|
# before interacting.
|
||||||
|
url: http://localhost:4175/regions/new
|
||||||
|
env:
|
||||||
|
BOUND_INDEX: ${BOUND_INDEX || "0"}
|
||||||
|
BOUND_NAME: ${BOUND_NAME || ""}
|
||||||
|
BOUND_DESCRIPTION: ${BOUND_DESCRIPTION || ""}
|
||||||
|
BOUND_GEOJSON: ${BOUND_GEOJSON || ""}
|
||||||
|
---
|
||||||
|
- runFlow:
|
||||||
|
when:
|
||||||
|
notVisible:
|
||||||
|
id: bound-${BOUND_INDEX}-name
|
||||||
|
commands:
|
||||||
|
- scrollUntilVisible:
|
||||||
|
element:
|
||||||
|
id: add-bound-button
|
||||||
|
direction: UP
|
||||||
|
timeout: 10000
|
||||||
|
speed: 50
|
||||||
|
visibilityPercentage: 60
|
||||||
|
centerElement: true
|
||||||
|
- tapOn:
|
||||||
|
id: add-bound-button
|
||||||
|
|
||||||
|
- scrollUntilVisible:
|
||||||
|
element:
|
||||||
|
id: bound-${BOUND_INDEX}-name
|
||||||
|
direction: DOWN
|
||||||
|
timeout: 10000
|
||||||
|
speed: 50
|
||||||
|
visibilityPercentage: 60
|
||||||
|
centerElement: true
|
||||||
|
- tapOn:
|
||||||
|
id: bound-${BOUND_INDEX}-name
|
||||||
|
- inputText: ${BOUND_NAME}
|
||||||
|
|
||||||
|
- scrollUntilVisible:
|
||||||
|
element:
|
||||||
|
id: bound-${BOUND_INDEX}-description
|
||||||
|
direction: DOWN
|
||||||
|
timeout: 10000
|
||||||
|
speed: 50
|
||||||
|
visibilityPercentage: 60
|
||||||
|
centerElement: true
|
||||||
|
- tapOn:
|
||||||
|
id: bound-${BOUND_INDEX}-description
|
||||||
|
- inputText: ${BOUND_DESCRIPTION}
|
||||||
|
|
||||||
|
- scrollUntilVisible:
|
||||||
|
element:
|
||||||
|
id: bound-${BOUND_INDEX}-geojson
|
||||||
|
direction: DOWN
|
||||||
|
timeout: 10000
|
||||||
|
speed: 50
|
||||||
|
visibilityPercentage: 60
|
||||||
|
centerElement: true
|
||||||
|
- tapOn:
|
||||||
|
id: bound-${BOUND_INDEX}-geojson
|
||||||
|
- inputText: ${BOUND_GEOJSON}
|
||||||
108
neo-tests/e2e/subflows/add-region.yaml
Normal file
108
neo-tests/e2e/subflows/add-region.yaml
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
# add-region.yaml: create a region with 1..N bounds.
|
||||||
|
# Args:
|
||||||
|
# REGION_NAME, REGION_DESCRIPTION
|
||||||
|
# BOUND_COUNT (default "1")
|
||||||
|
# BOUND_0_NAME, BOUND_0_DESCRIPTION, BOUND_0_GEOJSON
|
||||||
|
# BOUND_1_NAME, BOUND_1_DESCRIPTION, BOUND_1_GEOJSON (used when BOUND_COUNT > 1)
|
||||||
|
# TG_TOKEN, TG_CHAT (inherited from the caller)
|
||||||
|
# Bounds are added by the reusable add-bound.yaml subflow. The form is long, so
|
||||||
|
# every target is scrolled to before interacting; submit uses the
|
||||||
|
# create-region-submit button id.
|
||||||
|
url: http://localhost:4175/regions/new
|
||||||
|
env:
|
||||||
|
REGION_NAME: ${REGION_NAME || ""}
|
||||||
|
REGION_DESCRIPTION: ${REGION_DESCRIPTION || ""}
|
||||||
|
BOUND_COUNT: ${BOUND_COUNT || "1"}
|
||||||
|
BOUND_0_NAME: ${BOUND_0_NAME || ""}
|
||||||
|
BOUND_0_DESCRIPTION: ${BOUND_0_DESCRIPTION || ""}
|
||||||
|
BOUND_0_GEOJSON: ${BOUND_0_GEOJSON || ""}
|
||||||
|
BOUND_1_NAME: ${BOUND_1_NAME || ""}
|
||||||
|
BOUND_1_DESCRIPTION: ${BOUND_1_DESCRIPTION || ""}
|
||||||
|
BOUND_1_GEOJSON: ${BOUND_1_GEOJSON || ""}
|
||||||
|
---
|
||||||
|
- openLink: http://localhost:4175/regions/new
|
||||||
|
- extendedWaitUntil:
|
||||||
|
visible: Bounds (GeoJSON)
|
||||||
|
timeout: 30000
|
||||||
|
|
||||||
|
- scrollUntilVisible:
|
||||||
|
element:
|
||||||
|
id: region-name
|
||||||
|
direction: DOWN
|
||||||
|
timeout: 10000
|
||||||
|
speed: 50
|
||||||
|
visibilityPercentage: 60
|
||||||
|
centerElement: true
|
||||||
|
- tapOn:
|
||||||
|
id: region-name
|
||||||
|
- inputText: ${REGION_NAME}
|
||||||
|
|
||||||
|
- scrollUntilVisible:
|
||||||
|
element:
|
||||||
|
id: region-description
|
||||||
|
direction: DOWN
|
||||||
|
timeout: 10000
|
||||||
|
speed: 50
|
||||||
|
visibilityPercentage: 60
|
||||||
|
centerElement: true
|
||||||
|
- tapOn:
|
||||||
|
id: region-description
|
||||||
|
- inputText: ${REGION_DESCRIPTION}
|
||||||
|
|
||||||
|
- runFlow:
|
||||||
|
file: add-bound.yaml
|
||||||
|
env:
|
||||||
|
BOUND_INDEX: "0"
|
||||||
|
BOUND_NAME: ${BOUND_0_NAME}
|
||||||
|
BOUND_DESCRIPTION: ${BOUND_0_DESCRIPTION}
|
||||||
|
BOUND_GEOJSON: ${BOUND_0_GEOJSON}
|
||||||
|
|
||||||
|
- runFlow:
|
||||||
|
when:
|
||||||
|
true: ${Number(BOUND_COUNT) > 1}
|
||||||
|
commands:
|
||||||
|
- runFlow:
|
||||||
|
file: add-bound.yaml
|
||||||
|
env:
|
||||||
|
BOUND_INDEX: "1"
|
||||||
|
BOUND_NAME: ${BOUND_1_NAME}
|
||||||
|
BOUND_DESCRIPTION: ${BOUND_1_DESCRIPTION}
|
||||||
|
BOUND_GEOJSON: ${BOUND_1_GEOJSON}
|
||||||
|
|
||||||
|
- scrollUntilVisible:
|
||||||
|
element:
|
||||||
|
id: cred-0-bot-token
|
||||||
|
direction: DOWN
|
||||||
|
timeout: 10000
|
||||||
|
speed: 50
|
||||||
|
visibilityPercentage: 60
|
||||||
|
centerElement: true
|
||||||
|
- tapOn:
|
||||||
|
id: cred-0-bot-token
|
||||||
|
- inputText: ${TG_TOKEN}
|
||||||
|
|
||||||
|
- scrollUntilVisible:
|
||||||
|
element:
|
||||||
|
id: cred-0-chat-id
|
||||||
|
direction: DOWN
|
||||||
|
timeout: 10000
|
||||||
|
speed: 50
|
||||||
|
visibilityPercentage: 60
|
||||||
|
centerElement: true
|
||||||
|
- tapOn:
|
||||||
|
id: cred-0-chat-id
|
||||||
|
- inputText: ${TG_CHAT}
|
||||||
|
|
||||||
|
- scrollUntilVisible:
|
||||||
|
element:
|
||||||
|
id: create-region-submit
|
||||||
|
direction: DOWN
|
||||||
|
timeout: 10000
|
||||||
|
speed: 50
|
||||||
|
visibilityPercentage: 60
|
||||||
|
centerElement: true
|
||||||
|
- tapOn:
|
||||||
|
id: create-region-submit
|
||||||
|
- extendedWaitUntil:
|
||||||
|
visible: ${REGION_NAME}
|
||||||
|
timeout: 60000
|
||||||
20
neo-tests/e2e/subflows/login.yaml
Normal file
20
neo-tests/e2e/subflows/login.yaml
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
# login.yaml: sign in to the superadmin-ui.
|
||||||
|
# Args: SUPERADMIN_NAME, SUPERADMIN_PASSWORD (inherited if not passed).
|
||||||
|
url: http://localhost:4175/login
|
||||||
|
env:
|
||||||
|
SUPERADMIN_NAME: ${SUPERADMIN_NAME || ""}
|
||||||
|
SUPERADMIN_PASSWORD: ${SUPERADMIN_PASSWORD || ""}
|
||||||
|
---
|
||||||
|
- openLink: http://localhost:4175/login
|
||||||
|
- runFlow:
|
||||||
|
when:
|
||||||
|
visible: Sign in to continue
|
||||||
|
commands:
|
||||||
|
- tapOn: Enter your name
|
||||||
|
- inputText: ${SUPERADMIN_NAME}
|
||||||
|
- tapOn: Enter your password
|
||||||
|
- inputText: ${SUPERADMIN_PASSWORD}
|
||||||
|
- tapOn: Login
|
||||||
|
- extendedWaitUntil:
|
||||||
|
visible: Admins
|
||||||
|
timeout: 30000
|
||||||
|
|
@ -63,6 +63,15 @@ export const staffUsers = mf.table('staff_users', {
|
||||||
createdAt: timestamp('created_at').notNull().defaultNow(),
|
createdAt: timestamp('created_at').notNull().defaultNow(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Platform superadmins. Global by definition: no region, no role —
|
||||||
|
// every row in this table has full access via the superadmin.* scope.
|
||||||
|
export const superadmins = mf.table('superadmins', {
|
||||||
|
id: integer().primaryKey().generatedAlwaysAsIdentity(),
|
||||||
|
name: varchar({ length: 255 }).notNull().unique(),
|
||||||
|
password: varchar({ length: 255 }).notNull(),
|
||||||
|
createdAt: timestamp('created_at').notNull().defaultNow(),
|
||||||
|
});
|
||||||
|
|
||||||
export const storeInfo = mf.table('store_info', {
|
export const storeInfo = mf.table('store_info', {
|
||||||
id: integer().primaryKey().generatedAlwaysAsIdentity(),
|
id: integer().primaryKey().generatedAlwaysAsIdentity(),
|
||||||
name: varchar({ length: 255 }).notNull(),
|
name: varchar({ length: 255 }).notNull(),
|
||||||
|
|
|
||||||
13
packages/db_helper_sqlite/drizzle/0008_superadmins.sql
Normal file
13
packages/db_helper_sqlite/drizzle/0008_superadmins.sql
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
-- Migration: platform superadmins table.
|
||||||
|
-- One row per human superadmin. Global by definition (no region, no role);
|
||||||
|
-- authenticated via the superadmin.* scope (superadmin.auth.login).
|
||||||
|
-- Pure CREATE: safe on populated D1 databases (no drops, no rebuilds).
|
||||||
|
|
||||||
|
CREATE TABLE `superadmins` (
|
||||||
|
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||||
|
`name` text NOT NULL,
|
||||||
|
`password` text NOT NULL,
|
||||||
|
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX `superadmins_name_unique` ON `superadmins` (`name`);
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue