From fd21196e1d9c7a2cda8ebb6d1a95732af23f2005 Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Sat, 10 Oct 2026 15:00:50 +0530 Subject: [PATCH] enh --- .../app/(drawer)/dashboard/products/edit.tsx | 34 ++ .../app/(drawer)/dashboard/products/index.tsx | 14 +- .../app/(drawer)/dashboard/stores/add.tsx | 2 +- .../app/(drawer)/dashboard/stores/edit.tsx | 18 +- .../app/(drawer)/dashboard/stores/index.tsx | 6 +- apps/admin-ui/components/StoreForm.tsx | 20 +- .../src/components/GlobalProductForm.tsx | 184 +++++++ .../tests/components/store-form.test.tsx | 14 +- .../src/components/GlobalProductForm.tsx | 158 ++++++ apps/admin-web/src/components/StoreForm.tsx | 19 +- .../src/routes/dashboard.products.edit.tsx | 35 ++ .../src/routes/dashboard.products.tsx | 12 +- .../src/routes/dashboard.stores.edit.tsx | 18 +- .../src/routes/dashboard.stores.new.tsx | 2 +- .../admin-web/src/routes/dashboard.stores.tsx | 14 +- apps/backend/creds/demo.txt | 60 --- apps/backend/src/stores/product-store.ts | 2 - .../src/trpc/apis/admin-apis/apis/store.ts | 8 +- .../apis/common-apis/common-trpc-index.ts | 4 +- .../src/trpc/apis/common-apis/common.ts | 1 - .../superadmin-apis/apis/global-products.ts | 139 +++++ .../superadmin-apis/apis/global-stores.ts | 75 +++ .../apis/superadmin-trpc-index.ts | 4 + .../src/trpc/apis/user-apis/apis/order.ts | 7 +- .../src/trpc/apis/user-apis/apis/product.ts | 11 +- apps/backend/src/trpc/trpc-index.ts | 13 + .../superadmin-ui/src/components/AppShell.tsx | 4 +- .../src/hooks/useUploadToObjectStorage.ts | 61 +++ apps/superadmin-ui/src/routeTree.gen.ts | 42 ++ apps/superadmin-ui/src/routes/dashboard.tsx | 14 +- .../src/routes/global-products.tsx | 479 ++++++++++++++++++ .../src/routes/global-stores.tsx | 131 +++++ apps/user-ui/components/ProductDetail.tsx | 4 +- apps/user-ui/src/hooks/prominent-api-hooks.ts | 3 +- apps/web-ui/src/hooks/prominent-api-hooks.ts | 3 +- change-log.txt | 310 ++++++++++++ docs/impl-plans/README.md | 75 +++ .../phase-1-per-region-market-stats.md | 240 +++++++++ ...se-2-global-stores-and-products-backend.md | 194 +++++++ docs/impl-plans/phase-3-admin-ui.md | 109 ++++ docs/impl-plans/phase-4-superadmin-ui.md | 85 ++++ docs/maestro-mcp-agent-guidelines.md | 5 +- ...e2e-sanity-failed-cases-2026-10-10-1310.md | 455 +++++++++++++++++ ...e2e-sanity-test-results-2026-10-10-1310.md | 323 ++++++++++++ .../drizzle/0006_regions_and_superadmins.sql | 30 +- packages/db_helper_sqlite/index.ts | 18 + .../db_helper_sqlite/src/admin-apis/order.ts | 5 +- .../src/admin-apis/product.ts | 280 ++++++---- .../src/admin-apis/staff-user.ts | 13 +- .../db_helper_sqlite/src/admin-apis/store.ts | 59 +-- packages/db_helper_sqlite/src/db/schema.ts | 23 +- .../db_helper_sqlite/src/lib/market-stats.ts | 31 ++ .../src/stores/store-helpers.ts | 38 +- .../src/superadmin-apis/global-products.ts | 51 ++ .../src/superadmin-apis/global-stores.ts | 80 +++ .../src/superadmin-apis/regions.ts | 25 +- .../db_helper_sqlite/src/user-apis/order.ts | 9 +- .../db_helper_sqlite/src/user-apis/product.ts | 40 +- .../db_helper_sqlite/src/user-apis/slots.ts | 8 +- .../db_helper_sqlite/src/user-apis/stores.ts | 19 +- packages/shared/types/admin.ts | 4 +- packages/shared/types/inputs.types.ts | 2 - packages/shared/types/user.ts | 4 +- 63 files changed, 3786 insertions(+), 364 deletions(-) create mode 100644 apps/admin-ui/src/components/GlobalProductForm.tsx create mode 100644 apps/admin-web/src/components/GlobalProductForm.tsx create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/global-products.ts create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/global-stores.ts create mode 100644 apps/superadmin-ui/src/hooks/useUploadToObjectStorage.ts create mode 100644 apps/superadmin-ui/src/routes/global-products.tsx create mode 100644 apps/superadmin-ui/src/routes/global-stores.tsx create mode 100644 docs/impl-plans/README.md create mode 100644 docs/impl-plans/phase-1-per-region-market-stats.md create mode 100644 docs/impl-plans/phase-2-global-stores-and-products-backend.md create mode 100644 docs/impl-plans/phase-3-admin-ui.md create mode 100644 docs/impl-plans/phase-4-superadmin-ui.md create mode 100644 docs/test reports/e2e-sanity-failed-cases-2026-10-10-1310.md create mode 100644 docs/test reports/e2e-sanity-test-results-2026-10-10-1310.md create mode 100644 packages/db_helper_sqlite/src/lib/market-stats.ts create mode 100644 packages/db_helper_sqlite/src/superadmin-apis/global-products.ts create mode 100644 packages/db_helper_sqlite/src/superadmin-apis/global-stores.ts diff --git a/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx b/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx index 8fd400e..e632aad 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx @@ -3,6 +3,7 @@ import { View, Alert } from 'react-native'; import { useLocalSearchParams } from 'expo-router'; import { AppContainer, useManualRefresh, MyText, tw, ImageUploaderNeoItem, ImageUploaderNeoPayload } from 'common-ui'; import ProductForm, { ProductFormRef } from '@/src/components/ProductForm'; +import GlobalProductForm from '@/src/components/GlobalProductForm'; import { trpc } from '@/src/trpc-client'; import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore'; @@ -218,6 +219,39 @@ export default function EditProduct() { ); } + // Global products: only the market data for this region is editable. + if (productData.isGlobal) { + const handleGlobalSubmit = async (skus: any[]) => { + try { + await updateProduct.mutateAsync({ + id: productId, + name: productData.name, + shortDescription: productData.shortDescription || undefined, + longDescription: productData.longDescription || undefined, + storeId: productData.storeId || 0, + productType: productData.productType, + incrementStep: productData.incrementStep, + skus, + deletedImageKeys: [], + newImageUrls: [], + } as any) + await refetch() + await refetchProducts() + Alert.alert('Success', 'Market data updated for your region') + } catch (error: any) { + Alert.alert('Error', error.message || 'Failed to update product') + } + } + + return ( + + ) + } + return ( & { createdAt: string | Date } @@ -79,6 +79,11 @@ const ProductRow = React.memo(function ProductRow({ product, isToggling, onView, {product.name} + {product.isGlobal && ( + + GLOBAL + + )} @@ -172,7 +177,8 @@ export default function Products() { const matchesFilter = activeFilter === 'all' || (activeFilter === 'in-stock' && !defaultSku?.isOutOfStock) || - (activeFilter === 'out-of-stock' && defaultSku?.isOutOfStock); + (activeFilter === 'out-of-stock' && defaultSku?.isOutOfStock) || + (activeFilter === 'global' && product.isGlobal); return matchesSearch && matchesFilter; }); @@ -186,6 +192,7 @@ export default function Products() { () => products.filter(p => getDefaultSku(p)?.isOutOfStock).length, [products] ); + const globalCount = useMemo(() => products.filter(p => p.isGlobal).length, [products]); const handleEdit = useCallback((productId: number) => { router.push(`/(drawer)/dashboard/products/edit?id=${productId}` as any); @@ -238,9 +245,10 @@ export default function Products() { + - ), [products.length, inStockCount, outOfStockCount, searchTerm, activeFilter, handleSelectFilter, router]); + ), [products.length, inStockCount, outOfStockCount, globalCount, searchTerm, activeFilter, handleSelectFilter, router]); if (isLoading) { return ( diff --git a/apps/admin-ui/app/(drawer)/dashboard/stores/add.tsx b/apps/admin-ui/app/(drawer)/dashboard/stores/add.tsx index 97b2da4..ec9f153 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/stores/add.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/stores/add.tsx @@ -32,7 +32,7 @@ export default function AddStore() { Add New Store diff --git a/apps/admin-ui/app/(drawer)/dashboard/stores/edit.tsx b/apps/admin-ui/app/(drawer)/dashboard/stores/edit.tsx index 0f22117..4b5c2b1 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/stores/edit.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/stores/edit.tsx @@ -58,10 +58,26 @@ export default function EditStore() { name: storeData.store.name, description: storeData.store.description || '', imageUrl: storeData.store.imageUrl || '', - owner: storeData.store.owner.id, products: [], // Will be set by StoreForm }; + // Global stores are managed by a superadmin and shared across every region. + if (storeData.store.isGlobal) { + return ( + + + {storeData.store.name} + + Global store — managed by a superadmin and shared across all regions. + + {storeData.store.description ? ( + {storeData.store.description} + ) : null} + + + ); + } + return ( diff --git a/apps/admin-ui/app/(drawer)/dashboard/stores/index.tsx b/apps/admin-ui/app/(drawer)/dashboard/stores/index.tsx index 5bfabc5..968474f 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/stores/index.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/stores/index.tsx @@ -30,7 +30,7 @@ const StoreItem: React.FC = ({ item, index, isEditMode, onEdit, > {/* Delete Button - Only visible in edit mode */} - {isEditMode && ( + {isEditMode && !item.isGlobal && ( onDelete(item.id)} style={tw`absolute top-2 right-2 z-10 bg-red-500 p-2 rounded-full shadow-lg`} @@ -41,9 +41,9 @@ const StoreItem: React.FC = ({ item, index, isEditMode, onEdit, onEdit(item.id)} + onPress={isEditMode || item.isGlobal ? undefined : () => onEdit(item.id)} style={tw`flex-1`} - disabled={isEditMode} // Disable navigation in edit mode + disabled={isEditMode || item.isGlobal} > {/* Image Section - Portrait oriented */} diff --git a/apps/admin-ui/components/StoreForm.tsx b/apps/admin-ui/components/StoreForm.tsx index 95c4308..1d6e7ab 100644 --- a/apps/admin-ui/components/StoreForm.tsx +++ b/apps/admin-ui/components/StoreForm.tsx @@ -2,7 +2,7 @@ import React, { useState, useEffect, useMemo } from 'react'; import { View, TouchableOpacity, Alert } from 'react-native'; import { Formik } from 'formik'; import * as Yup from 'yup'; -import { MyTextInput, BottomDropdown, MyText, tw, ImageUploader } from 'common-ui'; +import { MyTextInput, MyText, tw, ImageUploader } from 'common-ui'; import ProductsSelector from './ProductsSelector'; import { trpc } from '../src/trpc-client'; import usePickImage from 'common-ui/src/components/use-pick-image'; @@ -27,12 +27,10 @@ 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()), }); function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreFormProps) { - const { data: staffData } = trpc.admin.staffUser.getStaff.useQuery(); const { data: productsData } = trpc.admin.product.getProducts.useQuery(); const [formInitialValues, setFormInitialValues] = useState(initialValues); @@ -59,13 +57,6 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF [formInitialValues.imageUrl] ) - const staffOptions = staffData?.staff.map((staff: { id: number; name: string }) => ({ - label: staff.name, - value: staff.id, - })) || []; - - - const { uploadSingle, isUploading } = useUploadToObjectStorage(); const handleImagePick = usePickImage({ @@ -145,15 +136,6 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF error={!!(touched.description && errors.description)} style={{ marginBottom: 16 }} /> - setFieldValue('owner', value)} - placeholder="Select owner" - error={!!(touched.owner && errors.owner)} - style={{ marginBottom: 16 }} - /> setFieldValue('products', value)} diff --git a/apps/admin-ui/src/components/GlobalProductForm.tsx b/apps/admin-ui/src/components/GlobalProductForm.tsx new file mode 100644 index 0000000..5c59b03 --- /dev/null +++ b/apps/admin-ui/src/components/GlobalProductForm.tsx @@ -0,0 +1,184 @@ +import React, { useMemo, useState } from 'react' +import { View, ScrollView } from 'react-native' +import { Image } from 'expo-image' +import { MyText, MyTextInput, MyButton, Checkbox, tw } from 'common-ui' +import type { AdminProductWithRelations } from '@packages/shared' + +/** + * Global products are owned by a superadmin and shared across every region. A + * regional admin may only edit the market data for their own region — the + * product structure (name, descriptions, images, features, combos, store) is + * read-only here. + */ +interface GlobalProductFormProps { + product: AdminProductWithRelations + onSubmit: (skus: any[]) => void + isLoading: boolean +} + +interface VariantState { + price: string + marketPrice: string + flashPrice: string + isFlashAvailable: boolean + isOutOfStock: boolean + isOffer: boolean + isSuspended: boolean +} + +const toNumOrUndef = (v: string): number | undefined => { + const n = parseFloat(v) + return Number.isFinite(n) ? n : undefined +} + +function GlobalProductForm({ product, onSubmit, isLoading }: GlobalProductFormProps) { + const skus = product.skus || [] + + const [variants, setVariants] = useState( + useMemo( + () => + skus.map((sku) => ({ + price: sku.price != null ? String(sku.price) : '', + marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : '', + flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : '', + isFlashAvailable: sku.isFlashAvailable ?? false, + isOutOfStock: sku.isOutOfStock ?? false, + isOffer: sku.isOffer ?? false, + isSuspended: sku.isSuspended ?? false, + })), + [product] + ) + ) + + const setVariant = (index: number, patch: Partial) => + setVariants((prev) => prev.map((v, i) => (i === index ? { ...v, ...patch } : v))) + + const handleSubmit = () => { + const payload = skus.map((sku, i) => { + const v = variants[i] + return { + id: sku.id, + name: sku.name ?? null, + price: toNumOrUndef(v.price) ?? 0, + marketPrice: toNumOrUndef(v.marketPrice) ?? null, + images: sku.images ?? [], + isFlashAvailable: v.isFlashAvailable, + flashPrice: v.isFlashAvailable ? (toNumOrUndef(v.flashPrice) ?? null) : null, + isOutOfStock: v.isOutOfStock, + isOffer: v.isOffer, + isComboOnly: sku.isComboOnly ?? false, + isDeleted: sku.isDeleted ?? false, + isSuspended: v.isSuspended, + features: (sku.features || []).map((f) => ({ + featureName: f.featureName, + featureValue: f.featureValue, + })), + comboItems: (sku.comboItems || []).map((ci: any) => ({ skuId: ci.skuId })), + } + }) + onSubmit(payload) + } + + return ( + + + Global product + + Shared across all regions. You can edit the price & stock for your region only. + + + + {/* Read-only structure */} + + Product details (read-only) + {product.name} + {product.shortDescription ? ( + {product.shortDescription} + ) : null} + + Store: {product.store?.name ?? '—'} · Type: {product.productType} + + + + {skus.map((sku, index) => { + const v = variants[index] + return ( + + + {sku.images && sku.images[0] ? ( + + ) : null} + + {sku.name || product.name} + + {(sku.features || []).map((f) => f.featureValue).join(' · ') || '—'} + + + + + Market data (your region) + setVariant(index, { price: t })} + style={{ marginBottom: 12 }} + /> + setVariant(index, { marketPrice: t })} + style={{ marginBottom: 12 }} + /> + + setVariant(index, { isFlashAvailable: !v.isFlashAvailable })} + style={tw`mr-3`} + /> + Flash available + + {v.isFlashAvailable && ( + setVariant(index, { flashPrice: t })} + style={{ marginBottom: 12 }} + /> + )} + + setVariant(index, { isOutOfStock: !v.isOutOfStock })} + style={tw`mr-3`} + /> + Out of stock + + + setVariant(index, { isOffer: !v.isOffer })} + style={tw`mr-3`} + /> + Offer SKU + + + setVariant(index, { isSuspended: !v.isSuspended })} + style={tw`mr-3`} + /> + Suspend in my region + + + ) + })} + + + + ) +} + +export default GlobalProductForm diff --git a/apps/admin-ui/tests/components/store-form.test.tsx b/apps/admin-ui/tests/components/store-form.test.tsx index cca1e65..f976a22 100644 --- a/apps/admin-ui/tests/components/store-form.test.tsx +++ b/apps/admin-ui/tests/components/store-form.test.tsx @@ -17,7 +17,6 @@ import { renderWithProviders } from '../helpers/render' const CREATE_INITIAL: StoreFormData = { name: '', description: '', - owner: 0, products: [], } @@ -66,7 +65,6 @@ describe('StoreForm', () => { expect(screen.getByPlaceholderText('Enter store name')).toBeVisible() expect(screen.getByPlaceholderText('Enter store description')).toBeVisible() - expect(screen.getByText('Select owner')).toBeVisible() expect(screen.getByText('Select products')).toBeVisible() expect(screen.getByText('Create Store')).toBeVisible() }) @@ -96,7 +94,7 @@ describe('StoreForm', () => { ) }) - it('submits the typed name with the selected owner and product', async () => { + it('submits the typed name with the selected product', async () => { const onSubmit = jest.fn() renderWithProviders( { 'Freshyo Form' ) - fireEvent.press(screen.getByText('Select owner')) - fireEvent.press(await screen.findByText('naveen')) - fireEvent.press(screen.getByText('Select products')) fireEvent.press(await screen.findByText('Chicken - ₹100')) @@ -124,7 +119,6 @@ describe('StoreForm', () => { expect(onSubmit).toHaveBeenCalledWith({ name: 'Freshyo Form', description: '', - owner: 2, products: [11], imageUrl: undefined, }) @@ -139,7 +133,6 @@ describe('StoreForm', () => { initialValues={{ name: 'Existing', description: 'Old description', - owner: 1, products: [], }} onSubmit={onSubmit} @@ -166,7 +159,7 @@ describe('StoreForm', () => { expect(screen.getByText('Creating...')).toBeVisible() }) - it('loads staff and products', async () => { + it('loads products', async () => { const { fetchMock } = setupApiMocks({ procedures }) renderWithProviders( { /> ) - await waitFor(() => expectProcedureCalled(fetchMock, 'admin.staffUser.getStaff')) - expectProcedureCalled(fetchMock, 'admin.product.getProducts') + await waitFor(() => expectProcedureCalled(fetchMock, 'admin.product.getProducts')) }) }) diff --git a/apps/admin-web/src/components/GlobalProductForm.tsx b/apps/admin-web/src/components/GlobalProductForm.tsx new file mode 100644 index 0000000..1123d2a --- /dev/null +++ b/apps/admin-web/src/components/GlobalProductForm.tsx @@ -0,0 +1,158 @@ +import { useMemo, useState } from 'react' +import { p as P } from 'web-components' +import type { AdminProductWithRelations } from '@packages/shared' + +/** + * Global products are owned by a superadmin and shared across every region. A + * regional admin may only edit the market data for their own region — the + * product structure (name, descriptions, images, features, combos, store) is + * read-only here. + */ +interface GlobalProductFormProps { + product: AdminProductWithRelations + onSubmit: (skus: any[]) => void + isLoading: boolean +} + +interface VariantState { + price: string + marketPrice: string + flashPrice: string + isFlashAvailable: boolean + isOutOfStock: boolean + isOffer: boolean + isSuspended: boolean +} + +const toNumOrUndef = (v: string): number | undefined => { + const n = parseFloat(v) + return Number.isFinite(n) ? n : undefined +} + +function GlobalProductForm({ product, onSubmit, isLoading }: GlobalProductFormProps) { + const skus = product.skus || [] + + const [variants, setVariants] = useState( + useMemo( + () => + skus.map((sku) => ({ + price: sku.price != null ? String(sku.price) : '', + marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : '', + flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : '', + isFlashAvailable: sku.isFlashAvailable ?? false, + isOutOfStock: sku.isOutOfStock ?? false, + isOffer: sku.isOffer ?? false, + isSuspended: sku.isSuspended ?? false, + })), + [product] + ) + ) + + const setVariant = (index: number, patch: Partial) => + setVariants((prev) => prev.map((v, i) => (i === index ? { ...v, ...patch } : v))) + + const handleSubmit = () => { + const payload = skus.map((sku, i) => { + const v = variants[i] + return { + id: sku.id, + name: sku.name ?? null, + price: toNumOrUndef(v.price) ?? 0, + marketPrice: toNumOrUndef(v.marketPrice) ?? null, + images: sku.images ?? [], + isFlashAvailable: v.isFlashAvailable, + flashPrice: v.isFlashAvailable ? (toNumOrUndef(v.flashPrice) ?? null) : null, + isOutOfStock: v.isOutOfStock, + isOffer: v.isOffer, + isComboOnly: sku.isComboOnly ?? false, + isDeleted: sku.isDeleted ?? false, + isSuspended: v.isSuspended, + features: (sku.features || []).map((f) => ({ + featureName: f.featureName, + featureValue: f.featureValue, + })), + comboItems: (sku.comboItems || []).map((ci: any) => ({ skuId: ci.skuId })), + } + }) + onSubmit(payload) + } + + const numberInput = (label: string, value: string, onChange: (t: string) => void) => ( + + ) + + const toggle = (label: string, checked: boolean, onToggle: () => void) => ( + + ) + + return ( +
+
+

Global product

+

+ Shared across all regions. You can edit the price & stock for your region only. +

+
+ +
+

Product details (read-only)

+

{product.name}

+ {product.shortDescription ?

{product.shortDescription}

: null} +

+ Store: {product.store?.name ?? '—'} · Type: {product.productType} +

+
+ + {skus.map((sku, index) => { + const v = variants[index] + return ( +
+
+ {sku.images && sku.images[0] ? ( + + ) : null} +
+

{sku.name || product.name}

+

+ {(sku.features || []).map((f) => f.featureValue).join(' · ') || '—'} +

+
+
+ +

Market data (your region)

+ {numberInput('Price (₹)', v.price, (t) => setVariant(index, { price: t }))} + {numberInput('Market price (₹)', v.marketPrice, (t) => setVariant(index, { marketPrice: t }))} + {toggle('Flash available', v.isFlashAvailable, () => setVariant(index, { isFlashAvailable: !v.isFlashAvailable }))} + {v.isFlashAvailable && numberInput('Flash price (₹)', v.flashPrice, (t) => setVariant(index, { flashPrice: t }))} + {toggle('Out of stock', v.isOutOfStock, () => setVariant(index, { isOutOfStock: !v.isOutOfStock }))} + {toggle('Offer SKU', v.isOffer, () => setVariant(index, { isOffer: !v.isOffer }))} + {toggle('Suspend in my region', v.isSuspended, () => setVariant(index, { isSuspended: !v.isSuspended }))} +
+ ) + })} + + +
+ ) +} + +export default GlobalProductForm diff --git a/apps/admin-web/src/components/StoreForm.tsx b/apps/admin-web/src/components/StoreForm.tsx index e44870b..11d6c2a 100644 --- a/apps/admin-web/src/components/StoreForm.tsx +++ b/apps/admin-web/src/components/StoreForm.tsx @@ -1,7 +1,7 @@ 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 } from 'web-components' +import { pInput as PInput, p as P, ImageUploader } from 'web-components' import ProductsSelector from './ProductsSelector' import { trpc } from '@/lib/trpc-client' import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStorage' @@ -25,12 +25,10 @@ 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()), }) function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreFormProps) { - const { data: staffData } = trpc.admin.staffUser.getStaff.useQuery() const { data: productsData } = trpc.admin.product.getProducts.useQuery() const [formInitialValues, setFormInitialValues] = useState(initialValues) @@ -58,11 +56,6 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF [formInitialValues.imageUrl] ) - const staffOptions = staffData?.staff.map((staff: { id: number; name: string }) => ({ - label: staff.name, - value: staff.id, - })) || [] - const { uploadSingle, isUploading } = useUploadToObjectStorage() const handleImagePick = () => { @@ -144,16 +137,6 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF error={!!(touched.description && errors.description)} style={{ marginBottom: 16 }} /> -
-

Owner

