From 5af1afd8ba01e3c18b1aedc427d53e583832f344 Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:53:12 +0530 Subject: [PATCH] enh --- .../app/(drawer)/dashboard/products/edit.tsx | 4 +- apps/admin-ui/src/components/ProductForm.tsx | 92 +- apps/admin-web/src/components/BannerForm.tsx | 2 + apps/admin-web/src/components/MultiSelect.tsx | 4 +- .../src/components/OrderOptionsMenu.tsx | 42 +- apps/admin-web/src/components/ProductForm.tsx | 81 +- .../src/components/SearchableSelect.tsx | 2 + apps/admin-web/src/components/SlotForm.tsx | 1 + apps/admin-web/src/components/StoreForm.tsx | 5 + apps/admin-web/src/components/TagForm.tsx | 7 + .../src/routes/dashboard.customize-app.tsx | 61 +- .../src/routes/dashboard.orders.list.tsx | 1 + .../src/routes/dashboard.orders.sequence.tsx | 4 +- .../src/routes/dashboard.products.tsx | 2 +- .../src/routes/dashboard.slots.detail.tsx | 1 + apps/backend/scripts/delete-orders-before.sql | 73 ++ apps/backend/src/app.ts | 17 +- apps/backend/src/dbService.ts | 1 + apps/backend/src/map-assets/jcl.geojson | 74 ++ .../src/trpc/apis/admin-apis/apis/product.ts | 20 +- .../src/trpc/apis/admin-apis/apis/store.ts | 11 + .../trpc/apis/superadmin-apis/apis/auth.ts | 47 + .../trpc/apis/superadmin-apis/apis/const.ts | 109 ++ .../trpc/apis/superadmin-apis/apis/product.ts | 341 ++++++ .../trpc/apis/superadmin-apis/apis/region.ts | 147 +++ .../trpc/apis/superadmin-apis/apis/staff.ts | 173 +++ .../trpc/apis/superadmin-apis/apis/store.ts | 172 +++ .../apis/superadmin-trpc-index.ts | 20 + .../trpc/apis/superadmin-apis/apis/upload.ts | 56 + apps/backend/src/trpc/router.ts | 2 + apps/backend/src/trpc/trpc-index.ts | 23 +- .../superadmin-ui/src/components/AppShell.tsx | 6 +- .../src/components/MultiSelect.tsx | 154 +++ .../src/components/ProductForm.tsx | 1049 +++++++++++++++++ .../src/components/ProductsSelector.tsx | 181 +++ .../src/components/SearchableSelect.tsx | 116 ++ .../src/components/StoreForm.tsx | 235 ++++ .../src/hooks/useUploadToObjectStorage.ts | 105 ++ apps/superadmin-ui/src/lib/auth-context.tsx | 8 +- apps/superadmin-ui/src/routeTree.gen.ts | 206 +++- .../src/routes/admins.$id.edit.tsx | 177 +++ apps/superadmin-ui/src/routes/admins.new.tsx | 145 +++ apps/superadmin-ui/src/routes/admins.tsx | 217 ++-- apps/superadmin-ui/src/routes/constants.tsx | 4 +- apps/superadmin-ui/src/routes/dashboard.tsx | 4 +- .../src/routes/products.$id.edit.tsx | 301 +++++ .../superadmin-ui/src/routes/products.new.tsx | 201 ++++ apps/superadmin-ui/src/routes/products.tsx | 152 +++ .../src/routes/regions.$id.edit.tsx | 4 +- apps/superadmin-ui/src/routes/regions.new.tsx | 12 +- apps/superadmin-ui/src/routes/regions.tsx | 2 +- .../src/routes/send-notifications.tsx | 2 +- .../src/routes/stores.$id.edit.tsx | 91 ++ apps/superadmin-ui/src/routes/stores.new.tsx | 54 + apps/superadmin-ui/src/routes/stores.tsx | 150 +++ apps/test2.sqlite-shm | Bin 0 -> 32768 bytes apps/test2.sqlite-wal | 0 apps/user-ui/components/RegionGate.tsx | 35 +- apps/user-ui/src/hooks/prominent-api-hooks.ts | 11 +- .../web-ui/src/components/AddToCartDialog.tsx | 2 +- apps/web-ui/src/components/AddressForm.tsx | 28 +- .../src/components/AddressRegionWatcher.tsx | 273 +++++ apps/web-ui/src/components/AppLayout.tsx | 15 +- .../components/CheckoutAddressSelector.tsx | 3 +- .../components/PaymentAndOrderComponent.tsx | 35 +- apps/web-ui/src/components/ProductCard.tsx | 14 +- apps/web-ui/src/components/ProtectedRoute.tsx | 6 +- .../QuickDeliveryAddressSelector.tsx | 152 +++ apps/web-ui/src/components/RegionBar.tsx | 57 + apps/web-ui/src/components/RegionGate.tsx | 224 ++++ .../src/components/RegionSwitchDialogs.tsx | 58 + apps/web-ui/src/components/cart-page.tsx | 955 +++++++++++++++ apps/web-ui/src/contexts/RegionContext.tsx | 124 ++ apps/web-ui/src/hooks/cart-query-hooks.ts | 47 + apps/web-ui/src/hooks/prominent-api-hooks.ts | 112 +- apps/web-ui/src/hooks/useRegionSwitch.tsx | 271 +++++ apps/web-ui/src/lib/auth-context.tsx | 29 +- apps/web-ui/src/routes/__root.tsx | 14 +- apps/web-ui/src/routes/cart.tsx | 151 +-- apps/web-ui/src/routes/flash.cart.tsx | 135 +-- apps/web-ui/src/routes/flash.checkout.tsx | 242 ++-- .../web-ui/src/routes/flash.order-success.tsx | 5 + apps/web-ui/src/routes/home.cart.tsx | 134 +-- apps/web-ui/src/routes/home.checkout.tsx | 239 ++-- apps/web-ui/src/routes/home.index.tsx | 76 +- apps/web-ui/src/routes/home.order-success.tsx | 5 + apps/web-ui/src/routes/home.search.tsx | 1 + apps/web-ui/src/routes/login.tsx | 50 +- apps/web-ui/src/routes/register.tsx | 5 + apps/web-ui/src/routes/slot-view.tsx | 124 +- change-logs/change-log.txt | 89 ++ change-logs/maestro-upgrade.txt | 6 + neo-tests/e2e/add-region.yaml | 39 + neo-tests/e2e/ensure-init-regions.yaml | 94 ++ neo-tests/e2e/subflows/add-admin.yaml | 32 + neo-tests/e2e/subflows/add-bound.yaml | 64 + neo-tests/e2e/subflows/add-region.yaml | 108 ++ neo-tests/e2e/subflows/login.yaml | 20 + packages/db_helper_postgres/src/db/schema.ts | 9 + .../drizzle/0008_superadmins.sql | 13 + .../drizzle/0009_all_region.sql | 67 ++ .../drizzle/meta/_journal.json | 14 + packages/db_helper_sqlite/index.ts | 9 + .../src/admin-apis/product.ts | 62 + .../src/admin-apis/staff-user.ts | 78 +- .../db_helper_sqlite/src/admin-apis/store.ts | 49 +- .../src/admin-apis/superadmin.ts | 28 + packages/db_helper_sqlite/src/db/schema.ts | 13 +- .../src/stores/store-helpers.ts | 4 +- .../db_helper_sqlite/src/user-apis/stores.ts | 6 +- packages/shared/index.ts | 4 +- packages/shared/types/admin.ts | 26 +- packages/shared/types/inputs.types.ts | 2 + packages/shared/types/ui-common.types.ts | 1 + .../src/components/checkbox.tsx | 3 + .../src/components/dropdown.tsx | 10 +- .../src/components/image-uploader-neo.tsx | 6 +- .../src/components/quantifier.tsx | 3 +- .../src/components/search-bar.tsx | 9 + .../__pycache__/gen_flows.cpython-313.pyc | Bin 0 -> 11301 bytes tests/e2e/full-suite/scripts/gen_flows.py | 6 +- 121 files changed, 8586 insertions(+), 1091 deletions(-) create mode 100644 apps/backend/scripts/delete-orders-before.sql create mode 100644 apps/backend/src/map-assets/jcl.geojson create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/auth.ts create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/const.ts create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/product.ts create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/region.ts create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/store.ts create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/upload.ts create mode 100644 apps/superadmin-ui/src/components/MultiSelect.tsx create mode 100644 apps/superadmin-ui/src/components/ProductForm.tsx create mode 100644 apps/superadmin-ui/src/components/ProductsSelector.tsx create mode 100644 apps/superadmin-ui/src/components/SearchableSelect.tsx create mode 100644 apps/superadmin-ui/src/components/StoreForm.tsx create mode 100644 apps/superadmin-ui/src/hooks/useUploadToObjectStorage.ts create mode 100644 apps/superadmin-ui/src/routes/admins.$id.edit.tsx create mode 100644 apps/superadmin-ui/src/routes/admins.new.tsx create mode 100644 apps/superadmin-ui/src/routes/products.$id.edit.tsx create mode 100644 apps/superadmin-ui/src/routes/products.new.tsx create mode 100644 apps/superadmin-ui/src/routes/products.tsx create mode 100644 apps/superadmin-ui/src/routes/stores.$id.edit.tsx create mode 100644 apps/superadmin-ui/src/routes/stores.new.tsx create mode 100644 apps/superadmin-ui/src/routes/stores.tsx create mode 100644 apps/test2.sqlite-shm create mode 100644 apps/test2.sqlite-wal create mode 100644 apps/web-ui/src/components/AddressRegionWatcher.tsx create mode 100644 apps/web-ui/src/components/QuickDeliveryAddressSelector.tsx create mode 100644 apps/web-ui/src/components/RegionBar.tsx create mode 100644 apps/web-ui/src/components/RegionGate.tsx create mode 100644 apps/web-ui/src/components/RegionSwitchDialogs.tsx create mode 100644 apps/web-ui/src/components/cart-page.tsx create mode 100644 apps/web-ui/src/contexts/RegionContext.tsx create mode 100644 apps/web-ui/src/hooks/useRegionSwitch.tsx create mode 100644 change-logs/maestro-upgrade.txt create mode 100644 neo-tests/e2e/add-region.yaml create mode 100644 neo-tests/e2e/ensure-init-regions.yaml create mode 100644 neo-tests/e2e/subflows/add-admin.yaml create mode 100644 neo-tests/e2e/subflows/add-bound.yaml create mode 100644 neo-tests/e2e/subflows/add-region.yaml create mode 100644 neo-tests/e2e/subflows/login.yaml create mode 100644 packages/db_helper_sqlite/drizzle/0008_superadmins.sql create mode 100644 packages/db_helper_sqlite/drizzle/0009_all_region.sql create mode 100644 packages/db_helper_sqlite/src/admin-apis/superadmin.ts create mode 100644 tests/e2e/full-suite/scripts/__pycache__/gen_flows.cpython-313.pyc diff --git a/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx b/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx index 63561d1..144721c 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx @@ -196,7 +196,9 @@ export default function EditProduct() { name: values.name, shortDescription: values.shortDescription || 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, incrementStep: 1, skus, diff --git a/apps/admin-ui/src/components/ProductForm.tsx b/apps/admin-ui/src/components/ProductForm.tsx index 5a333b0..f9c109a 100644 --- a/apps/admin-ui/src/components/ProductForm.tsx +++ b/apps/admin-ui/src/components/ProductForm.tsx @@ -5,7 +5,6 @@ import * as Yup from 'yup' import { MyTextInput, BottomDropdown, MyText, tw, ImageUploaderNeo, ImageUploaderNeoItem, ImageUploaderNeoPayload, Checkbox, InfoDialog } from 'common-ui' import MaterialIcons from '@expo/vector-icons/MaterialIcons' import { trpc } from '../trpc-client' -import { useIsSuperAdmin } from '../../hooks/useIsSuperAdmin' import type { CreateComboItemInput, CreateSkuInput } 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( Yup.object().shape({ storeIdsByRegion: Yup.mixed().test( @@ -161,8 +160,13 @@ const makeProductValidationSchema = (regions: RegionOption[]) => 'Store is required for every region', function (value: any) { 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 = value ?? {} - for (const region of regions) { + for (const region of applicable) { const storeId = map[region.id] if (storeId == null || Number(storeId) < 1) { return this.createError({ @@ -189,7 +193,7 @@ const collectErrorMessages = (errors: unknown, depth = 0): string[] => { 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 } // On edit, an all-regions product has no per-region store payload from the API, @@ -240,10 +244,21 @@ const ProductForm = forwardRef(({ clearImages: () => setVariantImages(initialValues.variants.map(() => [])), }), [initialValues.variants]) - const isSuperAdmin = useIsSuperAdmin() - // Non-superadmins may not flip all-regions availability (backend 403s either - // direction); lock the checkbox on all-region products. - const allRegionsLocked = !isSuperAdmin && !!initialValues.availableInAllRegions + // All-region products are managed from superadmin-ui only: the flag is + // hidden here (so global products can never be created from this app). + // Regional staff may still edit a global product, but every write applies + // 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 allStores: RegionStoreOption[] = useMemo( @@ -262,7 +277,7 @@ const ProductForm = forwardRef(({ ) const storesForRegion = (regionId: number) => allRegionsStores - .filter((store) => store.regionId === regionId) + .filter((store) => store.regionId === regionId || store.availableInAllRegions) .map((store) => ({ label: store.name, value: store.id })) const { data: regionsData } = trpc.admin.region.getRegions.useQuery() @@ -270,7 +285,21 @@ const ProductForm = forwardRef(({ () => (regionsData?.regions || []).map((region) => ({ id: region.id, name: region.name })), [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 skuOptions = (skusData?.skus || []).map((sku) => ({ @@ -344,26 +373,19 @@ const ProductForm = forwardRef(({ enableReinitialize > {({ 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 = {} - 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) - } - } + // Name-match prefill source for the own-region store dropdown when a + // regional staffer edits a global product (the API sends no per-region + // store payload, so match by the product's current store name). + const editStoreName = allStores.find((s) => s.id === initialValues.storeId)?.name return ( + {editingGlobalAsRegional && ( + + + Global product — changes you save here apply to {staffRegionName} only. + + + )} (({ onChangeText={handleChange('longDescription')} style={{ marginBottom: 16 }} /> - - - Available in all regions - {!values.availableInAllRegions ? ( (({ style={{ marginBottom: 16 }} /> ) : ( - regions.map((region) => { + editableRegions.map((region) => { const regionStores = storesForRegion(region.id) return ( @@ -441,7 +453,7 @@ const ProductForm = forwardRef(({ }) )} - + {errors.redirectUrl && touched.redirectUrl && ( diff --git a/apps/admin-web/src/components/MultiSelect.tsx b/apps/admin-web/src/components/MultiSelect.tsx index 6a34870..f022637 100644 --- a/apps/admin-web/src/components/MultiSelect.tsx +++ b/apps/admin-web/src/components/MultiSelect.tsx @@ -97,6 +97,7 @@ export function MultiSelect({ }} onSearch={onSearch} className="mb-3" + testID={testID ? `${testID}-search` : undefined} />
{filtered.map((option) => { @@ -104,7 +105,7 @@ export function MultiSelect({ return (
{ if (!option.disabled) toggle(option.value) }} @@ -138,6 +139,7 @@ export function MultiSelect({
+ + {order.isFirstOrder && ( + + )}
diff --git a/apps/admin-web/src/components/ProductForm.tsx b/apps/admin-web/src/components/ProductForm.tsx index f57619e..9118da3 100644 --- a/apps/admin-web/src/components/ProductForm.tsx +++ b/apps/admin-web/src/components/ProductForm.tsx @@ -6,7 +6,6 @@ import type { ImageUploaderNeoItem, ImageUploaderNeoPayload } from 'web-componen import SearchableSelect from './SearchableSelect' import { Plus, Trash2, X, RotateCcw, Info } from 'lucide-react' import { trpc } from '@/lib/trpc-client' -import { useIsSuperAdmin } from '../hooks/useIsSuperAdmin' import type { CreateComboItemInput, CreateSkuInput } from '@packages/shared' import type { SkuFeatureLike } from '@packages/shared' @@ -258,10 +257,9 @@ const ProductForm = forwardRef(({ clearImages: () => setVariantImages(initialValues.variants.map(() => [])), }), [initialValues.variants]) - const isSuperAdmin = useIsSuperAdmin() - // Non-superadmins may not flip all-regions availability (backend 403s either - // direction); lock the checkbox on all-region products. - const allRegionsLocked = !isSuperAdmin && !!initialValues.availableInAllRegions + // All-region products are managed from superadmin-ui only: the flag is + // hidden here, and edits to such products are read-only in this app. + const isAllRegionsProduct = !!initialValues.availableInAllRegions const { data: storesData } = trpc.admin.store.getStores.useQuery() const allStores: RegionStoreOption[] = useMemo( @@ -362,32 +360,22 @@ const ProductForm = forwardRef(({ enableReinitialize > {({ 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 = {} - 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 (
+ {isAllRegionsProduct && ( +
+

+ This product serves all regions and is managed from superadmin. Changes here are disabled. +

+
+ )} (({ value={values.shortDescription} onChange={handleChange('shortDescription')} style={{ marginBottom: 16 }} + data-testid="product-short-description-input" /> (({ value={values.longDescription} onChange={handleChange('longDescription')} style={{ marginBottom: 16 }} + data-testid="product-long-description-input" /> -
- -

Available in all regions

-
{!values.availableInAllRegions ? ( -
+

Store

(({ options={storeOptions} onValueChange={(value) => setFieldValue('storeId', Number(value))} className="w-full" + testID="product-store-dropdown" />
) : ( regions.map((region) => { const regionStores = storesForRegion(region.id) return ( -
+

Store — {region.name}

{regionStores.length === 0 && (

@@ -446,15 +429,16 @@ const ProductForm = forwardRef(({ setFieldValue(`storeIdsByRegion.${region.id}`, Number(value)) } className="w-full" + testID={`product-region-${region.id}-store-dropdown`} />

) }) )} - + -
+

Product Type

(({ ]} onValueChange={(value) => setFieldValue('productType', value as 'item' | 'combo')} className="w-full" + testID="product-type-dropdown" />
@@ -475,6 +460,7 @@ const ProductForm = forwardRef(({

Variants

@@ -607,6 +597,7 @@ const ProductForm = forwardRef(({ placeholder="MRP" type="number" inputMode="numeric" + data-testid={`variant-${vIndex}-market-price`} value={variant.marketPrice?.toString() ?? ''} onChange={handleChange(`variants.${vIndex}.marketPrice`)} /> @@ -617,6 +608,7 @@ const ProductForm = forwardRef(({ placeholder="Selling price" type="number" inputMode="numeric" + data-testid={`variant-${vIndex}-price`} value={variant.price?.toString() ?? ''} onChange={handleChange(`variants.${vIndex}.price`)} /> @@ -626,6 +618,7 @@ const ProductForm = forwardRef(({
{ setFieldValue(`variants.${vIndex}.isFlashAvailable`, !variant.isFlashAvailable) if (variant.isFlashAvailable) setFieldValue(`variants.${vIndex}.flashPrice`, null) @@ -637,6 +630,7 @@ const ProductForm = forwardRef(({
setFieldValue(`variants.${vIndex}.isOffer`, !variant.isOffer)} />

Offer SKU

@@ -646,6 +640,7 @@ const ProductForm = forwardRef(({
setFieldValue(`variants.${vIndex}.isComboOnly`, !variant.isComboOnly)} />

Combo Only SKU

@@ -653,9 +648,10 @@ const ProductForm = forwardRef(({ )} {mode === 'edit' && ( -
+
setFieldValue(`variants.${vIndex}.isSuspended`, !variant.isSuspended)} />

Suspend SKU

@@ -668,6 +664,7 @@ const ProductForm = forwardRef(({ placeholder="Enter flash price" type="number" inputMode="numeric" + data-testid={`variant-${vIndex}-flash-price`} value={variant.flashPrice?.toString() ?? ''} onChange={handleChange(`variants.${vIndex}.flashPrice`)} style={{ marginBottom: 12 }} @@ -676,6 +673,7 @@ const ProductForm = forwardRef(({ setVariantImages((prev) => { const next = [...prev] @@ -699,6 +697,7 @@ const ProductForm = forwardRef(({

Included Items

+ ) + })} +
+ )} + + {({ handleSubmit, values, setFieldValue }) => (
{constants.map((constant) => { diff --git a/apps/admin-web/src/routes/dashboard.orders.list.tsx b/apps/admin-web/src/routes/dashboard.orders.list.tsx index 0c1076b..8c477a2 100644 --- a/apps/admin-web/src/routes/dashboard.orders.list.tsx +++ b/apps/admin-web/src/routes/dashboard.orders.list.tsx @@ -392,6 +392,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType, refetch: () => void } latitude: order.latitude, longitude: order.longitude, status: order.status, + isFirstOrder: order.isFirstOrder, }} onViewDetails={handleMenuOption} onTogglePackaged={() => handleMarkPackaged(!order.isPackaged)} diff --git a/apps/admin-web/src/routes/dashboard.orders.sequence.tsx b/apps/admin-web/src/routes/dashboard.orders.sequence.tsx index 5f7c378..3511916 100644 --- a/apps/admin-web/src/routes/dashboard.orders.sequence.tsx +++ b/apps/admin-web/src/routes/dashboard.orders.sequence.tsx @@ -61,7 +61,8 @@ interface OrderWithSequence { addressId: number, adminNotes?: string | null, customerName?: string | null, - assignedUserName?: string | null + assignedUserName?: string | null, + isFirstOrder?: boolean } interface SlotProgressProps { @@ -721,6 +722,7 @@ function DeliverySequences() { adminNotes: selectedOrder?.adminNotes || null, latitude: selectedOrder?.latitude || null, longitude: selectedOrder?.longitude || null, + isFirstOrder: selectedOrder?.isFirstOrder, }} onViewDetails={() => { if (selectedOrder) { diff --git a/apps/admin-web/src/routes/dashboard.products.tsx b/apps/admin-web/src/routes/dashboard.products.tsx index 9658585..73ef542 100644 --- a/apps/admin-web/src/routes/dashboard.products.tsx +++ b/apps/admin-web/src/routes/dashboard.products.tsx @@ -124,7 +124,7 @@ function Products() { <>
Products - navigate({ to: '/dashboard/products/new' })}> + navigate({ to: '/dashboard/products/new' })} data-testid="add-product-button"> Add Product
diff --git a/apps/admin-web/src/routes/dashboard.slots.detail.tsx b/apps/admin-web/src/routes/dashboard.slots.detail.tsx index cbad4e8..1140c35 100644 --- a/apps/admin-web/src/routes/dashboard.slots.detail.tsx +++ b/apps/admin-web/src/routes/dashboard.slots.detail.tsx @@ -201,6 +201,7 @@ function SlotDetails() { + setOpen(false)}> +
+

{heading ?? placeholder ?? 'Select'}

+ { + setQuery(q) + onSearch?.(q) + }} + onSearch={onSearch} + className="mb-3" + testID={testID ? `${testID}-search` : undefined} + /> +
+ {filtered.map((option) => { + const checked = selectedSet.has(String(option.value)) + return ( +
{ + 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'}`} + > + e.stopPropagation()}> + { + if (!option.disabled) toggle(option.value) + }} + /> + + {option.label} + {checked ? : null} +
+ ) + })} + {filtered.length === 0 ? ( +

No options found

+ ) : null} +
+
+ + +
+
+
+
+ ) +} + +export default MultiSelect diff --git a/apps/superadmin-ui/src/components/ProductForm.tsx b/apps/superadmin-ui/src/components/ProductForm.tsx new file mode 100644 index 0000000..a282fdf --- /dev/null +++ b/apps/superadmin-ui/src/components/ProductForm.tsx @@ -0,0 +1,1049 @@ +import { useState, useImperativeHandle, forwardRef, useMemo, useEffect } from 'react' +import { Formik, FieldArray, useFormikContext } from 'formik' +import * as Yup from 'yup' +import { pInput as PInput, Dropdown, p as P, Checkbox, BottomDialog, ImageUploaderNeo } from 'web-components' +import type { ImageUploaderNeoItem, ImageUploaderNeoPayload } from 'web-components' +import SearchableSelect from './SearchableSelect' +import { Plus, Trash2, X, RotateCcw, Info } from 'lucide-react' +import { trpc } from '@/lib/trpc-client' +import type { CreateComboItemInput, CreateSkuInput } from '@packages/shared' +import type { SkuFeatureLike } from '@packages/shared' + +// Feature input shape — single source: shared SkuFeatureLike +type Attribute = SkuFeatureLike + +// Variant form state — anchored to the shared CreateSkuInput (numeric prices, +// same field names). Images are managed separately via variantImages state. +type Variant = Omit< + CreateSkuInput, + 'name' | 'price' | 'marketPrice' | 'flashPrice' | 'images' | 'features' | 'comboItems' +> & { + id?: number + name: string + price?: number + marketPrice: number | null + flashPrice: number | null + isFlashAvailable: boolean + isOffer: boolean + isComboOnly: boolean + isSuspended: boolean + features: Attribute[] + comboItems: CreateComboItemInput[] +} + +interface ProductFormData { + name: string + shortDescription: string + longDescription: string + regionId?: number | null + availableInAllRegions?: boolean + storeIdsByRegion?: Record + storeId: number + productType: 'item' | 'combo' + variants: Variant[] + /** True = one shared pricing set applies to every region. */ + matchForAll: boolean + /** Per-region per-variant market stats, keyed by region id, arrays aligned + * with variants by index. */ + regionStats: Record +} + +// One region's market-stats row for one variant. Numeric fields accept the +// raw TextInput strings; they are coerced on submit. +export interface VariantStats { + price?: number | string | null + marketPrice?: number | string | null + flashPrice?: number | string | null + isFlashAvailable: boolean + isOffer: boolean + isSuspended: boolean + isOutOfStock: boolean +} + +export interface ProductFormRef { + clearImages: () => void +} + +interface ProductFormProps { + mode: 'create' | 'edit' + initialValues: ProductFormData + onSubmit: (values: ProductFormData, variantImages: ImageUploaderNeoPayload[][], deletedImageKeys: string[]) => void + isLoading: boolean + existingVariantImages?: ImageUploaderNeoItem[][] + existingVariantImageKeys?: string[][] +} + +// Web rebuild of common-ui InfoDialog: info icon button + BottomDialog + p +function InfoDialog({ message, className }: { message?: string; className?: string }) { + const [open, setOpen] = useState(false) + return ( + <> + + setOpen(false)}> +
+

{message ?? ''}

+
+
+ + ) +} + +const defaultAttribute = (): Attribute => ({ featureName: '', featureValue: '' }) + +// The quantity feature is auto-added as the first attribute of every SKU. +const quantityAttribute = (): Attribute => ({ featureName: 'quantity', featureValue: '' }) + +const isQuantityFeature = (attr: Attribute): boolean => + (attr.featureName ?? '').trim().toLowerCase() === 'quantity' + +const defaultVariantStats = (): VariantStats => ({ + price: '', + marketPrice: '', + flashPrice: '', + isFlashAvailable: false, + isOffer: false, + isSuspended: false, + isOutOfStock: false, +}) + +const defaultVariant = (): Variant => ({ + id: undefined, + name: '', + price: undefined, + marketPrice: null, + isFlashAvailable: false, + flashPrice: null, + isOffer: false, + isComboOnly: false, + isDeleted: false, + isSuspended: false, + features: [quantityAttribute()], + comboItems: [], +}) + +const variantSignature = (attributes: Attribute[]): string => + attributes + .map((a) => `${(a.featureName ?? '').trim().toLowerCase()}::${a.featureValue.trim().toLowerCase()}`) + .sort() + .join('|') + +const makeProductValidationSchema = (regions: RegionOption[]) => + productValidationSchema.concat( + Yup.object().shape({ + storeIdsByRegion: Yup.mixed().test( + 'store-every-region', + 'Store is required for every region', + function (value: any) { + const map: Record = value ?? {} + const inScope = this.parent?.availableInAllRegions === true + ? regions + : regions.filter((r) => r.id === this.parent?.regionId) + for (const region of inScope) { + const storeId = map[region.id] + if (storeId == null || Number(storeId) < 1) { + return this.createError({ + message: `Create a store for "${region.name}" before saving`, + }) + } + } + return true + } + ), + regionStats: Yup.mixed().test( + 'region-stats', + 'Price is required', + function (value: any) { + const map: Record = value ?? {} + const variantCount = ((this.parent?.variants || []) as unknown[]).length + const inScope = this.parent?.availableInAllRegions === true + ? regions + : regions.filter((r) => r.id === this.parent?.regionId) + // When matched, only the primary tab is authoritative. + const primaryId = this.parent?.availableInAllRegions === true + ? regions[0]?.id + : this.parent?.regionId + const toCheck = this.parent?.matchForAll === true + ? inScope.filter((r) => r.id === primaryId) + : inScope + for (const region of toCheck) { + const entries = map[String(region.id)] || [] + for (let i = 0; i < variantCount; i++) { + const entry = entries[i] + const price = Number(entry?.price) + if (entry == null || entry.price === '' || entry.price == null || !Number.isFinite(price) || price <= 0) { + return this.createError({ + message: `Price is required for variant ${i + 1} in ${region.name}`, + }) + } + } + } + return true + } + ), + }) + ) + +const productValidationSchema = Yup.object().shape({ + name: Yup.string().required('Product name is required'), + regionId: Yup.number().when('availableInAllRegions', { + is: false, + then: (schema) => schema.required('Region is required').min(1, 'Region is required'), + otherwise: (schema) => schema.notRequired().nullable(), + }), + storeId: Yup.number().notRequired().nullable(), + productType: Yup.string().oneOf(['item', 'combo'], 'Product type is required').required('Product type is required'), + variants: Yup.array() + .min(1, 'At least one variant is required') + .of( + Yup.object().shape({ + features: Yup.array() + .min(1, 'At least one attribute is required') + .of( + Yup.object().shape({ + featureValue: Yup.string().required('Value is required'), + }) + ), + }) + ) + .test('unique-variants', 'Two variants have the same attributes', function (variants) { + if (!Array.isArray(variants)) return true + const seen = new Set() + for (const variant of variants) { + const attrs = variant?.features || [] + const signature = variantSignature(attrs as Attribute[]) + if (seen.has(signature)) { + return this.createError({ message: 'Two variants have the same attributes' }) + } + seen.add(signature) + } + return true + }) + .test('quantity-feature', 'Each SKU must have exactly one quantity feature', function (variants) { + if (!Array.isArray(variants)) return true + for (const variant of variants) { + const attrs = variant?.features || [] + const quantityCount = attrs.filter( + (a) => ((a as Attribute)?.featureName ?? '').trim().toLowerCase() === 'quantity' + ).length + if (quantityCount === 0) { + return this.createError({ message: 'Every SKU must have a quantity feature' }) + } + if (quantityCount > 1) { + return this.createError({ message: 'Each SKU can have only one quantity feature' }) + } + } + return true + }), +}) + +// Collect every string message from a Formik errors tree (objects, arrays, strings). +// Variant-level errors (e.g. 'Each SKU can have only one quantity feature') can get +// hidden by Formik when index-level errors are also present, so we walk everything. +const collectErrorMessages = (errors: unknown, depth = 0): string[] => { + if (depth > 6) return [] + if (typeof errors === 'string') return [errors] + if (Array.isArray(errors)) return errors.flatMap((e) => collectErrorMessages(e, depth + 1)) + if (errors && typeof errors === 'object') { + return Object.values(errors).flatMap((e) => collectErrorMessages(e, depth + 1)) + } + return [] +} + +type RegionStoreOption = { id: number; name: string; regionId?: number | null; availableInAllRegions?: boolean } +type RegionOption = { id: number; name: string } + +// On edit, an all-regions product has no per-region store payload from the API, +// so fill each region with the store whose name matches the current product store. +const RegionStorePrefill = ({ + stores, + regions, + currentStoreName, +}: { + stores: RegionStoreOption[] + regions: RegionOption[] + currentStoreName?: string +}) => { + const { values, setFieldValue } = useFormikContext() + useEffect(() => { + if (!values.availableInAllRegions || !currentStoreName) return + if (stores.length === 0 || regions.length === 0) return + const next: Record = { ...(values.storeIdsByRegion ?? {}) } + let changed = false + for (const region of regions) { + if (next[region.id] != null) continue + const match = stores.find((store) => (store.regionId === region.id || store.availableInAllRegions) && store.name === currentStoreName) + if (match) { + next[region.id] = match.id + changed = true + } + } + if (changed) setFieldValue('storeIdsByRegion', next) + }, [stores, regions, currentStoreName, values.availableInAllRegions, values.storeIdsByRegion, setFieldValue]) + return null +} + +type RegionTabContext = { + storesForRegion: (regionId: number) => { label: string; value: number }[] + regions: RegionOption[] + mode: 'create' | 'edit' +} + +// Pricing & availability, one tab per region. Each tab holds every variant's +// market-stats row plus that region's store. With match-for-all checked, edits +// propagate to every region; otherwise each tab is independent. +const RegionTabsSection = ({ storesForRegion, regions, mode }: RegionTabContext) => { + const { values, setFieldValue } = useFormikContext() + const [activeTab, setActiveTab] = useState(null) + + const applicableRegions = values.availableInAllRegions === true + ? regions + : regions.filter((r) => r.id === values.regionId) + const primaryRegionId = values.availableInAllRegions === true + ? regions[0]?.id ?? null + : (values.regionId as number | null | undefined) ?? null + + // Keep the active tab on a valid region as regions/mode resolve. + useEffect(() => { + if (applicableRegions.length === 0) { + if (activeTab !== null) setActiveTab(null) + return + } + if (activeTab == null || !applicableRegions.some((r) => r.id === activeTab)) { + setActiveTab(applicableRegions[0].id) + } + }, [applicableRegions, activeTab]) + + // Ensure every applicable region has a stats entry per variant (regions can + // resolve after the form initializes; variants can be added/removed). + useEffect(() => { + const variantCount = values.variants.length + let changed = false + const next: Record = { ...(values.regionStats ?? {}) } + for (const region of applicableRegions) { + const key = String(region.id) + const entries = [...(next[key] ?? [])] + while (entries.length < variantCount) { + // New rows mirror the primary tab while matched, else start blank. + const primary = next[String(primaryRegionId)]?.[entries.length] + entries.push(values.matchForAll && primary ? { ...primary } : defaultVariantStats()) + changed = true + } + if (entries.length !== (next[key] ?? []).length) { + next[key] = entries + } + } + if (changed) setFieldValue('regionStats', next) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [applicableRegions, values.variants.length, values.matchForAll]) + + const setStat = (regionId: number, vIndex: number, field: keyof VariantStats, value: unknown) => { + if (values.matchForAll) { + const next: Record = { ...(values.regionStats ?? {}) } + for (const region of applicableRegions) { + const key = String(region.id) + const entries = [...(next[key] ?? [])] + entries[vIndex] = { ...(entries[vIndex] ?? defaultVariantStats()), [field]: value } + next[key] = entries + } + setFieldValue('regionStats', next) + } else { + setFieldValue(`regionStats.${regionId}.${vIndex}.${field}`, value) + } + } + + const handleMatchToggle = () => { + const next = !values.matchForAll + setFieldValue('matchForAll', next) + if (next && activeTab != null) { + // Unify on the active tab's values. + const source = (values.regionStats ?? {})[String(activeTab)] ?? [] + const nextStats: Record = { ...(values.regionStats ?? {}) } + for (const region of applicableRegions) { + nextStats[String(region.id)] = values.variants.map((_, i) => ({ ...(source[i] ?? defaultVariantStats()) })) + } + setFieldValue('regionStats', nextStats) + } + } + + if (applicableRegions.length === 0) return null + const tab = applicableRegions.find((r) => r.id === activeTab) ?? applicableRegions[0] + const tabStores = storesForRegion(tab.id) + + return ( +
+

Pricing & availability

+ {applicableRegions.length > 1 && ( + + )} +
+ {applicableRegions.map((region) => ( + + ))} +
+
+
+

Store — {tab.name}

+ {tabStores.length === 0 && ( +

+ Create a store for "{tab.name}" before saving. +

+ )} + setFieldValue(`storeIdsByRegion.${tab.id}`, Number(value))} + className="w-full" + testID={`product-region-${tab.id}-store-dropdown`} + /> +
+ {values.variants.map((variant, vIndex) => { + const entry: VariantStats = (values.regionStats ?? {})[String(tab.id)]?.[vIndex] ?? defaultVariantStats() + const statsDisabled = values.matchForAll && applicableRegions.length > 1 && tab.id !== primaryRegionId + return ( +
+

+ Variant {vIndex + 1}{variant.name ? ` — ${variant.name}` : ''} +

+
+
+ setStat(tab.id, vIndex, 'marketPrice', e.target.value)} + disabled={statsDisabled} + /> +
+
+ setStat(tab.id, vIndex, 'price', e.target.value)} + disabled={statsDisabled} + /> +
+
+
+ { + setStat(tab.id, vIndex, 'isFlashAvailable', !entry.isFlashAvailable) + if (entry.isFlashAvailable) setStat(tab.id, vIndex, 'flashPrice', null) + }} + disabled={statsDisabled} + /> +

Flash Available

+
+
+ setStat(tab.id, vIndex, 'isOffer', !entry.isOffer)} + disabled={statsDisabled} + /> +

Offer SKU

+
+
+ setStat(tab.id, vIndex, 'isOutOfStock', !entry.isOutOfStock)} + disabled={statsDisabled} + /> +

Out of Stock

+
+ {mode === 'edit' && ( +
+ setStat(tab.id, vIndex, 'isSuspended', !entry.isSuspended)} + disabled={statsDisabled} + /> +

Suspend SKU

+
+ )} + {entry.isFlashAvailable && ( + setStat(tab.id, vIndex, 'flashPrice', e.target.value)} + disabled={statsDisabled} + style={{ marginBottom: 12 }} + /> + )} +
+ ) + })} +
+
+ ) +} + +const ProductForm = forwardRef(({ + mode, + initialValues, + onSubmit, + isLoading, + existingVariantImages = [], + existingVariantImageKeys = [], +}, ref) => { + const [variantImages, setVariantImages] = useState(() => + initialValues.variants.length > 0 + ? initialValues.variants.map((_, i) => existingVariantImages[i] || []) + : [[]] + ) + + useImperativeHandle(ref, () => ({ + clearImages: () => setVariantImages(initialValues.variants.map(() => [])), + }), [initialValues.variants]) + + // Superadmin scope is always super: the all-regions toggle is never locked here. + const allRegionsLocked = false + + const { data: storesData } = trpc.superadmin.store.getStores.useQuery() + const allStores: RegionStoreOption[] = useMemo( + () => (storesData?.stores || []) as RegionStoreOption[], + [storesData] + ) + const storeOptions = useMemo( + () => allStores.map((store) => ({ label: store.name, value: store.id })), + [allStores] + ) + + const { data: allRegionsStoresData } = trpc.superadmin.store.getStores.useQuery() + const allRegionsStores: RegionStoreOption[] = useMemo( + () => (allRegionsStoresData?.stores || []) as RegionStoreOption[], + [allRegionsStoresData] + ) + const storesForRegion = (regionId: number) => + allRegionsStores + .filter((store) => store.regionId === regionId || store.availableInAllRegions) + .map((store) => ({ label: store.name, value: store.id })) + + const { data: regionsData } = trpc.superadmin.region.getRegions.useQuery() + const regions: RegionOption[] = useMemo( + () => (regionsData?.regions || []).map((region) => ({ id: region.id, name: region.name })), + [regionsData] + ) + const validationSchema = useMemo(() => makeProductValidationSchema(regions), [regions]) + + const { data: skusData } = trpc.superadmin.product.getAllSkusSummary.useQuery() + const skuOptions = (skusData?.skus || []).map((sku) => ({ + label: sku.label, + value: sku.id, + })) + + // Make sure every SKU starts with a 'quantity' feature (auto-added at the + // beginning if the provided initial values don't have one). + const formInitialValues = useMemo(() => { + const variants = (initialValues.variants || []).map((v) => { + const hasQuantity = (v.features || []).some( + (a) => (a.featureName ?? '').trim().toLowerCase() === 'quantity' + ) + if (hasQuantity) return v + return { ...v, features: [quantityAttribute(), ...(v.features || [])] } + }) + const incoming = (initialValues as ProductFormData).regionStats ?? {} + const regionStats: Record = {} + for (const [rid, entries] of Object.entries(incoming)) { + regionStats[rid] = variants.map((_, i) => ({ ...defaultVariantStats(), ...(entries[i] ?? {}) })) + } + return { + ...initialValues, + matchForAll: (initialValues as ProductFormData).matchForAll ?? (mode === 'create'), + regionStats, + variants, + } + }, [initialValues, mode]) + + return ( + { + // Normalize feature names before sending to backend: the mandatory + // 'quantity' feature must always go out lowercase (case-insensitive + // matching means 'Quantity'/'QUANTITY' are treated the same), and + // names are trimmed like the backend does. + // TextInputs emit strings — coerce price fields to the numeric types + // the backend zod schema requires (price required; market/flash nullable). + const toNumber = (value: unknown): number | null => { + if (value == null || value === '') return null + const n = Number(value) + return Number.isFinite(n) ? n : null + } + const normalizedValues: ProductFormData = { + ...values, + variants: values.variants.map((v) => ({ + ...v, + price: toNumber(v.price) ?? undefined, + marketPrice: toNumber(v.marketPrice), + flashPrice: toNumber(v.flashPrice), + features: v.features.map((a) => ({ + ...a, + featureName: isQuantityFeature(a) ? 'quantity' : (a.featureName ?? '').trim() || null, + })), + })), + regionStats: Object.fromEntries( + Object.entries(values.regionStats ?? {}).map(([rid, entries]) => [ + rid, + entries.map((e) => ({ + ...e, + price: toNumber(e.price), + marketPrice: toNumber(e.marketPrice), + flashPrice: toNumber(e.flashPrice), + })), + ]) + ), + } + const images = variantImages.map((imgs) => + imgs.map((img) => ({ url: img.imgUrl, mimeType: img.mimeType })) + ) + const deletedKeys: string[] = [] + if (mode === 'edit') { + variantImages.forEach((currentImgs, vIndex) => { + const existing = existingVariantImages[vIndex] || [] + existing.forEach((existingImg) => { + if (!currentImgs.some((cur) => cur.imgUrl === existingImg.imgUrl)) { + const key = existingVariantImageKeys[vIndex]?.[existingVariantImages[vIndex]?.indexOf(existingImg)] + if (key) deletedKeys.push(key) + } + }) + }) + } + onSubmit(normalizedValues, images, deletedKeys) + }} + enableReinitialize + > + {({ 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 = {} + if (currentStoreName) { + for (const region of regions) { + const match = allStores.find( + (store) => (store.regionId === region.id || store.availableInAllRegions) && store.name === currentStoreName + ) + if (match) prefill[region.id] = match.id + } + } + setFieldValue('storeIdsByRegion', prefill) + } + } + return ( +
+ + + +
+ +

Available in all regions

+
+ + {!values.availableInAllRegions ? ( + <> +
+

Region

+ ({ label: region.name, value: region.id }))} + onValueChange={(value) => { + setFieldValue('regionId', Number(value)) + }} + className="w-full" + testID="product-region-dropdown" + /> +
+ + ) : null} + + + +
+

Product Type

+ setFieldValue('productType', value as 'item' | 'combo')} + className="w-full" + testID="product-type-dropdown" + /> +
+ + + {({ push, remove }) => ( +
+
+

Variants

+ +
+ + {values.variants.map((variant, vIndex) => { + const isExistingSku = variant.id != null + const isMarkedDeleted = !!variant.isDeleted + return ( +
+
+
+

Variant {vIndex + 1}

+ {isMarkedDeleted && ( +
+

Deleted

+
+ )} +
+ {(values.variants.length > 1 || isExistingSku) && ( + + )} +
+ + + + + {({ push: pushAttr, remove: removeAttr }) => ( +
+
+

Attributes

+ +
+ {variant.features.map((attr, aIndex) => { + const quantityCount = variant.features.filter(isQuantityFeature).length + // Quantity features are locked (non-editable), but if there + // are duplicates (e.g. 'quantity' + 'Quantity') the user must + // be able to delete the extras to fix the form. + const canDelete = variant.features.length > 1 && (!isQuantityFeature(attr) || quantityCount > 1) + return ( +
+
+ + setFieldValue( + `variants.${vIndex}.features.${aIndex}.featureName`, + e.target.value.trim().toLowerCase() === 'quantity' ? 'quantity' : e.target.value + ) + } + disabled={isQuantityFeature(attr)} + className={isQuantityFeature(attr) ? 'text-gray-400' : undefined} + /> +
+
+ +
+ {canDelete && ( + + )} +
+ ) + })} +
+ + +
+
+ )} +
+ +
+

+ Pricing, stock and flags are set per region below, under Pricing & availability. +

+
+ + {!(values.productType === 'combo' && (variant.comboItems?.length || 0) > 0) && ( +
+ setFieldValue(`variants.${vIndex}.isComboOnly`, !variant.isComboOnly)} + /> +

Combo Only SKU

+
+ )} + + + setVariantImages((prev) => { + const next = [...prev] + next[vIndex] = [...(next[vIndex] || []), ...payloads.map((pl) => ({ imgUrl: pl.url, mimeType: pl.mimeType }))] + return next + }) + } + onImageRemove={(payload) => + setVariantImages((prev) => { + const next = [...prev] + next[vIndex] = (next[vIndex] || []).filter((img) => img.imgUrl !== payload.url) + return next + }) + } + allowMultiple={true} + /> + + {values.productType === 'combo' && ( +
+
+

Included Items

+ +
+ {variant.comboItems?.map((ci, cIndex) => ( +
+
+ ({ + ...opt, + // Disable SKUs already picked in another row of this combo. + disabled: (variant.comboItems || []).some( + (item, idx) => idx !== cIndex && String(item.skuId) === String(opt.value) + ), + }))} + onValueChange={(val) => { + const current = variant.comboItems || [] + const isDuplicate = current.some( + (item, idx) => idx !== cIndex && String(item.skuId) === String(val) + ) + if (isDuplicate) { + window.alert('Duplicate: This product is already in the combo') + return + } + setFieldValue(`variants.${vIndex}.comboItems.${cIndex}.skuId`, Number(val)) + }} + placeholder="Select SKU" + /> +
+ +
+ ))} +
+ )} +
+ ) + })} + + +
+ )} +
+ + + + +
+ ) + }} +
+ ) +}) + +ProductForm.displayName = 'ProductForm' + +export default ProductForm diff --git a/apps/superadmin-ui/src/components/ProductsSelector.tsx b/apps/superadmin-ui/src/components/ProductsSelector.tsx new file mode 100644 index 0000000..cad7b88 --- /dev/null +++ b/apps/superadmin-ui/src/components/ProductsSelector.tsx @@ -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 + +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 ( +
+ {showGroups && groups.length > 0 && ( +
+ 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)" + /> +
+ )} + + {multiple ? ( + 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} + /> + ) : ( + { + onChange(Number(selectedValue)) + }} + placeholder={placeholder} + disabled={disabled} + error={error} + onSearch={setSearchQuery} + /> + )} +
+ ) +} diff --git a/apps/superadmin-ui/src/components/SearchableSelect.tsx b/apps/superadmin-ui/src/components/SearchableSelect.tsx new file mode 100644 index 0000000..ff73543 --- /dev/null +++ b/apps/superadmin-ui/src/components/SearchableSelect.tsx @@ -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 ( +
+

{label}

+ + setOpen(false)}> +
+

{label}

+ { + setQuery(q) + onSearch?.(q) + }} + onSearch={onSearch} + className="mb-3" + testID={testID ? `${testID}-search` : undefined} + /> +
+ {filtered.map((option) => { + const selected = String(option.value) === String(value) + return ( + + ) + })} + {filtered.length === 0 ? ( +

No options found

+ ) : null} +
+
+
+
+ ) +} + +export default SearchableSelect diff --git a/apps/superadmin-ui/src/components/StoreForm.tsx b/apps/superadmin-ui/src/components/StoreForm.tsx new file mode 100644 index 0000000..21c6f0b --- /dev/null +++ b/apps/superadmin-ui/src/components/StoreForm.tsx @@ -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 & { + 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(initialValues) + const [selectedImages, setSelectedImages] = useState<{ blob: Blob; mimeType: string }[]>([]) + const [displayImages, setDisplayImages] = useState<{ uri?: string }[]>([]) + const fileInputRef = useRef(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) => { + 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 ( + + {({ 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 ( +
+ + + +
+

Owner

+ setFieldValue('owner', Number(value))} + className="mb-4" + testID="store-owner-dropdown" + /> +
+
+ { + const next = !values.availableInAllRegions + setFieldValue('availableInAllRegions', next) + if (next) setFieldValue('regionId', null) + }} + testID="store-all-regions-checkbox" + /> +

Available in all regions

+
+ {!values.availableInAllRegions && ( +
+

Home Region

+ ({ label: r.name, value: r.id }))} + onValueChange={(value) => setFieldValue('regionId', Number(value))} + className="mb-4" + testID="store-region-dropdown" + /> +
+ )} + 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" + /> +
+

Store Image

+ + setFormInitialValues((prev) => ({ + ...prev, + imageUrl: undefined, + })) + } + allowMultiple={false} + /> +
+ +
+ ) + }} +
+ ) +} + +export default StoreForm diff --git a/apps/superadmin-ui/src/hooks/useUploadToObjectStorage.ts b/apps/superadmin-ui/src/hooks/useUploadToObjectStorage.ts new file mode 100644 index 0000000..685c3b5 --- /dev/null +++ b/apps/superadmin-ui/src/hooks/useUploadToObjectStorage.ts @@ -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(null) + const [progress, setProgress] = useState<{ completed: number; total: number } | null>(null) + + const generateUploadUrls = trpc.superadmin.upload.generateUploadUrls.useMutation() + + const upload = async (input: UploadBatchInput): Promise => { + 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 } diff --git a/apps/superadmin-ui/src/lib/auth-context.tsx b/apps/superadmin-ui/src/lib/auth-context.tsx index 50b96ec..fb65464 100644 --- a/apps/superadmin-ui/src/lib/auth-context.tsx +++ b/apps/superadmin-ui/src/lib/auth-context.tsx @@ -2,13 +2,13 @@ import React, { createContext, useContext, useState, useEffect, useCallback } fr import { trpc } from './trpc-client' import { useNavigate } from '@tanstack/react-router' -interface Staff { +interface Superadmin { id: number name: string } interface AuthState { - staff: Staff | null + staff: Superadmin | null isAuthenticated: boolean isLoading: boolean token: string | null @@ -32,7 +32,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { }) const [loginError, setLoginError] = useState(null) const navigate = useNavigate() - const loginMutation = trpc.admin.staffUser.login.useMutation() + const loginMutation = trpc.superadmin.auth.login.useMutation() useEffect(() => { const storedToken = localStorage.getItem('auth_token') @@ -55,7 +55,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { const data = await loginMutation.mutateAsync({ name, password }) localStorage.setItem('auth_token', data.token) setState({ - staff: data.staff, + staff: data.superadmin, token: data.token, isAuthenticated: true, isLoading: false, diff --git a/apps/superadmin-ui/src/routeTree.gen.ts b/apps/superadmin-ui/src/routeTree.gen.ts index 4b6662f..a95c92f 100644 --- a/apps/superadmin-ui/src/routeTree.gen.ts +++ b/apps/superadmin-ui/src/routeTree.gen.ts @@ -14,10 +14,18 @@ import { Route as AdminsRouteImport } from './routes/admins' import { Route as ConstantsRouteImport } from './routes/constants' import { Route as DashboardRouteImport } from './routes/dashboard' import { Route as LoginRouteImport } from './routes/login' +import { Route as ProductsRouteImport } from './routes/products' import { Route as RegionsRouteImport } from './routes/regions' 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 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 StoresIdEditRouteImport } from './routes/stores.$id.edit' const IndexRoute = IndexRouteImport.update({ id: '/', @@ -44,6 +52,11 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', + getParentRoute: () => rootRouteImport, +} as any) const RegionsRoute = RegionsRouteImport.update({ id: '/regions', path: '/regions', @@ -54,50 +67,109 @@ const SendNotificationsRoute = SendNotificationsRouteImport.update({ path: '/send-notifications', getParentRoute: () => rootRouteImport, } 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({ id: '/new', path: '/new', getParentRoute: () => RegionsRoute, } 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({ id: '/$id/edit', path: '/$id/edit', getParentRoute: () => RegionsRoute, } as any) +const StoresIdEditRoute = StoresIdEditRouteImport.update({ + id: '/$id/edit', + path: '/$id/edit', + getParentRoute: () => StoresRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/admins': typeof AdminsRoute + '/admins': typeof AdminsRouteWithChildren '/constants': typeof ConstantsRoute '/dashboard': typeof DashboardRoute '/login': typeof LoginRoute + '/products': typeof ProductsRouteWithChildren '/regions': typeof RegionsRouteWithChildren '/send-notifications': typeof SendNotificationsRoute + '/stores': typeof StoresRouteWithChildren + '/admins/new': typeof AdminsNewRoute + '/products/new': typeof ProductsNewRoute '/regions/new': typeof RegionsNewRoute + '/stores/new': typeof StoresNewRoute + '/admins/$id/edit': typeof AdminsIdEditRoute + '/products/$id/edit': typeof ProductsIdEditRoute '/regions/$id/edit': typeof RegionsIdEditRoute + '/stores/$id/edit': typeof StoresIdEditRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/admins': typeof AdminsRoute + '/admins': typeof AdminsRouteWithChildren '/constants': typeof ConstantsRoute '/dashboard': typeof DashboardRoute '/login': typeof LoginRoute + '/products': typeof ProductsRouteWithChildren '/regions': typeof RegionsRouteWithChildren '/send-notifications': typeof SendNotificationsRoute + '/stores': typeof StoresRouteWithChildren + '/admins/new': typeof AdminsNewRoute + '/products/new': typeof ProductsNewRoute '/regions/new': typeof RegionsNewRoute + '/stores/new': typeof StoresNewRoute + '/admins/$id/edit': typeof AdminsIdEditRoute + '/products/$id/edit': typeof ProductsIdEditRoute '/regions/$id/edit': typeof RegionsIdEditRoute + '/stores/$id/edit': typeof StoresIdEditRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute - '/admins': typeof AdminsRoute + '/admins': typeof AdminsRouteWithChildren '/constants': typeof ConstantsRoute '/dashboard': typeof DashboardRoute '/login': typeof LoginRoute + '/products': typeof ProductsRouteWithChildren '/regions': typeof RegionsRouteWithChildren '/send-notifications': typeof SendNotificationsRoute + '/stores': typeof StoresRouteWithChildren + '/admins/new': typeof AdminsNewRoute + '/products/new': typeof ProductsNewRoute '/regions/new': typeof RegionsNewRoute + '/stores/new': typeof StoresNewRoute + '/admins/$id/edit': typeof AdminsIdEditRoute + '/products/$id/edit': typeof ProductsIdEditRoute '/regions/$id/edit': typeof RegionsIdEditRoute + '/stores/$id/edit': typeof StoresIdEditRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath @@ -107,10 +179,18 @@ export interface FileRouteTypes { | '/constants' | '/dashboard' | '/login' + | '/products' | '/regions' | '/send-notifications' + | '/stores' + | '/admins/new' + | '/products/new' | '/regions/new' + | '/stores/new' + | '/admins/$id/edit' + | '/products/$id/edit' | '/regions/$id/edit' + | '/stores/$id/edit' fileRoutesByTo: FileRoutesByTo to: | '/' @@ -118,10 +198,18 @@ export interface FileRouteTypes { | '/constants' | '/dashboard' | '/login' + | '/products' | '/regions' | '/send-notifications' + | '/stores' + | '/admins/new' + | '/products/new' | '/regions/new' + | '/stores/new' + | '/admins/$id/edit' + | '/products/$id/edit' | '/regions/$id/edit' + | '/stores/$id/edit' id: | '__root__' | '/' @@ -129,20 +217,30 @@ export interface FileRouteTypes { | '/constants' | '/dashboard' | '/login' + | '/products' | '/regions' | '/send-notifications' + | '/stores' + | '/admins/new' + | '/products/new' | '/regions/new' + | '/stores/new' + | '/admins/$id/edit' + | '/products/$id/edit' | '/regions/$id/edit' + | '/stores/$id/edit' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute - AdminsRoute: typeof AdminsRoute + AdminsRoute: typeof AdminsRouteWithChildren ConstantsRoute: typeof ConstantsRoute DashboardRoute: typeof DashboardRoute LoginRoute: typeof LoginRoute + ProductsRoute: typeof ProductsRouteWithChildren RegionsRoute: typeof RegionsRouteWithChildren SendNotificationsRoute: typeof SendNotificationsRoute + StoresRoute: typeof StoresRouteWithChildren } declare module '@tanstack/react-router' { @@ -182,6 +280,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport + parentRoute: typeof rootRouteImport + } '/regions': { id: '/regions' path: '/regions' @@ -196,6 +301,27 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SendNotificationsRouteImport 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': { id: '/regions/new' path: '/new' @@ -203,6 +329,27 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RegionsNewRouteImport 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': { id: '/regions/$id/edit' path: '/$id/edit' @@ -210,9 +357,43 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RegionsIdEditRouteImport 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 { RegionsNewRoute: typeof RegionsNewRoute RegionsIdEditRoute: typeof RegionsIdEditRoute @@ -226,14 +407,29 @@ const RegionsRouteChildren: RegionsRouteChildren = { const RegionsRouteWithChildren = 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 = { IndexRoute: IndexRoute, - AdminsRoute: AdminsRoute, + AdminsRoute: AdminsRouteWithChildren, ConstantsRoute: ConstantsRoute, DashboardRoute: DashboardRoute, LoginRoute: LoginRoute, + ProductsRoute: ProductsRouteWithChildren, RegionsRoute: RegionsRouteWithChildren, SendNotificationsRoute: SendNotificationsRoute, + StoresRoute: StoresRouteWithChildren, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/apps/superadmin-ui/src/routes/admins.$id.edit.tsx b/apps/superadmin-ui/src/routes/admins.$id.edit.tsx new file mode 100644 index 0000000..fab153a --- /dev/null +++ b/apps/superadmin-ui/src/routes/admins.$id.edit.tsx @@ -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('') + const [regionId, setRegionId] = useState('') + 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 ( + + Loading admin... + + ) + } + + if (error || !member) { + return ( + + + {error ? 'Error loading admin' : 'Admin not found'} + + + ) + } + + return ( + +
+ + + Edit Admin + + Update {member.name}'s details. Leave the password blank to keep it unchanged. + + +
+ setName(e.target.value)} + /> +
+ +
+ setPassword(e.target.value)} + /> +
+ +
+ Role + +
+ +
+ Region + +
+ + + {updateStaffUser.isPending ? 'Saving...' : 'Save Changes'} + +
+
+ ) +} diff --git a/apps/superadmin-ui/src/routes/admins.new.tsx b/apps/superadmin-ui/src/routes/admins.new.tsx new file mode 100644 index 0000000..a7d5ab0 --- /dev/null +++ b/apps/superadmin-ui/src/routes/admins.new.tsx @@ -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('') + const [regionId, setRegionId] = useState('') + + 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 ( + +
+ + + Add Admin + + Create a staff user and assign them to a region. + + +
+ setName(e.target.value)} + /> +
+ +
+ setPassword(e.target.value)} + /> +
+ +
+ Role + +
+ +
+ Region + +
+ + + + {createStaffUser.isPending ? 'Creating...' : 'Create Admin'} + +
+
+ ) +} diff --git a/apps/superadmin-ui/src/routes/admins.tsx b/apps/superadmin-ui/src/routes/admins.tsx index 975f5fe..92beb6b 100644 --- a/apps/superadmin-ui/src/routes/admins.tsx +++ b/apps/superadmin-ui/src/routes/admins.tsx @@ -1,7 +1,6 @@ -import { useState } from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { UserPlus } from 'lucide-react' -import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components' +import { createFileRoute, Link, Outlet, useLocation, useNavigate } from '@tanstack/react-router' +import { Pencil, Plus, Trash2, UserCog } 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' @@ -10,132 +9,134 @@ export const Route = createFileRoute('/admins')({ component: () => ( - + ), }) -function CreateAdmin() { - const [name, setName] = useState('') - const [password, setPassword] = useState('') - const [roleId, setRoleId] = useState('') - const [regionId, setRegionId] = useState('') +// This route is the layout for /admins plus its children +// (/admins/new and /admins/$id/edit). Render the list only on the exact +// /admins path; otherwise hand off to the child route. +function Admins() { + const location = useLocation() - const { data: rolesData } = trpc.admin.staffUser.getRoles.useQuery() - const { data: regionsData } = trpc.admin.region.getRegions.useQuery() + if (location.pathname !== '/admins') { + return + } - const roles = rolesData?.roles ?? [] - const regions = regionsData?.regions ?? [] + return +} - const createStaffUser = trpc.admin.staffUser.createStaffUser.useMutation({ - onSuccess: (res) => { - window.alert('Success\n\nAdmin created successfully.') - setName('') - setPassword('') - setRoleId('') - setRegionId('') +function AdminsList() { + const navigate = useNavigate() + const utils = trpc.useUtils() + + const { data, isLoading, error, refetch } = trpc.superadmin.staffUser.getStaff.useQuery() + + const deleteStaffUser = trpc.superadmin.staffUser.deleteStaffUser.useMutation({ + onSuccess: () => { + void utils.superadmin.staffUser.getStaff.invalidate() }, 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 = () => { - 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), - }) + const staff = data?.staff ?? [] + + const handleDelete = (id: number, name: string) => { + if (!window.confirm(`Delete admin "${name}"? This cannot be undone.`)) return + deleteStaffUser.mutate({ id }) } return (
- Create Admin - - Create a staff user and assign them to a region. - - -
- setName(e.target.value)} - /> -
- -
- setPassword(e.target.value)} - /> -
- -
- Role - + + Add Admin +
-
- Region - -
+ {isLoading && ( + Loading admins... + )} - - - {createStaffUser.isPending ? 'Creating...' : 'Create Admin'} - + {error && ( +
+ Error loading admins + refetch()} + className="rounded-lg bg-blue-500 px-4 py-2 text-white" + > + Retry + +
+ )} + + {!isLoading && !error && staff.length === 0 && ( +
+ + No admins yet. + + Click "Add Admin" to create the first one. + +
+ )} + +
+ {staff.map((member) => ( +
+
+
+ +
+
+ + {member.name} + + + {member.roleName || 'No role'} · {member.regionName || 'No region'} + +
+
+ +
+ + + Edit + + +
+
+ ))} +
) diff --git a/apps/superadmin-ui/src/routes/constants.tsx b/apps/superadmin-ui/src/routes/constants.tsx index e8bdfe5..edee733 100644 --- a/apps/superadmin-ui/src/routes/constants.tsx +++ b/apps/superadmin-ui/src/routes/constants.tsx @@ -168,8 +168,8 @@ const ConstantInput: React.FC = ({ constantKey, value, setFi } function CustomizeApp() { - const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery() - const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation() + const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.superadmin.const.getConstants.useQuery() + const { mutate: updateConstants, isPending: isUpdating } = trpc.superadmin.const.updateConstants.useMutation() const handleSubmit = (values: ConstantFormData) => { const changedConstants = (constants || []) diff --git a/apps/superadmin-ui/src/routes/dashboard.tsx b/apps/superadmin-ui/src/routes/dashboard.tsx index 137b23f..31d670c 100644 --- a/apps/superadmin-ui/src/routes/dashboard.tsx +++ b/apps/superadmin-ui/src/routes/dashboard.tsx @@ -17,8 +17,8 @@ export const Route = createFileRoute('/dashboard')({ const CARDS = [ { to: '/admins', - title: 'Create Admin', - description: 'Create a staff user and assign them to a region.', + title: 'Admins', + description: 'View, create, edit and delete staff users.', icon: UserPlus, }, { diff --git a/apps/superadmin-ui/src/routes/products.$id.edit.tsx b/apps/superadmin-ui/src/routes/products.$id.edit.tsx new file mode 100644 index 0000000..1d2dfe6 --- /dev/null +++ b/apps/superadmin-ui/src/routes/products.$id.edit.tsx @@ -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(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, + storeId: 0, + productType: 'item' as const, + matchForAll: false, + regionStats: {} as Record, + 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 = {} + 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, + 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() + 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 = {} + 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 + ) + + 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 ( + +
+ Loading product... +
+
+ ) + } + + if (!productData) { + return ( + +
+ Product not found +
+
+ ) + } + + return ( + + + + ) +} diff --git a/apps/superadmin-ui/src/routes/products.new.tsx b/apps/superadmin-ui/src/routes/products.new.tsx new file mode 100644 index 0000000..ca13496 --- /dev/null +++ b/apps/superadmin-ui/src/routes/products.new.tsx @@ -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() + 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 + ) + + // 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 = {} + 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, + storeId: 1, + productType: 'item' as const, + matchForAll: true, + regionStats: {} as Record, + 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 ( + +
+ Add New Product + +
+
+ ) +} diff --git a/apps/superadmin-ui/src/routes/products.tsx b/apps/superadmin-ui/src/routes/products.tsx new file mode 100644 index 0000000..4b92bb4 --- /dev/null +++ b/apps/superadmin-ui/src/routes/products.tsx @@ -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: () => ( + + + + + + ), +}) + +// 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 + } + + return +} + +function ProductsList() { + const navigate = useNavigate() + const [activeTab, setActiveTab] = useState('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 ( + +
+
+
+ Products + + Products with no region serve all regions. + +
+ 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" + > + + Add Product + +
+ + {isLoading && ( + Loading products... + )} + + {error && ( +
+ Error loading products + refetch()} + className="rounded-lg bg-blue-500 px-4 py-2 text-white" + > + Retry + +
+ )} + + {!isLoading && !error && ( +
+ + {regions.map((region: any) => ( + + ))} +
+ )} + + {!isLoading && !error && visibleProducts.length === 0 && ( +
+ + + {activeTab === 'global' + ? 'No global products yet.' + : `No products in ${regions.find((r: any) => r.id === activeTab)?.name ?? 'this region'} yet.`} + +
+ )} + +
+ {visibleProducts.map((product: any) => ( +
+ + {product.name} + + + {product.availableInAllRegions + ? 'All regions' + : `Region #${product.regionId ?? '—'}`} + {' · '} + {(product.skus || []).length} variant{(product.skus || []).length === 1 ? '' : 's'} + +
+ + + Edit + +
+
+ ))} +
+
+
+ ) +} diff --git a/apps/superadmin-ui/src/routes/regions.$id.edit.tsx b/apps/superadmin-ui/src/routes/regions.$id.edit.tsx index 56c1db9..bcf9069 100644 --- a/apps/superadmin-ui/src/routes/regions.$id.edit.tsx +++ b/apps/superadmin-ui/src/routes/regions.$id.edit.tsx @@ -20,12 +20,12 @@ function EditRegion() { >([]) 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 }, { enabled: Number.isFinite(regionId) } ) - const updateRegion = trpc.admin.region.updateRegion.useMutation({ + const updateRegion = trpc.superadmin.region.updateRegion.useMutation({ onSuccess: () => { navigate({ to: '/regions' }) }, diff --git a/apps/superadmin-ui/src/routes/regions.new.tsx b/apps/superadmin-ui/src/routes/regions.new.tsx index f5823b0..cc6d3ed 100644 --- a/apps/superadmin-ui/src/routes/regions.new.tsx +++ b/apps/superadmin-ui/src/routes/regions.new.tsx @@ -19,7 +19,7 @@ function NewRegion() { { botToken: '', chatId: '' }, ]) - const createRegion = trpc.admin.region.createRegion.useMutation({ + const createRegion = trpc.superadmin.region.createRegion.useMutation({ onSuccess: () => { navigate({ to: '/regions' }) }, @@ -116,6 +116,7 @@ function NewRegion() {
@@ -166,12 +169,14 @@ function NewRegion() {
updateBound(index, 'name', e.target.value)} />
{ window.alert(`Success\n\n${response.message}`) setTitle('') diff --git a/apps/superadmin-ui/src/routes/stores.$id.edit.tsx b/apps/superadmin-ui/src/routes/stores.$id.edit.tsx new file mode 100644 index 0000000..334f929 --- /dev/null +++ b/apps/superadmin-ui/src/routes/stores.$id.edit.tsx @@ -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 ( + +
+ Loading store... +
+
+ ) + } + + const store = (storeData as any)?.store + if (!store) { + return ( + +
+ Store not found +
+
+ ) + } + + const initialValues: StoreFormData = { + name: store.name, + description: store.description || '', + owner: store.owner?.id ?? store.owner, + products: [], + regionId: store.regionId ?? null, + availableInAllRegions: !!store.availableInAllRegions, + } + + return ( + +
+ Edit Store + +
+
+ ) +} diff --git a/apps/superadmin-ui/src/routes/stores.new.tsx b/apps/superadmin-ui/src/routes/stores.new.tsx new file mode 100644 index 0000000..caf90fc --- /dev/null +++ b/apps/superadmin-ui/src/routes/stores.new.tsx @@ -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 ( + +
+ Add New Store + +
+
+ ) +} diff --git a/apps/superadmin-ui/src/routes/stores.tsx b/apps/superadmin-ui/src/routes/stores.tsx new file mode 100644 index 0000000..c8bee6d --- /dev/null +++ b/apps/superadmin-ui/src/routes/stores.tsx @@ -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: () => ( + + + + + + ), +}) + +// 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 + } + + return +} + +function StoresList() { + const navigate = useNavigate() + const [activeTab, setActiveTab] = useState('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 ( + +
+
+
+ Stores + + Stores with no home region serve all regions. + +
+ 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" + > + + Add Store + +
+ + {isLoading && ( + Loading stores... + )} + + {error && ( +
+ Error loading stores + refetch()} + className="rounded-lg bg-blue-500 px-4 py-2 text-white" + > + Retry + +
+ )} + + {!isLoading && !error && ( +
+ + {regions.map((region: any) => ( + + ))} +
+ )} + + {!isLoading && !error && visibleStores.length === 0 && ( +
+ + + {activeTab === 'global' + ? 'No global stores yet.' + : `No stores in ${regions.find((r: any) => r.id === activeTab)?.name ?? 'this region'} yet.`} + +
+ )} + +
+ {visibleStores.map((store: any) => ( +
+ + {store.name} + + + {store.availableInAllRegions ? 'All regions' : `Region #${store.regionId ?? '—'}`} + {' · '} + Owner: {store.owner?.name ?? `#${store.ownerId ?? store.owner}`} + +
+ + + Edit + +
+
+ ))} +
+
+
+ ) +} diff --git a/apps/test2.sqlite-shm b/apps/test2.sqlite-shm new file mode 100644 index 0000000000000000000000000000000000000000..fe9ac2845eca6fe6da8a63cd096d9cf9e24ece10 GIT binary patch literal 32768 zcmeIuAr62r3 = ({ children }) => { const [attempt, setAttempt] = useState(0); const passedRef = useRef(false); 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 () => { if (passedRef.current) return; + lastRunRef.current = Date.now(); setDetecting(true); - setDenied(false); - setServicesOff(false); - setDetectError(false); - setCoords(null); + if (!settledRef.current) { + setDenied(false); + setServicesOff(false); + setDetectError(false); + setCoords(null); + } try { const { status } = await Location.requestForegroundPermissionsAsync(); if (passedRef.current) return; @@ -48,7 +58,10 @@ const RegionGate: React.FC = ({ children }) => { } catch (error) { if (!passedRef.current) setDetectError(true); } finally { - if (!passedRef.current) setDetecting(false); + if (!passedRef.current) { + setDetecting(false); + settledRef.current = true; + } } }; @@ -57,11 +70,16 @@ const RegionGate: React.FC = ({ children }) => { // eslint-disable-next-line react-hooks/exhaustive-deps }, [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(() => { const sub = AppState.addEventListener('change', (next) => { if (appState.current.match(/inactive|background/) && next === 'active') { - setAttempt((a) => a + 1); + if (expectReturnRef.current || Date.now() - lastRunRef.current > 15000) { + setAttempt((a) => a + 1); + } + expectReturnRef.current = false; } appState.current = next; }); @@ -104,6 +122,7 @@ const RegionGate: React.FC = ({ children }) => { setAttempt((a) => a + 1); return; } + expectReturnRef.current = true; await Linking.openSettings(); }; @@ -112,7 +131,7 @@ const RegionGate: React.FC = ({ children }) => { return <>{children}; } - if (detecting || regionLoading || (!!coords && !resolved && !resolveFailed)) { + if ((detecting && !settledRef.current) || regionLoading || (!!coords && !resolved && !resolveFailed)) { return ( diff --git a/apps/user-ui/src/hooks/prominent-api-hooks.ts b/apps/user-ui/src/hooks/prominent-api-hooks.ts index e3d07d6..95820d6 100644 --- a/apps/user-ui/src/hooks/prominent-api-hooks.ts +++ b/apps/user-ui/src/hooks/prominent-api-hooks.ts @@ -98,7 +98,8 @@ export function buildProductsCacheUrl( return null } - return `${assetsDomain}${cachePathPrefix}${apiCacheKey}/v-${cacheVersion}/${filename}` + const url = `${assetsDomain}${apiCacheKey}/${cachePathPrefix}v-${cacheVersion}/${filename}` + return url } function useAvailabilityCacheUrl(): string | null { @@ -118,7 +119,8 @@ export function buildAvailabilityCacheUrl( 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 { @@ -138,7 +140,8 @@ export function buildSlotsCacheUrl( 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() { @@ -260,7 +263,7 @@ export function useStoreWithProducts(storeId: number) { const cachePathPrefix = essentialConsts?.cachePathPrefix ?? '' const cacheUrl = assetsDomain && apiCacheKey - ? `${assetsDomain}${cachePathPrefix}${apiCacheKey}/v-${cacheVersion}/stores/${storeId}.json` + ? `${assetsDomain}${apiCacheKey}/${cachePathPrefix}v-${cacheVersion}/stores/${storeId}.json` : null const version = cacheUrl ?? '' diff --git a/apps/web-ui/src/components/AddToCartDialog.tsx b/apps/web-ui/src/components/AddToCartDialog.tsx index 6e2c223..16b8501 100644 --- a/apps/web-ui/src/components/AddToCartDialog.tsx +++ b/apps/web-ui/src/components/AddToCartDialog.tsx @@ -73,7 +73,7 @@ export default function AddToCartDialog() { const availableSlots = availableSlotIds .map((slotId) => slotMap[slotId]) .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 isUpdate = (cartItem?.quantity || 0) >= 1 diff --git a/apps/web-ui/src/components/AddressForm.tsx b/apps/web-ui/src/components/AddressForm.tsx index da0b14d..5aafeb2 100644 --- a/apps/web-ui/src/components/AddressForm.tsx +++ b/apps/web-ui/src/components/AddressForm.tsx @@ -1,6 +1,7 @@ import React, { useState } from 'react' 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 * as Yup from 'yup' import type { AddressFormProps } from '@packages/shared' @@ -14,12 +15,22 @@ const validationSchema = Yup.object({ state: Yup.string().required('State is required'), pincode: Yup.string().required('Pincode is required').matches(/^\d{6}$/, 'Pincode must be 6 digits'), 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) { const [isSubmitting, setIsSubmitting] = useState(false) const [submitError, setSubmitError] = useState(null) 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>( initialValues?.latitude && initialValues?.longitude ? { latitude: initialValues.latitude, longitude: initialValues.longitude } @@ -36,6 +47,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false }: Addres pincode: initialValues?.pincode || '509001', isDefault: initialValues?.isDefault || false, googleMapsUrl: initialValues?.googleMapsUrl || '', + regionId: initialValues?.regionId ?? activeRegionId ?? '', }) const [errors, setErrors] = useState>({}) @@ -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 })) if (errors[field]) { setErrors((prev) => ({ ...prev, [field]: '' })) @@ -77,6 +89,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false }: Addres const payload = { ...values, + regionId: Number((values as { regionId?: unknown }).regionId), latitude: currentLocation?.latitude, longitude: currentLocation?.longitude, googleMapsUrl: values.googleMapsUrl || undefined, @@ -226,6 +239,17 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false }: Addres

Set as default address

+
+ handleChange('regionId', Number(value))} + testID="address-region-dropdown" + /> + {errors.regionId &&

{errors.regionId}

} +
+ +} + +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(null) + const [building, setBuilding] = useState(false) + const prevRef = useRef<{ id: number; regionId: number } | null>(null) + const dismissedRef = useRef(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 = {} + 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 ( + <> + + +
+

Deliver to {preview?.targetName}?

+

+ This address is in a different region. Your cart will change as follows: +

+
+ {preview?.lines.map((line, index) => ( +
+

+ {line.bigShift && line.outcome === 'moved' ? '⚠️ ' : ''} + {line.name} × {line.quantity} +

+ {line.outcome === 'moved' && ( +

+ 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)' : ''} +

+ )} + {line.outcome === 'removed' && ( +

Removed{line.reason ? ` — ${line.reason}` : ''}

+ )} +
+ ))} +
+
+ + +
+
+
+ + ) +} + +export default AddressRegionWatcher diff --git a/apps/web-ui/src/components/AppLayout.tsx b/apps/web-ui/src/components/AppLayout.tsx index b310dc3..f286ca0 100644 --- a/apps/web-ui/src/components/AppLayout.tsx +++ b/apps/web-ui/src/components/AppLayout.tsx @@ -2,6 +2,9 @@ import React from 'react' import { useLocation } from '@tanstack/react-router' import { BottomNavigation } from './BottomNavigation' import { FloatingCartBar } from './FloatingCartBar' +import { RegionGate } from './RegionGate' +import { RegionSwitchDialogs } from './RegionSwitchDialogs' +import { AddressRegionWatcher } from './AddressRegionWatcher' import { Sidebar } from './shell/Sidebar' import { Topbar } from './shell/Topbar' @@ -39,10 +42,17 @@ export function AppLayout({ const shouldShowCartBar = showCartBar && !shouldHideShell if (shouldHideShell) { - return
{children}
+ return ( +
+ {children} + + +
+ ) } return ( +
{/* Desktop rail */} @@ -61,5 +71,8 @@ export function AppLayout({ {/* Mobile bottom nav */}
+ + +
) } diff --git a/apps/web-ui/src/components/CheckoutAddressSelector.tsx b/apps/web-ui/src/components/CheckoutAddressSelector.tsx index 271b5b5..6f19699 100644 --- a/apps/web-ui/src/components/CheckoutAddressSelector.tsx +++ b/apps/web-ui/src/components/CheckoutAddressSelector.tsx @@ -69,9 +69,10 @@ export function CheckoutAddressSelector({ onAddressSelect, onAddAddress, onEditA
) : (
- {sortedAddresses.map((address: any) => ( + {sortedAddresses.map((address: any, index: number) => (
handleAddressSelect(address.id)} className={`relative cursor-pointer rounded-xl border-2 p-4 transition-all ${ selectedAddressId === address.id diff --git a/apps/web-ui/src/components/PaymentAndOrderComponent.tsx b/apps/web-ui/src/components/PaymentAndOrderComponent.tsx index ba4725a..50650ec 100644 --- a/apps/web-ui/src/components/PaymentAndOrderComponent.tsx +++ b/apps/web-ui/src/components/PaymentAndOrderComponent.tsx @@ -13,6 +13,12 @@ interface PaymentAndOrderProps { cartItems: any[] isFlashDelivery?: boolean 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({ @@ -20,6 +26,9 @@ export function PaymentAndOrderComponent({ cartItems, isFlashDelivery = false, onBack, + appliedCoupon = null, + couponId = null, + quotedDeliveryPrice, }: PaymentAndOrderProps) { const navigate = useNavigate() const queryClient = useQueryClient() @@ -42,13 +51,17 @@ export function PaymentAndOrderComponent({ return sum + price * item.quantity }, 0) + const couponDiscount = appliedCoupon?.amount || 0 + const discountedTotal = Math.max(0, totalPrice - couponDiscount) + const deliveryCharge = useMemo(() => { + if (quotedDeliveryPrice != null && !isNaN(quotedDeliveryPrice)) return quotedDeliveryPrice const threshold = isFlashDelivery ? constsData?.flashFreeDeliveryThreshold : constsData?.freeDeliveryThreshold const charge = isFlashDelivery ? constsData?.flashDeliveryCharge : constsData?.deliveryCharge - return totalPrice < threshold ? charge : 0 - }, [totalPrice, constsData, isFlashDelivery]) + return discountedTotal < threshold ? charge : 0 + }, [discountedTotal, constsData, isFlashDelivery, quotedDeliveryPrice]) - const finalTotalWithDelivery = totalPrice + deliveryCharge + const finalTotalWithDelivery = discountedTotal + deliveryCharge const placeOrderMutation = trpc.user.order.placeOrder.useMutation({ onSuccess: (data) => { @@ -93,6 +106,7 @@ export function PaymentAndOrderComponent({ })), addressId: selectedAddress, paymentMethod: paymentMethod, + couponId: couponId ?? undefined, userNotes: userNotes, isFlashDelivery: isFlashDelivery, } @@ -220,16 +234,24 @@ export function PaymentAndOrderComponent({ const threshold = isFlashDelivery ? constsData?.flashFreeDeliveryThreshold : constsData?.freeDeliveryThreshold - return threshold > 0 && totalPrice < threshold ? ( + return threshold > 0 && discountedTotal < threshold ? (

- Add products worth ₹{(threshold - totalPrice).toFixed(0)} for free delivery + Add products worth ₹{(threshold - discountedTotal).toFixed(0)} for free delivery

) : null })()} + {/* Applied Coupon */} + {appliedCoupon && ( +
+

Coupon Applied ({appliedCoupon.code})

+

-₹{couponDiscount.toFixed(2)}

+
+ )} + {/* Divider */}
@@ -281,7 +303,7 @@ export function PaymentAndOrderComponent({ {/* Bottom Action Bar */}
{!selectedAddress && ( -
+

Please select a delivery address to place order @@ -292,6 +314,7 @@ export function PaymentAndOrderComponent({ {imageUri && !imageError ? ( @@ -134,7 +137,7 @@ export function ProductCard({ */} {displayIsOutOfStock && ( -

+

Out of Stock

@@ -142,7 +145,7 @@ export function ProductCard({ )} {miniView && ( -
+
{quantity > 0 ? ( ) : (
{ e.stopPropagation() handleQuantityChange(1) }} > - +
)}
diff --git a/apps/web-ui/src/components/ProtectedRoute.tsx b/apps/web-ui/src/components/ProtectedRoute.tsx index 8022741..0bb5eb6 100644 --- a/apps/web-ui/src/components/ProtectedRoute.tsx +++ b/apps/web-ui/src/components/ProtectedRoute.tsx @@ -11,8 +11,10 @@ export function ProtectedRoute({ children }: { children: React.ReactNode }) { if (isLoading) return if (isAuthenticated) return - sessionStorage.setItem('auth_redirect', location.pathname) - navigate({ to: '/login', search: { redirect: location.pathname } }) + // Preserve full target (path + query) with a timestamp, like native AUTH_REDIRECT_KEY + const target = location.pathname + location.search + sessionStorage.setItem('auth_redirect', JSON.stringify({ target, at: Date.now() })) + navigate({ to: '/login', search: { redirect: target } }) }, [isAuthenticated, isLoading]) if (isLoading) { diff --git a/apps/web-ui/src/components/QuickDeliveryAddressSelector.tsx b/apps/web-ui/src/components/QuickDeliveryAddressSelector.tsx new file mode 100644 index 0000000..edfbf1f --- /dev/null +++ b/apps/web-ui/src/components/QuickDeliveryAddressSelector.tsx @@ -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 = ({ + 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 ( +
+ +

Delivery in within 1 hour

+
+ ) + } + + return ( + <> +
+ +
+ +
+
+ + setDialogOpen(false)}> +
+

Select Delivery Time

+ {slotOptions.map((slot: any) => ( + + ))} +
+
+ + ) +} + +export default QuickDeliveryAddressSelector diff --git a/apps/web-ui/src/components/RegionBar.tsx b/apps/web-ui/src/components/RegionBar.tsx new file mode 100644 index 0000000..2b02d86 --- /dev/null +++ b/apps/web-ui/src/components/RegionBar.tsx @@ -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 = ({ 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 ( +
+
+ + + +
+
+ ) +} + +export default RegionBar diff --git a/apps/web-ui/src/components/RegionGate.tsx b/apps/web-ui/src/components/RegionGate.tsx new file mode 100644 index 0000000..daa340e --- /dev/null +++ b/apps/web-ui/src/components/RegionGate.tsx @@ -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 ( +
+
+
+

Detecting your region…

+
+
+ ) + } + + 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 ( +
+
+

Unable to obtain location

+

{subheading}

+ + + {regionId != null && ( + + )} +
+
+ ) + } + } + + // 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 ( +
+
+

{pickerTitle}

+

{pickerMessage}

+ {regionsLoading ? ( +
+
+
+ ) : ( + regions.map((region: any) => ( + + )) + )} +
+
+ ) +} + +export default RegionGate diff --git a/apps/web-ui/src/components/RegionSwitchDialogs.tsx b/apps/web-ui/src/components/RegionSwitchDialogs.tsx new file mode 100644 index 0000000..0d32207 --- /dev/null +++ b/apps/web-ui/src/components/RegionSwitchDialogs.tsx @@ -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 ( + <> + + +
+

+ {results?.error ? 'Region switch failed' : `Cart updated for ${results?.regionName ?? ''}`} +

+ {results?.error ? ( +

{results.error}

+ ) : ( +
+ {results?.lines.length === 0 && ( +

Your cart is empty in this region.

+ )} + {(results?.lines ?? []).map((line, index) => ( +
+

+ {line.name} × {line.quantity} +

+ {line.outcome === 'kept' &&

No change

} + {line.outcome === 'moved' && ( +

+ 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.outcome === 'removed' && ( +

Removed{line.reason ? ` — ${line.reason}` : ''}

+ )} +
+ ))} +
+ )} + +
+
+ + ) +} + +export default RegionSwitchDialogs diff --git a/apps/web-ui/src/components/cart-page.tsx b/apps/web-ui/src/components/cart-page.tsx new file mode 100644 index 0000000..4efa4c6 --- /dev/null +++ b/apps/web-ui/src/components/cart-page.tsx @@ -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(null) + + if (groups.length === 0) return null + + return ( +
+
+

Delivery Slot

+
+ +
+ {groups.map((group, index) => ( +
0 ? 'border-t border-gray-100' : ''}`} + > +
+ +

{group.label}

+
+ +
+ ))} + + {!!mergeSuggestion && ( +
+
+

+ Deliver All items at {mergeSuggestion.label} +

+
+ +
+ )} +
+ + setOpenGroup(null)}> +
+
+
+

Items

+

{openGroup?.label}

+
+ +
+ + {openGroup?.items.map((item) => ( +
+ {item.image ? ( + + ) : ( +
+ )} +
+

{item.name}

+ {!!item.unitNotation &&

{item.unitNotation}

} +
+

x{item.quantity}

+
+ ))} +
+ +
+ ) +} + +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>({}) + 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() + 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>({}) + const [selectedCouponId, setSelectedCouponId] = useState(null) + const [couponDialogOpen, setCouponDialogOpen] = useState(false) + const [showAddAddress, setShowAddAddress] = useState(false) + const [regionPickOpen, setRegionPickOpen] = useState(false) + const [pendingRegionId, setPendingRegionId] = useState(null) + const [pendingAddresses, setPendingAddresses] = useState([]) + + 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(() => { + if (isFlashDelivery || cartItems.length === 0) return [] + const groupMap = new Map() + 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(() => { + 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 = {} + 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) + const next: Record = {} + 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 = {} + 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 ( +
+

Loading cart...

+
+ ) + } + + if (error) { + return ( +
+

Oops!

+

Failed to load your cart

+
+ ) + } + + return ( +
+
+
+ + {isFlashDelivery ? ( + + ) : ( + + )} +

+ {isFlashDelivery ? '1 Hr Delivery Cart' : 'Scheduled Delivery Cart'} +

+
+
+ +
+ {cartItems.length === 0 ? ( +
+
+ +
+

Your cart is empty

+

Looks like you haven't added anything to your cart yet.

+ +
+ ) : ( + <> +
+ {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 ( +
+
+
+ {product?.name + 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" + /> +

+ 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} +

+

+ {product?.productType !== 'combo' ? product?.unitNotation || '' : ''} +

+
+ { + 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} + /> +
+
+ + {!isFlashDelivery && ( +
+
+ + setSelectedSlots((prev) => ({ ...prev, [item.id]: Number(value) })) + } + /> + {productSlots.length === 0 && ( +

No delivery slots available

+ )} +
+
+

₹{itemPrice}

+ +
+
+ )} + + {isFlashDelivery && ( +
+
+

₹{itemPrice}

+ +
+
+ )} + + {!isAvailable && ( +
+

+ {productSlotInfo?.isOutOfStock + ? 'Out of Stock' + : isFlashDelivery && !flashEligibleProductIds.has(item.skuId) + ? 'Not available for flash delivery. Please remove' + : 'No delivery slots available'} +

+
+ )} +
+ {index < cartItems.length - 1 &&
} +
+ ) + })} +
+ + )} + + {cartItems.length > 0 && ( + + )} + + {hasAvailableItems && ( +
+
+
+ +
+

Offers & Coupons

+
+ ({ label: d.label, value: d.value }))} + value={selectedCouponId || ''} + onValueChange={(value) => setSelectedCouponId(value ? Number(value) : null)} + /> + {eligibleCoupons.length === 0 && ( +

No coupons available for this order

+ )} + {selectedCouponId && ( + + )} + {!isAuthenticated && ( + + )} + +
+ )} + + {!isFlashDelivery && cartItems.length > 0 && ( + + )} + + {isAuthenticated && ( +
+
+

Delivery Address

+ +
+
+ {selectedAddress ? ( +
+

+ {selectedAddress.name} • {selectedAddress.phone} +

+

+ {selectedAddress.addressLine1}, {selectedAddress.city} - {selectedAddress.pincode} +

+
+ ) : ( +

No address selected

+ )} + {addresses + .filter((a: any) => a.id !== selectedAddressId) + .slice(0, 3) + .map((address: any) => ( + + ))} +
+
+ )} + + {hasAvailableItems && ( +
+
+

Bill Details

+
+
+
+

Item Total

+

₹{Math.trunc(totalPrice)}

+
+ {totalSavings > 1 && ( +
+

Total Discount

+

₹{Math.trunc(totalSavings)}

+
+ )} + {discountAmount > 0 && ( +
+

Product Discount

+

-₹{Math.trunc(discountAmount)}

+
+ )} +
+

Delivery Fee

+

+ {deliveryCharge === 0 ? 'Free' : `₹${deliveryCharge}`} +

+
+ {deliveryCharge > 0 && (freeDeliveryThreshold || 0) > 0 && finalTotal < (freeDeliveryThreshold || 0) && ( +
+ +

+ Add products worth ₹{((freeDeliveryThreshold || 0) - finalTotal).toFixed(0)} for free delivery +

+
+ )} +
+
+

To Pay

+

₹{Math.trunc(finalTotalWithDelivery)}

+
+ {(discountAmount > 0 || deliveryCharge === 0 || totalSavings > 1) && ( +
+

+ You saved ₹ + {Math.trunc(discountAmount + totalSavings + (deliveryCharge === 0 ? (constsData as any)?.deliveryCharge || 0 : 0))} on + this order +

+
+ )} +
+
+
+ + +
+
+
+ )} +
+ + setCouponDialogOpen(false)}> +
+
+
+ +
+

Applied Coupons

+
+ {selectedCoupons.map((coupon) => ( +
+
+
+

{coupon.code}

+

{coupon.description}

+
+
+

+ {coupon.discountType === 'percentage' ? `${coupon.discountValue}% OFF` : `₹${coupon.discountValue} OFF`} +

+
+
+ {coupon.maxValue &&

Maximum discount up to ₹{coupon.maxValue}

} +
+ ))} + +
+
+ + setShowAddAddress(false)}> +
+ +
+
+ + setRegionPickOpen(false)}> +
+

+ {pendingRegionName ? `Addresses in ${pendingRegionName}` : 'Choose an address'} +

+

+ Your new address is in a different region. Pick one of its addresses to deliver to. +

+ {pendingAddresses.map((address: any) => ( + + ))} + +
+
+
+ ) +} + +export default CartPage diff --git a/apps/web-ui/src/contexts/RegionContext.tsx b/apps/web-ui/src/contexts/RegionContext.tsx new file mode 100644 index 0000000..b7e5cfc --- /dev/null +++ b/apps/web-ui/src/contexts/RegionContext.tsx @@ -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 +} + +const RegionContext = createContext(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 = ({ children }) => { + const [state, setState] = useState({ + 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 {children} +} + +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] + ) +} diff --git a/apps/web-ui/src/hooks/cart-query-hooks.ts b/apps/web-ui/src/hooks/cart-query-hooks.ts index 18c0fe5..9aa0baa 100644 --- a/apps/web-ui/src/hooks/cart-query-hooks.ts +++ b/apps/web-ui/src/hooks/cart-query-hooks.ts @@ -3,6 +3,8 @@ import type { CartData as SharedCartData } from '@packages/shared' type CartType = 'regular' | 'flash' +export type { CartType } + interface CartItem { id: number skuId: number @@ -13,6 +15,8 @@ interface CartItem { deliveryDate?: string | null } +export type LocalCartItem = CartItem + type CartData = SharedCartData function getCartKey(cartType: CartType): string { @@ -144,3 +148,46 @@ export function useRemoveFromCart(cartType: CartType = 'regular') { export function clearLocalCart(cartType: CartType = 'regular') { 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 => { + return readCart(cartType) +} + +export const saveLocalCart = async (items: LocalCartItem[], cartType: CartType = 'regular'): Promise => { + 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 => { + 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 => { + 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 diff --git a/apps/web-ui/src/hooks/prominent-api-hooks.ts b/apps/web-ui/src/hooks/prominent-api-hooks.ts index 446728d..2b95589 100644 --- a/apps/web-ui/src/hooks/prominent-api-hooks.ts +++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts @@ -2,6 +2,7 @@ import { useMemo, useEffect, useState } from 'react' import { useQuery } from '@tanstack/react-query' import axios from 'axios' import { trpc } from '../lib/trpc-client' +import { useRegion } from '../contexts/RegionContext' import type { ProductPriceFlags } from '@packages/shared' import type { AllProductsApiType, @@ -14,10 +15,48 @@ import type { } from '@backend/trpc/router' 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 = () => { - const query = trpc.common.essentialConsts.useQuery(undefined, { - refetchInterval: 60000, - }) + const { regionId, boundId } = useRegion() + const [initialData, setInitialData] = useState(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, + 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 } } @@ -91,53 +130,81 @@ type StoreWithProductsResponse = StoreWithProductsApiType type AvailabilityResponse = AvailabilityApiType type BaseProduct = AllProductsApiType['products'][number] -type AvailabilityEntry = AvailabilityApiType['availability'][number] +export type AvailabilityEntry = AvailabilityApiType['availability'][number] export type MergedProduct = BaseProduct & ProductPriceFlags -function useCacheUrl(filename: string): string | null { - const { data: essentialConsts } = useGetEssentialConsts() +/** Minimal consts surface needed to build CDN cache URLs (both the scaffold + * 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 apiCacheKey = essentialConsts?.apiCacheKey const cacheVersion = essentialConsts?.cacheVersion + const cachePathPrefix = essentialConsts?.cachePathPrefix ?? '' - if ( - !assetsDomain || - !apiCacheKey || - cacheVersion === undefined || - cacheVersion === null - ) { + if (!assetsDomain || !apiCacheKey || cacheVersion === undefined || cacheVersion === null) { return null } - return `${assetsDomain}${apiCacheKey}/v-${cacheVersion}/${filename}` + return `${assetsDomain}${apiCacheKey}/${cachePathPrefix}v-${cacheVersion}/${filename}` } -function useAvailabilityCacheUrl(): string | null { - const { data: essentialConsts } = useGetEssentialConsts() - +export function buildAvailabilityCacheUrl( + essentialConsts: CacheUrlConsts | null | undefined +): string | null { const assetsDomain = essentialConsts?.assetsDomain const availabilityVersionNum = essentialConsts?.availabilityVersionNum + const cachePathPrefix = essentialConsts?.cachePathPrefix ?? '' if (!assetsDomain || availabilityVersionNum === undefined || availabilityVersionNum === null) { return null } - return `${assetsDomain}av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}` + return `${assetsDomain}${cachePathPrefix}av-${availabilityVersionNum}/${CACHE_FILENAMES.availability}` } -function useSlotsCacheUrl(): string | null { - const { data: essentialConsts } = useGetEssentialConsts() - +export function buildSlotsCacheUrl( + essentialConsts: CacheUrlConsts | null | undefined +): string | null { const assetsDomain = essentialConsts?.assetsDomain const slotsVersionNum = essentialConsts?.slotsVersionNum + const cachePathPrefix = essentialConsts?.cachePathPrefix ?? '' if (!assetsDomain || slotsVersionNum === undefined || slotsVersionNum === 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() { @@ -289,10 +356,11 @@ export function useStoreWithProducts(storeId: number) { const assetsDomain = essentialConsts?.assetsDomain const apiCacheKey = essentialConsts?.apiCacheKey const cacheVersion = essentialConsts?.cacheVersion + const cachePathPrefix = essentialConsts?.cachePathPrefix ?? '' const cacheUrl = assetsDomain && apiCacheKey - ? `${assetsDomain}${apiCacheKey}/v-${cacheVersion}/stores/${storeId}.json` + ? `${assetsDomain}${apiCacheKey}/${cachePathPrefix}v-${cacheVersion}/stores/${storeId}.json` : null const version = cacheUrl ?? '' const { initialData, isReady } = usePersistedCache(CACHE_STORAGE_KEYS.storeProducts(storeId), version) diff --git a/apps/web-ui/src/hooks/useRegionSwitch.tsx b/apps/web-ui/src/hooks/useRegionSwitch.tsx new file mode 100644 index 0000000..de97ae3 --- /dev/null +++ b/apps/web-ui/src/hooks/useRegionSwitch.tsx @@ -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 + +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, + names: Record, + now: Date = new Date() +): { lines: LocalCartItem[]; results: Omit[] } { + const lines: LocalCartItem[] = [] + const results: Omit[] = [] + + 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 + +/** 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(slotsUrl), + axios.get<{ availability: AvailabilityEntry[] }>(availabilityUrl), + ]) + const slots = slotsRes.data.slots ?? [] + const availability = availabilityRes.data.availability ?? [] + const availabilityById: Record = {} + 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; oldSlotTimes: Record } { + const names: Record = {} + for (const [key, product] of Object.entries(useCentralProductStore.getState().productsById)) { + names[Number(key)] = (product as { name?: string })?.name ?? `Item ${key}` + } + const oldSlotTimes: Record = {} + 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(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 + isSwitching: boolean + switchMessage: string + results: RegionSwitchResults | null + clearResults: () => void + presentResults: (next: RegionSwitchResults) => void +} + +const RegionSwitchContext = createContext(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 {children} +} + +export const useRegionSwitchContext = (): RegionSwitchContextValue => { + const context = useContext(RegionSwitchContext) + if (context === undefined) { + throw new Error('useRegionSwitchContext must be used within a RegionSwitchProvider') + } + return context +} diff --git a/apps/web-ui/src/lib/auth-context.tsx b/apps/web-ui/src/lib/auth-context.tsx index b0ed0d7..889fc31 100644 --- a/apps/web-ui/src/lib/auth-context.tsx +++ b/apps/web-ui/src/lib/auth-context.tsx @@ -1,6 +1,7 @@ import React, { createContext, useContext, useState, useEffect, useCallback } from 'react' import { trpc } from './trpc-client' import { useNavigate } from '@tanstack/react-router' +import { useQueryClient } from '@tanstack/react-query' import type { User as SharedUser, AuthStateCore } from '@packages/shared' // 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, }) const navigate = useNavigate() + const queryClient = useQueryClient() // On mount, check for stored token useEffect(() => { @@ -51,10 +53,12 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { } }, []) - // Fetch user data when token is available - const { data: selfData } = trpc.user.user.getSelfData.useQuery(undefined, { + // Fetch user data when token is available (mirrors native: no retry, fresh on mount) + const { data: selfData, isError: selfError } = trpc.user.user.getSelfData.useQuery(undefined, { enabled: !!state.token && state.isAuthenticated, - retry: 1, + retry: false, + staleTime: 0, + refetchOnMount: true, }) useEffect(() => { @@ -65,10 +69,20 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { userDetails: selfData.data.user, isLoading: false, })) - } else if (selfData === undefined && state.token) { - // Token might be invalid + } else if (selfError && state.token) { + // 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) => { localStorage.setItem('auth_token', token) @@ -93,6 +107,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { const logout = useCallback(() => { localStorage.removeItem('auth_token') localStorage.removeItem('user_id') + queryClient.clear() setState({ user: null, userDetails: null, @@ -101,7 +116,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { token: null, }) navigate({ to: '/login' }) - }, [navigate]) + }, [navigate, queryClient]) const updateUser = useCallback((user: User) => { setState((prev) => ({ ...prev, user })) diff --git a/apps/web-ui/src/routes/__root.tsx b/apps/web-ui/src/routes/__root.tsx index d19532a..9ed42e5 100644 --- a/apps/web-ui/src/routes/__root.tsx +++ b/apps/web-ui/src/routes/__root.tsx @@ -6,6 +6,8 @@ import { ReactQueryDevtools } from '@tanstack/react-query-devtools' import { trpc, getTrpcClient } from '../lib/trpc-client' import { getQueryClient } from '../lib/query-client' import { AuthProvider } from '../lib/auth-context' +import { RegionProvider } from '../contexts/RegionContext' +import { RegionSwitchProvider } from '../hooks/useRegionSwitch' import appCss from '../styles.css?url' const queryClient = getQueryClient() @@ -38,10 +40,14 @@ function RootDocument({ children }: { children: React.ReactNode }) { - -
{children}
- -
+ + + +
{children}
+ +
+
+
= {} - 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 - } - }) +export const Route = createFileRoute('/cart')({ component: GenericCartRoute }) +function GenericCartRoute() { return ( -
-
-

- Review Before Delivery -

-

Your Cart

-
- - {cartItems.length === 0 ? ( -
-
- -
-

Your cart is empty

-

Fresh cuts are waiting at the counter

- -
- ) : ( -
- {/* Items */} -
- {cartItems.map((item) => { - const product = productsById[item.skuId] - const price = product.price - return ( -
- {product.name} -
-

{product.name}

-

- {product.unitNotation || ''} per unit -

-
- updateItem.mutate({ skuId: item.skuId, quantity: q })} - /> -

₹{price}

-
-
-
-

₹{price * item.quantity}

- -
-
- ) - })} -
- - {/* Coupons card */} -
-
-
- -
-

Offers & Coupons

-
- -
- - {/* Summary */} -
-
-

Bill Summary

-
-
-

Item Total

-

₹{total}

-
-
-

Delivery Fee

-

Calculated at checkout

-
-
-
-

Total

-

₹{total}

-
- - -
-
-
- )} -
+
) } diff --git a/apps/web-ui/src/routes/flash.cart.tsx b/apps/web-ui/src/routes/flash.cart.tsx index b17ea59..4b35636 100644 --- a/apps/web-ui/src/routes/flash.cart.tsx +++ b/apps/web-ui/src/routes/flash.cart.tsx @@ -1,136 +1,13 @@ -import { createFileRoute, useNavigate } 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 { createFileRoute } from '@tanstack/react-router' 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 }) - -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 - } - }) +export const Route = createFileRoute('/flash/cart')({ component: FlashCartRoute }) +function FlashCartRoute() { return ( - -
-
-

- 1 Hr Delivery -

-

- - Flash Cart -

-
- - {cartItems.length === 0 ? ( -
-
- -
-

Your flash cart is empty

-

Pick something from 1 hr delivery

- -
- ) : ( -
- {/* Items */} -
- {cartItems.map((item) => { - const product = productsById[item.skuId] - const price = product.price - return ( -
- {product.name} -
-

{product.name}

-

- {product.unitNotation || ''} per unit -

-
- updateItem.mutate({ skuId: item.skuId, quantity: q })} - /> -

₹{price}

-
-
-
-

₹{price * item.quantity}

- -
-
- ) - })} -
- - {/* Summary */} -
-
-

Bill Summary

-
-
-

Item Total

-

₹{total}

-
-
-

Delivery Fee

-

Calculated at checkout

-
-
-
-

Total

-

₹{total}

-
- - -
-
-
- )} -
+ + ) } diff --git a/apps/web-ui/src/routes/flash.checkout.tsx b/apps/web-ui/src/routes/flash.checkout.tsx index 30f6591..7e98032 100644 --- a/apps/web-ui/src/routes/flash.checkout.tsx +++ b/apps/web-ui/src/routes/flash.checkout.tsx @@ -1,132 +1,162 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router' -import { useState } from 'react' +import { useState, useMemo, useEffect } from 'react' import { useAuth } from '../lib/auth-context' import { useGetCart } from '../hooks/cart-query-hooks' import { useCentralProductStore } from '../lib/stores/central-product-store' +import { useCentralSlotStore } from '../lib/stores/central-slot-store' import { trpc } from '../lib/trpc-client' -import { clearLocalCart } from '../hooks/cart-query-hooks' -import { p, MyButton, LoadingDialog, AppContainer } from 'web-components' -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 { 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): { 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() { - const navigate = useNavigate() - const queryClient = useQueryClient() - const { isAuthenticated } = useAuth() - const { data: cart } = useGetCart('flash') - const productsById = useCentralProductStore((s) => s.productsById) - const [isLoading, setIsLoading] = useState(false) + return ( + + + + ) +} - 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(null) + + const cartItems = cartData?.items || [] + + const flashEligibleProductIds = useMemo(() => { + if (!products.length) return new Set() + 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 = {} + 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, }) - const [selectedAddressId, setSelectedAddressId] = useState(null) - const placeOrderMutation = trpc.user.order.placeOrder.useMutation({ - onSuccess: (data) => { - const order = data.data?.[0] - 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 totalPrice = selectedItems + .filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock) + .reduce((sum, item) => { + const product = productsById[item.skuId] + return sum + (product?.flashPrice ?? product?.price ?? 0) * item.quantity + }, 0) - const cartItems = (cart?.items || []).filter((item) => productsById[item.skuId]) + const appliedCoupon = useMemo(() => { + if (!selectedCouponId || !(couponsRaw as any)?.data) return null + const coupon = ((couponsRaw as any).data as any[]).find((c) => c.id === selectedCouponId) + if (!coupon) return null + if (coupon.maxLimitForUser && coupon.usages.length >= coupon.maxLimitForUser) return null + if (coupon.minOrder && parseFloat(coupon.minOrder) > totalPrice) return null + const amount = coupon.discountPercent + ? 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) + return { code: coupon.couponCode, amount } + }, [selectedCouponId, couponsRaw, totalPrice]) - let total = 0 - cartItems.forEach((item) => { - const product = productsById[item.skuId] - if (product) { - total += product.price * item.quantity - } - }) + const quoteDeliveryPrice = deliveryPrice != null && !isNaN(Number(deliveryPrice)) ? Number(deliveryPrice) : undefined - const handlePlaceOrder = () => { - if (!selectedAddressId) return - setIsLoading(true) - placeOrderMutation.mutate({ - selectedItems: cartItems.map((item) => ({ - skuId: item.skuId, - quantity: item.quantity, - slotId: null, - })), - addressId: selectedAddressId, - paymentMethod: 'cod', - isFlashDelivery: true, - }) + if (selectedItems.length === 0) { + return ( + +
+
+ +
+

+ {cartItems.length === 0 ? 'Your cart is empty' : 'No items to checkout'} +

+

+ {cartItems.length === 0 + ? 'Add some delicious items to your cart before checking out' + : "None of your cart items are available for flash delivery"} +

+ +
+
+ ) } return ( - -

- Flash Checkout -

- -
-

- Delivery Address -

- {addresses?.data?.map((addr: any) => ( +
+
+
- ))} -
- -
-

- Order Summary -

- {cartItems.map((item) => { - const product = productsById[item.skuId] - if (!product) return null - return ( -
-

- {product.name} x{item.quantity} -

-

- ₹{product.price * item.quantity} -

-
- ) - })} -
-
-

Total

-

- ₹{total} -

-
+

1 Hr Delivery Checkout

- - - - +
+
+ +
+
+ navigate({ to: '/flash/cart' })} + /> +
+
+
) } diff --git a/apps/web-ui/src/routes/flash.order-success.tsx b/apps/web-ui/src/routes/flash.order-success.tsx index db256c2..bd2ce5d 100644 --- a/apps/web-ui/src/routes/flash.order-success.tsx +++ b/apps/web-ui/src/routes/flash.order-success.tsx @@ -1,5 +1,6 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router' import { Zap } from 'lucide-react' +import { NextOrderGlimpse } from '../components/me/NextOrderGlimpse' export const Route = createFileRoute('/flash/order-success')({ component: FlashOrderSuccessPage, @@ -35,6 +36,10 @@ function FlashOrderSuccessPage() { > View My Orders + {/* Upcoming-order glimpse (matches user-ui order-success flow) */} +
+ +
) } diff --git a/apps/web-ui/src/routes/home.cart.tsx b/apps/web-ui/src/routes/home.cart.tsx index a4bab77..03a7c13 100644 --- a/apps/web-ui/src/routes/home.cart.tsx +++ b/apps/web-ui/src/routes/home.cart.tsx @@ -1,137 +1,13 @@ -import { createFileRoute, useNavigate } 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 { createFileRoute } from '@tanstack/react-router' 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 }) - -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 = {} - 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 - } - }) +export const Route = createFileRoute('/home/cart')({ component: HomeCartRoute }) +function HomeCartRoute() { return ( -
-
-

- Review Before Delivery -

-

Your Cart

-
- - {cartItems.length === 0 ? ( -
-
- -
-

Your cart is empty

-

Fresh cuts are waiting at the counter

- -
- ) : ( -
- {/* Items */} -
- {cartItems.map((item) => { - const product = productsById[item.skuId] - const price = product.price - return ( -
- {product.name} -
-

{product.name}

-

- {product.unitNotation || ''} per unit -

-
- updateItem.mutate({ skuId: item.skuId, quantity: q })} - /> -

₹{price}

-
-
-
-

₹{price * item.quantity}

- -
-
- ) - })} -
- - {/* Summary */} -
-
-

Bill Summary

-
-
-

Item Total

-

₹{total}

-
-
-

Delivery Fee

-

Calculated at checkout

-
-
-
-

Total

-

₹{total}

-
- - -
-
-
- )} -
+
) } diff --git a/apps/web-ui/src/routes/home.checkout.tsx b/apps/web-ui/src/routes/home.checkout.tsx index 488d469..e428dc9 100644 --- a/apps/web-ui/src/routes/home.checkout.tsx +++ b/apps/web-ui/src/routes/home.checkout.tsx @@ -1,134 +1,157 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router' -import { useState } from 'react' +import { useState, useMemo, useEffect } from 'react' import { useAuth } from '../lib/auth-context' import { useGetCart } from '../hooks/cart-query-hooks' import { useCentralProductStore } from '../lib/stores/central-product-store' +import { useCentralSlotStore } from '../lib/stores/central-slot-store' import { trpc } from '../lib/trpc-client' -import { clearLocalCart } from '../hooks/cart-query-hooks' import { p, MyButton, LoadingDialog, AppContainer, div } from 'web-components' 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): { 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() { - const navigate = useNavigate() - const queryClient = useQueryClient() - const { isAuthenticated } = useAuth() - const { data: cart } = useGetCart('regular') - const productsById = useCentralProductStore((s) => s.productsById) - const [isLoading, setIsLoading] = useState(false) + return ( + + + + ) +} - 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(null) + + const cartItems = cartData?.items || [] + + // Parse slots parameter from URL (format: "1:1,2,3;2:4,5") + const selectedSlots = useMemo(() => { + const parsed: Record = {} + 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, }) - const [selectedAddressId, setSelectedAddressId] = useState(null) - const placeOrderMutation = trpc.user.order.placeOrder.useMutation({ - onSuccess: (data) => { - const order = data.data?.[0] - 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 totalPrice = selectedItems + .filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock) + .reduce((sum, item) => { + const product = productsById[item.skuId] + return sum + (product?.price || 0) * item.quantity + }, 0) - const cartItems = (cart?.items || []).filter((item) => productsById[item.skuId]) + const appliedCoupon = useMemo(() => { + if (!selectedCouponId || !(couponsRaw as any)?.data) return null + const coupon = ((couponsRaw as any).data as any[]).find((c) => c.id === selectedCouponId) + if (!coupon) return null + if (coupon.maxLimitForUser && coupon.usages.length >= coupon.maxLimitForUser) return null + if (coupon.minOrder && parseFloat(coupon.minOrder) > totalPrice) return null + const amount = coupon.discountPercent + ? 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) + return { code: coupon.couponCode, amount } + }, [selectedCouponId, couponsRaw, totalPrice]) - let total = 0 - cartItems.forEach((item) => { - const product = productsById[item.skuId] - if (product) { - total += product.price * item.quantity - } - }) + const quoteDeliveryPrice = deliveryPrice != null && !isNaN(Number(deliveryPrice)) ? Number(deliveryPrice) : undefined - const handlePlaceOrder = () => { - if (!selectedAddressId) return - setIsLoading(true) - placeOrderMutation.mutate({ - selectedItems: cartItems.map((item) => ({ - skuId: item.skuId, - quantity: item.quantity, - slotId: null, - })), - addressId: selectedAddressId, - paymentMethod: 'cod', - isFlashDelivery: false, - }) + if (selectedItems.length === 0) { + return ( + +
+
+ +
+

+ {cartItems.length === 0 ? 'Your cart is empty' : 'No items to checkout'} +

+

+ {cartItems.length === 0 + ? 'Add some delicious items to your cart before checking out' + : 'Please select delivery slots for your items'} +

+ +
+
+ ) } return ( - -

- Checkout -

- - {/* Address Selection */} -
-

- Delivery Address -

- {addresses?.data?.map((addr: any) => ( -
setSelectedAddressId(addr.id)} - className={`mb-2 rounded-xl border p-3 ${ - selectedAddressId === addr.id - ? 'border-brand-500 bg-brand-50' - : 'border-gray-200' - }`} +
+
+
+
- ))} -
- - {/* Order Summary */} -
-

- Order Summary -

- {cartItems.map((item) => { - const product = productsById[item.skuId] - if (!product) return null - return ( -
-

- {product.name} x{item.quantity} -

-

- ₹{product.price * item.quantity} -

-
- ) - })} -
-
-

Total

-

- ₹{total} -

-
+ + +

Scheduled Delivery Checkout

- - - - +
+
+ +
+
+ navigate({ to: '/home/cart' })} + /> +
+
+
) } diff --git a/apps/web-ui/src/routes/home.index.tsx b/apps/web-ui/src/routes/home.index.tsx index 6391ac6..57f925e 100644 --- a/apps/web-ui/src/routes/home.index.tsx +++ b/apps/web-ui/src/routes/home.index.tsx @@ -13,6 +13,8 @@ import { useCentralSlotStore } from '../lib/stores/central-slot-store' import { AppLayout } from '../components/AppLayout' import { ProductCard } from '../components/ProductCard' import AddToCartDialog from '../components/AddToCartDialog' +import { NextOrderGlimpse } from '../components/me/NextOrderGlimpse' +import { RegionBar } from '../components/RegionBar' import { useProductSlotIdentifier } from '../hooks/useProductSlotIdentifier' import { usePopulateCentralStores } from '../hooks/usePopulateCentralStores' import { Store, ImageOff, Loader2, Clock, Truck } from 'lucide-react' @@ -97,6 +99,14 @@ function HomePage() { // Refs for scrollable sections const slotsScrollRef = useRef(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 usePopulateCentralStores() @@ -104,6 +114,8 @@ function HomePage() { // const banners = bannersData?.banners || [] const allProducts = productsData?.products || [] 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 const dashboardTags = productsData?.tags || [] @@ -143,7 +155,7 @@ function HomePage() { const rest: any[] = [] for (const id of orderedIds) { 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) else ordered.push(product) } @@ -155,8 +167,8 @@ function HomePage() { .sort((a: any, b: any) => { const slotA = getQuickestSlot(a.id) const slotB = getQuickestSlot(b.id) - const aOutOfStock = Boolean(productSlotsMap[a.id]?.isOutOfStock) || !slotA - const bOutOfStock = Boolean(productSlotsMap[b.id]?.isOutOfStock) || !slotB + const aOutOfStock = Boolean(productSlotsMap[a.id]?.isOutOfStock) || (slotsReady && !slotA) + const bOutOfStock = Boolean(productSlotsMap[b.id]?.isOutOfStock) || (slotsReady && !slotB) if (aOutOfStock && !bOutOfStock) return 1 if (!aOutOfStock && bOutOfStock) return -1 return 0 @@ -165,7 +177,7 @@ function HomePage() { map[tag.id] = [...ordered, ...rest, ...extra] } return map - }, [dashboardTags, allProducts, getQuickestSlot, productSlotsMap]) + }, [dashboardTags, allProducts, getQuickestSlot, productSlotsMap, slotsReady]) const activeTagProducts = activeTagId != null ? (productsByTagId[activeTagId] || []) : [] @@ -177,14 +189,14 @@ function HomePage() { const slotA = getQuickestSlot(a.id) const slotB = getQuickestSlot(b.id) - const aOutOfStock = Boolean(productSlotsMap[a.id]?.isOutOfStock) || !slotA - const bOutOfStock = Boolean(productSlotsMap[b.id]?.isOutOfStock) || !slotB + const aOutOfStock = Boolean(productSlotsMap[a.id]?.isOutOfStock) || (slotsReady && !slotA) + const bOutOfStock = Boolean(productSlotsMap[b.id]?.isOutOfStock) || (slotsReady && !slotB) if (aOutOfStock && !bOutOfStock) return 1 if (!aOutOfStock && bOutOfStock) return -1 return 0 }) - }, [productsData, productSlotsMap]) + }, [productsData, productSlotsMap, getQuickestSlot, slotsReady]) // Load-more model for All Products (matches user-ui: 21 at a time) 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 now = dayjs() return [...slots] - .filter((slot) => dayjs(slot.deliveryTime).isAfter(now)) + .filter((slot) => dayjs(slot.deliveryTime).isAfter(now) && dayjs(slot.freezeTime).isAfter(now)) .sort((a, b) => { const deliveryDiff = dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)) if (deliveryDiff !== 0) return deliveryDiff @@ -271,6 +283,13 @@ function HomePage() {
+ {/* Upcoming order glimpse (matches user-ui home ListHeader) */} +
+ +
+ + + {/* Explore Products Section — first, matching user-ui home order */} {dashboardTags.length > 0 && (
@@ -293,6 +312,7 @@ function HomePage() { return (
{/* Active tag products — brand-tinted container (matches user-ui) */} -
+
{activeTagProducts.length > 0 ? ( <>
{activeTagProducts .slice(0, expandedByTagId[activeTagId] ? undefined : 6) .map((product: any) => ( - handleProductPress(product.id)} - showDeliveryInfo={false} - miniView={true} - useAddToCartDialog={true} - /> +
+ handleProductPress(product.id)} + showDeliveryInfo={false} + miniView={true} + useAddToCartDialog={true} + /> +
))}
{activeTagProducts.length > 6 && !expandedByTagId[activeTagId] && (
+ {/* Upcoming-order glimpse (matches user-ui order-success flow) */} +
+ +
) } diff --git a/apps/web-ui/src/routes/home.search.tsx b/apps/web-ui/src/routes/home.search.tsx index 9f7f2fe..6dfa2c7 100644 --- a/apps/web-ui/src/routes/home.search.tsx +++ b/apps/web-ui/src/routes/home.search.tsx @@ -136,6 +136,7 @@ function SearchPage() { value={inputQuery} onChange={setInputQuery} onSearch={handleSearch} + testID="search-input" />
diff --git a/apps/web-ui/src/routes/login.tsx b/apps/web-ui/src/routes/login.tsx index 3f42197..f7cbd21 100644 --- a/apps/web-ui/src/routes/login.tsx +++ b/apps/web-ui/src/routes/login.tsx @@ -7,11 +7,50 @@ import { useGetEssentialConsts } from '../hooks/prominent-api-hooks' import { MyButton, pInput as PInput } from 'web-components' import type { LoginFormInputs } from '@packages/shared' -export const Route = createFileRoute('/login')({ component: LoginPage }) +export const Route = createFileRoute('/login')({ + component: LoginPage, + validateSearch: (search: Record): { 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 } { + 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() { const { loginWithToken } = useAuth() const navigate = useNavigate() + const { redirect } = Route.useSearch() + const navigateAfterLogin = () => { + const dest = consumeRedirect(redirect) + navigate(dest as any) + } const { data: constsData } = useGetEssentialConsts() const [step, setStep] = useState<'mobile' | 'choice' | 'otp' | 'password'>('mobile') const [selectedMobile, setSelectedMobile] = useState('') @@ -35,7 +74,7 @@ function LoginPage() { onSuccess: (data) => { if (data.success && data.token && data.user) { loginWithToken(data.token, data.user) - navigate({ to: '/home' }) + navigateAfterLogin() } }, }) @@ -113,7 +152,7 @@ function LoginPage() { { onSuccess: (res) => { loginWithToken(res.data.token, res.data.user) - navigate({ to: '/home' }) + navigateAfterLogin() }, } ) @@ -195,6 +234,7 @@ function LoginPage() { if (clean.length <= 10) onChange(clean) }} className="bg-gray-50" + data-testid="user-login-mobile" /> )} /> @@ -209,6 +249,7 @@ function LoginPage() { {[0, 1, 2, 3].map((i) => ( { inputRefs.current[i] = el }} className="h-14 w-14 rounded-xl border-2 text-center text-2xl font-bold" style={{ @@ -254,6 +295,7 @@ function LoginPage() { onChange={(e) => onChange(e.target.value)} type="password" className="bg-gray-50" + data-testid="user-login-password" /> )} /> @@ -263,6 +305,7 @@ function LoginPage() { { setStep('password'); setOtpCells(['', '', '', '']) }} className="mt-4 block text-center" > diff --git a/apps/web-ui/src/routes/register.tsx b/apps/web-ui/src/routes/register.tsx index 4f4f0a2..5449517 100644 --- a/apps/web-ui/src/routes/register.tsx +++ b/apps/web-ui/src/routes/register.tsx @@ -45,12 +45,14 @@ function RegisterPage() { value={name} onChange={(e) => setName(e.target.value)} required + data-testid="user-register-name" /> setEmail(e.target.value)} + data-testid="user-register-email" /> setPassword(e.target.value)} required + data-testid="user-register-password" />
diff --git a/apps/web-ui/src/routes/slot-view.tsx b/apps/web-ui/src/routes/slot-view.tsx index 3534c1a..2ac4d8a 100644 --- a/apps/web-ui/src/routes/slot-view.tsx +++ b/apps/web-ui/src/routes/slot-view.tsx @@ -26,8 +26,8 @@ import { } from "../hooks/cart-query-hooks"; import { usePopulateCentralProductStore } from "../hooks/usePopulateCentralProductStore"; import { AppLayout } from "../components/AppLayout"; -import { Truck, Store, Grid3X3, ChevronLeft, ShoppingCart, Clock, ChevronDown } from "lucide-react"; -import { Dialog } from "../components/Dialog"; +import { Truck, Store, Grid3X3, ShoppingCart, Clock } from "lucide-react"; +import { QuickDeliveryAddressSelector } from "../components/QuickDeliveryAddressSelector"; import type { CompactProductCardProps } from '@packages/shared'; export const Route = createFileRoute("/slot-view")({ @@ -47,7 +47,6 @@ function SlotViewPage() { const { productsById } = useCentralProductStore(); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); const { data: storesData } = useStores(); - const [showSlotDialog, setShowSlotDialog] = useState(false); // Populate central product store with products data usePopulateCentralProductStore(); @@ -57,55 +56,9 @@ function SlotViewPage() { // Find the specific slot from cached data 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 { 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 item = filteredProducts.find((p) => p.id === productId); 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 const slotProducts = slot?.products @@ -146,16 +91,6 @@ function SlotViewPage() { ? slotProducts.filter((p: any) => p.storeId === storeId) : 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) { return ( @@ -175,28 +110,16 @@ function SlotViewPage() { {/* Header with Dropdown - Matching Mobile App */}
- {/* Back Button */} - - - {/* Delivery Time Dropdown */}
- + + navigate({ + to: '/slot-view', + search: { slotId: newSlotId, storeId }, + }) + } + />
@@ -262,32 +185,9 @@ function SlotViewPage() {
- {/* Slot Selection Dialog */} - setShowSlotDialog(false)} title="Select Delivery Time"> -
- {slotOptions.map((slotOption) => ( - - ))} -
-
- ); + ) } interface StoreSidebarProps { diff --git a/change-logs/change-log.txt b/change-logs/change-log.txt index 33ce667..7438872 100644 --- a/change-logs/change-log.txt +++ b/change-logs/change-log.txt @@ -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: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 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 diff --git a/neo-tests/e2e/subflows/add-bound.yaml b/neo-tests/e2e/subflows/add-bound.yaml new file mode 100644 index 0000000..4d7139c --- /dev/null +++ b/neo-tests/e2e/subflows/add-bound.yaml @@ -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} diff --git a/neo-tests/e2e/subflows/add-region.yaml b/neo-tests/e2e/subflows/add-region.yaml new file mode 100644 index 0000000..4e9291f --- /dev/null +++ b/neo-tests/e2e/subflows/add-region.yaml @@ -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 diff --git a/neo-tests/e2e/subflows/login.yaml b/neo-tests/e2e/subflows/login.yaml new file mode 100644 index 0000000..cc7a65d --- /dev/null +++ b/neo-tests/e2e/subflows/login.yaml @@ -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 diff --git a/packages/db_helper_postgres/src/db/schema.ts b/packages/db_helper_postgres/src/db/schema.ts index 5239529..99127a5 100755 --- a/packages/db_helper_postgres/src/db/schema.ts +++ b/packages/db_helper_postgres/src/db/schema.ts @@ -63,6 +63,15 @@ export const staffUsers = mf.table('staff_users', { 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', { id: integer().primaryKey().generatedAlwaysAsIdentity(), name: varchar({ length: 255 }).notNull(), diff --git a/packages/db_helper_sqlite/drizzle/0008_superadmins.sql b/packages/db_helper_sqlite/drizzle/0008_superadmins.sql new file mode 100644 index 0000000..88ae318 --- /dev/null +++ b/packages/db_helper_sqlite/drizzle/0008_superadmins.sql @@ -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`); diff --git a/packages/db_helper_sqlite/drizzle/0009_all_region.sql b/packages/db_helper_sqlite/drizzle/0009_all_region.sql new file mode 100644 index 0000000..397bc6e --- /dev/null +++ b/packages/db_helper_sqlite/drizzle/0009_all_region.sql @@ -0,0 +1,67 @@ +-- Migration: all-region stores. +-- store_info.region_id becomes nullable (NULL = serves all regions) and gains +-- available_in_all_regions, mirroring product_info. The table is rebuilt +-- (create-copy-drop-rename) because SQLite cannot drop the NOT NULL from a +-- column, and product_market_stats.store_id references store_info, so the +-- stats table is rebuilt alongside it (leaves-first: market_stats has no +-- inbound FKs, so it drops first). IDs are preserved, so relatedStores JSON +-- and all other references survive unchanged. + +-- 1) replacement store table: nullable region + all-regions flag +CREATE TABLE `__new_store_info` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `name` text NOT NULL, + `description` text, + `image_url` text, + `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, + `owner` integer NOT NULL, + `region_id` integer, + `available_in_all_regions` integer NOT NULL DEFAULT 0, + FOREIGN KEY (`owner`) REFERENCES `staff_users`(`id`) ON UPDATE no action ON DELETE no action, + FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action +); +--> statement-breakpoint +INSERT INTO `__new_store_info` ( + `id`, `name`, `description`, `image_url`, `created_at`, `owner`, `region_id`, `available_in_all_regions` +) +SELECT + `id`, `name`, `description`, `image_url`, `created_at`, `owner`, `region_id`, 0 +FROM `store_info`; +--> statement-breakpoint +-- 2) rebuild market stats retargeted at the replacement store table +CREATE TABLE `__new_product_market_stats` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `sku_id` integer NOT NULL, + `region_id` integer NOT NULL, + `store_id` integer, + `market_price` numeric, + `our_price` numeric NOT NULL, + `is_flash_available` integer DEFAULT false NOT NULL, + `flash_price` numeric, + `is_out_of_stock` integer DEFAULT false NOT NULL, + `is_suspended` integer DEFAULT false NOT NULL, + `is_offer` integer DEFAULT false NOT NULL, + FOREIGN KEY (`sku_id`) REFERENCES `product_skus`(`id`) ON UPDATE no action ON DELETE no action, + FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action, + FOREIGN KEY (`store_id`) REFERENCES `__new_store_info`(`id`) ON UPDATE no action ON DELETE no action +); +--> statement-breakpoint +INSERT INTO `__new_product_market_stats` ( + `id`, `sku_id`, `region_id`, `store_id`, `market_price`, `our_price`, `is_flash_available`, `flash_price`, `is_out_of_stock`, `is_suspended`, `is_offer` +) +SELECT + `id`, `sku_id`, `region_id`, `store_id`, `market_price`, `our_price`, `is_flash_available`, `flash_price`, `is_out_of_stock`, `is_suspended`, `is_offer` +FROM `product_market_stats`; +--> statement-breakpoint +-- 3) drop originals, leaves first +DROP TABLE `product_market_stats`; +--> statement-breakpoint +DROP TABLE `store_info`; +--> statement-breakpoint +-- 4) promote the replacements (child FK clauses auto-rewrite to final names) +ALTER TABLE `__new_store_info` RENAME TO `store_info`; +--> statement-breakpoint +ALTER TABLE `__new_product_market_stats` RENAME TO `product_market_stats`; +--> statement-breakpoint +-- 5) recreate the index (name freed by the drops above) +CREATE UNIQUE INDEX `unique_sku_region` ON `product_market_stats` (`sku_id`, `region_id`); diff --git a/packages/db_helper_sqlite/drizzle/meta/_journal.json b/packages/db_helper_sqlite/drizzle/meta/_journal.json index dae2ffc..5a67988 100644 --- a/packages/db_helper_sqlite/drizzle/meta/_journal.json +++ b/packages/db_helper_sqlite/drizzle/meta/_journal.json @@ -57,6 +57,20 @@ "when": 1791100000000, "tag": "0007_region_scoping", "breakpoints": true + }, + { + "idx": 8, + "version": "6", + "when": 1791217960000, + "tag": "0008_superadmins", + "breakpoints": true + }, + { + "idx": 9, + "version": "6", + "when": 1791219132000, + "tag": "0009_all_region_stores", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts index 827b7af..d215cc5 100644 --- a/packages/db_helper_sqlite/index.ts +++ b/packages/db_helper_sqlite/index.ts @@ -140,8 +140,17 @@ export { getStaffNotifCred, upsertStaffNotifCred, getAllStaffNotifTokens, + updateStaffUserInfo, + deleteStaffUser, } from './src/admin-apis/staff-user' +export { + // Superadmin + getSuperadminByName, + getSuperadminById, + checkSuperadminExists, +} from './src/admin-apis/superadmin' + export { // Store getAllStores, diff --git a/packages/db_helper_sqlite/src/admin-apis/product.ts b/packages/db_helper_sqlite/src/admin-apis/product.ts index 7e1d232..f09ee23 100644 --- a/packages/db_helper_sqlite/src/admin-apis/product.ts +++ b/packages/db_helper_sqlite/src/admin-apis/product.ts @@ -71,6 +71,7 @@ import type { CreateProductInput, CreateSkuInput, ProductTagCore, + RegionSkuStats, SkuFeatureLike, Store, } from '@packages/shared' @@ -78,6 +79,22 @@ import type { type ProductRow = InferSelectModel type SkuRow = InferSelectModel type MarketStatsRow = InferSelectModel + +/** Build a market-stats SET clause from a per-region override. Only fields + * present in the override are applied; everything else keeps its row value + * (or, at insert time, the already-computed fan-out value). */ +function regionStatsSet(ov: RegionSkuStats): Record { + const set: Record = {} + if (ov.price !== undefined) set.ourPrice = ov.price != null ? String(ov.price) : '0' + if (ov.marketPrice !== undefined) set.marketPrice = ov.marketPrice != null ? String(ov.marketPrice) : null + if (ov.flashPrice !== undefined) set.flashPrice = ov.flashPrice != null ? String(ov.flashPrice) : null + if (ov.isFlashAvailable !== undefined) set.isFlashAvailable = ov.isFlashAvailable + if (ov.isOffer !== undefined) set.isOffer = ov.isOffer + if (ov.isSuspended !== undefined) set.isSuspended = ov.isSuspended + if (ov.isOutOfStock !== undefined) set.isOutOfStock = ov.isOutOfStock + if (ov.storeId !== undefined) set.storeId = ov.storeId + return set +} type SkuFeatureRow = InferSelectModel type StoreRow = InferSelectModel type SpecialDealRow = InferSelectModel @@ -96,6 +113,7 @@ const mapStore = (store: StoreRow): Store => ({ imageUrl: store.imageUrl, owner: store.owner, regionId: store.regionId, + availableInAllRegions: store.availableInAllRegions ?? false, createdAt: store.createdAt, // updatedAt: store.createdAt, }) @@ -400,6 +418,21 @@ export async function createProduct(input: CreateProductInput): Promise 0) { await runBatched(tx, sku.features, FEATURE_INSERT_CHUNK_SIZE, async (t, chunk) => { await t.insert(skuFeatures).values( @@ -644,6 +677,21 @@ export async function updateProduct(id: number, input: any): Promise 0) { await runBatched(tx, sku.features, FEATURE_INSERT_CHUNK_SIZE, async (t, chunk) => { @@ -699,6 +747,20 @@ export async function updateProduct(id: number, input: any): Promise 0) { await runBatched(tx, sku.features, FEATURE_INSERT_CHUNK_SIZE, async (t, chunk) => { await t.insert(skuFeatures).values( diff --git a/packages/db_helper_sqlite/src/admin-apis/staff-user.ts b/packages/db_helper_sqlite/src/admin-apis/staff-user.ts index 5424740..ed0349c 100644 --- a/packages/db_helper_sqlite/src/admin-apis/staff-user.ts +++ b/packages/db_helper_sqlite/src/admin-apis/staff-user.ts @@ -1,5 +1,5 @@ import { db } from '../db/db_index' -import { staffUsers, staffRoles, users, userDetails, orders, staffNotifCreds } from '../db/schema' +import { staffUsers, staffRoles, users, userDetails, orders, staffNotifCreds, storeInfo, coupons, reservedCoupons, userIncidents } from '../db/schema' import { eq, or, like, and, lt, desc } from 'drizzle-orm' import type { StaffUser } from '@packages/shared' @@ -131,3 +131,79 @@ export async function getAllStaffNotifTokens(regionId?: number | null): Promise< .innerJoin(staffUsers, eq(staffNotifCreds.staffUserId, staffUsers.id)) .where(regionId != null ? eq(staffUsers.regionId, regionId) : undefined) } + +export interface UpdateStaffUserInput { + name?: string + roleId?: number + regionId?: number + /** Pre-hashed with bcrypt before calling. */ + password?: string +} + +export async function updateStaffUserInfo( + id: number, + input: UpdateStaffUserInput +): Promise { + const existing = await getStaffUserById(id) + if (!existing) return null + + const patch: Partial<{ name: string; staffRoleId: number; regionId: number; password: string }> = {} + if (input.name !== undefined) patch.name = input.name.trim() + if (input.roleId !== undefined) patch.staffRoleId = input.roleId + if (input.regionId !== undefined) patch.regionId = input.regionId + if (input.password !== undefined) patch.password = input.password + if (Object.keys(patch).length === 0) return existing + + const [updated] = await db.update(staffUsers).set(patch).where(eq(staffUsers.id, id)).returning() + return { + id: updated.id, + name: updated.name, + password: updated.password, + staffRoleId: updated.staffRoleId, + regionId: updated.regionId, + createdAt: updated.createdAt, + } +} + +export type StaffDeleteBlocker = + | { type: 'stores'; count: number } + | { type: 'coupons'; count: number } + | { type: 'incidents'; count: number } + +/** Delete a staff user. Returns a blocker when other rows still reference them. */ +export async function deleteStaffUser(id: number): Promise<{ deleted: true } | { deleted: false; blocker: StaffDeleteBlocker }> { + const existing = await getStaffUserById(id) + if (!existing) return { deleted: true } + + const ownedStores = await db.query.storeInfo.findMany({ + where: eq(storeInfo.owner, id), + columns: { id: true }, + }) + if (ownedStores.length > 0) { + return { deleted: false, blocker: { type: 'stores', count: ownedStores.length } } + } + + const createdCoupons = await db.query.coupons.findMany({ + where: eq(coupons.createdBy, id), + columns: { id: true }, + }) + const createdReserved = await db.query.reservedCoupons.findMany({ + where: eq(reservedCoupons.createdBy, id), + columns: { id: true }, + }) + if (createdCoupons.length + createdReserved.length > 0) { + return { deleted: false, blocker: { type: 'coupons', count: createdCoupons.length + createdReserved.length } } + } + + const filedIncidents = await db.query.userIncidents.findMany({ + where: eq(userIncidents.addedBy, id), + columns: { id: true }, + }) + if (filedIncidents.length > 0) { + return { deleted: false, blocker: { type: 'incidents', count: filedIncidents.length } } + } + + await db.delete(staffNotifCreds).where(eq(staffNotifCreds.staffUserId, id)) + await db.delete(staffUsers).where(eq(staffUsers.id, id)) + return { deleted: true } +} diff --git a/packages/db_helper_sqlite/src/admin-apis/store.ts b/packages/db_helper_sqlite/src/admin-apis/store.ts index ea8d290..dbf98b2 100644 --- a/packages/db_helper_sqlite/src/admin-apis/store.ts +++ b/packages/db_helper_sqlite/src/admin-apis/store.ts @@ -1,12 +1,14 @@ import { db } from '../db/db_index' import { storeInfo, productSkus, productMarketStats } from '../db/schema' -import { eq, and, inArray } from 'drizzle-orm' +import { eq, and, inArray, or } from 'drizzle-orm' import { runBatched } from '../lib/run-batched' import type { Store, CreateStoreInput, UpdateStoreInput } from '@packages/shared' export async function getAllStores(regionId?: number): Promise { const stores = await db.query.storeInfo.findMany({ - where: regionId !== undefined ? eq(storeInfo.regionId, regionId) : undefined, + where: regionId !== undefined + ? or(eq(storeInfo.regionId, regionId), eq(storeInfo.availableInAllRegions, true)) + : undefined, with: { owner: true, }, @@ -27,11 +29,12 @@ export async function getStoreById(id: number): Promise { } export async function createStore( - input: CreateStoreInput & { regionId: number }, + input: CreateStoreInput & { regionId?: number | null }, products?: number[] ): Promise { return db.transaction(async (tx) => { - const regionId = input.regionId + const regionId = input.regionId ?? null + const availableInAllRegions = input.availableInAllRegions ?? false const [newStore] = await tx .insert(storeInfo) @@ -41,6 +44,7 @@ export async function createStore( imageUrl: input.imageUrl, owner: input.owner, regionId, + availableInAllRegions, }) .returning() @@ -67,10 +71,12 @@ export async function createStore( .update(productMarketStats) .set({ storeId: newStore.id }) .where( - and( - inArray(productMarketStats.skuId, chunk), - eq(productMarketStats.regionId, regionId) - ) + regionId != null + ? and( + inArray(productMarketStats.skuId, chunk), + eq(productMarketStats.regionId, regionId) + ) + : inArray(productMarketStats.skuId, chunk) ) }) } @@ -84,6 +90,7 @@ export async function createStore( imageUrl: newStore.imageUrl, owner: newStore.owner, regionId: newStore.regionId, + availableInAllRegions: newStore.availableInAllRegions, createdAt: newStore.createdAt, // updatedAt: newStore.updatedAt, } @@ -92,17 +99,18 @@ export async function createStore( export async function updateStore( id: number, - input: UpdateStoreInput & { regionId?: number }, + input: UpdateStoreInput & { regionId?: number | null }, products?: number[] ): Promise { return db.transaction(async (tx) => { - const { regionId: inputRegionId, ...storeFields } = input + const { regionId: inputRegionId, availableInAllRegions: inputFlag, ...storeFields } = input const [updatedStore] = await tx .update(storeInfo) .set({ ...storeFields, ...(inputRegionId !== undefined ? { regionId: inputRegionId } : {}), + ...(inputFlag !== undefined ? { availableInAllRegions: inputFlag } : {}), // updatedAt: new Date(), }) .where(eq(storeInfo.id, id)) @@ -117,10 +125,12 @@ export async function updateStore( .update(productMarketStats) .set({ storeId: null }) .where( - and( - eq(productMarketStats.storeId, id), - eq(productMarketStats.regionId, updatedStore.regionId) - ) + updatedStore.regionId != null + ? and( + eq(productMarketStats.storeId, id), + eq(productMarketStats.regionId, updatedStore.regionId) + ) + : eq(productMarketStats.storeId, id) ) // ProductsSelector sends SKU ids — resolve to the owning product ids. @@ -145,10 +155,12 @@ export async function updateStore( .update(productMarketStats) .set({ storeId: id }) .where( - and( - inArray(productMarketStats.skuId, chunk), - eq(productMarketStats.regionId, updatedStore.regionId) - ) + updatedStore.regionId != null + ? and( + inArray(productMarketStats.skuId, chunk), + eq(productMarketStats.regionId, updatedStore.regionId) + ) + : inArray(productMarketStats.skuId, chunk) ) }) } @@ -162,6 +174,7 @@ export async function updateStore( imageUrl: updatedStore.imageUrl, owner: updatedStore.owner, regionId: updatedStore.regionId, + availableInAllRegions: updatedStore.availableInAllRegions, createdAt: updatedStore.createdAt, // updatedAt: updatedStore.updatedAt, } diff --git a/packages/db_helper_sqlite/src/admin-apis/superadmin.ts b/packages/db_helper_sqlite/src/admin-apis/superadmin.ts new file mode 100644 index 0000000..b0730d4 --- /dev/null +++ b/packages/db_helper_sqlite/src/admin-apis/superadmin.ts @@ -0,0 +1,28 @@ +import { db } from '../db/db_index' +import { superadmins } from '../db/schema' +import { eq } from 'drizzle-orm' +import type { Superadmin } from '@packages/shared' + +export async function getSuperadminByName(name: string): Promise { + const row = await db.query.superadmins.findFirst({ + where: eq(superadmins.name, name), + }) + + return (row as Superadmin) || null +} + +export async function getSuperadminById(id: number): Promise { + const row = await db.query.superadmins.findFirst({ + where: eq(superadmins.id, id), + }) + + return (row as Superadmin) || null +} + +export async function checkSuperadminExists(name: string): Promise { + const existing = await db.query.superadmins.findFirst({ + where: eq(superadmins.name, name), + columns: { id: true }, + }) + return !!existing +} diff --git a/packages/db_helper_sqlite/src/db/schema.ts b/packages/db_helper_sqlite/src/db/schema.ts index cdc397e..d31ef3e 100644 --- a/packages/db_helper_sqlite/src/db/schema.ts +++ b/packages/db_helper_sqlite/src/db/schema.ts @@ -158,6 +158,15 @@ export const staffUsers = sqliteTable('staff_users', { createdAt: timestampText('created_at').notNull().default(sql`CURRENT_TIMESTAMP`), }) +// Platform superadmins. Global by definition: no region, no role — +// every row in this table has full access via the superadmin.* scope. +export const superadmins = sqliteTable('superadmins', { + id: integer().primaryKey({ autoIncrement: true }), + name: text().notNull().unique(), + password: text().notNull(), + createdAt: timestampText('created_at').notNull().default(sql`CURRENT_TIMESTAMP`), +}) + export const storeInfo = sqliteTable('store_info', { id: integer().primaryKey({ autoIncrement: true }), name: text().notNull(), @@ -165,7 +174,9 @@ export const storeInfo = sqliteTable('store_info', { imageUrl: text('image_url'), createdAt: timestampText('created_at').notNull().default(sql`CURRENT_TIMESTAMP`), owner: integer('owner').notNull().references(() => staffUsers.id), - regionId: integer('region_id').notNull().references(() => regions.id), + // NULL when the store serves all regions. Existing rows belong to region 1. + regionId: integer('region_id').references(() => regions.id), + availableInAllRegions: integer('available_in_all_regions', { mode: 'boolean' }).notNull().default(false), }) export const units = sqliteTable('units', { diff --git a/packages/db_helper_sqlite/src/stores/store-helpers.ts b/packages/db_helper_sqlite/src/stores/store-helpers.ts index 6bc7a5a..b0e130e 100644 --- a/packages/db_helper_sqlite/src/stores/store-helpers.ts +++ b/packages/db_helper_sqlite/src/stores/store-helpers.ts @@ -15,7 +15,7 @@ import { productTagInfo, userIncidents, } from '../db/schema' -import { eq, and, gt, sql, isNotNull, asc } from 'drizzle-orm' +import { eq, and, gt, sql, isNotNull, asc, or } from 'drizzle-orm' import { composeSkuName, composeUnitNotation } from '../lib/sku-features' import { DEFAULT_REGION_ID } from '@packages/shared' import type { ProductTagData, TagProductMapping, UserNegativityData, StoreSummary, BannerData, SpecialDealCore, ProductDetailCore, ProductPriceFlags, ProductTagCore, UserProductDeliverySlot, UserProductComboItem } from '@packages/shared' @@ -163,7 +163,7 @@ export async function getAllStoresForCache( regionId: number = DEFAULT_REGION_ID ): Promise { return db.query.storeInfo.findMany({ - where: eq(storeInfo.regionId, regionId), + where: or(eq(storeInfo.regionId, regionId), eq(storeInfo.availableInAllRegions, true)), columns: { id: true, name: true, description: true }, }) } diff --git a/packages/db_helper_sqlite/src/user-apis/stores.ts b/packages/db_helper_sqlite/src/user-apis/stores.ts index 536da56..778f94d 100644 --- a/packages/db_helper_sqlite/src/user-apis/stores.ts +++ b/packages/db_helper_sqlite/src/user-apis/stores.ts @@ -1,6 +1,6 @@ import { db } from '../db/db_index' import { productMarketStats, productSkus, storeInfo } from '../db/schema' -import { and, asc, eq, inArray } from 'drizzle-orm' +import { and, asc, eq, inArray, or } from 'drizzle-orm' import type { UserStoreDetailData, UserStoreProductData, UserStoreSummaryData, StoreSummary } from '@packages/shared' import { DEFAULT_REGION_ID } from '@packages/shared' import { composeSkuName, composeUnitNotation } from '../lib/sku-features' @@ -24,7 +24,7 @@ export async function getStoreSummaries( name: storeInfo.name, description: storeInfo.description, imageUrl: storeInfo.imageUrl, - }).from(storeInfo).where(eq(storeInfo.regionId, regionId)) + }).from(storeInfo).where(or(eq(storeInfo.regionId, regionId), eq(storeInfo.availableInAllRegions, true))) const skus = await db.query.productSkus.findMany({ with: { product: true, marketStats: true }, @@ -71,7 +71,7 @@ export async function getStoreDetail( regionId: number = DEFAULT_REGION_ID ): Promise { const storeData = await db.query.storeInfo.findFirst({ - where: and(eq(storeInfo.id, storeId), eq(storeInfo.regionId, regionId)), + where: and(eq(storeInfo.id, storeId), or(eq(storeInfo.regionId, regionId), eq(storeInfo.availableInAllRegions, true))), columns: { id: true, name: true, diff --git a/packages/shared/index.ts b/packages/shared/index.ts index 1e6def5..8d5692e 100644 --- a/packages/shared/index.ts +++ b/packages/shared/index.ts @@ -18,9 +18,9 @@ export const DEFAULT_REGION_ID = 1 * Framework-agnostic: apps may override it (e.g. VITE_API_URL) at build time. */ // export const BASE_API_URL = 'https://worker.freshyo.in' -export const BASE_API_URL = 'https://devapi.freshyo.in' +// export const BASE_API_URL = 'https://devapi.freshyo.in' // export const BASE_API_URL = 'http://192.168.100.126:8787' -// export const BASE_API_URL = 'http://192.168.1.5:8787' +export const BASE_API_URL = 'http://192.168.1.5:8787' // Re-export all types from the types folder export * from './types' diff --git a/packages/shared/types/admin.ts b/packages/shared/types/admin.ts index 2d14a2c..930a2e6 100644 --- a/packages/shared/types/admin.ts +++ b/packages/shared/types/admin.ts @@ -26,13 +26,21 @@ export interface StaffUser { createdAt: Date; } +export interface Superadmin { + id: number; + name: string; + password: string; + createdAt: Date; +} + export interface Store { id: number; name: string; description: string | null; imageUrl: string | null; owner: number; - regionId: number; + regionId: number | null; + availableInAllRegions: boolean; createdAt: Date; // updatedAt: Date; } @@ -358,6 +366,22 @@ export interface CreateSkuInput extends SkuFlagCore { flashPrice?: number | null features: SkuFeatureLike[] comboItems?: CreateComboItemInput[] + /** Per-region market-stats overrides, keyed by region id. Missing fields + * fall back to the base SKU values above. Absent entirely = fan-out. */ + regionStats?: Record | null +} + +/** Per-region market-stats values for one SKU. All optional — anything + * missing falls back to the SKU's base values. */ +export interface RegionSkuStats { + price?: number | null + marketPrice?: number | null + flashPrice?: number | null + isFlashAvailable?: boolean + isOffer?: boolean + isSuspended?: boolean + isOutOfStock?: boolean + storeId?: number | null } export interface CreateProductInput { diff --git a/packages/shared/types/inputs.types.ts b/packages/shared/types/inputs.types.ts index 71bec98..2037e48 100644 --- a/packages/shared/types/inputs.types.ts +++ b/packages/shared/types/inputs.types.ts @@ -18,6 +18,7 @@ export interface CreateStoreInput { description?: string imageUrl?: string owner: number + availableInAllRegions?: boolean } export interface UpdateStoreInput { @@ -25,6 +26,7 @@ export interface UpdateStoreInput { description?: string imageUrl?: string owner?: number + availableInAllRegions?: boolean } // --- Auth wire types (identical backend auth API ↔ user-ui) --- diff --git a/packages/shared/types/ui-common.types.ts b/packages/shared/types/ui-common.types.ts index f670443..e96b563 100644 --- a/packages/shared/types/ui-common.types.ts +++ b/packages/shared/types/ui-common.types.ts @@ -78,6 +78,7 @@ export interface ImageUploaderNeoProps { onImageAdd: (images: ImageUploaderNeoPayload[]) => void onImageRemove: (image: ImageUploaderNeoPayload) => void allowMultiple?: boolean + testID?: string } // Text-button extras — packages/ui `MyTextButtonProps` + packages/web-components `pButtonProps` diff --git a/packages/web-components/src/components/checkbox.tsx b/packages/web-components/src/components/checkbox.tsx index edcb1d1..37d3358 100644 --- a/packages/web-components/src/components/checkbox.tsx +++ b/packages/web-components/src/components/checkbox.tsx @@ -9,6 +9,7 @@ interface CheckboxProps { checkColor?: string label?: string disabled?: boolean + testID?: string } export function Checkbox({ @@ -19,12 +20,14 @@ export function Checkbox({ checkColor = '#FFFFFF', label, disabled = false, + testID, }: CheckboxProps) { return (