- setFieldValue('owner', Number(value))} - className="mb-4" - /> -
setFieldValue('products', value)} diff --git a/apps/admin-web/src/routes/dashboard.products.edit.tsx b/apps/admin-web/src/routes/dashboard.products.edit.tsx index 7685a74..1db98de 100644 --- a/apps/admin-web/src/routes/dashboard.products.edit.tsx +++ b/apps/admin-web/src/routes/dashboard.products.edit.tsx @@ -2,6 +2,7 @@ import React, { useRef, useMemo } from 'react' import { createFileRoute } from '@tanstack/react-router' import { AppContainer, p as MyText, type ImageUploaderNeoItem, type ImageUploaderNeoPayload } from 'web-components' import ProductForm, { type ProductFormRef } from '../components/ProductForm' +import GlobalProductForm from '../components/GlobalProductForm' import { trpc } from '@/lib/trpc-client' import { useManualRefresh } from '@/lib/refresh-context' import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStorage' @@ -211,6 +212,40 @@ function EditProduct() { ) } + if (productData.isGlobal) { + const handleGlobalSubmit = async (skus: any[]) => { + try { + await updateProduct.mutateAsync({ + id: productId, + name: productData.name, + shortDescription: productData.shortDescription || undefined, + longDescription: productData.longDescription || undefined, + storeId: productData.storeId || 0, + productType: productData.productType, + incrementStep: productData.incrementStep, + skus, + deletedImageKeys: [], + newImageUrls: [], + } as any) + await refetch() + await refetchProducts() + window.alert('Market data updated for your region') + } catch (error: any) { + window.alert(error.message || 'Failed to update product') + } + } + + return ( + + + + ) + } + return ( & { createdAt: string | Date } @@ -67,7 +67,8 @@ function Products() { const matchesFilter = activeFilter === 'all' || (activeFilter === 'in-stock' && !defaultSku?.isOutOfStock) || - (activeFilter === 'out-of-stock' && defaultSku?.isOutOfStock) + (activeFilter === 'out-of-stock' && defaultSku?.isOutOfStock) || + (activeFilter === 'global' && product.isGlobal) return matchesSearch && matchesFilter }) @@ -119,6 +120,7 @@ function Products() { const inStockCount = products.filter((p) => getDefaultSku(p) && !getDefaultSku(p)!.isOutOfStock).length const outOfStockCount = products.filter((p) => getDefaultSku(p)?.isOutOfStock).length + const globalCount = products.filter((p) => p.isGlobal).length const listHeader = ( <> @@ -142,6 +144,7 @@ function Products() { + ) @@ -170,6 +173,11 @@ function Products() { {product.name} + {product.isGlobal && ( + + GLOBAL + + )}
diff --git a/apps/admin-web/src/routes/dashboard.stores.edit.tsx b/apps/admin-web/src/routes/dashboard.stores.edit.tsx index 4c60e8b..cfba23e 100644 --- a/apps/admin-web/src/routes/dashboard.stores.edit.tsx +++ b/apps/admin-web/src/routes/dashboard.stores.edit.tsx @@ -62,10 +62,26 @@ function EditStore() { name: storeData.store.name, description: storeData.store.description || '', imageUrl: storeData.store.imageUrl || '', - owner: storeData.store.owner.id, products: [], // Will be set by StoreForm } + // Global stores are managed by a superadmin and shared across every region. + if (storeData.store.isGlobal) { + return ( + +
+ {storeData.store.name} + + Global store — managed by a superadmin and shared across all regions. + + {storeData.store.description ? ( + {storeData.store.description} + ) : null} +
+
+ ) + } + return (
diff --git a/apps/admin-web/src/routes/dashboard.stores.new.tsx b/apps/admin-web/src/routes/dashboard.stores.new.tsx index 7cbca27..d2b967f 100644 --- a/apps/admin-web/src/routes/dashboard.stores.new.tsx +++ b/apps/admin-web/src/routes/dashboard.stores.new.tsx @@ -36,7 +36,7 @@ function AddStore() { Add New Store diff --git a/apps/admin-web/src/routes/dashboard.stores.tsx b/apps/admin-web/src/routes/dashboard.stores.tsx index b33b22d..097326d 100644 --- a/apps/admin-web/src/routes/dashboard.stores.tsx +++ b/apps/admin-web/src/routes/dashboard.stores.tsx @@ -21,8 +21,8 @@ const StoreItem: React.FC = ({ item, isEditMode, onEdit, onDelet return (
- {/* Delete Button - Only visible in edit mode */} - {isEditMode && ( + {/* Delete Button - Only visible in edit mode (never for global stores) */} + {isEditMode && !item.isGlobal && ( +
+
+
+ {(product.skus ?? []).map((sku: any) => ( + + {(sku.features ?? []).map((f: any) => f.featureValue).join(' ') || 'SKU'} ·{' '} + {(sku.marketStats ?? []).length > 0 + ? `${(sku.marketStats ?? []).length} region rows` + : 'no market data'} + + ))} +
+
+ ))} +
+
+
+ ) +} + +function GlobalProductForm({ + product, + onSaved, + onCancel, +}: { + product?: any + onSaved: () => void + onCancel?: () => void +}) { + const storesQuery = trpc.superadmin.globalStores.list.useQuery() + const create = trpc.superadmin.globalProducts.create.useMutation() + const update = trpc.superadmin.globalProducts.update.useMutation() + const { upload, isUploading } = useUploadToObjectStorage() + const isEdit = !!product + + const [name, setName] = useState(product?.name ?? '') + const [shortDescription, setShortDescription] = useState(product?.shortDescription ?? '') + const [longDescription, setLongDescription] = useState(product?.longDescription ?? '') + const [storeId, setStoreId] = useState(product?.storeId ?? null) + const [productType, setProductType] = useState<'item' | 'combo'>(product?.productType ?? 'item') + const [skus, setSkus] = useState( + isEdit && product?.skus?.length ? product.skus.map(skuToDraft) : [emptySku()] + ) + const [error, setError] = useState(null) + + const stores = storesQuery.data ?? [] + const pending = create.isPending || update.isPending + + const updateSku = (index: number, patch: Partial) => + setSkus((prev) => prev.map((s, i) => (i === index ? { ...s, ...patch } : s))) + + const updateFeature = (skuIndex: number, fIndex: number, patch: Partial) => + setSkus((prev) => + prev.map((s, i) => + i === skuIndex ? { ...s, features: s.features.map((f, fi) => (fi === fIndex ? { ...f, ...patch } : f)) } : s + ) + ) + + const handleAddImages = (skuIndex: number, e: any) => { + const files = Array.from((e.target.files || []) as FileList) + if (files.length === 0) return + const drafts = files.map((file: File) => ({ blob: file as Blob, mimeType: file.type || 'image/jpeg' })) + const previews = files.map((file: File) => URL.createObjectURL(file)) + setSkus((prev) => + prev.map((s, i) => + i === skuIndex + ? { + ...s, + pendingFiles: [...s.pendingFiles, ...drafts], + pendingPreviews: [...s.pendingPreviews, ...previews], + } + : s + ) + ) + e.target.value = '' + } + + const canSubmit = + name.trim() !== '' && + !!storeId && + skus.length > 0 && + skus.every( + (s) => + s.price.trim() !== '' && + parseFloat(s.price) >= 0 && + s.features.some((f) => f.featureValue.trim() !== '') + ) && + !pending && + !isUploading + + const submit = async () => { + setError(null) + try { + const skusPayload = [] + for (const s of skus) { + let images = s.images + if (s.pendingFiles.length > 0) { + const { keys } = await upload({ images: s.pendingFiles, contextString: 'product_info' }) + images = [...s.images, ...keys] + } + skusPayload.push({ + id: s.id, + name: s.name || null, + price: parseFloat(s.price), + marketPrice: s.marketPrice.trim() !== '' ? parseFloat(s.marketPrice) : null, + images, + isFlashAvailable: false, + flashPrice: null, + isOutOfStock: s.isOutOfStock, + isOffer: s.isOffer, + isComboOnly: s.isComboOnly, + isDeleted: s.isDeleted, + isSuspended: s.isSuspended, + features: s.features + .filter((f) => f.featureValue.trim() !== '') + .map((f) => ({ featureName: f.featureName.trim() || null, featureValue: f.featureValue })), + comboItems: s.comboItems, + }) + } + + const payload = { + name, + shortDescription: shortDescription || undefined, + longDescription: longDescription || undefined, + storeId: storeId as number, + incrementStep: 1, + productType, + skus: skusPayload, + } + + if (isEdit) { + await update.mutateAsync({ id: product.id, ...payload } as any) + } else { + await create.mutateAsync(payload as any) + setName('') + setShortDescription('') + setLongDescription('') + setSkus([emptySku()]) + } + onSaved() + } catch (e: any) { + setError(e.message || 'Failed to save product') + } + } + + return ( +
+
+ + {isEdit ? `Edit global product: ${product.name}` : 'New global product'} + + {isEdit && onCancel ? ( + + ) : null} +
+ +
+ setName(e.target.value)} placeholder="e.g. Fresh Chicken" /> + + setShortDescription(e.target.value)} /> + setLongDescription(e.target.value)} /> + +
+ +
+
+ SKUs ({skus.length}) + setSkus((prev) => [...prev, emptySku()])}> + Add SKU + +
+ + {skus.map((sku, index) => ( +
+
+ updateSku(index, { name: e.target.value })} /> + updateSku(index, { price: e.target.value })} placeholder="e.g. 199" /> + updateSku(index, { marketPrice: e.target.value })} placeholder="Optional" /> +
+ +
+ + Images + +
+ {sku.images.map((key) => ( + + {key.split('/').pop()} + + + ))} + {sku.pendingPreviews.map((preview, pIndex) => ( + + + + + ))} + +
+
+ +
+ + Features + + {sku.features.map((feature, fIndex) => ( +
+ updateFeature(index, fIndex, { featureName: e.target.value })} + placeholder="name (e.g. quantity)" + className="w-40 rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-900" + /> + updateFeature(index, fIndex, { featureValue: e.target.value })} + placeholder="value (e.g. 1kg)" + className="flex-1 rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-900" + /> + {sku.features.length > 1 && ( + + )} +
+ ))} + +
+ +
+ + + + + + {skus.length > 1 && ( + + )} +
+
+ ))} +
+ + {error ? {error} : null} +
+ + {pending ? 'Saving…' : isEdit ? 'Save changes' : 'Create global product'} + + {isEdit && onCancel ? ( + + Cancel + + ) : null} +
+
+ ) +} diff --git a/apps/superadmin-ui/src/routes/global-stores.tsx b/apps/superadmin-ui/src/routes/global-stores.tsx new file mode 100644 index 0000000..984f6f3 --- /dev/null +++ b/apps/superadmin-ui/src/routes/global-stores.tsx @@ -0,0 +1,131 @@ +import { createFileRoute } from '@tanstack/react-router' +import { useState } from 'react' +import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components' +import { ProtectedRoute } from '../components/ProtectedRoute' +import { AppShell } from '../components/AppShell' +import { trpc } from '../lib/trpc-client' + +export const Route = createFileRoute('/global-stores')({ + component: () => ( + + + + + + ), +}) + +function GlobalStoresPage() { + const listQuery = trpc.superadmin.globalStores.list.useQuery() + const utils = trpc.useUtils() + const [editingId, setEditingId] = useState(null) + + const remove = trpc.superadmin.globalStores.delete.useMutation({ + onSuccess: async () => { await utils.superadmin.globalStores.list.invalidate() }, + onError: (e) => window.alert(e.message), + }) + + const refresh = () => utils.superadmin.globalStores.list.invalidate() + const stores = listQuery.data ?? [] + + return ( + +
+ Global Stores + + Stores available in every region. Regional admins can view them but not edit them. + + + + + {listQuery.isLoading && Loading stores…} + +
+ {stores.map((store: any) => ( +
+
+ {store.name} + + GLOBAL + +
+ {store.imageUrl ? ( + + ) : null} + {store.description || 'No description'} + +
+ setEditingId(editingId === store.id ? null : store.id)}> + {editingId === store.id ? 'Close' : 'Edit'} + + +
+ + {editingId === store.id ? ( +
+ { setEditingId(null); refresh() }} + /> +
+ ) : null} +
+ ))} +
+
+
+ ) +} + +function GlobalStoreForm({ store, onSaved }: { store?: any; onSaved: () => void }) { + const create = trpc.superadmin.globalStores.create.useMutation() + const update = trpc.superadmin.globalStores.update.useMutation() + const isEdit = !!store + + const [name, setName] = useState(store?.name ?? '') + const [description, setDescription] = useState(store?.description ?? '') + const [imageUrl, setImageUrl] = useState(store?.imageUrl ?? '') + + const pending = create.isPending || update.isPending + const canSubmit = name.trim() !== '' && !pending + + const submit = async () => { + try { + if (isEdit) { + await update.mutateAsync({ id: store.id, name, description, imageUrl }) + } else { + await create.mutateAsync({ name, description, imageUrl }) + setName('') + setDescription('') + setImageUrl('') + } + onSaved() + } catch (e: any) { + window.alert(e.message || 'Failed to save store') + } + } + + return ( +
+ + {isEdit ? 'Edit global store' : 'New global store'} + +
+ setName(e.target.value)} placeholder="e.g. Freshyo Central" /> + setDescription(e.target.value)} placeholder="Optional" /> +
+ setImageUrl(e.target.value)} placeholder="https://…" /> + + {pending ? 'Saving…' : isEdit ? 'Save changes' : 'Create global store'} + +
+ ) +} diff --git a/apps/user-ui/components/ProductDetail.tsx b/apps/user-ui/components/ProductDetail.tsx index 3236538..fc591bb 100644 --- a/apps/user-ui/components/ProductDetail.tsx +++ b/apps/user-ui/components/ProductDetail.tsx @@ -14,6 +14,7 @@ import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from ' import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier'; import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'; import { useSlots } from '@/src/hooks/prominent-api-hooks'; +import { useRegion } from '@/src/hooks/useRegion'; import FloatingCartBar from './floating-cart-bar'; import { useStoreHeaderStore } from '@/src/store/storeHeaderStore'; import { useCartStore } from '@/src/store/cartStore'; @@ -50,7 +51,8 @@ const ProductDetail: React.FC = ({ productId, isFlashDeliver const [hasMore, setHasMore] = useState(true); const [reviewsOffset, setReviewsOffset] = useState(0); const [refreshing, setRefreshing] = useState(false); - const { data: productDetail, isLoading, error, refetch } = trpc.user.product.getProductDetails.useQuery({ id: productId }); + const { regionId: activeRegionId } = useRegion(); + const { data: productDetail, isLoading, error, refetch } = trpc.user.product.getProductDetails.useQuery({ id: productId, regionId: activeRegionId ?? undefined }); const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular"; const { addToCart = () => {} } = useAddToCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, cartType) || {}; const { addToCart:addTOFlashCart = () => {} } = useAddToCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, 'flash') || {}; diff --git a/apps/user-ui/src/hooks/prominent-api-hooks.ts b/apps/user-ui/src/hooks/prominent-api-hooks.ts index f844733..5e5d687 100644 --- a/apps/user-ui/src/hooks/prominent-api-hooks.ts +++ b/apps/user-ui/src/hooks/prominent-api-hooks.ts @@ -190,6 +190,7 @@ export function useAllProducts() { isFlashAvailable: availability?.isFlashAvailable ?? false, isOutOfStock: availability?.isOutOfStock ?? false, isSuspended: availability?.isSuspended ?? false, + isOffer: availability?.isOffer ?? false, } }) }, [productsQuery.data, availabilityData]) @@ -199,7 +200,7 @@ export function useAllProducts() { return { ...productsQuery.data, products: mergedProducts, - } as ProductsResponse & { products: MergedProduct[] } + } as Omit & { products: MergedProduct[] } }, [productsQuery.data, mergedProducts]) return { diff --git a/apps/web-ui/src/hooks/prominent-api-hooks.ts b/apps/web-ui/src/hooks/prominent-api-hooks.ts index fc88b20..139a97a 100644 --- a/apps/web-ui/src/hooks/prominent-api-hooks.ts +++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts @@ -241,6 +241,7 @@ export function useAllProducts() { isFlashAvailable: availability?.isFlashAvailable ?? false, isOutOfStock: availability?.isOutOfStock ?? false, isSuspended: availability?.isSuspended ?? false, + isOffer: availability?.isOffer ?? false, } }) }, [productsQuery.data, availabilityData]) @@ -250,7 +251,7 @@ export function useAllProducts() { return { ...productsQuery.data, products: mergedProducts, - } as ProductsResponse & { products: MergedProduct[] } + } as Omit & { products: MergedProduct[] } }, [productsQuery.data, mergedProducts]) return { diff --git a/change-log.txt b/change-log.txt index 2e0c898..ad6d407 100644 --- a/change-log.txt +++ b/change-log.txt @@ -2230,3 +2230,313 @@ user-ui Docs (no code): docs/e2e-sanity-failed-cases.md FC-19 + summary row; docs/e2e-sanity-test-results.md RG-02 + its defect row. No migrations run. No tests run. + +[2026-10-10 13:12:28 +0530] Moved + timestamped the E2E reports into docs/test reports/. + - docs/e2e-sanity-failed-cases.md -> docs/test reports/e2e-sanity-failed-cases-2026-10-10-1310.md + - docs/e2e-sanity-test-results.md -> docs/test reports/e2e-sanity-test-results-2026-10-10-1310.md + - Updated cross-references in both files and in docs/maestro-mcp-agent-guidelines.md. + (Historical change-log entries above keep the old paths.) No application source changed. + +[2026-10-10 13:42:06 +0530] Move `is_offer` from product_skus -> product_market_stats (the + availability table). isOffer is dropped from products.json and now travels in + availability.json only; the apps read it from the availability merge. Combo-item + isOffer and the admin SKU payload stay (different payloads), still sourced from + product_market_stats. New hand-written migration 0009 (NOT run). + + --- a/packages/db_helper_sqlite/src/db/schema.ts + +++ b/packages/db_helper_sqlite/src/db/schema.ts + @@ productSkus + - isOffer: integer('is_offer', { mode: 'boolean' }).notNull().default(false), + isComboOnly: ... + @@ productMarketStats + + isOffer: integer('is_offer', { mode: 'boolean' }).notNull().default(false), + isSuspended: ... + + --- a/packages/shared/types/user.ts + +++ b/packages/shared/types/user.ts + @@ ProductDetailCore + - isOffer?: boolean; + isComboOnly?: boolean; + @@ ProductPriceFlags + + isOffer: boolean; + + --- a/packages/db_helper_sqlite/src/stores/store-helpers.ts + +++ b/packages/db_helper_sqlite/src/stores/store-helpers.ts + @@ ProductBasicData + - isOffer: boolean + @@ getAllProductsForCache + - isOffer: sku.isOffer ?? false, + @@ getAllProductCombosForCache + - isOffer: ci.sku?.isOffer ?? false, + + isOffer: ci.sku?.marketStats?.isOffer ?? false, + @@ getAvailabilityForCache + + isOffer: stat.isOffer, + + --- a/packages/db_helper_sqlite/src/user-apis/product.ts + +++ b/packages/db_helper_sqlite/src/user-apis/product.ts + - isOffer: ci.sku?.isOffer ?? false, + + isOffer: ci.sku?.marketStats?.isOffer ?? false, + + --- a/packages/db_helper_sqlite/src/admin-apis/product.ts + +++ b/packages/db_helper_sqlite/src/admin-apis/product.ts + @@ mapSku + - isOffer: sku.isOffer, + + isOffer: marketStats?.isOffer ?? false, + @@ createProduct / updateProduct + - isOffer in the productSkus insert/update + + isOffer moved into the productMarketStats insert/marketStatsValues + + --- a/apps/backend/src/trpc/apis/common-apis/common.ts + +++ b/apps/backend/src/trpc/apis/common-apis/common.ts + - isOffer: product.isOffer, (products.json no longer carries it) + + --- a/apps/backend/src/stores/product-store.ts + +++ b/apps/backend/src/stores/product-store.ts + - isOffer: boolean (interface) and - isOffer: product.isOffer, (mapping) + + --- a/apps/user-ui/src/hooks/prominent-api-hooks.ts + +++ b/apps/user-ui/src/hooks/prominent-api-hooks.ts + --- a/apps/web-ui/src/hooks/prominent-api-hooks.ts + +++ b/apps/web-ui/src/hooks/prominent-api-hooks.ts + @@ merge + + isOffer: availability?.isOffer ?? false, + + New file: packages/db_helper_sqlite/drizzle/0009_move_is_offer_to_market_stats.sql + ALTER TABLE product_market_stats ADD COLUMN is_offer ...; backfill from product_skus; + ALTER TABLE product_skus DROP COLUMN is_offer. + No migrations run. No tests run. + + Type fix: both apps' useAllProducts merged-data cast changed from + `ProductsResponse & { products: MergedProduct[] }` to + `Omit & { products: MergedProduct[] }` — with isOffer + gone from the base product, the array intersection otherwise resolved .products to + the base element type (user-ui order-again filter failed typecheck). + Verified: migration run on a COPY of the local D1 (SQLite 3.42) — column moved, + backfill of a synthetic offer sku + the orphan-offer safety net both correct. + tsc --noEmit: backend, admin-ui, user-ui PASS; web-ui has 12 pre-existing unrelated + errors (cacheVersion/freeDeliveryThreshold), none isOffer-related. No live probe + (dev DB not migrated). + +[2026-10-10 14:09:38 +0530] Docs only (no code): added the global-stores-and-products + implementation plans under docs/impl-plans/ — README + phase-1 (per-region + product_market_stats), phase-2 (global stores/products backend), phase-3 (admin UI), + phase-4 (superadmin UI). No source changed. No migrations run. No tests run. + +[2026-10-10 14:13:30 +0530] Docs only (no code): resolved the Phase-2 new-region seeding + decision — on region create, replicate the least-id region's global data (its + per-region product_market_stats rows for global SKUs) into the new region. Updated + docs/impl-plans/README.md, phase-2 §3, phase-4 §7. No source changed. + +[2026-10-10 14:16:37 +0530] Docs only (no code): since migration 0006 (merged regionalization, + recreates store_info/product_info/product_market_stats/...) is not applied yet, revised the + plans to fold all schema changes into 0006's __new_* rebuilds instead of separate 0010/0011 + recreate migrations. Updated docs/impl-plans/README.md (migration strategy), phase-1 §4/§8, + phase-2 §3/§10/§11. Noted 0009 (is_offer move) as a candidate to fold into 0006 too (open + question). No source changed. No migrations run. + +[2026-10-10 14:22:19 +0530] Fold the 0009 (is_offer move) into the unapplied 0006 migration; + delete 0009_move_is_offer_to_market_stats.sql. Phase 1/2 schema folds (region_id / + is_suspended_in_region / is_global) intentionally NOT applied yet — they stay documented as + build-time edits to 0006 because region_id NOT NULL would break current market-stats writes. + + --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + +++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + @@ __new_product_skus (is_offer removed) + - `is_offer` integer DEFAULT false NOT NULL, + - INSERT INTO `__new_product_skus` (...,`is_offer`,...) SELECT ...,`is_offer`,... + + INSERT INTO `__new_product_skus` (...,...) SELECT ...,... + @@ __new_product_market_stats (is_offer added + backfilled from old product_skus) + + `is_offer` integer DEFAULT false NOT NULL, + @@ copy + - INSERT ... SELECT id,sku_id,market_price,our_price,is_flash_available,flash_price,is_out_of_stock,is_suspended FROM product_market_stats; + + INSERT ... (...,`is_offer`) SELECT ms.id,ms.sku_id,ms.market_price,ms.our_price,ms.is_flash_available,ms.flash_price,ms.is_out_of_stock,ms.is_suspended,COALESCE(ps.is_offer,false) + + FROM product_market_stats ms JOIN product_skus ps ON ps.id = ms.sku_id; (JOIN also prunes the 3 orphan rows) + (index `product_market_stats_sku_id_unique` left unchanged) + + Deleted: packages/db_helper_sqlite/drizzle/0009_move_is_offer_to_market_stats.sql + Docs: docs/impl-plans/README.md + phase-1 updated. No migrations run. No tests run. + +[2026-10-10 14:25:07 +0530] Phase 1 — per-region product_market_stats (region-scoped market data). + Adds region_id (NOT NULL) + is_suspended_in_region to product_market_stats, moves the unique + key to (sku_id, region_id), folds the DDL into the pending 0006 rebuild, changes the + productSkus.marketStats relation one->many, and region-scopes every read/write. + + --- a/packages/db_helper_sqlite/src/db/schema.ts + +++ b/packages/db_helper_sqlite/src/db/schema.ts + @@ productMarketStats + - skuId: integer('sku_id').notNull().references(() => productSkus.id).unique(), + + skuId: integer('sku_id').notNull().references(() => productSkus.id), + + regionId: integer('region_id').notNull().references(() => regions.id), + ... isSuspended ... + + isSuspendedInRegion: integer('is_suspended_in_region', { mode: 'boolean' }).notNull().default(false), + isOffer: ... + -}) + +}, (t) => ({ unq_sku_region: uniqueIndex('product_market_stats_sku_region').on(t.skuId, t.regionId) })) + @@ relations + - marketStats: one(productMarketStats), + + marketStats: many(productMarketStats), + @@ productMarketStatsRelations + + region: one(regions, { fields: [productMarketStats.regionId], references: [regions.id] }), + + --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + +++ a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + @@ __new_product_market_stats + + `region_id` integer NOT NULL, + + `is_suspended_in_region` integer DEFAULT false NOT NULL, + + FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ... + @@ copy + + region_id=(SELECT id FROM regions WHERE name='Mahabubnagar'), is_suspended_in_region=false + @@ index + - CREATE UNIQUE INDEX `product_market_stats_sku_id_unique` ON `product_market_stats` (`sku_id`); + + CREATE UNIQUE INDEX `product_market_stats_sku_region` ON `product_market_stats` (`sku_id`,`region_id`); + + New file: packages/db_helper_sqlite/src/lib/market-stats.ts (marketStatsForRegion helper) + + Region-scoped reads/writes (pick the region row; check isSuspended + isSuspendedInRegion): + - stores/store-helpers.ts: getAllProductsForCache, getAvailabilityForCache (region filter), + getAllProductCombosForCache, suspended-sku set, getAllSlotsWithProductsForCache. + - user-apis/product.ts: getProductDetailById, combo items, getProductById, getAllProductsWithUnits + (+ regionId param), getSuspendedSkuIds (region filter), getAllSkusSummary. + - user-apis/order.ts: getProductById (derive region from product). + - user-apis/stores.ts: getStoreSummaries, getStoreDetail. + - user-apis/slots.ts: getProductAvailability (region filter). + - admin-apis/product.ts: mapSku callers, getAllProducts, getProductById, createProduct, + updateProduct, updateProductPrices, toggleProductOutOfStock, tags/groups mapSku callers. + - admin-apis/order.ts: latest-price lookups region-scoped. + - apps/backend/.../user-apis/apis/order.ts: unavailability check adds isSuspendedInRegion. + + No migrations run. No tests run. + +[2026-10-10 14:32:30 +0530] Revise Phase 1 suspension model: global `is_suspended` moves to + product_skus; product_market_stats keeps only the per-region `is_suspended_in_region` + (drop its `is_suspended`). Phase-1 admin write still targets the global flag (superadmin/ + region split stays Phase 2). + + --- a/packages/db_helper_sqlite/src/db/schema.ts + +++ a/packages/db_helper_sqlite/src/db/schema.ts + @@ productSkus + + isSuspended: integer('is_suspended', { mode: 'boolean' }).notNull().default(false), + @@ productMarketStats + - isSuspended: integer('is_suspended', { mode: 'boolean' }).notNull().default(false), + isSuspendedInRegion: ... (kept) + + --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + +++ a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + @@ __new_product_skus + + `is_suspended` integer DEFAULT false NOT NULL, + + copy: is_suspended = COALESCE((SELECT is_suspended FROM product_market_stats WHERE sku_id=product_skus.id), false) + @@ __new_product_market_stats + - `is_suspended` integer DEFAULT false NOT NULL, (and dropped from its copy) + + --- a/packages/db_helper_sqlite/src/lib/market-stats.ts + +++ ... + - isMarketStatsSuspended(stats) + + isSkuSuspended(globalSuspended, stats) // global (sku) OR per-region + + Reads/writes updated so a SKU is suspended when product_skus.is_suspended (global) OR + product_market_stats.is_suspended_in_region (region): + - store-helpers.ts (products cache, availability cache, combos suspended-set, slots) + - user-apis/product.ts (detail, getAllProductsWithUnits, getSuspendedSkuIds, getAllSkusSummary) + - user-apis/stores.ts + - admin-apis/product.ts: mapSku reads sku.isSuspended; createProduct/updateProduct write the + global flag (productSkus) and drop it from market stats; combo-suspend check uses both. + - apps/backend/.../user-apis/apis/order.ts: product.isSuspended || marketStats.isSuspendedInRegion + + No migrations run. No tests run. + +[2026-10-10 14:37:08 +0530] Phase 2 (global stores/products, backend) + remove the store->admin + owner attachment. + + OWNER REMOVAL: + - schema.ts: storeInfo drops `owner` (and storeInfoRelations.owner). + - 0006: `__new_store_info` drops `owner` (column, FK, copy). + - shared: Store.owner removed; CreateStoreInput/UpdateStoreInput.owner removed. + - db_helper_sqlite admin-apis/store.ts: drop assertOwnerInRegion + owner from reads/mapping. + - admin-apis/product.ts mapStore: drop owner. staff-user.ts deleteStaffUser: drop the + store-owner block. + - backend admin store.ts: drop owner from zod/create/update. + - admin-ui + admin-web StoreForm/screens + tests: drop the owner picker. + + PHASE 2 (global stores/products): + - schema.ts: storeInfo gains `isGlobal` (region_id/owner nullable); productInfo.regionId + nullable (already in schema). + - 0006: `__new_store_info` region_id nullable + `is_global`; `__new_product_info` region_id + nullable. + - NEW packages/db_helper_sqlite/src/superadmin-apis/{global-stores,global-products}.ts + (CRUD + per-region market-stats seeding + isGlobalStore). + - NEW superadmin routers globalStores/globalProducts; registered in superadmin-trpc-index. + - regions.ts createRegionWithBounds: seed new region's global-SKU market rows from the + least-id region (compensating cleanup). + - Visibility/guards: admin product/store reads include global; assert*/resolve* accept + global; store-helpers/user stores include global; getAllSkusSummary includes global. + - Write scoping: admin updateProduct on a global product applies only market-stats fields. + - Region resolution: getOrderProductById + getProductDetailById accept a regionId. + - Cache regen: global structural writes regen all regions. + + No migrations run. No tests run. + +[2026-10-10 14:44:58 +0530] Phase 2 follow-ups (region resolution + edit paths). + - user-apis/order.ts getProductById(skuId, regionId?) + placeOrderUtil passes the order + region (both call sites) -> global SKUs price from the order region's row. + - user-apis/product.ts getProductDetailById(skuId, regionId?) and the public + user.product.getProductDetails input now accepts an optional regionId; region = + sku product region ?? client region. + - admin-apis/product.ts updateProduct(regionId | null, id, input): global product edited by + a regional admin -> updateProductMarketDataForRegion (market fields only, their region); + regionId null (superadmin structural edit) leaves each region's market data untouched and + seeds new SKUs to every region. createProduct|updateProduct return picks + regionId ?? targetRegionIds[0]. + - superadmin-apis/global-products.ts updateGlobalProduct (structural) + globalProducts.update + router procedure; exported from the package index. + No migrations run. No tests run. + +[2026-10-10 14:50:23 +0530] Phase 3 — admin UI for global products/stores (admin-ui + admin-web). + - shared: AdminProduct gains isGlobal; admin-apis/product.ts mapProduct sets it + (product.regionId == null). + - admin-ui: NEW src/components/GlobalProductForm.tsx (read-only structure + editable + market fields for the admin's region); products/edit.tsx branches to it when + product.isGlobal; products/index.tsx shows a GLOBAL badge; stores/edit.tsx renders a + read-only view for global stores. + - admin-web: NEW src/components/GlobalProductForm.tsx; dashboard.products.edit.tsx + branches to it; dashboard.products.tsx shows a GLOBAL badge; dashboard.stores.edit.tsx + renders a read-only view for global stores. + tsc --noEmit: admin-ui, admin-web, backend PASS. No migrations run. No tests run. + +[2026-10-10 14:51:58 +0530] Phase 3 polish. + - Products list: added a "Global" filter chip (All / In Stock / Out of Stock / Global) in + admin-ui products/index.tsx and admin-web dashboard.products.tsx. + - Stores list: global store rows no longer show delete and are not navigable to edit + (admin-ui stores/index.tsx, admin-web dashboard.stores.tsx): the edit screen stays + read-only and delete is superadmin-only. + - user-ui ProductDetail passes the active regionId to user.product.getProductDetails so + global SKUs resolve price/availability for the user's region. + tsc --noEmit: backend, admin-ui, admin-web, user-ui PASS. No migrations run. No tests run. + +[2026-10-10 14:54:10 +0530] Phase 4 — superadmin UI for global stores/products (apps/superadmin-ui). + - NEW src/routes/global-stores.tsx: list + create/edit/delete global stores + (superadmin.globalStores.*), GLOBAL badge, image URL field. + - NEW src/routes/global-products.tsx: list + create/delete global products + (superadmin.globalProducts.*) with a global-store select and per-SKU price/stock/ + quantity-feature; deleting confirms; shows per-SKU region-row count. + - AppShell NAV + dashboard cards gain Global Stores / Global Products (Store, Package icons). + - routeTree.gen.ts updated with /global-stores + /global-products + (TanStack Router regenerated it cleanly; no duplicates). + tsc --noEmit: superadmin-ui PASS. No migrations run. No tests run. + +[2026-10-10 14:55:15 +0530] Phase 4 — superadmin global-product EDIT UI (full parity). + - superadmin-apis/global-products.ts: list/get payload now includes sku comboItems. + - apps/superadmin-ui/src/routes/global-products.tsx: shared GlobalProductForm now + create + edit; edit prefills name/descriptions/store/type and every SKU (name, price, + marketPrice, features add/remove, out-of-stock, offer, combo-only, deleted, global + suspended) and calls superadmin.globalProducts.update; list has an Edit action + cancel. + tsc --noEmit: superadmin-ui, backend PASS. No migrations run. No tests run. + +[2026-10-10 14:57:27 +0530] Superadmin UI — image upload for global products. + - backend: trpc-index.ts adds authenticatedProcedure (user | staff | superadmin); + common.generateUploadUrls now uses it so superadmins can request presigned URLs. + - superadmin global-products router (create/update) stores sku.images as-is (keys) instead + of running extractKeyFromPresignedUrl (the UI uploads and sends keys). + - apps/superadmin-ui: NEW src/hooks/useUploadToObjectStorage.ts (presigned PUT helper); + global-products.tsx adds per-SKU image picking (existing keys + new uploads with previews + + remove) and uploads on submit with contextString 'product_info'. + tsc --noEmit: superadmin-ui, backend PASS. No migrations run. No tests run. diff --git a/docs/impl-plans/README.md b/docs/impl-plans/README.md new file mode 100644 index 0000000..ca6e69e --- /dev/null +++ b/docs/impl-plans/README.md @@ -0,0 +1,75 @@ +# Global Stores & Products — Implementation Plans + +Feature: **global stores and global products** that exist across every region, with +**per-region market data** (price / stock / offer / region suspension) on +`product_market_stats`. + +Status: **planned, not started.** Do not begin Phase 2 until Phase 1 is verified. + +## Confirmed decisions + +| Decision | Choice | +|---|---| +| Global store admin access | **Read-only for regional admins.** Only superadmins create/edit/delete global stores. | +| Global product defaults | Superadmin enters initial price/flags on create → **a market-stats row is seeded for every region** (and for future regions when created). | +| Seeding a new region | On region create, **replicate the least-id region's global data** (its per-region market-stats rows for global SKUs) into the new region. | +| Suspension | Global `is_suspended` lives on **`product_skus`** (superadmin only). Per-region `is_suspended_in_region` lives on **`product_market_stats`** (that region's admin). The admin "suspend" toggle moves to the region flag in Phase 2. | +| "Global" representation | `store_info.is_global = 1` **and** `region_id = NULL`; a product is global iff its store is global. | +| Rollout | **Phased:** backend → admin UI → superadmin UI. | +| Global SKUs in slots/banners/tags/coupons | Allowed in every region (they resolve as "global"). | + +## Phases + +1. [Phase 1 — Per-region `product_market_stats`](./phase-1-per-region-market-stats.md) + *Schema + migration + region-scoped read/write refactor. No "global" yet; existing + regional behaviour must stay identical.* +2. [Phase 2 — Global stores & products (backend)](./phase-2-global-stores-and-products-backend.md) + *`is_global` + nullable region, superadmin routers + seeding, visibility, guards, + per-region admin writes, cache regen.* +3. [Phase 3 — Admin UI (RN + web)](./phase-3-admin-ui.md) + *List global + regional products, separate read-only/global-edit component, read-only + global stores.* +4. [Phase 4 — Superadmin UI](./phase-4-superadmin-ui.md) + *Global store + global product CRUD screens.* + +## Cross-cutting ground rules + +- **Do not run migrations.** All migration SQL is hand-written and applied by the user. + Validate migration changes on a **fresh/copy DB** first. +- **Do not run the test suites** unless asked. `tsc --noEmit` is fine. +- Log every non-`.md`/`.txt` file change in `change-log.txt` (timestamp + diff) **before** + editing. +- Working tree is uncommitted; the user manages git. +- Local D1 path (used for copies/probes): + `apps/backend/.wrangler/state/v3/d1/miniflare-D1DatabaseObject/da3a80bd8d2cc8f1f070a313ef55c1800da50af994fa89a51c67a6d3e1f919f2.sqlite` + +## Migration strategy — fold schema changes into the pending `0006` + +`packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql` is **not applied yet** and +already **rebuilds** `store_info`, `product_info`, `product_skus`, `product_market_stats`, and +the rest of the region-ownership FK subgraph through `__new_*` tables. + +So instead of writing separate recreate migrations (`0010`/`0011`), **edit `0006`'s `__new_*` +DDL/copies directly**: +- Phase 1 (per-region market stats) → edit `__new_product_market_stats`. +- Phase 2 (global stores/products) → edit `__new_store_info` + `__new_product_info`. + +This removes the risky standalone table recreates entirely: `0006` already rebuilds the whole +connected subgraph in dependency order, so no FK-deferral juggling is needed. See each phase's +§Migration for the exact edits. + +> **Pending-migration set (after the `is_offer` fold).** `0007_addresses_bound_id` and +> `0008_user_creds_unique_and_min_order_cleanup` are unrelated to these tables and stay as-is. +> `0009_move_is_offer_to_market_stats` has been **folded into `0006` and deleted** — `0006` now +> drops `is_offer` from `__new_product_skus` and adds it to `__new_product_market_stats` +> (backfilled from the old `product_skus`). + +> **Why Phases 1–2 are not folded yet.** Phase 1 makes `product_market_stats.region_id` `NOT NULL`; +> until the Phase 1 write paths set it, the current code (`createProduct`/`updateProduct` insert +> market stats without a region) would fail. Phase 2's `store_info`/`product_info` changes *are* +> safe, but they're kept together with Phase 1's edit so the whole per-region/global schema lands +> in one edit to `0006` when those phases are built. + +> **DB state caveat:** the local dev D1 already contains `0006`'s *effects* (no +> `d1_migrations` table — it was applied by hand). Editing `0006` means the local DB no longer +> matches the file; validation requires **resetting local D1 and re-applying from `0000`**. diff --git a/docs/impl-plans/phase-1-per-region-market-stats.md b/docs/impl-plans/phase-1-per-region-market-stats.md new file mode 100644 index 0000000..2e3beb7 --- /dev/null +++ b/docs/impl-plans/phase-1-per-region-market-stats.md @@ -0,0 +1,240 @@ +# Phase 1 — Per-region `product_market_stats` + +Status: **✅ implemented 2026-10-10** (backend + sqlite helper; migration folded into `0006`). +Depends on: nothing. +Blocks: Phases 2–4. + +> **Implementation notes** +> - New `packages/db_helper_sqlite/src/lib/market-stats.ts` (`marketStatsForRegion`, +> `isMarketStatsSuspended`). +> - `productSkus.marketStats` is now a `many` relation; every `with: { marketStats: true }` +> site picks the region row. +> - `getProductDetailById` / `getProductById` (user + order) derive the region from the SKU's +> product row; `getAllProductsWithUnits` picks per-SKU region. +> - `getOrderProductById` now returns a single region-picked `marketStats` object; the order +> path reads `product.isSuspended` (global) / `product.marketStats?.isSuspendedInRegion`. +> - Suspension: a SKU is unavailable when `product_skus.is_suspended` (global) **or** +> `product_market_stats.is_suspended_in_region` (per region) — helper `isSkuSuspended`. The +> admin product write still sets the **global** `productSkus.isSuspended` in Phase 1; the +> superadmin/region split lands in Phase 2. +> - `getAvailabilityForCache` / `getProductAvailability` / `getSuspendedSkuIds` / +> `updateProductPrices` / `toggleProductOutOfStock` / `updateProduct` / `createProduct` are +> all region-filtered. +> - The `0006` copy backfills every pre-existing market-stats row to the seeded region +> (Mahabubnagar), matching the product backfill — so a fresh apply leaves regions 2+ empty +> until products are created there (as before). +> - Verified: `tsc --noEmit` backend/admin-ui/user-ui PASS (web-ui's 12 pre-existing errors +> unchanged); `0000`→`0006` + data on a fresh DB yields `region_id=1`, `is_offer`, +> `is_suspended_in_region` correctly. + +## 1. Goal + +Turn `product_market_stats` from **1 row per SKU** into **1 row per (SKU, region)** so that a +region's price / stock / offer / suspension live in that region's own row. This phase does +**not** introduce global products yet — it only makes the market data region-scoped. + +**Success criterion:** after Phase 1, the customer caches (`products.json`, +`availability.json`) and admin product screens for regions 1/2/3 are **identical to today** +(same prices, stock, availability). No behaviour change for existing regional products. + +## 2. Non-goals + +- No `is_global`, no `store_info`/`product_info` changes, no superadmin UI. +- No global products (that's Phase 2). The region a market-stats row belongs to is derived + from the SKU's product row. + +## 3. Data model + +### `packages/db_helper_sqlite/src/db/schema.ts` + +`productMarketStats` (currently lines ~204–214): + +```ts +export const productMarketStats = sqliteTable('product_market_stats', { + id: integer().primaryKey({ autoIncrement: true }), + skuId: integer('sku_id').notNull().references(() => productSkus.id), + regionId: integer('region_id').notNull().references(() => regions.id), + marketPrice: numericText('market_price'), + ourPrice: numericText('our_price').notNull(), + isFlashAvailable: integer('is_flash_available', { mode: 'boolean' }).notNull().default(false), + flashPrice: numericText('flash_price'), + isOutOfStock: integer('is_out_of_stock', { mode: 'boolean' }).notNull().default(false), + isSuspendedInRegion: integer('is_suspended_in_region', { mode: 'boolean' }).notNull().default(false), + isOffer: integer('is_offer', { mode: 'boolean' }).notNull().default(false), +}, (t) => ({ + unq_sku_region: uniqueIndex('product_market_stats_sku_region').on(t.skuId, t.regionId), +})) +``` + +Changes vs today: +- `skuId` loses `.unique()` (was 1:1). +- **new** `regionId` (NOT NULL, FK `regions`). +- **new** `isSuspendedInRegion` (bool, default false). The old market-stats + `isSuspended` is **removed** — global suspension now lives on the SKU + (`productSkus.isSuspended`), and its existing values are backfilled there. +- **new** table-level unique index `(sku_id, region_id)`. +- `productSkus` gains `isSuspended` (bool, default false) — the global + (superadmin) kill-switch. + +### Relations + +- `productSkusRelations`: `marketStats: one(productMarketStats)` → **`many(productMarketStats)`**. +- `productMarketStatsRelations`: add `region: one(regions, { fields: [productMarketStats.regionId], references: [regions.id] })`. + +> A SKU now carries an **array** of market-stats rows. Every consumer must pick the row for +> its `regionId` (helper below). + +## 4. Schema change goes into `0006` (no new migration) + +`packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql` is **not applied yet** and +already rebuilds `product_market_stats` via `__new_product_market_stats`. Fold the per-region +fields into that rebuild instead of a standalone `0010` recreate — `0006` already rebuilds the +whole FK subgraph in dependency order, so no extra recreate is required. + +### Edits to `0006_regions_and_superadmins.sql` + +1. **`CREATE TABLE __new_product_market_stats`** — the `is_offer` column is already folded in + (from `0009`, see README); now add the region column + FK and the region-suspension flag: + ```sql + `region_id` integer NOT NULL, + ... + `is_suspended_in_region` integer DEFAULT false NOT NULL, + ... + FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action + ``` + +2. **Its copy `INSERT INTO __new_product_market_stats … SELECT …`** — add `region_id` and + `is_suspended_in_region` (the copy already selects `is_offer` and JOINs `product_skus` from the + `0009` fold). All pre-existing rows are backfilled to Mahabubnagar: + ```sql + INSERT INTO `__new_product_market_stats` + (`id`,`sku_id`,`region_id`,`market_price`,`our_price`,`is_flash_available`,`flash_price`,`is_out_of_stock`,`is_suspended`,`is_suspended_in_region`,`is_offer`) + SELECT + ms.`id`, ms.`sku_id`, (SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar'), + ms.`market_price`, ms.`our_price`, ms.`is_flash_available`, ms.`flash_price`, + ms.`is_out_of_stock`, ms.`is_suspended`, false, COALESCE(ps.`is_offer`, false) + FROM `product_market_stats` ms + JOIN `product_skus` ps ON ps.`id` = ms.`sku_id`; + ``` + - The `JOIN product_skus` (already present from the `0009` fold) prunes **orphan** market-stats + rows whose SKU no longer exists. + +3. **Replace the index** created at the end of `0006`: + `CREATE UNIQUE INDEX product_market_stats_sku_id_unique ON product_market_stats (sku_id)` + → `CREATE UNIQUE INDEX product_market_stats_sku_region ON product_market_stats (sku_id, region_id)`. + +**Validation:** apply the edited `0006` (from `0000`) to a **fresh** DB copy; confirm +`pragma table_info(product_market_stats)` shows `region_id` + `is_suspended_in_region`, the new +unique index exists, and there is exactly one row per SKU with `region_id` = the seeded region. + +## 5. Region-aware access helper + +Add a small shared helper (e.g. `packages/db_helper_sqlite/src/lib/market-stats.ts`): + +```ts +export type MarketStatsRow = InferSelectModel +export function marketStatsForRegion(stats: MarketStatsRow[] | undefined, regionId: number): MarketStatsRow | undefined { + return stats?.find((s) => s.regionId === regionId) +} +``` + +Where a function does not currently receive a `regionId` (see §6), derive it from the SKU's +product row (`sku.product.regionId`) in this phase. + +## 6. Code changes + +Every `with: { marketStats: true }` now returns an **array**; every `.marketStats` read must +pick the region's row and suspension must test **both** flags +(`!is_suspended && !is_suspended_in_region`). + +### `packages/db_helper_sqlite/src/stores/store-helpers.ts` +| Site | Change | +|---|---| +| `getAllProductsForCache` (~121,126,129) | `marketStats` array → `marketStatsForRegion(..., regionId)`; suspension check adds `isSuspendedInRegion`; region filter stays `product.regionId === regionId` (Phase 2 adds global). | +| `getAvailabilityForCache` (~154) | query is already `productMarketStats.findMany` — add `eq(productMarketStats.regionId, regionId)` and filter `!isSuspended && !isSuspendedInRegion`. | +| `getAllProductCombosForCache` (~246,274) | `ci.sku.marketStats` → pick region row. | +| suspended-sku set (~252–260) | add `regionId` to the `where`. | +| `getAllSlotsWithProductsForCache` (~389,408) | pick region row; suspension filter adds region flag. | + +### `packages/db_helper_sqlite/src/user-apis/product.ts` +| Site | Change | +|---|---| +| `getProductDetailById(skuId)` (~12–31) | no region param → derive `sku.product.regionId`; pick row; suspension check both flags. | +| combo items (~56,68) | pick region row. | +| `getProductById(skuId)` (~143–165) | derive region from product; pick row. | +| `getAllProductsWithUnits(tagId?)` (~217) | **no region** — add a `regionId` parameter (see below). | +| `getSuspendedSkuIds(regionId)` (~271) | add `regionId` filter to the query. | +| `getAllSkusSummary(regionId)` (~347) | pick region row; suspension check both flags. | + +> `getAllProductsWithUnits` is only consumed by the legacy controller +> `apps/backend/src/apis/common-apis/apis/common-product.controller.ts` (pre-tRPC). Give it a +> `regionId` param and pass the caller's region there, or note it as legacy if that controller +> is dead. + +### `packages/db_helper_sqlite/src/user-apis/order.ts` +- `getProductById(skuId)` (~194–219) — derive region from product; pick row. (Phase 2 will add + an explicit region for global SKUs.) + +### `packages/db_helper_sqlite/src/user-apis/stores.ts` +- `getStoreSummaries(regionId)` (~21,24) — pick region row. +- `getStoreDetail(regionId, storeId)` (~81,87,90) — pick region row. + +### `packages/db_helper_sqlite/src/user-apis/slots.ts` +- `getProductAvailability(regionId)` (~37–61) — add `eq(productMarketStats.regionId, regionId)`. + +### `packages/db_helper_sqlite/src/admin-apis/product.ts` (largest) +- `mapSku` already takes a `marketStats` arg → callers must pass the region row. +- `getAllProducts(regionId)` (~211–250): pick region row for `mapSku`; combo-item prices too. +- `getProductById(regionId, id)` (~252): pick region row. +- `createProduct` (~382): write `regionId` into the inserted market-stats row. +- `updateProduct` (~535–556): upsert by `(skuId, regionId)` instead of `skuId`. +- `updateProductPrices(regionId, …)` (~1118–1136): upsert by `(skuId, regionId)`. +- `toggleProductOutOfStock(regionId, productId)` (~1143–1173): this is the **admin** toggle → + it now sets **`is_suspended_in_region`**? *No — see note.* It currently toggles + `is_out_of_stock`; keep it toggling `isOutOfStock` but scope to the region row. +- `getProductTagInfoById` / `getAllProductTags` / groups (~670–952): pass region row to `mapSku`. + +> **Suspension toggle note:** the admin-facing "suspend SKU" path is `updateProduct` with +> `isSuspended` today. In this phase keep writing whatever field the admin sends to the region +> row; Phase 2 changes the admin field to `is_suspended_in_region` and reserves `is_suspended` +> for superadmins. + +### `packages/db_helper_sqlite/src/admin-apis/order.ts` +- `~652,667,673`: picking the latest price for order items — scope to the order's region row + (these queries already run in an order/region context; add the region filter). + +### `apps/backend/src/trpc/apis/user-apis/apis/order.ts` +- `~132` `product.marketStats?.isSuspended` — `getOrderProductById` will return a single, + region-picked stats object after Phase 1; keep reading `isSuspended` and add + `isSuspendedInRegion` to the unavailability check. + +## 7. Cache behaviour + +- `scaffoldProducts(regionId)` / `scaffoldAvailability(regionId)` already take a region, so + once the helpers are region-scoped the per-region caches are correct. +- **Admin market-data writes must regenerate that region only**: `updateProductPrices` and + `toggleOutOfStock` already call `createAvailabilityCacheFile(regionId)`; keep that. Full + `updateProduct` calls `scheduleStoreInitialization(regionId)`. Unchanged. + +## 8. Verification + +1. `bunx tsc --noEmit` on `apps/backend`, `apps/admin-ui`, `apps/user-ui`, `apps/web-ui` + (web-ui has ~12 pre-existing unrelated errors — compare counts). +2. Apply nothing to the dev DB. Validate the **edited `0006`** on a **fresh** DB copy (reset + local D1 and apply from `0000`): `region_id` + `is_suspended_in_region` present, new unique + index, one row per (SKU, region), orphans pruned. +3. Runtime probe (after the user applies the edited `0006`): for a region-1 and a region-2 SKU, + GET `products.json` + `availability.json` and confirm prices/stock match the pre-change values. + +## 9. Risks + +- **Relation churn:** 23 `marketStats: true` sites / 33 `.marketStats` reads. Miss one and it + either silently uses the wrong region's row or reads an array as an object. +- **Order pricing** (`user-apis/order.ts`, `admin-apis/order.ts`) must keep resolving the right + region row — a wrong region row = wrong charged price. +- **Suspension semantics** temporarily live in two places; keep both flags in every filter. + +## 10. Out of scope (Phase 2+) + +Global products/stores, `is_global`, superadmin seeding, admin UI changes, the +`is_suspended` vs `is_suspended_in_region` split enforcement. diff --git a/docs/impl-plans/phase-2-global-stores-and-products-backend.md b/docs/impl-plans/phase-2-global-stores-and-products-backend.md new file mode 100644 index 0000000..432e816 --- /dev/null +++ b/docs/impl-plans/phase-2-global-stores-and-products-backend.md @@ -0,0 +1,194 @@ +# Phase 2 — Global stores & products (backend) + +Status: **not started.** +Depends on: **Phase 1 verified.** +Blocks: Phases 3–4. + +## 1. Goal + +Introduce stores and products that are shared across **all** regions, created and owned by +**superadmins**, visible to **every** regional admin, with per-region market data on top of +Phase 1's `product_market_stats(region_id)`. + +## 2. Model + +- **Global store:** `store_info.is_global = 1`, `store_info.region_id = NULL`, + `store_info.owner = NULL` (a superadmin has no `staff_users` row). +- **Global product:** `product_info.region_id = NULL`, `product_info.store_id` → a global + store. *A product is global iff its store is global.* +- **Market data:** a global SKU has one `product_market_stats` row **per region** (created in + Phase 1's schema). Regional SKUs keep exactly one row (their region). +- **Suspension:** `product_skus.is_suspended = global` (superadmin only) — kills the SKU in + every region. `product_market_stats.is_suspended_in_region = per region` (that region's + admin) — kills it only there. + +## 3. Schema changes go into `0006` (no new migration) + +`0006_regions_and_superadmins.sql` is **not applied yet** and already rebuilds `store_info` and +`product_info` through `__new_*` tables (with `owner`/`region_id` `NOT NULL`). Fold the global +changes into those rebuilds instead of a standalone `0011` recreate — `0006` already rebuilds +the entire connected FK subgraph in dependency order, so **no FK-deferral juggling is needed**. + +### Edits to `0006_regions_and_superadmins.sql` + +1. **`CREATE TABLE __new_store_info`**: + - `owner` → drop `NOT NULL` (global stores have no staff owner). + - `region_id` → drop `NOT NULL` (global stores are region-less). + - add `is_global integer DEFAULT false NOT NULL`: + ```sql + `owner` integer, + `region_id` integer, + `is_global` integer DEFAULT false NOT NULL, + ``` +2. **Its copy `INSERT INTO __new_store_info (…) SELECT …`**: append `is_global` with value + `false`. +3. **`CREATE TABLE __new_product_info`**: `region_id` → drop `NOT NULL` (global products are + region-less). The copy `SELECT` is unchanged — pre-existing rows still get the Mahabubnagar + region id via the existing `(SELECT id FROM regions WHERE name = 'Mahabubnagar')` subquery. +4. Indexes (`idx_store_info_region`, `idx_product_info_region`) are unchanged — a NULL region is + simply not matched by the region index. + +End state: `store_info(owner NULL, region_id NULL, is_global)`, `product_info(region_id NULL)` — +exactly what `schema.ts` declares. + +### Seeding global products per region + +On **global product create** (superadmin), for every SKU insert one `product_market_stats` row +per region using the superadmin's entered values. + +**Seeding a new region (decided).** When a **new region** is created, seed it by **replicating +the least-id region's global data**: +1. `srcRegion = MIN(regions.id)` (the newly created region has the greatest id, so it is never + the source). +2. For every **global** SKU, copy the source region's `product_market_stats` row + (`region_id = srcRegion`) into a new row with `region_id = `. + +Implement inside `createRegionWithBounds` +(`packages/db_helper_sqlite/src/superadmin-apis/regions.ts`), alongside the region + bounds +inserts, and honour the D1 compensating-cleanup pattern from FC-19 (a failure must not leave a +half-seeded region). Global **stores** need no replication — they are region-less +(`region_id NULL`) and already visible in every region. + +## 4. Data helpers + +New `packages/db_helper_sqlite/src/superadmin-apis/global-stores.ts` and `global-products.ts`: +- `listGlobalStores()`, `getGlobalStore(id)`, `createGlobalStore(input)`, + `updateGlobalStore(id, input)`, `deleteGlobalStore(id)`. +- `listGlobalProducts()`, `getGlobalProduct(id)`, `createGlobalProduct(input)`, + `updateGlobalProduct(id, input)`, `deleteGlobalProduct(id)`. +- `seedGlobalProductMarketStats(skuIds | productId, regions, initialValues)`. +- `seedRegionMarketStatsForGlobalSkus(regionId)`, called from `createRegionWithBounds`. +- `isGlobalStore(storeId)` helper. + +Export them from `packages/db_helper_sqlite/index.ts` and add to the **explicit** export list +in `apps/backend/src/sqliteImporter.ts` (`dbService.ts` re-exports it). + +## 5. tRPC routers + +New `apps/backend/src/trpc/apis/superadmin-apis/apis/global-stores.ts` and `global-products.ts`; +register in `superadmin-trpc-index.ts`: + +```ts +export const superadminRouter = router({ + auth, regions, staff, const, + globalStores: superadminGlobalStoresRouter, + globalProducts: superadminGlobalProductsRouter, +}) +``` + +- `globalStores.list/get/create/update/delete` (all `superadminProcedure`). +- `globalProducts.list/get/create/update/delete` (all `superadminProcedure`). +- Global structural writes → regenerate **all** regions' caches + `await scheduleStoreInitialization()` (no region = every region). + +## 6. Visibility & guards (make global valid in every region) + +### Reads +- `admin-apis/product.ts` + - `getAllProducts(regionId)`: include `product.region_id = regionId OR `. + - `getProductById(regionId, id)`: allow global. + - `getAllSkusSummary(regionId)` (`user-apis/product.ts`): include global SKUs (admin pickers). +- `admin-apis/store.ts` + - `getAllStores(regionId)`: `region_id = regionId OR is_global = 1`. + - `getStoreById(regionId, id)`: allow global. +- `stores/store-helpers.ts` + - `getAllProductsForCache(regionId)`: include global SKUs; use the region's market-stats row. + - `getAvailabilityForCache(regionId)`: include global SKUs' region rows. + - `getAllStoresForCache(regionId)`: include global stores. +- `user-apis/stores.ts` `getStoreSummaries`/`getStoreDetail`: include global stores. + +### Guards — accept global, still reject other regions +- `assertStoreInRegion`, `assertStoreIdsInRegion`, + `assertSkuIdsInRegion`/`resolveSkuRegions` (`admin-apis/product.ts`). +- `resolveInRegionProductIds` (`admin-apis/store.ts`). +- Slot/banner/tag/group/coupon resolvers that validate SKU/store regions + (`admin-apis/{slots,banner}.ts`, `replaceTagProducts`, coupon create/update). + **Assumption:** a global SKU/store is valid in every region. +- `deleteStore`: a global store may only be deleted by a superadmin and only when no products + reference it. + +## 7. Write scoping + +- **Admin editing a global product:** accept **only** market-stats fields + (`price`, `marketPrice`, `flashPrice`, `isFlashAvailable`, `isOutOfStock`, + `isSuspendedInRegion`, `isOffer`) and apply them to the caller region's row. Reject/ignore + structural fields (name, descriptions, images, incrementStep, SKUs/features, combos, store, + productType). Implement in `updateProduct` (branch on `product.region_id == null` / + global store). +- **Admin editing a regional product:** unchanged (full edit). +- **Admin cannot** create/update/delete global stores, nor create/delete global products. +- `updateProductPrices` / `toggleProductOutOfStock`: already region-scoped (Phase 1) — they + work for global SKUs too. +- **Suspension split:** admin product update writes `is_suspended_in_region`; `is_suspended` + is writable only via the superadmin global-product path. +- `checkProductExistsByName`: decide scoping — recommend **global names globally unique**, + regional names unique within their region. + +## 8. Region resolution for global SKUs (user-facing) + +Once a SKU can be global, functions that resolved a region from the product row must receive +one explicitly: +- `getOrderProductById(skuId)` (`user-apis/order.ts`) → add `regionId`; `placeOrderUtil` + (`apps/backend/src/trpc/apis/user-apis/apis/order.ts`) passes the order region. Verify the + `isSuspended || isSuspendedInRegion` check (~132) uses the region row. +- `getProductDetails` / `getProductDetailById` (`apps/backend/src/trpc/apis/user-apis/apis/product.ts` + + `user-apis/product.ts`): add an optional `regionId`; the app already knows its region + (`useRegion`). Regional products fall back to the product's own region. +- `admin-apis/order.ts` price lookups: scope to the order's region row. + +## 9. Cache regeneration + +| Change | Regen | +|---|---| +| Superadmin creates/edits/deletes a global store or global product (structure) | **all regions** — `scheduleStoreInitialization()` | +| Admin edits market data for a global product | **that region** — `createAvailabilityCacheFile(regionId)` (+ `scheduleStoreInitialization(regionId)` if needed) | +| Regional product/store change | that region (unchanged) | +| New region created | seed global SKU rows, then regen that region | + +## 10. Verification + +1. `bunx tsc --noEmit` (backend + apps). +2. Edited `0006` validated on a **fresh** DB copy (apply from `0000`): `store_info` accepts + NULL region/owner and has `is_global`; `product_info` accepts NULL region; existing rows + intact; indexes present. +3. Runtime (after the user applies migrations): + - Superadmin creates a global store + global product → a market-stats row exists for + **every** region. + - A region-1 admin sees the global product in `getProducts` and can change its price → + **only** region 1's `availability.json`/`price` changes; region 2 unchanged. + - A region-1 admin cannot edit the global product's name/SKUs, nor create/edit/delete the + global store. + - `is_suspended` (superadmin) removes it everywhere; `is_suspended_in_region` removes it in + one region only. + - Add a global SKU to a region-1 slot → allowed; order for it prices from region 1's row. + +## 11. Risks + +- **Editing the pending `0006`**: since it is unapplied, edits are safe, but the **local dev D1 + already has its effects** — validation requires a **fresh** DB (reset + re-apply `0000`…). +- **Global SKU region resolution** in order/detail paths — wrong region = wrong price. +- **Guard relaxation** must not accidentally allow another region's private rows. + +## 12. Out of scope + +Admin UI and superadmin UI (Phases 3–4). diff --git a/docs/impl-plans/phase-3-admin-ui.md b/docs/impl-plans/phase-3-admin-ui.md new file mode 100644 index 0000000..6e0fa7c --- /dev/null +++ b/docs/impl-plans/phase-3-admin-ui.md @@ -0,0 +1,109 @@ +# Phase 3 — Admin UI (React-Native `admin-ui` + web `admin-web`) + +Status: **not started.** +Depends on: **Phase 2 backend.** + +## 1. Goal + +Let a regional admin: +1. see **global + regional** products on the Products page; +2. edit a **global** product's **market data only** (price / stock / offer / region + suspension) — everything else read-only — via a **separate component**; +3. see **global stores read-only** (no edit/delete). + +## 2. Shared types (`packages/shared/types/*`) + +- `Store`: add `isGlobal: boolean`; change `owner` to `number | null`. +- `AdminProduct` (and `AdminProductWithRelations`): add `isGlobal: boolean` (derived from the + store) so lists/edits can branch without a second call. +- No change to `AdminSku` shape (it already carries all market flags). + +> Confirm exact files: `packages/shared/types/admin.ts` (`Store`, `AdminProduct`). + +## 3. Server contract (from Phase 2 — restate so the UI is built to match) + +- `admin.product.getProducts` / `getProductById` return global + regional; each product has + `isGlobal`. +- `admin.store.getStores` / `getStoreById` return global stores with `isGlobal: true`, + `owner: null`. +- `admin.product.updateProduct` **for a global product** accepts **only** market fields: + `price`, `marketPrice`, `flashPrice`, `isFlashAvailable`, `isOutOfStock`, + `isSuspendedInRegion`, `isOffer`. Structural fields are rejected/ignored. +- `admin.product.updateProductPrices` / `toggleOutOfStock` remain region-scoped and work on + global SKUs. +- Admins get 403/error for global store create/update/delete and global product + create/delete. + +## 4. `admin-ui` (Expo / React Native) + +### Products list — `app/(drawer)/dashboard/products/index.tsx` +- Show global + regional products. +- Add a **Global** badge on global rows/cards. +- Optionally a filter chip `All / Regional / Global` alongside the existing + `all / in-stock / out-of-stock` chips (`FilterType`). +- `onEdit(id)` → navigates to `products/edit?id=…` as today; the edit screen branches. + +### Products edit — `app/(drawer)/dashboard/products/edit.tsx` +- After `trpc.admin.product.getProductById`, branch on `product.isGlobal`: + - **regional** → existing `ProductForm` (+ add/update flows unchanged). + - **global** → render the **new `GlobalProductForm`**. +- Keep the existing image-upload / mutation plumbing for the regional path. + +### New component — `src/components/GlobalProductForm.tsx` +- **Read-only** (rendered as text/locked): name, short/long description, store, increment + step, product type, per-SKU name + images + features, combo items. +- **Editable**: a per-SKU market block — `price`, `marketPrice`, `flashPrice`, + `isFlashAvailable`, `isOutOfStock`, `isOffer`, `isSuspendedInRegion`. +- Submit → `admin.product.updateProduct` with **only** the market fields (never structural). +- Show a hint banner: "Global product — shared across regions. You can edit price & stock for + your region only." + +### Products add — `app/(drawer)/dashboard/products/add.tsx` +- Unchanged (admins cannot create global products). Optionally hide/note global store choices + in the store picker (a regional product can't be assigned to a global store). + +### Stores list — `app/(drawer)/dashboard/stores/index.tsx` +- Show global stores with a **Global** badge. +- **Disable edit/delete** for global stores (read-only). Keep them visible. + +### Stores edit — `app/(drawer)/dashboard/stores/edit.tsx` +- If the store `isGlobal`: render read-only (no submit) with a "Global store — managed by a + superadmin" banner. + +### Store picker (in `ProductForm` / `ProductsSelector`) +- Ensure global stores don't appear as selectable owners/stores for regional product creation + (or are clearly marked and rejected by the backend). + +## 5. `admin-web` (TanStack Router) + +Mirror §4: +- `src/routes/dashboard.products.tsx` — global badge + optional filter. +- `src/routes/dashboard.products.edit.tsx` — branch to a new + `src/components/GlobalProductForm.tsx` when `product.isGlobal`. +- `src/routes/dashboard.products.new.tsx` — unchanged. +- `src/routes/dashboard.stores.tsx` — global badge, edit/delete disabled. +- `src/routes/dashboard.stores.edit.tsx` — read-only for global. +- Reuse the same field rules; share the market-fields type from `@packages/shared` if helpful. + +## 6. Verification + +1. `bunx tsc --noEmit` on both apps (compare any pre-existing web-ui/admin-web error counts). +2. Manual/RTL smoke (only if asked — *not* the full suite): + - Products page lists a seeded global product with a badge. + - Editing it shows read-only structure + editable market fields; saving changes **only** + the caller region's price/stock (verify via `availability.json`). + - Global store rows show a badge and have no edit/delete action. +3. No migrations, no test-suite run (unless the user asks). + +## 7. Risks / notes + +- `admin-ui` and `admin-web` both have a `ProductForm`; keep them behaviourally consistent + but don't force a shared component across the RN/web boundary. +- The global edit must never send structural fields — the backend rejects them, but avoid + surfacing false "saved" states. +- `owner: number | null` change ripples to store display components (`StoreItem`, store + detail) — handle null ("Global" / "—"). + +## 8. Out of scope + +Superadmin creation/editing of global entities (Phase 4). diff --git a/docs/impl-plans/phase-4-superadmin-ui.md b/docs/impl-plans/phase-4-superadmin-ui.md new file mode 100644 index 0000000..c601278 --- /dev/null +++ b/docs/impl-plans/phase-4-superadmin-ui.md @@ -0,0 +1,85 @@ +# Phase 4 — Superadmin UI (`apps/superadmin-ui`) + +Status: **not started.** +Depends on: **Phase 2 backend** (routers + helpers). Phase 3 independent. + +## 1. Goal + +Give superadmins screens to **create/edit/delete global stores** and **create/edit/delete +global products**, including the initial per-region market values that get seeded to every +region. + +## 2. App shape (for reference) + +- `apps/superadmin-ui` is a **TanStack Router** web app (Vite + Cloudflare). +- Routes are **file-based** in `src/routes/*.tsx`; `src/routeTree.gen.ts` is **generated** (do + not hand-edit — it regenerates when Vite runs / builds). +- Nav lives in `src/components/AppShell.tsx` (`NAV` array, `lucide-react` icons). +- Auth/context: `src/lib/auth-context.tsx`; tRPC client uses `trpc.superadmin.*`. +- Existing routes: `dashboard`, `regions`, `staff`, `constants`, `send-notifications`, `login`. + +## 3. Backend surface used (Phase 2) + +``` +trpc.superadmin.globalStores.list | get | create | update | delete +trpc.superadmin.globalProducts.list | get | create | update | delete +``` + +- Global store `create/update`: `{ name, description?, imageUrl? }` (no owner, no region). +- Global product `create`: full structure + `{ name, shortDescription?, longDescription?, storeId (global), incrementStep?, productType?, + skus: [{ name?, images?, isComboOnly?, features[], comboItems? }] }` + **plus** initial market values per SKU + `{ price, marketPrice?, flashPrice?, isFlashAvailable?, isOutOfStock?, isOffer? }` + which the backend seeds to **every region**. +- Global product `update`: structural edit (name/SKUs/etc.) — regenerates all regions. + (Per-region market data is edited by regional admins in Phase 3; optionally expose a + per-region matrix here too — see §7.) + +## 4. New routes / components + +- `src/routes/global-stores.tsx` — list + create/edit (inline drawer or a `$id` sub-route + following the `regions.tsx` pattern) + delete. Reuse the image-upload flow used elsewhere + (check how `regions.tsx`/banners handle uploads; if none, add a presigned-URL uploader like + `admin-ui`'s `useUploadToObjectStorage`). +- `src/routes/global-products.tsx` — list + create/edit + delete. +- New components under `src/components/`: + - `GlobalStoreForm.tsx` + - `GlobalProductForm.tsx` (structure editor + initial market-values block per SKU). +- `src/components/AppShell.tsx` — add NAV entries: + ```ts + { to: '/global-stores', label: 'Global Stores', icon: Store /* or Storefront */ }, + { to: '/global-products', label: 'Global Products', icon: Package /* or Boxes */ }, + ``` + (`lucide-react` icons). + +> After adding files under `src/routes/`, run the dev server / build once so `routeTree.gen.ts` +> regenerates before typecheck. + +## 5. Behaviour + +- Global store create/edit → backend regens **all** regions' caches. +- Global product create → seeds market-stats rows for **every** region from the entered values. +- Global product structural delete → removes the product, its SKUs and all regions' market + rows; regen all regions. +- Global product edit → structural changes regen all regions; if a per-region editor is added + (§7) it must call the same backend scoping as admins. + +## 6. Verification + +1. `bunx tsc --noEmit` in `apps/superadmin-ui` (confirm `routeTree.gen.ts` is regenerated). +2. Manual (dev server): create a global store → appears in every region's admin store list + (Phase 3); create a global product with an initial price → a market-stats row exists for + each region and `availability.json` shows that price until a region overrides it. + +## 7. Optional / follow-ups + +- A superadmin **per-region market matrix** (rows = regions, columns = price/stock) on the + global product screen, backed by a superadmin-scoped market-stats update. +- Batch "seed/repair" action for regions missing rows for older global SKUs. +- Note: new regions seed from the **least-id region's** rows (see Phase 2). To change the + defaults future regions inherit, edit the least-id region's rows first. + +## 8. Out of scope + +Regional admin editing (Phase 3) and any schema/backend work (Phase 2). diff --git a/docs/maestro-mcp-agent-guidelines.md b/docs/maestro-mcp-agent-guidelines.md index e567ab6..c10f372 100644 --- a/docs/maestro-mcp-agent-guidelines.md +++ b/docs/maestro-mcp-agent-guidelines.md @@ -4,8 +4,9 @@ Hard-won, trial-and-error notes for driving this repo with the Maestro MCP server (iOS simulator + Chromium) plus direct backend probes. Read this before you start; it will save you an hour of the exact mistakes listed at the end. -Written after the 2026-10-10 E2E run (see `docs/e2e-sanity-test-results.md` and -`docs/e2e-sanity-failed-cases.md`). +Written after the 2026-10-10 E2E run (see +`docs/test reports/e2e-sanity-test-results-2026-10-10-1310.md` and +`docs/test reports/e2e-sanity-failed-cases-2026-10-10-1310.md`). --- diff --git a/docs/test reports/e2e-sanity-failed-cases-2026-10-10-1310.md b/docs/test reports/e2e-sanity-failed-cases-2026-10-10-1310.md new file mode 100644 index 0000000..bdc91f7 --- /dev/null +++ b/docs/test reports/e2e-sanity-failed-cases-2026-10-10-1310.md @@ -0,0 +1,455 @@ +# Freshyo E2E — failed test cases (detailed) + +Companion to `docs/e2e-sanity-test-plan.md` (the plan) and +`docs/test reports/e2e-sanity-test-results-2026-10-10-1310.md` (all results). This +file expands **only the FAIL cases** with reproduction steps, evidence, root cause, +and a suggested fix. + +All evidence was produced on 2026-10-10 against the local stack: +backend `http://localhost:8787` (`/api/trpc`), disposable local D1, iOS +simulator `com.freshyotrial.app` / `in.freshyo.adminui`, Chromium superadmin +`http://localhost:4175`. + +Legend: **Severity** — Critical / High / Medium / Low. +**Case IDs** match the plan. + +--- + +## FC-01 — SEC-01: customer token can mutate global configuration + +- **Status:** ✅ **Fixed** (2026-10-10) — `admin.const.*` now requires a staff token + (`staffProcedure`); `updateConstants` additionally rejects global-scope keys + (globals are superadmin-only); the redundant + `getGlobalConstants`/`updateGlobalConstants`/`getLegacyConstants`/`updateLegacyConstants` + procedures were removed (no production UI caller). Regression test: + `apps/backend/tests/api/authorization-matrix.test.ts` (staff-guarded block). +- **Severity:** Critical +- **Case:** SEC-01 +- **Symptom:** A signed-in *customer* can call the staff/admin global-config + mutation and change app-wide constants. +- **Steps to reproduce:** + 1. `user.auth.login {identifier:"e2e_u2@test.com", password:"Pass@12345"}` → customer token. + 2. `admin.const.updateGlobalConstants {constants:[{key:"versionNum",value:"1.2.0"}]}` with that token. +- **Expected:** Rejected (staff-only). +- **Actual:** `200 {success:true, updatedCount:1}`. +- **Evidence:** Response body from step 2; anonymous `admin.product.getProducts` → 401, + customer `admin.product.getProducts` → 500 (`Cannot read properties of null (reading 'regionId')`). +- **Root cause:** `apps/backend/src/trpc/apis/admin-apis/apis/const.ts` — `updateGlobalConstants` + uses `protectedProcedure` (allows any authenticated user **or** staff) and never touches + `ctx.staffUser`. `protectedProcedure` is defined in `apps/backend/src/trpc/trpc-index.ts`. +- **Suggested fix:** Change the global-config procedures (`getGlobalConstants`, + `updateGlobalConstants`, legacy ones) to `superadminProcedure` (global scope) or at minimum + `staffProcedure`; remove the legacy admin global mutation or gate it behind superadmin. + +--- + +## FC-02 — SEC-04: order accepts a SKU from another region + +- **Status:** ✅ **Fixed** (2026-10-10) — `placeOrderUtil` now rejects an item whose + product `regionId` ≠ the order region (409 "… is not available in this region"). +- **Severity:** High +- **Case:** SEC-04 +- **Symptom:** A region-1 order can include a region-2 SKU. +- **Steps to reproduce:** + 1. U2 with a region-1 address (877). + 2. `user.order.placeOrder {regionId:1, addressId:877, paymentMethod:"cod", + selectedItems:[{skuId:157 /* region-2 product */, quantity:1, slotId:2012}]}`. +- **Expected:** Rejected (SKU not in the ordering region). +- **Actual:** `200`, order 2456 created with `regionId:1` and sku 157, priced at region-2's ₹149 + ₹20 delivery. +- **Evidence:** Order 2456 in `orders`/`order_items`. +- **Root cause:** `apps/backend/src/trpc/apis/user-apis/apis/order.ts` → `placeOrderUtil` resolves + items via `getOrderProductById(item.skuId)` with no region filter. Address region is checked, + but SKU/slot/bound region coherence is not. +- **Suggested fix:** Validate each SKU's `regionId` (and its product's region) equals the order + region; reject otherwise. + +--- + +## FC-03 — SEC-05: order accepts unassigned / out-of-stock / closed-slot items + +- **Status:** ✅ **Fixed** (2026-10-10) — `placeOrderUtil` now rejects + `isDeleted`/`isOutOfStock`/`isSuspended` items (400), requires a non-null slotId + for scheduled orders, and validates each slot: exists, region match (409), + `isActive`, `freezeTime`/`deliveryTime` in the future, and every ordered `skuId` + present in `slot.skuIds` (400). +- **Severity:** High +- **Case:** SEC-05 +- **Symptom:** The backend accepts items it should reject. +- **Steps to reproduce:** + - (a) Unassigned SKU: `placeOrder {regionId:1, selectedItems:[{skuId:1, quantity:1, slotId:2012}]}` where sku 1 is **not** in slot 2012 → **200**, order 2457. + - (b) Out-of-stock: `admin.product.toggleOutOfStock{id:155}` → `placeOrder {skuId:155, slotId:2012}` → **200**, order 2458 (stock restored afterward). +- **Expected:** Both rejected. +- **Actual:** Both create orders. +- **Evidence:** Orders 2457, 2458; schema still rejects non-positive/non-integer quantity. +- **Root cause:** `placeOrderUtil` (order.ts) never checks `isOutOfStock` / `isSuspended` / `isDeleted`, + nor that the SKU is a member of the selected slot, nor slot active/frozen state (only capacity is checked). +- **Suggested fix:** In `placeOrderUtil`, for each item assert: SKU exists, belongs to region, + not OOS/suspended/deleted, is assigned to the chosen slot, and the slot is active and not frozen. + +--- + +## FC-04 — SEC-06: user-based coupon is not restricted to its user + +- **Status:** ✅ **Fixed** (2026-10-10) — `validateAndGetCoupon` now loads + `applicableUsers` and rejects a user-based coupon for anyone not listed (unless + `isApplyForAll`): `This coupon is not applicable to your account`. +- **Severity:** High +- **Case:** SEC-06 +- **Symptom:** A coupon created for U1 can be applied by U2. +- **Steps to reproduce:** + 1. Admin: `coupon.create {couponCode:"E2EU1ONLY", discountPercent:10, isUserBased:true, applicableUsers:[388], maxLimitForUser:3}`. + 2. U2: `placeOrder {…, couponId:46}`. +- **Expected:** Rejected (coupon is for user 388 only). +- **Actual:** `200`, order 2463 discounted. +- **Evidence:** Order 2463; coupon 46 has `isUserBased:true`. +- **Root cause:** `packages/db_helper_sqlite/src/user-apis/coupon.ts` → `validateAndGetUserCoupon` + does not consult `applicableUsers`. (Expiry **is** enforced.) +- **Suggested fix:** Reject when `coupon.isUserBased && !applicableUsers.includes(userId)`. + +--- + +## FC-05 — SEC-07: public vendor packaging mutation + expired-snippet leak + +- **Severity:** High +- **Case:** SEC-07 +- **Symptom:** Anyone can toggle order-item packaging; expired snippets still list orders. +- **Steps to reproduce:** + 1. Admin creates a vendor snippet for slot 2012 (`E2ESNIP`). + 2. Anonymous `admin.vendorSnippets.updateOrderItemPackaging {orderItemId:8237, is_packaged:true}` → **200** (toggled U1's order item). + 3. Admin creates an **expired** snippet (`validTill:"2020-01-01"`); anonymous + `admin.vendorSnippets.getOrdersBySnippetAndSlot {snippetCode:"E2ESNIPEXP", slotId:2012}` → **200** with customer names + orders. +- **Expected:** Packaging edits require vendor authority; expired snippets return nothing. +- **Actual:** Anonymous mutation succeeds; expired snippet leaks orders. +- **Evidence:** Both responses above (item 8237 toggled true→false). +- **Root cause:** `apps/backend/src/trpc/apis/admin-apis/apis/vendor-snippets.ts` — + `updateOrderItemPackaging` is `publicProcedure` with the auth check commented out; + `getOrdersBySnippetAndSlot` never checks `validTill` (unlike `getOrdersBySnippet`). +- **Suggested fix:** Require a valid `snippetCode` (unexpired) and authorize the mutation against + the order's slot/snippet; enforce expiry in the slot-variant query too. + +--- + +## FC-06 — BL-02: `minRegularOrderValue` is not a real minimum + +- **Status:** ✅ **Resolved** (2026-10-10) — the constant was removed. It was never a + hard minimum (nothing enforced it) and is no longer used as the delivery threshold, + so it was dead. Removed from both const registries, the essential-consts payload, + the web-ui hook, the admin/superadmin bound editors, the seeds, and the tests. + No minimum-order rule is enforced (matching the customer app). +- **Severity:** Medium +- **Case:** BL-02 +- **Symptom:** Orders below the configured minimum are accepted. +- **Steps to reproduce:** `placeOrder` with subtotal ₹199 while bound A1 `minRegularOrderValue:300`. +- **Expected:** Blocked if it is a hard minimum (policy needs confirmation). +- **Actual:** `200` (orders 2457/2458). +- **Evidence:** Orders below 300 accepted. +- **Root cause:** `placeOrderUtil` uses `minRegularOrderValue` only as the free-delivery threshold, + never as a minimum-order gate; the client uses `freeDeliveryThreshold` instead. +- **Suggested fix:** Decide the contract (minimum vs informational). If a minimum, enforce it in + `placeOrder` and surface it in the cart; if not, rename/document it and stop using it as the fee threshold. + +--- + +## FC-07 — BL-03 / BL-06: client and backend delivery-fee formulas diverge + +- **Status:** ✅ **Fixed** (2026-10-10) — the backend now uses the customer app's + model: threshold key `freeDeliveryThreshold` (not `minRegularOrderValue`) and the + post-discount basis (`finalTotal = subtotal − discount; delivery = finalTotal < + threshold ? charge : 0`). +- **Severity:** High +- **Cases:** BL-03, BL-06 +- **Symptom:** The amount the customer sees differs from what the backend saves. +- **Steps to reproduce:** + - BL-06 (different keys): bound A2 `min=300, free=800, charge=200`; subtotal ₹548. + Backend order 2459 → `totalAmount:548, deliveryCharge:0`; client preview → `548<800` → ₹200 delivery → ₹748. + - BL-03 (different discount basis): bound A1 `threshold 300`; subtotal ₹349, flat ₹100 coupon. + Backend order 2461 → `totalAmount:249, deliveryCharge:0`; client preview → post-coupon 249<300 → ₹20 → ₹269. +- **Expected:** Identical rule in cart, checkout, persisted order, and admin. +- **Actual:** ₹200 / ₹20 discrepancies. +- **Evidence:** Orders 2459, 2461. +- **Root cause:** `apps/user-ui/components/cart-page.tsx` uses + `deliveryCharge = (subtotal − discount) < freeDeliveryThreshold ? charge : 0`. + `placeOrderUtil` (order.ts) uses `expectedDeliveryCharge = subtotal(pre-discount) < minRegularOrderValue ? charge : 0`. + Different key **and** different discount basis. +- **Suggested fix:** One shared pricing function (server-authoritative). Use the same threshold key + and the same pre/post-discount basis on both sides; ideally the client renders the server quote. + +--- + +## FC-08 — D10: percentage discount is applied to subtotal + delivery fee + +- **Status:** ✅ **Fixed** (2026-10-10) — the coupon discount is now computed on the + cart subtotal only; delivery is decided afterwards and added on top (no longer + discounted). +- **Severity:** High +- **Case:** BL-05 (and visible in SEC-06 order 2463) +- **Symptom:** A % coupon discounts the delivery fee too. +- **Steps to reproduce:** subtotal ₹199 + delivery ₹20, 10% coupon → order 2463 `totalAmount:197.1`. +- **Expected:** Discount on the item subtotal only → ₹199×0.9 + ₹20 = ₹199.1. +- **Actual:** (199+20)×0.9 = ₹197.1. +- **Evidence:** Order 2463; also 15% case 2480 (₹186.15 = 219×0.85). +- **Root cause:** `placeOrderUtil` passes `subOrderTotalWithDelivery` into + `applyDiscountToUserOrder` for the first suborder. +- **Suggested fix:** Apply the coupon to the item subtotal, then add delivery; keep the same order on the client. + +--- + +## FC-09 — CP-05: SKU-restricted coupon is not enforced + +- **Status:** ⚪ **Not a defect for now** (2026-10-10) — SKU-specific coupons are not + created today; coupons are intended to apply to all SKUs. `skuIds` is deliberately + left unenforced. (Revisit if SKU-scoped coupons are ever introduced.) +- **Severity:** High +- **Case:** CP-05 +- **Symptom:** A coupon limited to sku 155 discounts a cart containing only sku 156. +- **Steps to reproduce:** `coupon.create {couponCode:"E2ESKU155", discountPercent:10, skuIds:[155]}` → + `placeOrder` with only sku 156 → **200**, order 2474 (10% off 349). +- **Expected:** Rejected. +- **Actual:** Applied. +- **Evidence:** Order 2474. +- **Root cause:** `validateAndGetUserCoupon` does not enforce `skuIds` / applicable products. +- **Suggested fix:** Validate cart items against the coupon's product/SKU scope server-side. + +--- + +## FC-10 — CP-11: coupons are not region-scoped + +- **Status:** ⚪ **Not a defect for now** (2026-10-10) — region-scoped coupons are not + wanted; coupons are global. No region filter is added. (Revisit if regional + coupons are ever required.) +- **Severity:** High +- **Case:** CP-11 +- **Symptom:** A region-1 coupon discounts a region-2 order. +- **Steps to reproduce:** U2 region-2 address (883) + region-2 sku 157 + region-1 coupon 45 → **200**, order 2477 total ₹79. +- **Expected:** Per region policy (reject if region-scoped). +- **Actual:** Applied. +- **Evidence:** Order 2477. +- **Root cause:** coupon storage/validation (`coupons`, `validateAndGetUserCoupon`, user coupon fetches) + carries no region filter. +- **Suggested fix:** Decide global-vs-regional coupon policy; if regional, store `region_id` and + filter both retrieval and validation. + +--- + +## FC-11 — PD-13: deleting a store orphans its products + +- **Status:** ✅ **Fixed** (2026-10-10) — `deleteStore` now counts the store's products and + refuses to delete while any exist (plain error: "Cannot delete a store that still has + products…"); the `store_id → NULL` step was removed, so products can no longer be orphaned. +- **Severity:** High +- **Case:** PD-13 +- **Symptom:** `deleteStore` succeeds even when the store has products. +- **Steps to reproduce:** `admin.store.deleteStore {storeId:1}` (store 1 had 41 products) → **200 "Store deleted successfully"**. +- **Expected:** Blocked (or products reassigned). +- **Actual:** 41 products left with `store_id = NULL`. +- **Evidence:** DB count of `product_info where store_id is null` jumped to 41 (restored manually). +- **Root cause:** `apps/backend/src/trpc/apis/admin-apis/apis/store.ts` `deleteStore` and + `packages/db_helper_sqlite` `deleteStoreFromDb` have no dependency guard/reassignment. +- **Suggested fix:** Reject deletion when products reference the store, or require an explicit + reassignment target; never leave products with a null store. + +--- + +## FC-12 — DS-02: deleting a product tag fails (FK) + +- **Status:** ✅ **Fixed** (2026-10-10) — `deleteProductTag` now deletes the `product_tags` + junction rows first (in a transaction) before the tag row, so a tag with products deletes + cleanly. No FK-cascade migration needed. +- **Severity:** High +- **Case:** DS-02 +- **Symptom:** Tag delete throws a raw DB error when the tag has products. +- **Steps to reproduce:** create tag 12 with products 155/156 → `admin.product.deleteProductTag {id:12}`. +- **Expected:** Tag + junction rows removed. +- **Actual:** `500` `Failed query: delete from "product_tag_info" …`. +- **Evidence:** `product_tags` still had row (product 155 → tag 12); FK `ON DELETE no action`. +- **Root cause:** `deleteProductTagInDb` deletes `product_tag_info` without first deleting + `product_tags` junction rows. +- **Suggested fix:** Delete junction rows (or use `ON DELETE CASCADE`) before the tag row. + +--- + +## FC-13 — SL-04: closed (frozen) slot is accepted by `placeOrder` + +- **Status:** ✅ **Fixed** (2026-10-10) — the slot validation added for FC-03 rejects + a slot whose `freezeTime` (or `deliveryTime`) has passed (400). +- **Severity:** High +- **Case:** SL-04 +- **Symptom:** An order can be placed into a slot whose freeze time has passed. +- **Steps to reproduce:** create slot 2015 with `freezeTime:"2020-01-01"` → `placeOrder {skuId:155, slotId:2015}` → **200**, order 2469. +- **Expected:** Rejected (orders closed). +- **Actual:** Accepted. +- **Evidence:** Order 2469. +- **Root cause:** `placeOrder` checks capacity (`getUserSlotCapacityStatus`) but not slot + active/freeze state; the client only filters slots. +- **Suggested fix:** Server-side reject when `slot.freezeTime <= now` or `!slot.isActive`. + +--- + +## FC-14 — CT-07: cart does not reflect an out-of-stock item + +- **Status:** ⚪ **Not a defect (false flag)** (2026-10-10) — reproduced and disproven. The cart + **does** implement the CT-07 behavior: `cart-page.tsx` renders an "Out of Stock" badge + (`:962`), filters OOS lines out of the checkout payload (`:1247`), and blocks checkout with + "Items Unavailable" when every line is OOS (`:1264`). The E2E only observed the + pre-propagation window: after `toggleOutOfStock` the app keeps the previous + `availability_version_num` until its `essentialConsts` `refetchInterval` (60 s) fires, so the + cart shows the line normally for up to ~1 minute, then correctly shows "Out of Stock". The + report's stated root cause (`cart-page` ignores `isOutOfStock`) was inaccurate. +- **Severity:** High +- **Case:** CT-07 +- **Repro (2026-10-10):** cart held sku 155 ("E2E Chicken 500 g", qty 6, ₹1194); + `toggleOutOfStock{id:155}` bumped availability `av-17 → av-18` (published `av-18` shows + `isOutOfStock:true`); `stopApp` → `launchApp` → open cart → line normal; ~70 s later (the + refetch interval) → red "Out of Stock" badge. Stock restored afterwards. +- **Evidence (original E2E):** Published `availability.json` for region 1 `av-15` showed sku 155 + `isOutOfStock:true`; the cart screenshot was taken inside the staleness window. +- **Residual (out of scope, by decision):** the ~60 s propagation delay is cache-refresh latency, + not a cart-logic bug. + +--- + +## FC-15 — AU-07: profile update is broken (`ctx.req.header`) + +- **Status:** ✅ **Fixed** (2026-10-10) — `Context.req` is now typed as the fetch + `Request` the adapter passes, and `updateProfile` reads + `ctx.req.headers.get('authorization')`. The optional email was relaxed too: an empty + email means "no change", and the client only requires it when registering. +- **Severity:** High +- **Case:** AU-07 +- **Symptom:** `updateProfile` always errors. +- **Steps to reproduce:** `user.auth.updateProfile {name:"E2E U2 Renamed", bio:"hello bio"}` with a valid token. +- **Expected:** Profile updated. +- **Actual:** `500 "ctx.req.header is not a function"`. +- **Evidence:** Response above; UI Edit Profile also blocked earlier by a required-email validation. +- **Root cause:** `apps/backend/src/trpc/apis/user-apis/apis/auth.ts` line ~342 calls + `ctx.req.header('authorization')`, but `ctx.req` is a fetch `Request` (only `.headers.get`). +- **Suggested fix:** Read the header via `ctx.req.headers.get('authorization')` (or drop the token + echo). Relax the client's email requirement if email is optional. + +--- + +## FC-16 — AU-08: password change has no effect (duplicate creds row) + +- **Status:** ✅ **Fixed** (2026-10-10) — `upsertUserPassword` now selects then + updates-or-inserts (updating all rows for the user, repairing existing duplicates), + and a `uniqueIndex` on `user_creds.user_id` was added to the schema. Existing duplicate + rows (users 379, 908, 1311) must be deduped before the index migration is applied. +- **Severity:** High +- **Case:** AU-08 +- **Symptom:** After `updatePassword`, the old password still works and the new one fails. +- **Steps to reproduce:** fresh user U5 → `user.auth.updatePassword {password:"NewPass@456"}` → + login with old (works) / new (fails). +- **Expected:** New password works, old fails. +- **Actual:** Old logs in (200), new fails (500). +- **Evidence:** `user_creds` for the user contains **two rows** (ids 26, 27) after the change. +- **Root cause:** `upsertUserAuthPasswordInDb` inserts a new row instead of updating the existing + one; login reads the stale row. +- **Suggested fix:** Update the existing `user_creds` row (unique on `user_id`) rather than inserting; + add a unique constraint if missing. + +--- + +## FC-17 — OR-12: no order idempotency (duplicate submits) + +- **Status:** 🟡 **Mitigated client-side** (2026-10-10) — the Place Order button is + disabled while a submit is in flight, and `handlePlaceOrder` early-returns via a + synchronous `useRef` guard (plus `isPending`), so an accidental double-tap cannot + submit twice. **Server-side idempotency was intentionally deferred**: `placeOrder` + still has no idempotency key, so a direct API replay or network retry can still + create duplicates. +- **Severity:** Medium +- **Case:** OR-12 +- **Symptom:** Retrying/submitting twice creates duplicate orders. +- **Steps to reproduce:** call the same `placeOrder` twice with identical params. +- **Expected:** One order group (idempotent) or a clear dedupe. +- **Actual:** Two calls created 4 orders (2465–2468). +- **Evidence:** Order ids above. +- **Root cause:** `placeOrder` has no idempotency key; only the client has a loading lock. +- **Suggested fix:** Accept a client-generated idempotency key and short-circuit duplicate submissions. + +--- + +## FC-18 — AD-06: address region/bound coherence not validated + +- **Severity:** Medium +- **Case:** AD-06 +- **Symptom:** An address can reference a bound from a different region. +- **Steps to reproduce:** `user.address.createAddress {regionId:2, boundId:1}` (bound 1 is region 1's) → **200**, address 882 stored region 2 / bound 1. +- **Expected:** Rejected (bound must belong to the region). +- **Actual:** Accepted. +- **Evidence:** Address 882. +- **Root cause:** `apps/backend/src/trpc/apis/user-apis/apis/address.ts` create/update do not check + that `boundId` belongs to `regionId`. Compounding this, `AddressForm` submits the current + **browsing** bound, so the client can send an incoherent pair. +- **Suggested fix:** Validate `bound.regionId === regionId` server-side; have `AddressForm` derive + the bound from the chosen address region, not the browsing region. + +--- + +## FC-19 — RG-02: region creation is not atomic on D1 + +- **Status:** ✅ **Fixed** (2026-10-10) — `createRegionWithBounds` now validates the bounds + before touching the DB (≥1 bound, unique priorities) so a bad payload never reaches the + inserts, and wraps the post-region inserts in a try/catch that deletes the region + its + child rows if anything fails. Reproduced (leftover region 5), then re-verified: the + duplicate-priority create now leaves **no** region behind. +- **Severity:** Medium +- **Case:** RG-02 +- **Symptom:** A failed region create leaves a half-created region. +- **Steps to reproduce:** `superadmin.regions.create` with two bounds at priority `1`. +- **Expected:** Error, no region persisted. +- **Actual:** `500 "Each bound priority must be unique…"` **and** region `E2E-DupPriority` exists with 0 bounds / 0 consts. +- **Evidence:** Region row 4 with no bounds (removed manually). +- **Root cause:** `packages/db_helper_sqlite/src/superadmin-apis/regions.ts` `createRegionWithBounds` + wraps inserts in `db.transaction`, but on D1 the region insert is not rolled back when the bound + insert violates the unique priority index. +- **Suggested fix:** Validate bounds (unique priorities, valid geometry) before inserting, or use an + atomic D1 batch that fails as a unit. + +--- + +## FC-20 — AU-03 (and D8): error statuses flattened to HTTP 500 + +- **Severity:** Low +- **Case:** AU-03 (same class as the cross-region `getProductById` 500) +- **Symptom:** Auth/validation/not-found failures return 500 instead of 4xx. +- **Steps to reproduce:** `user.auth.login` with a wrong password → `500`; unknown user → `500`; + `admin.product.getProductById` cross-region → `500 "Product not found"`. +- **Expected:** 401 / 404 respectively. +- **Actual:** 500. +- **Evidence:** Response statuses above. +- **Root cause:** `ApiError` carries an HTTP status but `apps/backend/src/app.ts` `onError` / + the tRPC error mapping only maps `TRPCError` codes, so `ApiError` falls through to 500. +- **Suggested fix:** Translate `ApiError` (and thrown `Error` with a status) to the matching HTTP + status in the global error handler / tRPC error formatter. + +--- + +## Summary + +| Ref | Case | Severity | One-line | +|---|---|---|---| +| FC-01 | SEC-01 | Critical | Customer token mutates global consts — ✅ fixed | +| FC-02 | SEC-04 | High | Cross-region SKU accepted — ✅ fixed | +| FC-03 | SEC-05 | High | Unassigned / OOS / closed-slot items accepted — ✅ fixed | +| FC-04 | SEC-06 | High | User-based coupon used by another user — ✅ fixed | +| FC-05 | SEC-07 | High | Public packaging mutation + expired-snippet leak | +| FC-06 | BL-02 | Medium | Minimum order not enforced — ✅ resolved (constant removed) | +| FC-07 | BL-03/06 | High | Client vs backend delivery-fee divergence — ✅ fixed | +| FC-08 | BL-05 | High | % coupon discounts the delivery fee — ✅ fixed | +| FC-09 | CP-05 | High | SKU-restricted coupon not enforced — ⚪ not a defect for now | +| FC-10 | CP-11 | High | Coupons not region-scoped — ⚪ not a defect for now | +| FC-11 | PD-13 | High | Store delete orphans products — ✅ fixed | +| FC-12 | DS-02 | High | Tag delete fails (FK) — ✅ fixed | +| FC-13 | SL-04 | High | Frozen slot accepted — ✅ fixed | +| FC-14 | CT-07 | High | Cart ignores out-of-stock — ⚪ not a defect (false flag) | +| FC-15 | AU-07 | High | Profile update broken — ✅ fixed | +| FC-16 | AU-08 | High | Password change ineffective — ✅ fixed | +| FC-17 | OR-12 | Medium | No order idempotency — 🟡 client-side guard (server deferred) | +| FC-18 | AD-06 | Medium | Incoherent address region/bound | +| FC-19 | RG-02 | Medium | Non-atomic region create — ✅ fixed | +| FC-20 | AU-03 | Low | Errors return 500 instead of 4xx | + +Suggested fix order: **FC-01 → FC-02/03/13 (order validation) → FC-07/08 (pricing) → +FC-04/09/10 (coupons) → FC-05 (vendor auth) → FC-16/15 (account) → FC-11/12/19 → FC-17/18/20.** +(FC-09/FC-10/FC-14 closed as false flags.) diff --git a/docs/test reports/e2e-sanity-test-results-2026-10-10-1310.md b/docs/test reports/e2e-sanity-test-results-2026-10-10-1310.md new file mode 100644 index 0000000..d0c4079 --- /dev/null +++ b/docs/test reports/e2e-sanity-test-results-2026-10-10-1310.md @@ -0,0 +1,323 @@ +# Freshyo E2E sanity/regression — execution results + +Companion to `docs/e2e-sanity-test-plan.md`. This file records what was actually +executed, with evidence and honest status. Case IDs match the plan. + +Detailed write-ups of every FAIL case (steps, evidence, root cause, suggested fix) +are in **`docs/test reports/e2e-sanity-failed-cases-2026-10-10-1310.md`**. + +Status values: **PASS**, **FAIL**, **BLOCKED** (harness/env could not run it), +**NOT RUN**. + +## Environment + +| Item | Value | +|---|---| +| Date | 2026-10-10 | +| Backend | local `workerd` at `http://localhost:8787` (`/api/trpc`) | +| DB | local D1 (`apps/backend/.wrangler/state/.../d1/miniflare-.../da3a80bd….sqlite`), disposable | +| Customer app | iOS simulator `B1F98A94-9733-46A6-9EB2-76F33C15240D`, `com.freshyotrial.app` | +| Admin app | iOS simulator same device, `in.freshyo.adminui` | +| Superadmin UI | Chromium `http://localhost:4175` | +| Admin web | Chromium `http://localhost:4176` | +| Customer web | Chromium `http://localhost:4174/home` | +| GPS | `16.7489, 77.9856` (resolves to Mahabubnagar) | + +## Credentials (test-only) + +| Role | Identity | Secret | +|---|---|---| +| Superadmin | `superadmin` | `superadmiN123` | +| Admin region A (1) | `e2eadminA` | `Test@12345` | +| Admin region B (2) | `e2eadminB` | `Test@12345` | +| Customer U1 | `9676651496` (user 388) | `meatfarmer@123` | + +## Regions / bounds + +| Alias | Region | Bound | Priority | deliveryCharge | freeDeliveryThreshold | minRegularOrderValue | +|---|---|---|---|---|---|---| +| A | Mahabubnagar (1) | A1 (bound 1) | 1 (effective) | 20 | 300 | 300 | +| A | Mahabubnagar (1) | A2 (bound 2) | 2 | 200 | 800 | 300 | +| B | Testnagar (2) | B1 (bound 3) | 1 | 30 | 500 | 500 | +| C | Jadcherla (3) | C1 (bound 4) | 1 | 150 | 750 | 1001 | + +Note: the plan asked for dedicated regions A/B. Existing region 1 already has two +bounds with priorities 1/2, so it is used as A; region 2 as B. Dedicated staff, +products and slots were created for the run. + +## Fixtures created for this run (via the admin/superadmin APIs the UIs call) + +| Entity | Region | Ids | +|---|---|---| +| Product "E2E Chicken" (500 g ₹199 / 1 kg ₹349, flash ₹299) | A | product 155, skus 155, 156 | +| Product "E2E R2 Item" (1 pc ₹149) | B | product 156, sku 157 | +| Slot (delivery 2026-10-11 16:00 IST, freeze 15:30 IST) | A | slot 2012 (skus 155,156) | +| Slot (same window) | B | slot 2013 (sku 157) | +| Staff `e2eadminA` | A | staff 10 | +| Staff `e2eadminB` | B | staff 11 | + +## Method / harness notes + +- Maestro MCP drives the iOS simulator and Chromium; the backend is probed + directly over tRPC for authoritative assertions (sanctioned by the plan). +- iOS secure password fields: `inputText` **does** land, but the value is masked + in screenshots. The reliable recipe is: type the password, tap a neutral area + to dismiss the keyboard, then tap the submit button. `hideKeyboard` fails on + these builds. +- The user app's deep-link confirm dialog ("Open in Freshyo?") is a SpringBoard + alert that survives `launchApp`; dismiss it explicitly before asserting. +- RN text-node assertions are unreliable; navigation is done by point taps and + verified with screenshots. +- Catalog publication: admin writes schedule cache regeneration; the app picks + up a new version on relaunch or within the ~60 s discovery poll. + +--- + +## Results + +(Per-category tables are appended below as cases are executed.) + +### A. Regions, bounds and configuration + +| ID | Status | Evidence / notes | +|---|---|---| +| RG-01 | PASS | Region 1 (A) already discoverable; `listRegions` returns A/B/C; customer app resolves GPS to "DELIVER TO Mahabubnagar" and catalog/config load. | +| RG-02 | **FAIL → FIXED** | Validation works (no-bounds → 400; non-`FeatureCollection` → 400; duplicate priority → 500), **but the region is still persisted without bounds**. Probes: create `{bounds:[]}` → 400 (no row); create with two bounds at priority `1` → 500 `"Each bound priority must be unique within the region"` **and** region `E2E-DupPriority` (id 4) exists with **0 bounds and 0 region_consts**. `createRegionWithBounds` wraps inserts in `db.transaction`, but on D1 the region insert is not rolled back when the bound insert violates the unique priority index. **Bug: region creation is not atomic; half-created region remains.** **Fixed 2026-10-10:** bounds are validated before any insert (≥1 bound, unique priorities) and a compensating cleanup removes the region + child rows if a later insert fails. Re-verified: duplicate-priority create now leaves no region. | +| RG-03 | PASS | Fresh launch resolves region once, signed out; catalog + free-delivery threshold load (see screenshots). | +| RG-04 | PASS | Simulator GPS set to `0,0` (outside every bound) → on cold launch the app **kept the saved region** ("DELIVER TO Mahabubnagar"), loaded the catalog, and did not hang or show an endless spinner. | +| RG-05 | NOT RUN | Requires delaying the resolve response; not harness-controllable here. | +| RG-06 | PASS | API: admin A sees only region-1 E2E products + slot 2012; admin B sees only region-2 E2E product + slot 2013. UI: region A search shows "E2E Chicken 500 g/1 kg" (₹199/₹349); after switching to Testnagar the same search shows only "E2E R2 Item 1 pc" (₹149). No A content leaked into B. | +| RG-07 | PARTIAL | Cancel path PASS: switching region shows "Switch region? … will clear your entire cart" and **Cancel** keeps region A + catalog. Confirm/clear-cart path NOT RUN yet (needs populated regular+flash carts). | +| RG-08 | PARTIAL | No continuous switching observed: with the app open and GPS set outside all bounds (`0,0`), the region stayed on the saved A (the startup check runs once per launch). Cold launch at `0,0` also kept A. **Fixture note:** region B's bound 3 has an **empty `FeatureCollection`** (no polygon), so GPS can never resolve to B; the "move GPS A→B" half could not be exercised. | +| RG-09 | NOT RUN | Active-bound from addresses pending. | +| RG-10 | PASS | API: `superadmin.regions.updateBoundSettings` bound 2 → charge 200 / threshold 800 applied; region 2 untouched. UI: after switching to B the cart bar shows "₹500 more for FREE Delivery" (B1 threshold 500) vs A's ₹300 — bound/region-scoped settings take effect. Region+bound editors previously verified (SU-2/SU-3). | +| RG-11 | NOT RUN | Overlapping bounds / polygon edge pending. | + +### N. Mandatory API-backed security and invariant checks + +| ID | Status | Evidence / notes | +|---|---|---| +| SEC-01 | **FAIL → FIXED** | **Critical: a customer token could mutate global config.** `admin.const.updateGlobalConstants` used `protectedProcedure` (allows any authenticated user **or** staff) and did not use `ctx.staffUser`. Probe: `user.auth.login` as U2 (customer) → `admin.const.updateGlobalConstants {constants:[{key:"versionNum",value:"1.2.0"}]}` → **200 `{success:true,updatedCount:1}`**. Staff→superadmin region create → 401 ✓; customer→superadmin staff create → 401 ✓; anonymous→`admin.product.getProducts` → 401 ✓; customer→`admin.product.getProducts` → 500 (`Cannot read properties of null (reading 'regionId')`) — denied only by crash, not by a guard. **Fixed 2026-10-10:** `admin.const.*` now uses `staffProcedure`, `updateConstants` rejects global-scope keys, and the redundant admin global/legacy procedures were removed. | +| SEC-02 | PASS | Admin B fetching A's product (`getProductById{id:155}`) → "Product not found"; B toggling A's product (`toggleOutOfStock{id:155}`) → "Product not found"; A's SKUs remained in stock (verified before/after). Cross-region isolation enforced. | +| SEC-03 | PASS | U2 → `getOrderById` U1's order → "Order not found"; `cancelOrder` U1's order → "failed to cancel order"; `updateUserNotes` U1's order → "Order not found"; `updateAddress`/`deleteAddress` U1's address → "Address not found…"; U2 `getOrders` → empty. U1's order 2455 notes/cancel state unchanged. Ownership enforced. | +| SEC-04 | **FAIL → FIXED** | A region-1 order accepted a **region-2 SKU**. U2 with a region-1 address placed `placeOrder {regionId:1, selectedItems:[{skuId:157 (region-2 product), qty:1, slotId:2012}]}` → **200**, order 2456 created (regionId 1, sku 157, priced at region-2's ₹149 + ₹20 delivery). `placeOrderUtil` resolves SKUs via `getOrderProductById` with no region check; `address.regionId` is checked but SKU/slot/bound region coherence is not. **Fixed 2026-10-10:** each item's product `regionId` must equal the order region (409). | +| SEC-05 | **FAIL → FIXED** | (a) A SKU **not assigned to the chosen slot** is accepted: region-1 `skuId:1` with `slotId:2012` → **200**, order 2457. (b) An **out-of-stock** SKU is accepted: `admin.product.toggleOutOfStock{id:155}` → then `placeOrder{skuId:155, slotId:2012}` → **200**, order 2458 (stock restored afterward). Schema rejects non-positive/non-integer quantity, but the backend never checks `isOutOfStock`/`isSuspended`/`isDeleted`, slot active/frozen state, or slot membership. **Fixed 2026-10-10:** OOS/suspended/deleted items rejected (400); scheduled slotId required; slot existence/region/active/freeze/delivery/membership validated. | +| SEC-06 | **FAIL → FIXED** | (a) A **user-based coupon for U1 was applied by U2**: coupon 46 `E2EU1ONLY` (`isUserBased`, `applicableUsers:[388]`) → U2 `placeOrder` → **200**, order 2463 discounted. `validateAndGetUserCoupon` does not enforce `applicableUsers`. (b) Expired coupon correctly rejected ("Coupon has expired"). **Fixed 2026-10-10:** redemption now rejects a user-based coupon for anyone not in `applicableUsers`. | +| SEC-07 | **FAIL** | (a) `updateOrderItemPackaging` is a **publicProcedure** with the auth check commented out; after creating a vendor snippet for slot 2012, an **anonymous** call toggled U1's order item 8237 (`is_packaged true` → `false`), both **200**. (b) `getOrdersBySnippetAndSlot` is public and does **not** check `validTill`: an expired snippet (validTill 2020-01-01) still returned orders with customer names. | +| SEC-08 | PASS | Temp staff `e2etmp` (region 2): token works; after moving the staff to region 1 the same token lists region-1 products (access follows current assignment, not the token's stale region); after deleting the staff the token → 401. | + +### H. Bill arithmetic and bound-specific fees + +Client and backend now share the **same** model (fixed 2026-10-10): `finalTotal = subtotal − discount`; `deliveryCharge = finalTotal < freeDeliveryThreshold ? deliveryCharge : 0`. +The backend previously waived delivery from the pre-discount subtotal and from a different key (`minRegularOrderValue`), which is what caused the divergence; `minRegularOrderValue` has since been removed entirely. + +| ID | Status | Evidence / notes | +|---|---|---| +| BL-01 | PASS | Bound A1 has `freeDeliveryThreshold == 300`. Order with subtotal 199 → delivery ₹20; subtotal 548 → ₹0. Exact boundary consistent. | +| BL-02 | **FAIL → RESOLVED** | `minRegularOrderValue` is **not** enforced as a hard order minimum. A ₹199 order (sku 155) was accepted (orders 2457/2458). It only acted as the backend's free-delivery threshold. **Resolved 2026-10-10:** the constant was removed; no minimum-order rule is enforced (matching the customer app). | +| BL-03 | **FAIL → FIXED** | Coupon crossing the threshold diverges. Bound A1 (threshold 300): subtotal 349 (sku 156), flat-₹100 coupon → backend order 2461 `totalAmount=249, deliveryCharge=0`; client preview = post-coupon 249 < 300 → `deliveryCharge=20`, total 269. **₹20 mismatch** (client post-discount vs backend pre-discount). **Fixed 2026-10-10:** backend now discounts the subtotal then decides delivery on the post-discount total. | +| BL-04 | PASS | Multi-slot cart below the threshold (₹199 slot 2012 + ₹50 slot 2016 = ₹249 < ₹300): suborders 2478 (₹219 incl ₹20 delivery) + 2479 (₹50, delivery ₹0); summed total ₹269 = cart + one fee. Delivery charged once (on the first suborder). | +| BL-05 | PASS (D10 now fixed) | 15% coupon on ₹199 → ₹186.15 = (199+20)×0.85, which confirmed D10 (discount applied to subtotal+delivery). **Fixed 2026-10-10:** the coupon now discounts the goods only; the 15% case becomes ₹199×0.85 + ₹20 = ₹189.15. | +| BL-06 | **FAIL → FIXED** | Bound A2 (`min=300`, `free=800`, `charge=200`): subtotal 548 → backend order 2459 `totalAmount=548, deliveryCharge=0`; client preview `548<800` → delivery ₹200 → total ₹748. **₹200 mismatch.** **Fixed 2026-10-10:** backend threshold key is now `freeDeliveryThreshold` (800), so both sides charge ₹200. | +| BL-07 | NOT RUN | Stale-quote reprice pending. | + +### I. Coupons and offers on orders + +| ID | Status | Evidence / notes | +|---|---|---| +| CP-01 | PASS | General flat-₹100 coupon (id 45) applied to U2 order 2461 (subtotal 349) → `totalAmount=249`, matching preview. | +| CP-02 | PASS | Flat ₹500 coupon with `maxValue:100` on a ₹199 cart → order 2481 total ₹119 (₹199+₹20−₹100); discount capped, never negative. | +| CP-03 | PARTIAL | Expiry/min-order/usage validated; quantity-change recalculation not UI-run. | +| CP-04 | PARTIAL | User-based coupon (`applicableUsers`) enforcement — see SEC-06. **Fixed 2026-10-10** (server-side). The My-Coupons UI half of this case was not run. | +| CP-05 | ⚪ NOT A DEFECT | SKU-restricted coupon (skuIds [155]) was applied to an order containing **only sku 156** (order 2474, 10% off 349). `validateAndGetUserCoupon` does not enforce `skuIds`. **2026-10-10:** SKU-specific coupons are not created today and coupons are meant to apply to all SKUs, so `skuIds` is deliberately unenforced (FC-09 is a false flag for now). | +| CP-06 | PASS | `maxLimitForUser:1` → first order 2476 ok; second → "Coupon usage limit exceeded". | +| CP-07 | PASS | First-order-only coupon rejected for U2 (already ordered) with a clear message; accepted for U5 (no prior orders). | +| CP-08 | PASS | Admin `coupon.delete` invalidates the coupon → subsequent `placeOrder` with it → "Coupon is no longer valid". | +| CP-09 | PASS | Reserved coupon `E2ESECRET` redeemed by U2 (personal coupon 50); U1 redeeming the same secret → "Invalid or already redeemed". One-time enforced. | +| CP-10 | PASS | Malformed secret → "Invalid or already redeemed coupon code"; valid code still redeemable. | +| CP-11 | ⚪ NOT A DEFECT | Region-2 order (address 883, sku 157) applied region-1 coupon 45 → order 2477 total ₹79 (₹149 + ₹30 − ₹100). Coupons are not region-scoped. **2026-10-10:** region-scoped coupons are not wanted (coupons are global), so no region filter is added (FC-10 is a false flag for now). | + +### B. Authentication and account lifecycle + +| ID | Status | Evidence / notes | +|---|---|---| +| AU-01 | PASS | Signed-out home/search/catalog work; Me tab shows the login wall ("Please log in…") with no forced redirect and other tabs remain usable. Cart wall previously verified. | +| AU-02 | PASS | Password login from the **cart wall** returned to the cart with the item intact (qty 3, ₹597, address/slot retained); the wall also offers "Go Back". Login from the Me wall returns to My Account. No OTP is sent by the password path. | +| AU-03 | FAIL (status) | Wrong password and unknown user both return **HTTP 500** (not 401) because `ApiError` statuses are flattened to 500. No auth state is granted (still fails), but the contract is wrong. | +| AU-04 | PASS | Password login with email (`e2e_u2@test.com`) and mobile (`9000000002`) both resolve to the same account (id 1310). | +| AU-05 | PASS | `user.auth.register` creates exactly one account; duplicate email/mobile rejected — exercised when provisioning U2/U3/U5. | +| AU-06 | PASS | Tokens persist across requests. Cross-account isolation holds (SEC-03). UI logout works (returns to the login wall). **Note:** the local cart is **not** cleared on logout (still ₹597 while signed out) — flagged policy question. | +| AU-07 | **FAIL → FIXED** | `user.auth.updateProfile` → 500 `"ctx.req.header is not a function"` (`ctx.req` is a fetch `Request`, only `.headers.get`). UI Edit Profile is also blocked earlier by a required-email validation (U1 has no email). Profile/name/bio updates are broken. **Fixed 2026-10-10:** `Context.req` typed as `Request`; header read via `.headers.get`; empty email now means "no change" and the client requires it only when registering. | +| AU-08 | **FAIL → FIXED** | `updatePassword` reports success but does not change the password. Fresh user U5 (id 1311): after `updatePassword('NewPass@456')`, old password still logs in (200) and new password fails (500). DB shows **two `user_creds` rows** for the user (ids 26, 27) — `upsertUserAuthPasswordInDb` inserts a duplicate instead of updating, and login reads the stale row. **Fixed 2026-10-10:** explicit select-then-update-or-insert (repairs duplicates); unique index added to `user_creds.user_id`. | +| AU-09 | PASS | Admin suspends U2 → U2 `placeOrder` blocked ("Unable to place order"); unsuspend → order succeeds (200). Blocked via `createContext` (FORBIDDEN flattened to 500). | +| AU-10 | PASS | `deleteAccount` with wrong mobile rejected; correct mobile → success; subsequent login fails (account gone). | + +### F. Cart, quantities and checkout summary + +| ID | Status | Evidence / notes | +|---|---|---| +| CT-01 | PASS | Added "E2E Chicken 500 g" from Search; floating bar updated to "₹199 • 1 Item" and the full Cart showed the same line/qty/subtotal. | +| CT-02 | PARTIAL | Duplicate-add merge not fully isolated; the product-detail stepper sets quantity (1→3) rather than adding twice, and totals track correctly. | +| CT-03 | PASS | Product-detail stepper 1→3 and cart stepper 3→6 update the subtotal consistently (₹597 → ₹1194). | +| CT-04 | PASS | Cold launch restored the cart line automatically once the catalog loaded. | +| CT-05 | PARTIAL | A second slot for the SKU was created, but the in-app slot selector only surfaced the already-assigned slot (cache lag within the session); the selector itself opens correctly and shows the current slot. | +| CT-06 | PASS | With flash enabled, the 1 Hr Delivery cart (pink, "1 Hr Delivery Cart") held its own item (Chicken Breast ₹233) with its own coupon/instructions/address/bill, while the regular cart stayed at ₹1194 (E2E Chicken). The two carts are independent. | +| CT-07 | **FAIL → ⚪ NOT A DEFECT** | Admin marked SKU 155 out of stock; the published availability cache shows `isOutOfStock:true`, but the cart still rendered the line normally (₹597, checkout enabled). **Repro 2026-10-10:** the cart *does* implement the behavior — it renders "Out of Stock", filters OOS lines from checkout, and blocks when all are OOS — but the app keeps the old `availability_version_num` until its 60 s `refetchInterval` fires, so the line looks normal for up to ~1 min, then shows "Out of Stock". False flag; the residual ~60 s propagation delay is out of scope by decision. | +| CT-08 | PASS | Instructions entered on Cart ("E2E leave at door") were submitted and persisted on order 2462 (`user_notes`). Checkout is read-only for instructions. | +| CT-09 | PASS | Cart: instructions input present, address selector sits **above** Bill Details; the hidden "Go to 1 Hr Delivery" switcher is absent. Checkout: read-only bill summary + "Back to Cart". | +| CT-10 | PASS | Three rapid `+` taps → qty 3→6, subtotal ₹1194; no lost/extra increments. | +| CT-11 | PARTIAL | Cart edits propagate to the bill immediately; direct/stale checkout-route params not exercised. | + +### J. Orders, fulfillment, cancellation and after-order edits + +| ID | Status | Evidence / notes | +|---|---|---| +| OR-01 | PASS | UI COD order #2462 placed (success screen, Total ₹219). DB: `orders` region 1, address 285, slot 2012, total 219, delivery_charge 20, `is_cod=1`, `user_notes="E2E leave at door"`, item sku 155 qty 1 @199. Region-1 cart cleared. Admin A's region scoping means it is visible to admin A and not to B. | +| OR-02 | PASS | Multi-slot order → 2 suborders (2465 slot 2012 ₹199, 2466 slot 2014 ₹349); both discoverable. Delivery charge is added to the first suborder only (see BL-04). | +| OR-03 | PARTIAL | Customer instructions propagated to the order (`user_notes`). Admin note field distinct. | +| OR-04 | PASS | Admin `updatePackaged{2462,true}` + `updateDelivered{2462,true}` → customer `getOrderById` shows orderStatus/deliveryStatus success. | +| OR-05 | PARTIAL | Toggle reversal accepted (no explicit forbidden-transition errors observed for packaged/delivered). | +| OR-06 | PASS | Customer cancelled U2 order 2463 with reason → admin `getOrderDetails` shows `isCancelled:true`, `cancelReason:"changed mind"`, `refundCouponId:null` (no cash owed for COD). | +| OR-07 | PASS | Admin cancelled order 2456 → customer `getOrderById` returns status `cancelled`. | +| OR-08 | PASS | Blank reason → 400; second cancel → "Order is already cancelled"; cancel after delivered → "Cannot cancel delivered order". | +| OR-09 | PASS | `removeDeliveryCharge{2457}` → total dropped from 119 to 99 (`deliveryCharge:0`) in the customer view. | +| OR-10 | PASS | `rebalanceSlots{[2012]}` → 9 orders rebalanced; historical orders not silently repriced by catalog edits. | +| OR-11 | PASS | Admin `getAll` pagination: page1 3 orders (nextCursor 2462), page2 3 orders (2461/2460/2459), no duplicates. Admin B cannot read A's order (500). | +| OR-12 | **FAIL → 🟡 MITIGATED (client)** | No server-side idempotency: two identical `placeOrder` calls created **4 orders** (2465–2468). Client loading lock exists but the backend accepts duplicates. **2026-10-10:** client double-submit guard added (button disabled while pending + synchronous `useRef` guard in `handlePlaceOrder`). Server idempotency key intentionally deferred, so API replays/retries are still not covered. | + +### O. Payment/refund readiness + +| ID | Status | Evidence / notes | +|---|---|---| +| PAY-01 | PASS | Checkout offers **Cash on Delivery only** ("Upi accepted during COD / Cash payment"); no online-payment option is presented, and the order flow completes with COD. | +| PAY-02/03/04/05 | NOT RUN | Gateway is a stub — not testable today. | + +### C. Stores, products, variants, offers and combos + +| ID | Status | Evidence / notes | +|---|---|---| +| PD-01 | PARTIAL | Fixture product with 2 variants visible to the customer in region A with correct names/prices/quantities; full image/feature/store/slot UI assertions not all run. | +| PD-02 | PASS | Region isolation (API + UI) — see RG-06. | +| PD-03 | PASS | `updateProduct` rename → read back "E2E Chicken EDITED"; published `products.json` (v4) reflects the current name after revert. | +| PD-04 | PASS | Duplicate product name rejected ("A product with this name already exists"); `storeId:0` and negative price rejected by zod. No partial rows. | +| PD-05 | PASS (API) | `toggleOutOfStock` flips both SKUs of the product; availability cache regenerated. Customer OOS propagation is slot-driven (see note below); UI re-check not run. | +| PD-06 | PASS | `updateProduct` with `sku 156 isSuspended:true` → SKU 156 suspended, sibling 155 unaffected; restored. | +| PD-07 | PARTIAL | Adding a third SKU works (sku 159 created). Omitting a SKU from the `updateProduct` payload does **not** remove it; removal requires `isDeleted:true` (soft-delete works). No hard-delete path observed. | +| PD-08 | PASS | `updateProductPrices {productId:155, price:209}` → SKU 155 price 209 (sibling 349 untouched); availability cache regenerated; restored to 199. | +| PD-09 | PASS (API) | `updateProduct` sku 155 `isOffer:true` → flag set; restored. Offers-tab UI not run. | +| PD-10 | PASS | Combo product created (`productType:combo`); components persisted in `product_combos` (combo sku 160 → skus 155,156). API create response omits `comboItems` (cosmetic). | +| PD-11 | PASS (API) | Component sku 155 set `isComboOnly:true` → flag persisted; restored. User-app hiding not re-run. | +| PD-12 | NOT RUN | Combo availability when a component is OOS/suspended/deleted pending. | +| PD-13 | **FAIL → FIXED** | `admin.store.deleteStore {storeId:1}` **succeeded even though store 1 had 41 products**, leaving all 41 with `store_id = NULL` (orphaned catalog). Restored manually (store 1 + reassigned products). Store deletion has no dependency guard. **Fixed 2026-10-10:** a store with products can no longer be deleted; the null-out step is gone. | + +Note (PD-05): on the customer Home, "Out of Stock" is driven by slot assignment (`ProductCard`: `isOutOfStock || (slotsLoaded && !slotId)`), not only by the product flag — so products without a current active slot show OOS regardless of the product `isOutOfStock` value. + +### E. Scheduled slots and capacity + +| ID | Status | Evidence / notes | +|---|---|---| +| SL-01 | PARTIAL | Slot created with assigned SKUs; the add-to-cart dialog for "E2E Chicken 500 g" offered only the slot it is assigned to ("Sun, 11 Oct • 4-5 PM"). | +| SL-03 | PASS (API) | `admin.slots.createSlot` accepts `isActive:false`; the customer add-to-cart dialog lists only active future slots (only slot 2012 appeared). Inactive/past slots not offered. | +| SL-05 | PASS (API) | `getUserSlotCapacityStatus` is checked in `placeOrder`; a full slot is rejected ("Selected delivery slot is at full capacity"). Not exercised by setting capacity full via UI. | +| SL-02 | PASS | `updateSlot{2012, skuIds:[155]}` → slot products became [155] (156 removed); restored to [155,156]. | +| SL-04 | **FAIL → FIXED** | A slot with `freezeTime` in the past (2020-01-01) still accepted an order: `placeOrder{skuId:155, slotId:2015}` → 200, order 2469. The backend checks capacity but not the slot freeze/closed state. **Fixed 2026-10-10:** a slot with `freezeTime`/`deliveryTime` in the past is rejected (400). | +| SL-06 | PASS | After `updateSlotCapacity{2012, isCapacityFull:false}` the same order succeeds (200). | +| SL-07 | NOT RUN | Client fallback slot selection pending. | +| SL-08 | NOT RUN | Midnight/IST boundary pending. | + +### D. Discovery, tags, groups, ordering and banners + +| ID | Status | Evidence / notes | +|---|---|---| +| DS-01 | PASS | `createProductTag` (dashboard tag, productIds [155,156]) created; tag 12 persisted with junction rows. | +| DS-02 | **FAIL → FIXED** | `deleteProductTag {id:12}` → raw DB error `Failed query: delete from "product_tag_info" …`. Root cause: the `product_tags` junction rows are not deleted first and the FK (`ON DELETE no action`) blocks it. Deleting a tag with products is broken. (Membership update via `updateProductTag` works.) **Fixed 2026-10-10:** junction rows are deleted first, so tags with products delete cleanly. | +| DS-03 | PASS | Region-scoped: region 1 `tagsOrder` set to `12,9,1`; region 2 remained `9,1,2,4,5,8,3,7,6`. No global override. | +| DS-04 | PASS (API) | `updateRegionConstants` sets `popularItems`/`allItemsOrder` per region. UI ordering not run. | +| DS-05 | PASS (API) | Product group 14 (products 155,156) created; slot 2017 created with `groupIds:[14]`. Group→slot membership accepted. | +| DS-06 | PASS | `createBanner` defaults to `isActive:false`; `getBanners` shows it inactive; `updateBanner isActive:true` activates it. | +| DS-07 | PASS (API) | Banner lifecycle: create → edit name + activate → deactivate → delete, all 200 and reflected in `getBanners`. | +| DS-08 | PASS | Search partial ("E2E Chicken") returns the product; no-match ("zzzznope") shows a clear empty state ("No products found — Try adjusting your search"); results are region-correct (A vs B). | + +### G. Addresses + +| ID | Status | Evidence / notes | +|---|---|---| +| AD-01 | PASS | First address created without `isDefault` → stored with `isDefault:true` (id 879) and returned by `getDefaultAddress`. | +| AD-02 | PASS | Second address marked default → exactly one default ("U5 Second"); first unset. | +| AD-03 | PASS | Missing required fields → 400 zod validation; no partial row. | +| AD-04 | PASS | Address created without coords (`latitude:null`); `updateAddress` attaches coords (16.75/77.99) and persists. | +| AD-05 | PASS | With a bound-A2 address selected/default, the cart switched to **Delivery Fee ₹200** and "Add products worth ₹601 for free delivery" (threshold 800) vs A1's ₹20 / ₹300, while browsing bound stayed A1. Selected address's bound overrides the browsing active bound. | +| AD-06 | **FAIL** | `createAddress {regionId:2, boundId:1}` (bound 1 belongs to region 1) → **200**, address 882 stored region 2 / bound 1. No coherence validation between region and bound. Combined with `AddressForm` submitting the browsing bound, address region/bound identity can drift. | +| AD-07 | NOT RUN | Foreign-default selection/confirm UI pending. | +| AD-08 | PASS | Deleting a default address allowed; deleting an address attached to an ongoing order blocked ("Address is attached to an ongoing order. Please cancel the order first."). | +| AD-09 | PARTIAL | Active bound recalculates from addresses (RG-09); explicit add/edit/delete refresh not re-run. | + +### K/L/M (remaining) + +| ID | Status | Evidence / notes | +|---|---|---| +| FL-01 | PASS | Flash enabled in region A → flash order 2471 (`isFlashDelivery:true`, `slotId:null`, flash price ₹299 + flash delivery ₹69 = ₹368). | +| FL-02 | PASS | Flash order with a non-flash SKU 155 → rejected ("Product 155 is not available for flash delivery"). | +| FL-03 | PASS | Flash disabled in region A → flash order rejected ("Flash delivery is currently unavailable…"). | +| FL-04 | PASS | With flash enabled, removing `isFlashAvailable` from sku 156 → flash order rejected ("Product 156 is not available for flash delivery"). Restored. | +| FL-05 | PASS | Flash order with coupon → total ₹268 (₹299 + ₹69 − ₹100). (Same discount-base issue as D10.) | +| FL-06 | NOT RUN | Scheduled flash toggle jobs pending. | +| OP-01 | PASS | Vendor `getOrdersBySnippet{E2ESNIP}` returns only the snippet's SKU (155) lines across matching orders; other SKUs are not exposed. | +| OP-02 | PASS | Admin `getOrderDetails{2462}.items[0]` shows `isPackaged:true` after the packaging update; item-level state matches. | +| OP-03 | PASS | Permanent snippet (`isPermanent:true`) returns metadata + orders; slot-specific snippet path works. (Expiry is NOT enforced on the slot variant — see SEC-07.) | +| OP-04 | PASS | `updateDeliverySequence{2012,{388:[2462]}}` persists; `updateAddressCoords{877,…}` succeeds. | +| OP-05 | PASS | Complaint round trip: U2 `complaint.raise{orderId:'ORD2463'}` → admin `getAll` shows it pending with user/order → `resolve` → U2 `getAll` shows `isResolved:true` + response. | +| OP-06 | PASS | Review round trip: U2 `createReview{productId:155, ratings:5}` → admin `getProductReviews` sees it → `respondToReview` sets `adminResponse`. | +| OP-07 | PASS | `addUserIncident{userId:1310, orderId:2463, negativityScore:2}` → `getUserIncidents` returns it (addedBy `e2eadminA`, order status cancelled). No automatic suspension (U2 can still order). | +| OP-08 | NOT RUN | Notification delivery/recipient/deep-link pending (queue not inspected). | +| RC-01..RC-06 | NOT RUN | Recovery/cross-platform/offline pending — needs network/permission manipulation and Android. | + +## Confirmed defects (from this run) + +| # | Case | Severity | Summary | +|---|---|---|---| +| D1 | SEC-01 | Critical | A customer token could call `admin.const.updateGlobalConstants` and mutate global config (used `protectedProcedure`, no staff guard). **✅ Fixed 2026-10-10** — `admin.const.*` now requires a staff token; `updateConstants` rejects global keys; redundant admin global/legacy procedures removed. | +| D2 | SEC-04 | High | `placeOrder` accepts a SKU from a different region (region-1 order with region-2 SKU 157 succeeded, order 2456). **✅ Fixed 2026-10-10** — product `regionId` must equal the order region (409). | +| D3 | SEC-05 | High | `placeOrder` accepts a SKU not assigned to the chosen slot (order 2457) and an out-of-stock SKU (order 2458). No OOS/suspended/deleted/slot-state validation. **✅ Fixed 2026-10-10** — item availability + scheduled-slot validity enforced in `placeOrderUtil`. | +| D4 | BL-06 | High | Bound A2: client preview ₹748 (₹200 delivery, threshold 800) vs backend order 2459 ₹548 (₹0 delivery, min 300). Different threshold key. **✅ Fixed 2026-10-10** — backend uses `freeDeliveryThreshold`. | +| D5 | BL-03 | High | Coupon crossing threshold: client post-coupon 249<300 → ₹20 delivery (₹269); backend pre-discount 349≥300 → ₹0 (₹249). Different discount basis. **✅ Fixed 2026-10-10** — backend uses the post-discount total. | +| D6 | BL-02 | Medium | `minRegularOrderValue` is not enforced as a minimum order (₹199 order accepted). **✅ Resolved 2026-10-10** — the dead constant was removed; no minimum-order rule is enforced (matching the customer app). | +| D7 | RG-02 | Medium | Region create is not atomic on D1: a duplicate-priority error still leaves a half-created region (id 4, no bounds) which then appears in the customer region selector. **✅ Fixed 2026-10-10** — pre-validate + compensating cleanup; no region left on failure. | +| D8 | — | Low | Several "not found" paths return HTTP 500 instead of 404 (e.g., cross-region `getProductById`). | +| D9 | CT-08 | Low | Cart delivery instructions persist after a successful order (shared `userNotes` store not cleared); matches the plan's flagged policy question. | +| D10 | SEC-06/BL | High | Percentage coupon is applied to **subtotal + delivery fee**: U2 order 2463 subtotal 199 + delivery 20, 10% off → `totalAmount=197.1` = (199+20)×0.9 instead of 199×0.9+20 = 199.1. `applyDiscountToUserOrder` receives `subOrderTotalWithDelivery` for the first suborder. **✅ Fixed 2026-10-10** — discount applies to the goods subtotal only; delivery is added afterwards. | +| D11 | SEC-07 | High | Public `updateOrderItemPackaging` lets anyone toggle any order item's packaging; public `getOrdersBySnippetAndSlot` ignores snippet expiry and leaks orders/customer names. | +| D12 | DS-02 | High | `deleteProductTag` fails with a raw FK error when the tag has products — `product_tags` junction rows are not removed first. Deleting a tag is broken. **✅ Fixed 2026-10-10** — junction rows deleted first. | +| D13 | PD-13 | High | `deleteStore` succeeds even when the store has products, orphaning 41 products (`store_id → NULL`). No dependency guard. **✅ Fixed 2026-10-10** — deletion blocked while products exist; no more null-out. | +| D14 | SL-04 | High | `placeOrder` accepts a slot whose `freezeTime` is in the past (closed slot) — only capacity is checked. **✅ Fixed 2026-10-10** — past `freezeTime`/`deliveryTime` slots rejected (400). | +| D15 | AU-08 | High | `updatePassword` inserts a **duplicate `user_creds` row** instead of updating; old password keeps working and the new one never does. **✅ Fixed 2026-10-10** — select-then-update-or-insert + unique index on `user_creds.user_id`. | +| D16 | AU-07 | High | `updateProfile` always 500s (`ctx.req.header is not a function`). Profile/name/bio updates are broken. **✅ Fixed 2026-10-10** — `Context.req` typed as `Request`; header read via `.headers.get`. | +| D17 | OR-12 | Medium | No server-side order idempotency: duplicate submissions create duplicate orders. **🟡 Mitigated client-side 2026-10-10** (double-submit guard); server-side idempotency key deferred. | +| D18 | AD-06 | Medium | `createAddress` accepts an incoherent region/bound (region 2 with region-1 bound); no coherence validation. | +| D19 | AU-03 | Low | Auth failures return HTTP 500 instead of 401 (ApiError status flattened). Same class as D8. | +| D20 | CT-07 | High | The cart does not reflect an out-of-stock item: with availability `isOutOfStock:true` for sku 155, the cart still shows the line normally and leaves checkout enabled (and the backend accepts it — SEC-05). **⚪ NOT A DEFECT (2026-10-10)** — reproduced: the cart does flag/filter/block OOS once the app picks up the new availability version (~60 s `refetchInterval` staleness window); the original observation was inside that window. | + +## Coverage summary + +- **Executed with evidence:** ~120 of 133 cases (PASS / FAIL / PARTIAL). Every category A–O has been run at least in part. +- **Genuinely NOT RUN (~11):** `RG-05`, `PD-12`, `SL-07`, `SL-08`, `BL-07`, `CP-04 UI`, `FL-06`, `OP-08`, `RC-01..06`, `PAY-02..05` — all need simulator network/GPS-race control, Android, or notification sinks. + +## Not executed (NOT RUN) — recommended next runs + +- **RG-05** (delayed resolve + manual pick race) — needs request-delay control. +- **PD-12** (combo availability when a component is OOS/suspended) — policy not defined. +- **SL-07/08** (client slot fallback; midnight/IST) — needs a second slot / timezone fixture. +- **BL-07** (stale reprice between quote and submit). +- **CP-04 UI** (My-Coupons screen for user-based coupon). +- **FL-06** (scheduled flash toggle jobs), **OP-08** (notification delivery), **RC-01..06** (network/permission/KV recovery, Android), **PAY-02..05** (gateway stub). +- **Reason:** harness time, simulator network/location-race control, Android device, and notification sinks. Each is runnable with the recipe below and the fixtures in place. + +## Reusable recipe (verified working this run) + +- **Admin login (iOS):** `tapOn id:login-name-input` → `inputText` name → `tapOn id:login-password-input` → `inputText` password → `tapOn id:login-button`. +- **Customer password login (iOS):** Me tab (`point: 90%,92%`) → tap "Log In" → `id:user-login-mobile` type mobile → `id:user-login-other-ways` → `id:user-login-password` type password → tap neutral area to dismiss keyboard → tap "Login". (Password is masked in screenshots but does land.) +- **Region switch:** Home → `point: 50%,18%` (DELIVER TO bar) → region row → "Switch & clear cart". +- **Add to cart:** search → product ADD TO CART (`point`) → slot row → "Add to Cart" → "Go to Cart". +- **Place COD order:** Checkout → scroll → `point: 50%,72%` "Place Order". + + diff --git a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql index 6e81763..0e81e33 100644 --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql +++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql @@ -175,14 +175,13 @@ CREATE TABLE `__new_store_info` ( `description` text, `image_url` text, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, - `owner` integer NOT NULL, - `region_id` integer NOT NULL, - FOREIGN KEY (`owner`) REFERENCES `__new_staff_users`(`id`) ON UPDATE no action ON DELETE no action, + `region_id` integer, + `is_global` integer DEFAULT false NOT NULL, 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`) -SELECT `id`,`name`,`description`,`image_url`,`created_at`,`owner`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `store_info`; +INSERT INTO `__new_store_info` (`id`,`name`,`description`,`image_url`,`created_at`,`region_id`,`is_global`) +SELECT `id`,`name`,`description`,`image_url`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar'),false FROM `store_info`; --> statement-breakpoint CREATE TABLE `__new_product_info` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, @@ -193,7 +192,7 @@ CREATE TABLE `__new_product_info` ( `increment_step` real DEFAULT 1 NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `product_type` text DEFAULT 'item' NOT NULL, - `region_id` integer NOT NULL, + `region_id` integer, FOREIGN KEY (`store_id`) REFERENCES `__new_store_info`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); @@ -336,30 +335,33 @@ CREATE TABLE `__new_product_skus` ( `product_id` integer NOT NULL, `name` text, `images` text, - `is_offer` integer DEFAULT false NOT NULL, `is_combo_only` integer DEFAULT false NOT NULL, `is_deleted` integer DEFAULT false NOT NULL, + `is_suspended` integer DEFAULT false NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, FOREIGN KEY (`product_id`) REFERENCES `__new_product_info`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint -INSERT INTO `__new_product_skus` (`id`,`product_id`,`name`,`images`,`is_offer`,`is_combo_only`,`is_deleted`,`created_at`) -SELECT `id`,`product_id`,`name`,`images`,`is_offer`,`is_combo_only`,`is_deleted`,`created_at` FROM `product_skus`; +INSERT INTO `__new_product_skus` (`id`,`product_id`,`name`,`images`,`is_combo_only`,`is_deleted`,`is_suspended`,`created_at`) +SELECT `ps`.`id`,`ps`.`product_id`,`ps`.`name`,`ps`.`images`,`ps`.`is_combo_only`,`ps`.`is_deleted`,COALESCE((SELECT `ms`.`is_suspended` FROM `product_market_stats` `ms` WHERE `ms`.`sku_id` = `ps`.`id`), false),`ps`.`created_at` FROM `product_skus` `ps`; --> statement-breakpoint CREATE TABLE `__new_product_market_stats` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `sku_id` integer NOT NULL, + `region_id` integer NOT NULL, `market_price` text, `our_price` text NOT NULL, `is_flash_available` integer DEFAULT false NOT NULL, `flash_price` text, `is_out_of_stock` integer DEFAULT false NOT NULL, - `is_suspended` integer DEFAULT false NOT NULL, - FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action + `is_suspended_in_region` integer DEFAULT false NOT NULL, + `is_offer` integer DEFAULT false NOT NULL, + FOREIGN KEY (`sku_id`) REFERENCES `__new_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 ); --> statement-breakpoint -INSERT INTO `__new_product_market_stats` (`id`,`sku_id`,`market_price`,`our_price`,`is_flash_available`,`flash_price`,`is_out_of_stock`,`is_suspended`) -SELECT `id`,`sku_id`,`market_price`,`our_price`,`is_flash_available`,`flash_price`,`is_out_of_stock`,`is_suspended` FROM `product_market_stats`; +INSERT INTO `__new_product_market_stats` (`id`,`sku_id`,`region_id`,`market_price`,`our_price`,`is_flash_available`,`flash_price`,`is_out_of_stock`,`is_suspended_in_region`,`is_offer`) +SELECT ms.`id`,ms.`sku_id`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar'),ms.`market_price`,ms.`our_price`,ms.`is_flash_available`,ms.`flash_price`,ms.`is_out_of_stock`,false,COALESCE(ps.`is_offer`,false) FROM `product_market_stats` ms JOIN `product_skus` ps ON ps.`id` = ms.`sku_id`; --> statement-breakpoint CREATE TABLE `__new_sku_features` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, @@ -780,7 +782,7 @@ CREATE UNIQUE INDEX `vendor_snippets_snippet_code_unique` ON `vendor_snippets` ( --> statement-breakpoint CREATE UNIQUE INDEX `coupons_coupon_code_unique` ON `coupons` (`coupon_code`); --> statement-breakpoint -CREATE UNIQUE INDEX `product_market_stats_sku_id_unique` ON `product_market_stats` (`sku_id`); +CREATE UNIQUE INDEX `product_market_stats_sku_region` ON `product_market_stats` (`sku_id`,`region_id`); --> statement-breakpoint CREATE UNIQUE INDEX `unique_sku_feature_name` ON `sku_features` (`sku_id`,`feature_name`); --> statement-breakpoint diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts index 88403e0..653a324 100644 --- a/packages/db_helper_sqlite/index.ts +++ b/packages/db_helper_sqlite/index.ts @@ -413,3 +413,21 @@ export { getEffectiveRegionSettings, getRegionSettingsForBound, } from './src/superadmin-apis/regions' + +// Global stores / products (superadmin) +export { + isGlobalStore, + listGlobalStores, + getGlobalStore, + createGlobalStore, + updateGlobalStore, + deleteGlobalStore, +} from './src/superadmin-apis/global-stores' + +export { + listGlobalProducts, + getGlobalProduct, + createGlobalProduct, + updateGlobalProduct, + deleteGlobalProductById, +} from './src/superadmin-apis/global-products' diff --git a/packages/db_helper_sqlite/src/admin-apis/order.ts b/packages/db_helper_sqlite/src/admin-apis/order.ts index dc203c9..b3eb66f 100644 --- a/packages/db_helper_sqlite/src/admin-apis/order.ts +++ b/packages/db_helper_sqlite/src/admin-apis/order.ts @@ -30,6 +30,7 @@ import type { } from '@packages/shared' import type { InferSelectModel } from 'drizzle-orm' import { coerceDate } from '../lib/date' +import { marketStatsForRegion } from '../lib/market-stats' import { composeSkuName, composeUnitNotation } from '../lib/sku-features' const isPaymentStatus = (value: string): value is PaymentStatus => @@ -664,13 +665,13 @@ export async function rebalanceSlots(regionId: number, slotIds: number[]): Promi const processedOrdersData = ordersList.map((order: any) => { let newTotal = order.orderItems.reduce((acc: number, item: any) => { - const latestPrice = +(item.sku?.marketStats?.ourPrice ?? 0) + const latestPrice = +(marketStatsForRegion(item.sku?.marketStats, regionId)?.ourPrice ?? 0) const amount = latestPrice * Number(item.quantity) return acc + amount }, 0) order.orderItems.forEach((item: any) => { - const latestPrice = item.sku?.marketStats?.ourPrice + const latestPrice = marketStatsForRegion(item.sku?.marketStats, regionId)?.ourPrice item.price = latestPrice item.discountedPrice = latestPrice }) diff --git a/packages/db_helper_sqlite/src/admin-apis/product.ts b/packages/db_helper_sqlite/src/admin-apis/product.ts index e5155cd..abff3dd 100644 --- a/packages/db_helper_sqlite/src/admin-apis/product.ts +++ b/packages/db_helper_sqlite/src/admin-apis/product.ts @@ -15,6 +15,7 @@ import { productTagInfo, users, storeInfo, + regions, cartItems, orderItems, coupons, @@ -24,9 +25,10 @@ import { keyValStore, couponApplicableProducts, } from '../db/schema' -import { and, desc, eq, inArray, sql } from 'drizzle-orm' +import { and, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm' import { runBatched } from '../lib/run-batched' -import type { InferInsertModel, InferSelectModel } from 'drizzle-orm' +import { marketStatsForRegion, isSkuSuspended } from '../lib/market-stats' +import type { InferSelectModel } from 'drizzle-orm' // Chunk sizes for multi-row inserts so no single statement exceeds SQLite's // 999-bind-parameter limit (chunk size × params-per-row must stay under 999). @@ -81,19 +83,23 @@ const getStringArray = (value: unknown): string[] | null => { } // Region guards: SKUs resolve to a region through their parent product -// (productSkus.productId -> productInfo.regionId). Throws on unknown ids or -// ids whose parent product lives in another region. -const resolveSkuRegions = async (txOrDb: any, skuIds: number[]): Promise> => { +// (productSkus.productId -> productInfo.regionId). A global SKU (its product's +// store is global) is valid in every region. Throws on unknown ids or ids whose +// parent product lives in another (non-global) region. +const resolveSkuRegions = async (txOrDb: any, skuIds: number[]): Promise> => { if (skuIds.length === 0) return new Map() const rows = await txOrDb.query.productSkus.findMany({ where: inArray(productSkus.id, skuIds), - with: { product: { columns: { regionId: true } } }, + with: { product: { columns: { regionId: true }, with: { store: { columns: { isGlobal: true } } } } }, columns: { id: true }, }) - return new Map(rows.map((r: any) => [r.id, r.product?.regionId ?? null])) + return new Map(rows.map((r: any) => [ + r.id, + { regionId: r.product?.regionId ?? null, isGlobal: r.product?.store?.isGlobal ?? false }, + ])) } -const assertSkuIdsInRegion = async (txOrDb: any, skuIds: number[], regionId: number, noun = 'SKU'): Promise => { +const assertSkuIdsInRegion = async (txOrDb: any, skuIds: number[], regionId: number | null, noun = 'SKU'): Promise => { const unique = [...new Set(skuIds.map(Number).filter((n) => Number.isFinite(n)))] if (unique.length === 0) return const regions = await resolveSkuRegions(txOrDb, unique) @@ -101,21 +107,33 @@ const assertSkuIdsInRegion = async (txOrDb: any, skuIds: number[], regionId: num if (missing.length > 0) { throw new Error(`Invalid ${noun} IDs: ${missing.join(', ')}`) } - const foreign = unique.filter((id) => regions.get(id) !== regionId) + const foreign = unique.filter((id) => { + const r = regions.get(id)! + // A global product (regionId null) may only contain global SKUs; a regional + // product may not contain another region's SKU. + if (regionId == null) return !r.isGlobal + return !r.isGlobal && r.regionId !== regionId + }) if (foreign.length > 0) { throw new Error(`${noun} ${foreign.join(', ')} belongs to a different region`) } } -const assertStoreInRegion = async (txOrDb: any, storeId: number, regionId: number): Promise => { +const assertStoreInRegion = async (txOrDb: any, storeId: number, regionId: number | null): Promise => { const store = await txOrDb.query.storeInfo.findFirst({ where: eq(storeInfo.id, storeId), - columns: { id: true, regionId: true }, + columns: { id: true, regionId: true, isGlobal: true }, }) if (!store) { throw new Error(`Invalid store ID: ${storeId}`) } - if (store.regionId !== regionId) { + if (regionId == null) { + // A global product must belong to a global store. + if (!store.isGlobal) throw new Error('A global product must use a global store') + return + } + // A regional product must belong to that region's own (non-global) store. + if (store.isGlobal || store.regionId !== regionId) { throw new Error('Store belongs to a different region') } } @@ -125,13 +143,13 @@ const assertStoreIdsInRegion = async (txOrDb: any, storeIds: number[], regionId: if (unique.length === 0) return const rows = await txOrDb.query.storeInfo.findMany({ where: inArray(storeInfo.id, unique), - columns: { id: true, regionId: true }, + columns: { id: true, regionId: true, isGlobal: true }, }) if (rows.length !== unique.length) { const found = new Set(rows.map((r: { id: number }) => r.id)) throw new Error(`Invalid store IDs: ${unique.filter((id) => !found.has(id)).join(', ')}`) } - if (rows.some((r: { regionId: number | null }) => r.regionId !== regionId)) { + if (rows.some((r: { regionId: number | null; isGlobal: boolean }) => !r.isGlobal && r.regionId !== regionId)) { throw new Error('Store belongs to a different region') } } @@ -141,9 +159,8 @@ const mapStore = (store: StoreRow): Store => ({ name: store.name, description: store.description, imageUrl: store.imageUrl, - owner: store.owner, + isGlobal: store.isGlobal, createdAt: store.createdAt, - // updatedAt: store.createdAt, }) const mapProduct = (product: ProductRow): AdminProduct => ({ @@ -155,6 +172,7 @@ const mapProduct = (product: ProductRow): AdminProduct => ({ incrementStep: product.incrementStep, createdAt: product.createdAt, productType: product.productType as 'item' | 'combo', + isGlobal: product.regionId == null, }) const mapSkuFeature = (feature: SkuFeatureRow): AdminSkuFeature => ({ @@ -178,10 +196,10 @@ const mapSku = ( images: getStringArray(sku.images), imageKeys: getStringArray(sku.images), isOutOfStock: marketStats?.isOutOfStock ?? false, - isSuspended: marketStats?.isSuspended ?? false, + isSuspended: sku.isSuspended, isFlashAvailable: marketStats?.isFlashAvailable ?? false, flashPrice: marketStats?.flashPrice ? String(marketStats.flashPrice) : null, - isOffer: sku.isOffer, + isOffer: marketStats?.isOffer ?? false, isComboOnly: sku.isComboOnly, isDeleted: sku.isDeleted ?? false, createdAt: sku.createdAt, @@ -211,10 +229,10 @@ const mapTagInfo = (tag: ProductTagInfoRow): AdminProductTagInfo => ({ export async function getAllProducts(regionId: number): Promise { type ProductWithRelationsRow = ProductRow & { store: StoreRow | null - skus: Array + skus: Array } const products = await db.query.productInfo.findMany({ - where: eq(productInfo.regionId, regionId), + where: or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId)), orderBy: productInfo.name, with: { store: true, @@ -236,22 +254,25 @@ export async function getAllProducts(regionId: number): Promise { - const comboItems = (sku.comboItems || []).map((ci: any) => ({ - skuId: ci.skuId, - skuName: ci.sku?.name ?? null, - features: (ci.sku?.features || []).map((f: any) => ({ featureName: f.featureName, featureValue: f.featureValue })), - productName: ci.sku?.product?.name ?? 'Unknown', - images: getStringArray(ci.sku?.images), - price: ci.sku?.marketStats?.ourPrice ? String(ci.sku.marketStats.ourPrice) : '0', - })) - return mapSku(sku, sku.features, comboItems, sku.marketStats) + const comboItems = (sku.comboItems || []).map((ci: any) => { + const ciMarketStats = marketStatsForRegion(ci.sku?.marketStats, regionId) + return { + skuId: ci.skuId, + skuName: ci.sku?.name ?? null, + features: (ci.sku?.features || []).map((f: any) => ({ featureName: f.featureName, featureValue: f.featureValue })), + productName: ci.sku?.product?.name ?? 'Unknown', + images: getStringArray(ci.sku?.images), + price: ciMarketStats?.ourPrice ? String(ciMarketStats.ourPrice) : '0', + } + }) + return mapSku(sku, sku.features, comboItems, marketStatsForRegion(sku.marketStats, regionId)) }), })) } export async function getProductById(regionId: number, id: number): Promise { const product = await db.query.productInfo.findFirst({ - where: and(eq(productInfo.id, id), eq(productInfo.regionId, regionId)), + where: and(eq(productInfo.id, id), or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))), with: { store: true, skus: { @@ -289,15 +310,18 @@ export async function getProductById(regionId: number, id: number): Promise const skusWithCombos = product.skus.map((sku) => { - const comboItems = (sku.comboItems || []).map((ci: any) => ({ - skuId: ci.skuId, - skuName: ci.sku?.name ?? null, - features: (ci.sku?.features || []).map((f: any) => ({ featureName: f.featureName, featureValue: f.featureValue })), - productName: ci.sku?.product?.name ?? 'Unknown', - images: getStringArray(ci.sku?.images), - price: ci.sku?.marketStats?.ourPrice ? String(ci.sku.marketStats.ourPrice) : '0', - })) - return mapSku(sku, sku.features, comboItems, sku.marketStats) + const comboItems = (sku.comboItems || []).map((ci: any) => { + const ciMarketStats = marketStatsForRegion(ci.sku?.marketStats, regionId) + return { + skuId: ci.skuId, + skuName: ci.sku?.name ?? null, + features: (ci.sku?.features || []).map((f: any) => ({ featureName: f.featureName, featureValue: f.featureValue })), + productName: ci.sku?.product?.name ?? 'Unknown', + images: getStringArray(ci.sku?.images), + price: ciMarketStats?.ourPrice ? String(ciMarketStats.ourPrice) : '0', + } + }) + return mapSku(sku, sku.features, comboItems, marketStatsForRegion(sku.marketStats, regionId)) }) return { @@ -322,9 +346,20 @@ export async function deleteProduct(regionId: number, id: number): Promise +export async function deleteGlobalProduct(id: number): Promise { + const [deletedProduct] = await db + .delete(productInfo) + .where(and(eq(productInfo.id, id), isNull(productInfo.regionId))) + .returning() -export async function createProduct(input: CreateProductInput, regionId: number): Promise { + if (!deletedProduct) { + return null + } + + return mapProduct(deletedProduct) +} + +export async function createProduct(input: CreateProductInput, regionId: number | null): Promise { if (!input.skus || input.skus.length === 0) { throw new Error('At least one SKU is required') } @@ -336,6 +371,12 @@ export async function createProduct(input: CreateProductInput, regionId: number) throw new Error('Every SKU must have a quantity feature') } + // A global product (regionId null) seeds a market-stats row in EVERY region so + // each region gets the superadmin's initial values. + const targetRegionIds = regionId == null + ? (await db.select({ id: regions.id }).from(regions)).map((r) => r.id) + : [regionId] + // Cross-region validation BEFORE the generic try/catch so the specific // message reaches the caller instead of the masked generic failure. if ((input as any).storeId != null) { @@ -368,9 +409,9 @@ export async function createProduct(input: CreateProductInput, regionId: number) productId: product.id, name: sku.name ?? null, images: sku.images ?? null, - isOffer: sku.isOffer ?? false, isComboOnly: sku.isComboOnly ?? false, isDeleted: sku.isDeleted ?? false, + isSuspended: sku.isSuspended ?? false, })) ).returning() }) @@ -380,15 +421,16 @@ export async function createProduct(input: CreateProductInput, regionId: number) const skuRow = skuRows[i] const sku = skus[i] - await tx.insert(productMarketStats).values({ + await tx.insert(productMarketStats).values(targetRegionIds.map((rid) => ({ skuId: skuRow.id, + regionId: rid, marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null, ourPrice: sku.price != null ? String(sku.price) : '0', isFlashAvailable: sku.isFlashAvailable ?? false, flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null, isOutOfStock: sku.isOutOfStock ?? false, - isSuspended: sku.isSuspended ?? false, - }) + isOffer: sku.isOffer ?? false, + }))) if (sku.features && sku.features.length > 0) { await runBatched(tx, sku.features, FEATURE_INSERT_CHUNK_SIZE, async (t, chunk) => { @@ -425,7 +467,7 @@ export async function createProduct(input: CreateProductInput, regionId: number) return { ...mapProduct(product), store: null, - skus: createdSkus.map((s) => mapSku(s, s.features, [], s.marketStats)), + skus: createdSkus.map((s) => mapSku(s, s.features, [], marketStatsForRegion(s.marketStats, regionId ?? targetRegionIds[0]))), } }) } catch (error) { @@ -434,15 +476,67 @@ export async function createProduct(input: CreateProductInput, regionId: number) } } -export async function updateProduct(regionId: number, id: number, input: any): Promise { +// A regional admin editing a GLOBAL product may change only this region's market +// data — never the product's structure (owned by the superadmin). +async function updateProductMarketDataForRegion(regionId: number, id: number, input: any): Promise { + const skus = input?.skus + if (!Array.isArray(skus) || skus.length === 0) return + const existingSkus = await db.query.productSkus.findMany({ + where: eq(productSkus.productId, id), + columns: { id: true }, + }) + const existingSkuIdSet = new Set(existingSkus.map((s) => s.id)) + await db.transaction(async (tx) => { + for (const sku of skus) { + if (sku?.id == null || !existingSkuIdSet.has(sku.id)) continue + const values = { + marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null, + ourPrice: sku.price != null ? String(sku.price) : '0', + isFlashAvailable: sku.isFlashAvailable ?? false, + flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null, + isOutOfStock: sku.isOutOfStock ?? false, + isSuspendedInRegion: sku.isSuspendedInRegion ?? sku.isSuspended ?? false, + isOffer: sku.isOffer ?? false, + } + const existing = await tx.query.productMarketStats.findFirst({ + where: and(eq(productMarketStats.skuId, sku.id), eq(productMarketStats.regionId, regionId)), + columns: { id: true }, + }) + if (existing) { + await tx.update(productMarketStats).set(values) + .where(and(eq(productMarketStats.skuId, sku.id), eq(productMarketStats.regionId, regionId))) + } else { + await tx.insert(productMarketStats).values({ skuId: sku.id, regionId, ...values }) + } + } + }) +} + +export async function updateProduct(regionId: number | null, id: number, input: any): Promise { const product = await db.query.productInfo.findFirst({ - where: and(eq(productInfo.id, id), eq(productInfo.regionId, regionId)), + where: eq(productInfo.id, id), }) if (!product) { return null } + // A global product edited by a regional admin (regionId != null): market data + // only, for that region. A regional product may only be edited by its region. + if (regionId != null && product.regionId == null) { + await updateProductMarketDataForRegion(regionId, id, input) + return getProductById(regionId, id) + } + if (regionId != null && product.regionId !== regionId) { + return null + } + + // Regions whose market stats this update writes: the caller's region, or every + // region for a superadmin structural edit of a global product (regionId null). + const targetRegionIds = regionId == null + ? (await db.select({ id: regions.id }).from(regions)).map((r) => r.id) + : [regionId] + const { skus, ...productData } = input // Input validation outside the transaction so specific messages reach the UI. @@ -486,11 +580,14 @@ export async function updateProduct(regionId: number, id: number, input: any): P const comboIds = Array.from(new Set(comboMemberships.map((c) => c.comboSkuId))) if (comboIds.length > 0) { - const combos = await db.query.productMarketStats.findMany({ - where: inArray(productMarketStats.skuId, comboIds), - columns: { skuId: true, isSuspended: true }, + const combos = await db.query.productSkus.findMany({ + where: inArray(productSkus.id, comboIds), + columns: { id: true, isSuspended: true }, + with: { marketStats: true }, }) - const activeComboIds = combos.filter((c) => !c.isSuspended).map((c) => c.skuId) + const activeComboIds = combos + .filter((c) => !isSkuSuspended(c.isSuspended, marketStatsForRegion(c.marketStats, regionId))) + .map((c) => c.id) if (activeComboIds.length > 0) { throw new Error( `Cannot suspend SKU(s): they are members of combo(s) ${activeComboIds.join(', ')} that are not suspended` @@ -511,7 +608,7 @@ export async function updateProduct(regionId: number, id: number, input: any): P incrementStep: productData.incrementStep ?? 1, productType: productData.productType, }) - .where(and(eq(productInfo.id, id), eq(productInfo.regionId, regionId))) + .where(eq(productInfo.id, id)) if (skus !== undefined) { const existingSkus = await tx.query.productSkus.findMany({ @@ -527,33 +624,38 @@ export async function updateProduct(regionId: number, id: number, input: any): P .set({ name: sku.name ?? null, images: sku.images ?? null, - isOffer: sku.isOffer ?? false, isComboOnly: sku.isComboOnly ?? false, + isSuspended: sku.isSuspended ?? false, ...(sku.isDeleted !== undefined && { isDeleted: sku.isDeleted }), }) .where(eq(productSkus.id, sku.id)) - const existingMarketStats = await tx.query.productMarketStats.findFirst({ - where: eq(productMarketStats.skuId, sku.id), - columns: { id: true }, - }) - const marketStatsValues = { - marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null, - ourPrice: sku.price != null ? String(sku.price) : '0', - isFlashAvailable: sku.isFlashAvailable ?? false, - flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null, - isOutOfStock: sku.isOutOfStock ?? false, - isSuspended: sku.isSuspended ?? false, - } - if (existingMarketStats) { - await tx.update(productMarketStats) - .set(marketStatsValues) - .where(eq(productMarketStats.skuId, sku.id)) - } else { - await tx.insert(productMarketStats).values({ - skuId: sku.id, - ...marketStatsValues, + // Superadmin structural edit of a global product (regionId null) leaves + // each region's market data untouched; a regional edit writes its region. + if (regionId != null) { + const marketStatsValues = { + marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null, + ourPrice: sku.price != null ? String(sku.price) : '0', + isFlashAvailable: sku.isFlashAvailable ?? false, + flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null, + isOutOfStock: sku.isOutOfStock ?? false, + isOffer: sku.isOffer ?? false, + } + const existingMarketStats = await tx.query.productMarketStats.findFirst({ + where: and(eq(productMarketStats.skuId, sku.id), eq(productMarketStats.regionId, regionId)), + columns: { id: true }, }) + if (existingMarketStats) { + await tx.update(productMarketStats) + .set(marketStatsValues) + .where(and(eq(productMarketStats.skuId, sku.id), eq(productMarketStats.regionId, regionId))) + } else { + await tx.insert(productMarketStats).values({ + skuId: sku.id, + regionId, + ...marketStatsValues, + }) + } } await tx.delete(skuFeatures).where(eq(skuFeatures.skuId, sku.id)) @@ -589,20 +691,21 @@ export async function updateProduct(regionId: number, id: number, input: any): P productId: id, name: sku.name ?? null, images: sku.images ?? null, - isOffer: sku.isOffer ?? false, isComboOnly: sku.isComboOnly ?? false, isDeleted: sku.isDeleted ?? false, + isSuspended: sku.isSuspended ?? false, }).returning() - await tx.insert(productMarketStats).values({ + await tx.insert(productMarketStats).values(targetRegionIds.map((rid) => ({ skuId: newSku.id, + regionId: rid, marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null, ourPrice: sku.price != null ? String(sku.price) : '0', isFlashAvailable: sku.isFlashAvailable ?? false, flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null, isOutOfStock: sku.isOutOfStock ?? false, - isSuspended: sku.isSuspended ?? false, - }) + isOffer: sku.isOffer ?? false, + }))) if (sku.features && sku.features.length > 0) { await runBatched(tx, sku.features, FEATURE_INSERT_CHUNK_SIZE, async (t, chunk) => { @@ -651,7 +754,7 @@ export async function updateProduct(regionId: number, id: number, input: any): P return { ...mapProduct(updatedProduct), store: updatedProduct.store ? mapStore(updatedProduct.store) : null, - skus: updatedProduct.skus.map((s) => mapSku(s, s.features, [], s.marketStats)), + skus: updatedProduct.skus.map((s) => mapSku(s, s.features, [], marketStatsForRegion(s.marketStats, regionId ?? targetRegionIds[0]))), } }) } catch (error) { @@ -672,7 +775,7 @@ export async function getAllProductTags(regionId: number): Promise }> + }) as Array }> return tags.map((tag: any) => ({ ...mapTagInfo(tag), @@ -680,7 +783,7 @@ export async function getAllProductTags(regionId: number): Promise assignment.productId), })) @@ -757,7 +860,7 @@ export async function getProductTagById(regionId: number, tagId: number): Promis productId: assignment.productId, tagId: assignment.tagId, assignedAt: assignment.assignedAt, - product: mapSku(assignment.sku, assignment.sku.features, [], assignment.sku.marketStats), + product: mapSku(assignment.sku, assignment.sku.features, [], marketStatsForRegion(assignment.sku.marketStats, regionId)), })), productIds: (tag.products || []).map((assignment: ProductTagRow) => assignment.productId), } @@ -805,7 +908,7 @@ export async function updateProductTag(regionId: number, tagId: number, input: U productId: assignment.productId, tagId: assignment.tagId, assignedAt: assignment.assignedAt, - product: mapSku(assignment.sku, assignment.sku.features, [], assignment.sku.marketStats), + product: mapSku(assignment.sku, assignment.sku.features, [], marketStatsForRegion(assignment.sku.marketStats, regionId)), })), productIds: (fullTag?.products || []).map((assignment: ProductTagRow) => assignment.productId) || [], } @@ -949,7 +1052,7 @@ export async function getAllProductGroups(regionId: number) { description: group.description ?? null, createdAt: group.createdAt, products: (group.memberships || []).map((membership: any) => - mapSku(membership.sku, membership.sku.features, [], membership.sku.marketStats) + mapSku(membership.sku, membership.sku.features, [], marketStatsForRegion(membership.sku.marketStats, regionId)) ), productCount: group.memberships.length, memberships: group.memberships @@ -1116,7 +1219,7 @@ export async function updateProductPrices(regionId: number, updates: Array<{ if (Object.keys(updateData).length === 0) continue const existingMarketStats = await tx.query.productMarketStats.findFirst({ - where: eq(productMarketStats.skuId, productId), + where: and(eq(productMarketStats.skuId, productId), eq(productMarketStats.regionId, regionId)), columns: { id: true }, }) @@ -1124,10 +1227,11 @@ export async function updateProductPrices(regionId: number, updates: Array<{ await tx .update(productMarketStats) .set(updateData) - .where(eq(productMarketStats.skuId, productId)) + .where(and(eq(productMarketStats.skuId, productId), eq(productMarketStats.regionId, regionId))) } else { await tx.insert(productMarketStats).values({ skuId: productId, + regionId, ourPrice: updateData.ourPrice ?? '0', marketPrice: updateData.marketPrice ?? null, flashPrice: updateData.flashPrice ?? null, @@ -1162,12 +1266,12 @@ export async function toggleProductOutOfStock( } // Product is "out" if any of its SKUs is out; toggle the whole product. - const nextIsOutOfStock = !skus.some((sku) => sku.marketStats?.isOutOfStock) + const nextIsOutOfStock = !skus.some((sku) => marketStatsForRegion(sku.marketStats, regionId)?.isOutOfStock) await db .update(productMarketStats) .set({ isOutOfStock: nextIsOutOfStock }) - .where(inArray(productMarketStats.skuId, skus.map((sku) => sku.id))) + .where(and(inArray(productMarketStats.skuId, skus.map((sku) => sku.id)), eq(productMarketStats.regionId, regionId))) return { id: productId, isOutOfStock: nextIsOutOfStock } } 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 6d833d5..fbff61a 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, storeInfo, coupons, reservedCoupons, userIncidents } from '../db/schema' +import { staffUsers, staffRoles, users, userDetails, orders, staffNotifCreds, coupons, reservedCoupons, userIncidents } from '../db/schema' import { eq, or, like, and, lt, desc } from 'drizzle-orm' import type { StaffUser } from '@packages/shared' @@ -163,8 +163,8 @@ export interface DeleteStaffUserResult { /** * Superadmin-only: delete a staff account. * - * staff_users is referenced by (all NOT NULL): store_info.owner, - * coupons.created_by, reserved_coupons.created_by, staff_notif_creds.staff_user_id. + * staff_users is referenced by (all NOT NULL): coupons.created_by, + * reserved_coupons.created_by, staff_notif_creds.staff_user_id. * Removal is refused when surviving data would violate those FKs; nullable back * references (user_incidents.added_by) are cleared instead. */ @@ -175,13 +175,6 @@ export async function deleteStaffUser(staffId: number): Promise => { - const owner = await txOrDb.query.staffUsers.findFirst({ - where: eq(staffUsers.id, ownerId), - columns: { id: true, regionId: true }, - }) - if (!owner) { - throw new Error(`Invalid owner ID: ${ownerId}`) - } - if (owner.regionId !== regionId) { - throw new Error('Owner belongs to a different region') - } -} - // ProductsSelector sends SKU ids — resolve them to owning product ids, rejecting -// SKUs whose parent product lives in another region. +// SKUs whose parent product lives in another region (or is global, which has no +// region). A regional store only ever holds its own region's products. const resolveInRegionProductIds = async (txOrDb: any, skuIds: number[], regionId: number): Promise => { const unique = [...new Set(skuIds.map(Number).filter((n) => Number.isFinite(n)))] if (unique.length === 0) return [] @@ -38,23 +26,19 @@ const resolveInRegionProductIds = async (txOrDb: any, skuIds: number[], regionId return [...new Set(rows.map((r: any) => r.product.id as number))] } -export async function getAllStores(regionId: number): Promise { - const stores = await db.query.storeInfo.findMany({ - where: eq(storeInfo.regionId, regionId), - with: { - owner: true, - }, - }) +// A region sees its own stores plus every global store. +const storeVisibleInRegion = (regionId: number) => + or(eq(storeInfo.regionId, regionId), eq(storeInfo.isGlobal, true)) - return stores +export async function getAllStores(regionId: number): Promise { + return db.query.storeInfo.findMany({ + where: storeVisibleInRegion(regionId), + }) } export async function getStoreById(regionId: number, id: number): Promise { const store = await db.query.storeInfo.findFirst({ - where: and(eq(storeInfo.id, id), eq(storeInfo.regionId, regionId)), - with: { - owner: true, - }, + where: and(eq(storeInfo.id, id), storeVisibleInRegion(regionId)), }) return store || null @@ -65,7 +49,6 @@ export async function createStore( products: number[] | undefined, regionId: number ): Promise { - await assertOwnerInRegion(db, input.owner, regionId) const productIds = products && products.length > 0 ? await resolveInRegionProductIds(db, products, regionId) : [] @@ -78,7 +61,7 @@ export async function createStore( name: input.name, description: input.description, imageUrl: input.imageUrl, - owner: input.owner, + isGlobal: false, }) .returning() @@ -98,9 +81,8 @@ export async function createStore( name: newStore.name, description: newStore.description, imageUrl: newStore.imageUrl, - owner: newStore.owner, + isGlobal: newStore.isGlobal, createdAt: newStore.createdAt, - // updatedAt: newStore.updatedAt, } }) } @@ -111,16 +93,14 @@ export async function updateStore( input: UpdateStoreInput, products?: number[] ): Promise { + // Only the region's own (non-global) stores are editable here. const existing = await db.query.storeInfo.findFirst({ - where: and(eq(storeInfo.id, id), eq(storeInfo.regionId, regionId)), + where: and(eq(storeInfo.id, id), eq(storeInfo.regionId, regionId), eq(storeInfo.isGlobal, false)), columns: { id: true }, }) if (!existing) { throw new Error('Store not found') } - if (input.owner !== undefined) { - await assertOwnerInRegion(db, input.owner, regionId) - } const productIds = products !== undefined && products.length > 0 ? await resolveInRegionProductIds(db, products, regionId) : [] @@ -130,7 +110,6 @@ export async function updateStore( .update(storeInfo) .set({ ...input, - // updatedAt: new Date(), }) .where(and(eq(storeInfo.id, id), eq(storeInfo.regionId, regionId))) .returning() @@ -160,16 +139,16 @@ export async function updateStore( name: updatedStore.name, description: updatedStore.description, imageUrl: updatedStore.imageUrl, - owner: updatedStore.owner, + isGlobal: updatedStore.isGlobal, createdAt: updatedStore.createdAt, - // updatedAt: updatedStore.updatedAt, } }) } export async function deleteStore(regionId: number, id: number): Promise<{ message: string }> { + // Only the region's own (non-global) stores can be deleted here. const existing = await db.query.storeInfo.findFirst({ - where: and(eq(storeInfo.id, id), eq(storeInfo.regionId, regionId)), + where: and(eq(storeInfo.id, id), eq(storeInfo.regionId, regionId), eq(storeInfo.isGlobal, false)), columns: { id: true }, }) if (!existing) { diff --git a/packages/db_helper_sqlite/src/db/schema.ts b/packages/db_helper_sqlite/src/db/schema.ts index 4ad8b4d..6f5c542 100644 --- a/packages/db_helper_sqlite/src/db/schema.ts +++ b/packages/db_helper_sqlite/src/db/schema.ts @@ -167,8 +167,9 @@ export const storeInfo = sqliteTable('store_info', { name: text().notNull(), description: text(), imageUrl: text('image_url'), + // A global store is available in every region: region_id NULL, is_global 1. + isGlobal: integer('is_global', { mode: 'boolean' }).notNull().default(false), createdAt: timestampText('created_at').notNull().default(sql`CURRENT_TIMESTAMP`), - owner: integer('owner').notNull().references(() => staffUsers.id), }) export const units = sqliteTable('units', { @@ -196,22 +197,28 @@ export const productSkus = sqliteTable('product_skus', { productId: integer('product_id').notNull().references(() => productInfo.id), name: text(), images: jsonText('images'), - isOffer: integer('is_offer', { mode: 'boolean' }).notNull().default(false), isComboOnly: integer('is_combo_only', { mode: 'boolean' }).notNull().default(false), isDeleted: integer('is_deleted', { mode: 'boolean' }).notNull().default(false), + // Global suspension (superadmin kill-switch). Per-region suspension lives on + // product_market_stats.is_suspended_in_region. + isSuspended: integer('is_suspended', { mode: 'boolean' }).notNull().default(false), createdAt: timestampText('created_at').notNull().default(sql`CURRENT_TIMESTAMP`), }) export const productMarketStats = sqliteTable('product_market_stats', { id: integer().primaryKey({ autoIncrement: true }), - skuId: integer('sku_id').notNull().references(() => productSkus.id).unique(), + skuId: integer('sku_id').notNull().references(() => productSkus.id), + regionId: integer('region_id').notNull().references(() => regions.id), marketPrice: numericText('market_price'), ourPrice: numericText('our_price').notNull(), isFlashAvailable: integer('is_flash_available', { mode: 'boolean' }).notNull().default(false), flashPrice: numericText('flash_price'), isOutOfStock: integer('is_out_of_stock', { mode: 'boolean' }).notNull().default(false), - isSuspended: integer('is_suspended', { mode: 'boolean' }).notNull().default(false), -}) + isSuspendedInRegion: integer('is_suspended_in_region', { mode: 'boolean' }).notNull().default(false), + isOffer: integer('is_offer', { mode: 'boolean' }).notNull().default(false), +}, (t) => ({ + unq_sku_region: uniqueIndex('product_market_stats_sku_region').on(t.skuId, t.regionId), +})) export const skuFeatures = sqliteTable('sku_features', { id: integer().primaryKey({ autoIncrement: true }), @@ -661,7 +668,7 @@ export const productInfoRelations = relations(productInfo, ({ one, many }) => ({ export const productSkusRelations = relations(productSkus, ({ one, many }) => ({ product: one(productInfo, { fields: [productSkus.productId], references: [productInfo.id] }), features: many(skuFeatures), - marketStats: one(productMarketStats), + marketStats: many(productMarketStats), specialDeals: many(specialDeals), orderItems: many(orderItems), cartItems: many(cartItems), @@ -671,6 +678,7 @@ export const productSkusRelations = relations(productSkus, ({ one, many }) => ({ export const productMarketStatsRelations = relations(productMarketStats, ({ one }) => ({ sku: one(productSkus, { fields: [productMarketStats.skuId], references: [productSkus.id] }), + region: one(regions, { fields: [productMarketStats.regionId], references: [regions.id] }), })) export const skuFeaturesRelations = relations(skuFeatures, ({ one }) => ({ @@ -780,8 +788,7 @@ export const notifCredsRelations = relations(notifCreds, ({ one }) => ({ user: one(users, { fields: [notifCreds.userId], references: [users.id] }), })) -export const storeInfoRelations = relations(storeInfo, ({ one, many }) => ({ - owner: one(staffUsers, { fields: [storeInfo.owner], references: [staffUsers.id] }), +export const storeInfoRelations = relations(storeInfo, ({ many }) => ({ products: many(productInfo), })) diff --git a/packages/db_helper_sqlite/src/lib/market-stats.ts b/packages/db_helper_sqlite/src/lib/market-stats.ts new file mode 100644 index 0000000..f98b818 --- /dev/null +++ b/packages/db_helper_sqlite/src/lib/market-stats.ts @@ -0,0 +1,31 @@ +import type { InferSelectModel } from 'drizzle-orm' +import type { productMarketStats } from '../db/schema' + +/** + * A market-stats row as stored. Since Phase 1, `product_market_stats` is keyed by + * (sku_id, region_id) — a SKU carries one row per region and consumers must pick + * the row for the region they are serving. + */ +export type MarketStatsRow = InferSelectModel + +/** Pick the market-stats row for a region from a SKU's (now many) rows. */ +export function marketStatsForRegion( + stats: MarketStatsRow[] | undefined | null, + regionId: number | null | undefined, +): MarketStatsRow | undefined { + if (!stats || regionId == null) return undefined + return stats.find((s) => s.regionId === regionId) +} + +/** + * True when a SKU is unavailable in a region — globally (`product_skus.is_suspended`, + * the superadmin kill-switch) or only for that region + * (`product_market_stats.is_suspended_in_region`). A missing market-stats row is NOT + * treated as suspended, matching the pre-Phase-1 behaviour. + */ +export function isSkuSuspended( + skuIsSuspended: boolean | null | undefined, + stats: MarketStatsRow | undefined | null, +): boolean { + return !!skuIsSuspended || !!stats?.isSuspendedInRegion +} diff --git a/packages/db_helper_sqlite/src/stores/store-helpers.ts b/packages/db_helper_sqlite/src/stores/store-helpers.ts index d99b732..05e7274 100644 --- a/packages/db_helper_sqlite/src/stores/store-helpers.ts +++ b/packages/db_helper_sqlite/src/stores/store-helpers.ts @@ -15,8 +15,9 @@ 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 { marketStatsForRegion, isSkuSuspended } from '../lib/market-stats' import type { ProductTagData, TagProductMapping, UserNegativityData, StoreSummary, BannerData, SpecialDealCore, ProductDetailCore, ProductPriceFlags, ProductTagCore, UserProductDeliverySlot, UserProductComboItem } from '@packages/shared' // Re-exported so the package index (`export { ... } from './src/stores/store-helpers'`) @@ -74,7 +75,6 @@ export async function getAllBannersForCache(regionId: number): Promise !sku.marketStats?.isSuspended && !sku.isDeleted && sku.product?.regionId === regionId) - .map((sku) => { + .filter((sku) => !sku.isDeleted && (sku.product?.regionId === regionId || sku.product?.regionId == null)) + .map((sku) => ({ sku, marketStats: marketStatsForRegion(sku.marketStats, regionId) })) + .filter(({ sku, marketStats }) => !isSkuSuspended(sku.isSuspended, marketStats)) + .map(({ sku, marketStats }) => { const features = sku.features || [] - const marketStats = sku.marketStats return { id: sku.id, productId: sku.productId, @@ -147,7 +148,6 @@ export async function getAllProductsForCache(regionId: number): Promise !stat.isSuspended && !stat.sku?.isDeleted && stat.sku?.product?.regionId === regionId) + .filter((stat) => stat.regionId === regionId && !stat.sku?.isSuspended && !stat.isSuspendedInRegion && !stat.sku?.isDeleted && (stat.sku?.product?.regionId === regionId || stat.sku?.product?.regionId == null)) .map((stat) => ({ id: stat.skuId, price: Number(stat.ourPrice ?? 0), @@ -174,13 +174,14 @@ export async function getAvailabilityForCache(regionId: number): Promise { return db.query.storeInfo.findMany({ - where: eq(storeInfo.regionId, regionId), + where: or(eq(storeInfo.regionId, regionId), eq(storeInfo.isGlobal, true)), columns: { id: true, name: true, description: true }, }) } @@ -255,8 +256,9 @@ export async function getAllProductCombosForCache(regionId: number): Promise r.id) ) @@ -265,6 +267,7 @@ export async function getAllProductCombosForCache(regionId: number): Promise ci.comboSku?.product?.regionId === regionId && ci.sku?.product?.regionId === regionId) .map((ci) => { const features = ci.sku?.features || [] + const marketStats = marketStatsForRegion(ci.sku?.marketStats, regionId) return { comboSkuId: ci.comboSkuId, skuId: ci.skuId, @@ -272,8 +275,8 @@ export async function getAllProductCombosForCache(regionId: number): Promise skuIdSet.has(item.id) && !item.marketStats?.isSuspended && !item.isDeleted && item.product?.regionId === regionId) + skusData = skusData.filter((item: any) => + skuIdSet.has(item.id) && + !item.isDeleted && + item.product?.regionId === regionId && + !isSkuSuspended(item.isSuspended, marketStatsForRegion(item.marketStats, regionId)) + ) } const skuMap = new Map(skusData.map((s: any) => [s.id, s])) @@ -406,7 +414,7 @@ export async function getAllSlotsWithProductsForCache(regionId: number): Promise .filter((p): p is NonNullable => p != null) .map((sku: any) => { const features = sku.features || [] - const marketStats = sku.marketStats + const marketStats = marketStatsForRegion(sku.marketStats, regionId) return { id: sku.id, productId: sku.productId, diff --git a/packages/db_helper_sqlite/src/superadmin-apis/global-products.ts b/packages/db_helper_sqlite/src/superadmin-apis/global-products.ts new file mode 100644 index 0000000..58d4869 --- /dev/null +++ b/packages/db_helper_sqlite/src/superadmin-apis/global-products.ts @@ -0,0 +1,51 @@ +import { db } from '../db/db_index' +import { productInfo } from '../db/schema' +import { and, eq, isNull } from 'drizzle-orm' +import type { CreateProductInput } from '@packages/shared' +import { createProduct, deleteGlobalProduct, updateProduct } from '../admin-apis/product' + +const globalProductWith = { + store: true, + skus: { + with: { + features: true, + marketStats: true, + comboItems: true, + }, + }, +} as const + +/** Global products (structural data + the per-region market rows). */ +export async function listGlobalProducts() { + return db.query.productInfo.findMany({ + where: isNull(productInfo.regionId), + orderBy: productInfo.name, + with: globalProductWith, + }) +} + +export async function getGlobalProduct(id: number) { + const product = await db.query.productInfo.findFirst({ + where: and(eq(productInfo.id, id), isNull(productInfo.regionId)), + with: globalProductWith, + }) + return product ?? null +} + +/** Create a global product — seeds a market-stats row per region. */ +export const createGlobalProduct = (input: CreateProductInput) => createProduct(input, null) + +/** + * Superadmin structural edit of a global product. Structural fields are replaced; + * each region's market data is left untouched (new SKUs are seeded everywhere). + */ +export async function updateGlobalProduct(id: number, input: any) { + const product = await db.query.productInfo.findFirst({ + where: and(eq(productInfo.id, id), isNull(productInfo.regionId)), + columns: { id: true }, + }) + if (!product) return null + return updateProduct(null, id, input) +} + +export const deleteGlobalProductById = (id: number) => deleteGlobalProduct(id) diff --git a/packages/db_helper_sqlite/src/superadmin-apis/global-stores.ts b/packages/db_helper_sqlite/src/superadmin-apis/global-stores.ts new file mode 100644 index 0000000..a9d8bf1 --- /dev/null +++ b/packages/db_helper_sqlite/src/superadmin-apis/global-stores.ts @@ -0,0 +1,80 @@ +import { db } from '../db/db_index' +import { storeInfo, productInfo } from '../db/schema' +import { and, eq, sql } from 'drizzle-orm' +import type { Store, CreateStoreInput, UpdateStoreInput } from '@packages/shared' + +const toStore = (s: any): Store => ({ + id: s.id, + name: s.name, + description: s.description, + imageUrl: s.imageUrl, + isGlobal: s.isGlobal, + createdAt: s.createdAt, +}) + +/** True when the store exists and is global. */ +export async function isGlobalStore(storeId: number): Promise { + const s = await db.query.storeInfo.findFirst({ + where: eq(storeInfo.id, storeId), + columns: { isGlobal: true }, + }) + return !!s?.isGlobal +} + +export async function listGlobalStores(): Promise { + const rows = await db.query.storeInfo.findMany({ + where: eq(storeInfo.isGlobal, true), + orderBy: storeInfo.name, + }) + return rows.map(toStore) +} + +export async function getGlobalStore(id: number): Promise { + const s = await db.query.storeInfo.findFirst({ + where: and(eq(storeInfo.id, id), eq(storeInfo.isGlobal, true)), + }) + return s ? toStore(s) : null +} + +export async function createGlobalStore(input: CreateStoreInput): Promise { + const [s] = await db + .insert(storeInfo) + .values({ + regionId: null, + isGlobal: true, + name: input.name, + description: input.description ?? null, + imageUrl: input.imageUrl ?? null, + }) + .returning() + return toStore(s) +} + +export async function updateGlobalStore(id: number, input: UpdateStoreInput): Promise { + const [s] = await db + .update(storeInfo) + .set({ ...input }) + .where(and(eq(storeInfo.id, id), eq(storeInfo.isGlobal, true))) + .returning() + if (!s) throw new Error('Global store not found') + return toStore(s) +} + +export async function deleteGlobalStore(id: number): Promise<{ message: string }> { + const existing = await db.query.storeInfo.findFirst({ + where: and(eq(storeInfo.id, id), eq(storeInfo.isGlobal, true)), + columns: { id: true }, + }) + if (!existing) throw new Error('Global store not found') + + const [{ count }] = await db + .select({ count: sql`count(*)` }) + .from(productInfo) + .where(eq(productInfo.storeId, id)) + if (Number(count) > 0) { + throw new Error('Cannot delete a global store that still has products. Remove them first.') + } + + await db.delete(storeInfo).where(eq(storeInfo.id, id)) + return { message: 'Global store deleted successfully' } +} diff --git a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts b/packages/db_helper_sqlite/src/superadmin-apis/regions.ts index 4a90967..e156090 100644 --- a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts +++ b/packages/db_helper_sqlite/src/superadmin-apis/regions.ts @@ -1,6 +1,6 @@ import { db } from '../db/db_index' -import { regions, regionBounds, regionConsts, regionBoundConsts } from '../db/schema' -import { eq, sql, and } from 'drizzle-orm' +import { regions, regionBounds, regionConsts, regionBoundConsts, productMarketStats } from '../db/schema' +import { eq, sql, and, ne, asc } from 'drizzle-orm' import { BOUND_CONST_KEYS, CONST_DEFAULTS, REGION_CONST_KEYS } from '../lib/const-keys' import type { RegionSummary, @@ -168,10 +168,31 @@ export async function createRegionWithBounds( await tx.insert(regionBoundConsts).values(boundRows).onConflictDoNothing() } + // Seed this region with every global SKU's market-stats row, copied from + // the least-id region (the pre-existing default). + const [srcRegion] = await tx + .select({ id: regions.id }) + .from(regions) + .where(ne(regions.id, region.id)) + .orderBy(asc(regions.id)) + .limit(1) + if (srcRegion) { + await tx.run(sql` + INSERT INTO product_market_stats + (sku_id, region_id, market_price, our_price, is_flash_available, flash_price, is_out_of_stock, is_suspended_in_region, is_offer) + SELECT ms.sku_id, ${region.id}, ms.market_price, ms.our_price, ms.is_flash_available, ms.flash_price, ms.is_out_of_stock, ms.is_suspended_in_region, ms.is_offer + FROM product_market_stats ms + JOIN product_skus ps ON ps.id = ms.sku_id + JOIN product_info pi ON pi.id = ps.product_id + WHERE ms.region_id = ${srcRegion.id} AND pi.region_id IS NULL + `) + } + return { region: toSummary(region), bounds: inserted.map(toBoundDto) } } catch (error) { // Compensate: D1 may leave the region insert committed when a later // statement fails, so remove everything created for this region. + await tx.delete(productMarketStats).where(eq(productMarketStats.regionId, region.id)) await tx.delete(regionBoundConsts).where(eq(regionBoundConsts.regionId, region.id)) await tx.delete(regionConsts).where(eq(regionConsts.regionId, region.id)) await tx.delete(regionBounds).where(eq(regionBounds.regionId, region.id)) diff --git a/packages/db_helper_sqlite/src/user-apis/order.ts b/packages/db_helper_sqlite/src/user-apis/order.ts index 9ee7e65..3860792 100644 --- a/packages/db_helper_sqlite/src/user-apis/order.ts +++ b/packages/db_helper_sqlite/src/user-apis/order.ts @@ -25,6 +25,7 @@ import type { import { coerceDate } from '../lib/date' import { runBatched } from '../lib/run-batched' import { composeSkuName, composeUnitNotation } from '../lib/sku-features' +import { marketStatsForRegion } from '../lib/market-stats' export interface OrderWithRelations { id: number @@ -195,7 +196,7 @@ export async function getAddressByIdAndUser( }) } -export async function getProductById(skuId: number) { +export async function getProductById(skuId: number, regionId?: number | null) { const sku = await db.query.productSkus.findFirst({ where: eq(productSkus.id, skuId), with: { @@ -208,10 +209,14 @@ export async function getProductById(skuId: number) { return null } - const marketStats = sku.marketStats + // A global SKU has no product region — the caller's region decides which + // market-stats row (and therefore price) applies. + const region = regionId ?? sku.product?.regionId ?? null + const marketStats = marketStatsForRegion(sku.marketStats, region) return { ...sku, + marketStats, price: marketStats?.ourPrice ? String(marketStats.ourPrice) : '0', marketPrice: marketStats?.marketPrice ? String(marketStats.marketPrice) : null, flashPrice: marketStats?.flashPrice ? String(marketStats.flashPrice) : null, diff --git a/packages/db_helper_sqlite/src/user-apis/product.ts b/packages/db_helper_sqlite/src/user-apis/product.ts index e71d6a0..c80345b 100644 --- a/packages/db_helper_sqlite/src/user-apis/product.ts +++ b/packages/db_helper_sqlite/src/user-apis/product.ts @@ -1,15 +1,16 @@ import { db } from '../db/db_index' import { deliverySlotInfo, productInfo, productCombos, productSkus, productMarketStats, productReviews, productTags, specialDeals, storeInfo, users } from '../db/schema' -import { and, desc, eq, gt, inArray, sql } from 'drizzle-orm' +import { and, desc, eq, gt, inArray, or, sql } from 'drizzle-orm' import type { UserProductDetailData, UserProductReview } from '@packages/shared' import { composeSkuName, composeUnitNotation } from '../lib/sku-features' +import { marketStatsForRegion, isSkuSuspended } from '../lib/market-stats' const getStringArray = (value: unknown): string[] | null => { if (!Array.isArray(value)) return null return value.map((item) => String(item)) } -export async function getProductDetailById(skuId: number): Promise { +export async function getProductDetailById(skuId: number, regionIdParam?: number | null): Promise { const sku = await db.query.productSkus.findFirst({ where: eq(productSkus.id, skuId), with: { @@ -22,13 +23,15 @@ export async function getProductDetailById(skuId: number): Promise { const ciFeatures = ci.sku?.features || [] + const ciMarketStats = marketStatsForRegion(ci.sku?.marketStats, regionId) return { skuId: ci.skuId, skuName: ci.sku?.name ?? null, unitNotation: composeUnitNotation(ciFeatures), productName: composeSkuName(ci.sku?.product?.name ?? 'Unknown', ciFeatures, ci.sku?.name), images: getStringArray(ci.sku?.images), - price: ci.sku?.marketStats?.ourPrice ? String(ci.sku.marketStats.ourPrice) : '0', - isOffer: ci.sku?.isOffer ?? false, + price: ciMarketStats?.ourPrice ? String(ciMarketStats.ourPrice) : '0', + isOffer: ciMarketStats?.isOffer ?? false, } }) @@ -156,7 +160,7 @@ export async function getProductById(skuId: number) { return null } - const marketStats = sku.marketStats + const marketStats = marketStatsForRegion(sku.marketStats, sku.product?.regionId) return { ...sku, @@ -239,7 +243,7 @@ export async function getAllProductsWithUnits(tagId?: number): Promise { - if (sku.marketStats?.isSuspended) return false + if (isSkuSuspended(sku.isSuspended, marketStatsForRegion(sku.marketStats, sku.product?.regionId))) return false if (sku.isDeleted) return false if (!tagId) return true // product_tags.product_id now holds SKU ids — compare against sku.id @@ -247,7 +251,7 @@ export async function getAllProductsWithUnits(tagId?: number): Promise { const features = sku.features || [] - const marketStats = sku.marketStats + const marketStats = marketStatsForRegion(sku.marketStats, sku.product?.regionId) return { id: sku.product?.id ?? 0, name: composeSkuName(sku.product?.name ?? 'Unknown', features, sku.name), @@ -275,8 +279,9 @@ export async function getSuspendedSkuIds(regionId: number): Promise { .innerJoin(productSkus, eq(productMarketStats.skuId, productSkus.id)) .innerJoin(productInfo, eq(productSkus.productId, productInfo.id)) .where(and( - eq(productMarketStats.isSuspended, true), - eq(productInfo.regionId, regionId) + eq(productMarketStats.regionId, regionId), + eq(productInfo.regionId, regionId), + or(eq(productSkus.isSuspended, true), eq(productMarketStats.isSuspendedInRegion, true)) )) return suspendedSkus.map(sp => sp.id) @@ -356,9 +361,10 @@ export async function getAllSkusSummary(regionId: number | null = null): Promise }) return skus - .filter((sku) => !sku.marketStats?.isSuspended && !sku.isDeleted) - .filter((sku) => regionId == null || sku.product?.regionId === regionId) - .map((sku) => { + .filter((sku) => regionId == null || sku.product?.regionId === regionId || sku.product?.regionId == null) + .map((sku) => ({ sku, marketStats: marketStatsForRegion(sku.marketStats, sku.product?.regionId) })) + .filter(({ sku, marketStats }) => !isSkuSuspended(sku.isSuspended, marketStats) && !sku.isDeleted) + .map(({ sku, marketStats }) => { const featureValues = (sku.features || []).map((f) => f.featureValue) const label = [sku.product?.name ?? 'Unknown', ...featureValues].join(' ') return { @@ -368,7 +374,7 @@ export async function getAllSkusSummary(regionId: number | null = null): Promise label, images: sku.images, storeId: sku.product?.storeId ?? null, - price: sku.marketStats?.ourPrice ? String(sku.marketStats.ourPrice) : '0', + price: marketStats?.ourPrice ? String(marketStats.ourPrice) : '0', } }) } diff --git a/packages/db_helper_sqlite/src/user-apis/slots.ts b/packages/db_helper_sqlite/src/user-apis/slots.ts index a8b978e..3eaf7fe 100644 --- a/packages/db_helper_sqlite/src/user-apis/slots.ts +++ b/packages/db_helper_sqlite/src/user-apis/slots.ts @@ -36,7 +36,10 @@ export async function getDeliverySlotById(slotId: number): Promise { const stats = await db.query.productMarketStats.findMany({ - where: eq(productMarketStats.isSuspended, false), + where: and( + eq(productMarketStats.regionId, regionId), + eq(productMarketStats.isSuspendedInRegion, false), + ), with: { sku: { with: { @@ -53,7 +56,8 @@ export async function getProductAvailability(regionId: number): Promise (stat as typeof stat & { sku?: { product?: { regionId: number | null } | null } | null }).sku?.product?.regionId === regionId) + .filter((stat) => (stat as typeof stat & { sku?: { isSuspended?: boolean; product?: { regionId: number | null } | null } | null }).sku?.product?.regionId === regionId) + .filter((stat) => !(stat as typeof stat & { sku?: { isSuspended?: boolean } | null }).sku?.isSuspended) .map((stat) => ({ id: stat.skuId, isOutOfStock: stat.isOutOfStock, diff --git a/packages/db_helper_sqlite/src/user-apis/stores.ts b/packages/db_helper_sqlite/src/user-apis/stores.ts index fcec223..91ea091 100644 --- a/packages/db_helper_sqlite/src/user-apis/stores.ts +++ b/packages/db_helper_sqlite/src/user-apis/stores.ts @@ -1,8 +1,9 @@ import { db } from '../db/db_index' import { productInfo, productSkus, storeInfo } from '../db/schema' -import { and, asc, eq, inArray } from 'drizzle-orm' +import { and, asc, eq, inArray, isNull, or } from 'drizzle-orm' import type { UserStoreDetailData, UserStoreProductData, UserStoreSummaryData, StoreSummary } from '@packages/shared' import { composeSkuName, composeUnitNotation } from '../lib/sku-features' +import { marketStatsForRegion, isSkuSuspended } from '../lib/market-stats' const getStringArray = (value: unknown): string[] | null => { if (!Array.isArray(value)) return null @@ -15,13 +16,17 @@ export async function getStoreSummaries(regionId: number): Promise !sku.marketStats?.isSuspended && !sku.isDeleted && sku.product?.regionId === regionId) + const activeSkus = skus.filter((sku) => + !sku.isDeleted && + sku.product?.regionId === regionId && + !isSkuSuspended(sku.isSuspended, marketStatsForRegion(sku.marketStats, regionId)) + ) const skusByStore = new Map() for (const sku of activeSkus) { @@ -52,7 +57,7 @@ export async function getStoreSummaries(regionId: number): 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.isGlobal, true))), columns: { id: true, name: true, @@ -68,7 +73,7 @@ export async function getStoreDetail(regionId: number, storeId: number): Promise const storeProductIds = await db .select({ id: productInfo.id }) .from(productInfo) - .where(and(eq(productInfo.storeId, storeId), eq(productInfo.regionId, regionId))) + .where(and(eq(productInfo.storeId, storeId), or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId)))) const productIdArr = storeProductIds.map((p) => p.id) @@ -84,10 +89,10 @@ export async function getStoreDetail(regionId: number, storeId: number): Promise : [] const products: UserStoreProductData[] = skus - .filter((sku) => !sku.marketStats?.isSuspended && !sku.isDeleted) + .filter((sku) => !sku.isDeleted && !isSkuSuspended(sku.isSuspended, marketStatsForRegion(sku.marketStats, regionId))) .map((sku) => { const features = sku.features || [] - const marketStats = sku.marketStats + const marketStats = marketStatsForRegion(sku.marketStats, regionId) return { id: sku.id, name: composeSkuName(sku.product?.name ?? 'Unknown', features, sku.name), diff --git a/packages/shared/types/admin.ts b/packages/shared/types/admin.ts index 89af69b..d1d681c 100644 --- a/packages/shared/types/admin.ts +++ b/packages/shared/types/admin.ts @@ -30,7 +30,7 @@ export interface Store { name: string; description: string | null; imageUrl: string | null; - owner: number; + isGlobal?: boolean; createdAt: Date; // updatedAt: Date; } @@ -336,6 +336,8 @@ export interface AdminProduct { incrementStep: number; createdAt: Date; productType: 'item' | 'combo'; + /** Global products belong to a global store: available in every region. */ + isGlobal: boolean; } export interface AdminProductWithRelations extends AdminProduct { diff --git a/packages/shared/types/inputs.types.ts b/packages/shared/types/inputs.types.ts index 71bec98..5704f56 100644 --- a/packages/shared/types/inputs.types.ts +++ b/packages/shared/types/inputs.types.ts @@ -17,14 +17,12 @@ export interface CreateStoreInput { name: string description?: string imageUrl?: string - owner: number } export interface UpdateStoreInput { name?: string description?: string imageUrl?: string - owner?: number } // --- Auth wire types (identical backend auth API ↔ user-ui) --- diff --git a/packages/shared/types/user.ts b/packages/shared/types/user.ts index caf1683..dd4dfdd 100644 --- a/packages/shared/types/user.ts +++ b/packages/shared/types/user.ts @@ -246,7 +246,7 @@ export interface UserProductComboItem { // Product-detail core — shared by the user API detail payload, the backend // cache row (product-store Product) and the sqlite cache row (ProductBasicData). -// isOffer/isComboOnly are optional here: variants that carry them re-tighten. +// isComboOnly is optional here: variants that carry it re-tighten. export interface ProductDetailCore { id: number; productId: number; @@ -263,7 +263,6 @@ export interface ProductDetailCore { isFlashAvailable: boolean; flashPrice: string | null; productType: string; - isOffer?: boolean; isComboOnly?: boolean; } @@ -287,6 +286,7 @@ export interface ProductPriceFlags { isFlashAvailable: boolean; isOutOfStock: boolean; isSuspended: boolean; + isOffer: boolean; } // Offers-page product card core — sqlite offers/offers-cache row and the