This commit is contained in:
shafi54 2026-10-10 19:56:02 +05:30
parent a2f1ddb1ad
commit 1d8aca9b84
36 changed files with 2609 additions and 226 deletions

View file

@ -6,7 +6,7 @@ import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { MyText, tw, MyButton, useManualRefresh, SearchBar, useMarkDataFetchers, MyFlatList } from 'common-ui';
import { trpc } from '@/src/trpc-client';
import { SuccessToast, ErrorToast } from '@/services/toaster';
import VariantStockDialog from '@/src/components/VariantStockDialog';
import type { AdminSku } from '@packages/shared';
type FilterType = 'all' | 'in-stock' | 'out-of-stock' | 'global';
@ -17,6 +17,24 @@ function getDefaultSku(product: { skus?: SerializedAdminSku[] }): SerializedAdmi
return product.skus?.[0] ?? null
}
type StockState = 'in' | 'partial' | 'out'
/** Stock is per variant, so the row, filters and counters must aggregate instead of reading skus[0]. */
function getStockState(product: { skus?: SerializedAdminSku[] }): StockState {
const skus = product.skus ?? []
if (skus.length === 0) return 'in'
const outCount = skus.filter((sku) => sku.isOutOfStock).length
if (outCount === 0) return 'in'
if (outCount === skus.length) return 'out'
return 'partial'
}
const STOCK_STYLES: Record<StockState, { dot: string; text: string; label: string; button: string }> = {
in: { dot: 'bg-green-500', text: 'text-green-500', label: 'In', button: 'bg-green-600' },
partial: { dot: 'bg-amber-500', text: 'text-amber-600', label: 'Partial', button: 'bg-amber-500' },
out: { dot: 'bg-red-500', text: 'text-red-500', label: 'Out', button: 'bg-red-500' },
}
function FilterButton({
filter,
label,
@ -45,16 +63,18 @@ function FilterButton({
type ProductRowProps = {
product: any
isToggling: boolean
onView: (productId: number) => void
onEdit: (productId: number) => void
onToggle: (product: { id: number }) => void
onManageStock: (product: any) => void
}
const ProductRow = React.memo(function ProductRow({ product, isToggling, onView, onEdit, onToggle }: ProductRowProps) {
const ProductRow = React.memo(function ProductRow({ product, onView, onEdit, onManageStock }: ProductRowProps) {
const defaultSku = getDefaultSku(product)
const skuImages = defaultSku?.images ?? null
const isOut = defaultSku?.isOutOfStock ?? false
const stockState = getStockState(product)
const stockStyle = STOCK_STYLES[stockState]
const skuCount = product.skus?.length ?? 0
const outCount = (product.skus ?? []).filter((sku: SerializedAdminSku) => sku.isOutOfStock).length
return (
<View style={tw`bg-white rounded-2xl shadow-lg mb-4 overflow-hidden`}>
@ -85,9 +105,9 @@ const ProductRow = React.memo(function ProductRow({ product, isToggling, onView,
</View>
)}
<View style={tw`flex-row items-center`}>
<View style={tw`w-3 h-3 rounded-full mr-1 ${isOut ? 'bg-red-500' : 'bg-green-500'}`} />
<MyText style={tw`text-sm ${isOut ? 'text-red-500' : 'text-green-500'} font-semibold`}>
{isOut ? 'Out' : 'In'}
<View style={tw`w-3 h-3 rounded-full mr-1 ${stockStyle.dot}`} />
<MyText style={tw`text-sm ${stockStyle.text} font-semibold`}>
{stockStyle.label}
</MyText>
</View>
</View>
@ -100,7 +120,7 @@ const ProductRow = React.memo(function ProductRow({ product, isToggling, onView,
<View style={tw`flex-row justify-between items-center mb-3`}>
<MyText style={tw`text-sm text-gray-500 font-medium`}>
{product.skus?.length ?? 0} Variants
{skuCount} Variants{outCount > 0 ? ` · ${outCount} out` : ''}
</MyText>
</View>
@ -123,14 +143,11 @@ const ProductRow = React.memo(function ProductRow({ product, isToggling, onView,
</TouchableOpacity>
<TouchableOpacity
onPress={() => onToggle(product)}
disabled={isToggling}
style={tw`flex-1 ${isOut ? 'bg-green-500' : 'bg-orange-500'} p-3 rounded-lg flex-row items-center justify-center ${isToggling ? 'opacity-50' : ''}`}
onPress={() => onManageStock(product)}
style={tw`flex-1 ${stockStyle.button} p-3 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name={isOut ? 'check-circle' : 'block'} size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>
{isOut ? 'Stock' : 'Out'}
</MyText>
<MaterialIcons name="tune" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>Stock</MyText>
</TouchableOpacity>
</View>
</View>
@ -145,15 +162,8 @@ export default function Products() {
const { data: productsData, isLoading, error, refetch } = trpc.admin.product.getProducts.useQuery();
const toggleOutOfStock = trpc.admin.product.toggleOutOfStock.useMutation({
onSuccess: async (res) => {
await refetch();
SuccessToast(res.message);
},
onError: (err) => {
ErrorToast(err.message || 'Failed to update stock status');
},
});
// Stock is chosen per variant in a dialog now (the single button used to flip everything).
const [stockDialogProduct, setStockDialogProduct] = useState<any | null>(null);
useManualRefresh(refetch);
@ -170,14 +180,12 @@ export default function Products() {
const filteredProducts = useMemo(() => {
const term = searchTerm.toLowerCase();
return products.filter(product => {
const defaultSku = getDefaultSku(product)
const matchesSearch = product.name.toLowerCase().includes(term) ||
(product.shortDescription?.toLowerCase().includes(term));
const matchesFilter = activeFilter === 'all' ||
(activeFilter === 'in-stock' && !defaultSku?.isOutOfStock) ||
(activeFilter === 'out-of-stock' && defaultSku?.isOutOfStock) ||
(activeFilter === 'in-stock' && getStockState(product) === 'in') ||
(activeFilter === 'out-of-stock' && getStockState(product) !== 'in') ||
(activeFilter === 'global' && product.isGlobal);
return matchesSearch && matchesFilter;
@ -185,11 +193,11 @@ export default function Products() {
}, [products, searchTerm, activeFilter]);
const inStockCount = useMemo(
() => products.filter(p => { const sku = getDefaultSku(p); return sku && !sku.isOutOfStock }).length,
() => products.filter(p => getStockState(p) === 'in').length,
[products]
);
const outOfStockCount = useMemo(
() => products.filter(p => getDefaultSku(p)?.isOutOfStock).length,
() => products.filter(p => getStockState(p) !== 'in').length,
[products]
);
const globalCount = useMemo(() => products.filter(p => p.isGlobal).length, [products]);
@ -202,9 +210,9 @@ export default function Products() {
router.push(`/(drawer)/dashboard/products/detail/${productId}` as any);
}, [router]);
const handleToggleStock = useCallback((product: { id: number }) => {
toggleOutOfStock.mutate({ id: product.id });
}, [toggleOutOfStock]);
const handleManageStock = useCallback((product: any) => {
setStockDialogProduct(product);
}, []);
const handleSelectFilter = useCallback((filter: FilterType) => setActiveFilter(filter), []);
@ -213,12 +221,11 @@ export default function Products() {
const renderItem = useCallback(({ item: product }: { item: any }) => (
<ProductRow
product={product}
isToggling={toggleOutOfStock.isPending && toggleOutOfStock.variables?.id === product.id}
onView={handleViewDetails}
onEdit={handleEdit}
onToggle={handleToggleStock}
onManageStock={handleManageStock}
/>
), [toggleOutOfStock.isPending, toggleOutOfStock.variables?.id, handleViewDetails, handleEdit, handleToggleStock]);
), [handleViewDetails, handleEdit, handleManageStock]);
const listHeader = useMemo(() => (
<>
@ -309,6 +316,13 @@ export default function Products() {
windowSize={5}
removeClippedSubviews
/>
<VariantStockDialog
open={stockDialogProduct != null}
product={stockDialogProduct}
onClose={() => setStockDialogProduct(null)}
onApplied={refetch}
/>
</View>
);
}

View file

@ -0,0 +1,159 @@
import React, { useEffect, useMemo, useState } from 'react'
import { View } from 'react-native'
import { BottomDialog, Checkbox, MyButton, MyText, tw } from 'common-ui'
import { trpc } from '@/src/trpc-client'
import { ErrorToast, SuccessToast } from '@/services/toaster'
type DialogSku = {
id: number
name?: string | null
features?: Array<{ featureName?: string | null; featureValue?: string | null }>
isOutOfStock?: boolean
}
type DialogProduct = {
id: number
name: string
skus?: DialogSku[]
}
/** "500 g" / "500 g, boneless" / the SKU name / a fallback — whatever identifies the variant. */
function variantLabel(sku: DialogSku): string {
const featureValues = (sku.features ?? [])
.map((feature) => feature.featureValue)
.filter((value): value is string => !!value)
if (featureValues.length > 0) return featureValues.join(', ')
if (sku.name) return sku.name
return `Variant #${sku.id}`
}
interface VariantStockDialogProps {
open: boolean
product: DialogProduct | null
onClose: () => void
/** Called after a successful change so the caller can refetch the product list. */
onApplied?: () => void
}
/**
* Per-variant stock control.
*
* The list's single button used to flip every variant at once, which cannot express
* "one variant is out" (PD-06) and silently collapsed a partial state. This dialog
* lets the admin pick which variants to change and in which direction.
*/
const VariantStockDialog: React.FC<VariantStockDialogProps> = ({ open, product, onClose, onApplied }) => {
const skus = useMemo(() => product?.skus ?? [], [product])
const [selected, setSelected] = useState<number[]>([])
// Every time the dialog opens (or targets another product) start from "all variants".
useEffect(() => {
if (open) setSelected(skus.map((sku) => sku.id))
}, [open, product?.id, skus.length])
const toggleSku = (skuId: number) => {
setSelected((current) =>
current.includes(skuId) ? current.filter((id) => id !== skuId) : [...current, skuId]
)
}
const updateStock = trpc.admin.product.toggleOutOfStock.useMutation({
onSuccess: (res) => {
SuccessToast(res.message)
onApplied?.()
onClose()
},
onError: (err) => {
ErrorToast(err.message || 'Failed to update stock status')
},
})
const apply = (isOutOfStock: boolean) => {
if (!product || selected.length === 0) return
updateStock.mutate({ id: product.id, skuIds: selected, isOutOfStock })
}
const outCount = skus.filter((sku) => sku.isOutOfStock).length
const isPartial = outCount > 0 && outCount < skus.length
const allSelected = skus.length > 0 && selected.length === skus.length
return (
<BottomDialog open={open} onClose={onClose}>
<View style={tw`p-5`}>
<MyText style={tw`text-lg font-bold text-gray-900`}>Stock</MyText>
<MyText style={tw`text-gray-500 text-sm mt-1 mb-4`} numberOfLines={2}>
{product?.name ?? ''}
</MyText>
{isPartial && (
<View style={tw`bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 mb-3`}>
<MyText style={tw`text-amber-700 text-xs`}>
{outCount} of {skus.length} variants are out of stock
</MyText>
</View>
)}
<View style={tw`flex-row justify-between items-center mb-2`}>
<MyText style={tw`text-gray-600 text-xs font-semibold uppercase`}>
Variants ({selected.length}/{skus.length})
</MyText>
<MyText
onPress={() => setSelected(allSelected ? [] : skus.map((sku) => sku.id))}
style={tw`text-blue-600 text-xs font-bold`}
>
{allSelected ? 'Clear all' : 'Select all'}
</MyText>
</View>
{skus.map((sku) => (
<View key={sku.id} style={tw`flex-row items-center py-2 border-b border-gray-100`}>
<Checkbox
testID={`variant-stock-${sku.id}`}
checked={selected.includes(sku.id)}
onPress={() => toggleSku(sku.id)}
style={tw`mr-3`}
/>
<MyText style={tw`flex-1 text-gray-800`} numberOfLines={1}>
{variantLabel(sku)}
</MyText>
<View style={tw`flex-row items-center`}>
<View style={tw`w-2 h-2 rounded-full mr-1 ${sku.isOutOfStock ? 'bg-red-500' : 'bg-green-500'}`} />
<MyText style={tw`text-xs ${sku.isOutOfStock ? 'text-red-500' : 'text-green-600'}`}>
{sku.isOutOfStock ? 'Out' : 'In'}
</MyText>
</View>
</View>
))}
<View style={tw`flex-row gap-2 mt-5`}>
<MyButton
onPress={() => apply(true)}
loading={updateStock.isPending}
disabled={selected.length === 0 || updateStock.isPending}
variant="red"
textContent="Mark out of stock"
style={tw`flex-1`}
/>
<MyButton
onPress={() => apply(false)}
loading={updateStock.isPending}
disabled={selected.length === 0 || updateStock.isPending}
variant="green"
textContent="Mark in stock"
style={tw`flex-1`}
/>
</View>
<MyButton
onPress={onClose}
disabled={updateStock.isPending}
fillColor="gray1"
textContent="Cancel"
style={tw`mt-2`}
/>
</View>
</BottomDialog>
)
}
export default VariantStockDialog

View file

@ -1,4 +1,5 @@
import type { ConstValueType } from '@packages/shared'
import { ApiError } from '@/src/lib/api-error'
export const CONST_KEYS = {
freeDeliveryThreshold: 'freeDeliveryThreshold',
@ -140,3 +141,47 @@ for (const k of GLOBAL_CONST_KEYS) CONST_SCOPE[k] = 'global'
for (const k of REGION_CONST_KEYS) CONST_SCOPE[k] = 'region'
for (const k of BOUND_CONST_KEYS) CONST_SCOPE[k] = 'bound'
for (const k of LEGACY_CONST_KEYS) CONST_SCOPE[k] = 'legacy'
/** Where a key of a given scope has to be written. */
const SCOPE_ENDPOINT: Record<ConstScope, string> = {
global: 'the global constants endpoint',
region: 'updateRegionConstants',
bound: 'updateBoundSettings',
legacy: 'the legacy key_val_store endpoint',
}
/**
* The resolved settings payload reads every key from the table its scope names, so a key
* written through the wrong endpoint is stored and acknowledged but can never take effect —
* a silent no-op reported as success (F6). Reject those writes instead.
*
* Region writes also reject the cache-pipeline version counters, which used to be dropped
* silently.
*/
export function assertConstantKeysInScope(
keys: string[],
expected: 'region' | 'bound',
endpoint: string
): void {
const problems = [...new Set(keys)].flatMap((key) => {
const scope = CONST_SCOPE[key]
if (!scope) {
return [`${key} is not a known constant`]
}
if (scope !== expected) {
return [`${key} is a ${scope} constant — use ${SCOPE_ENDPOINT[scope]}`]
}
if (expected === 'region' && key.includes('version')) {
return [`${key} is a version counter owned by the cache pipeline and cannot be set here`]
}
return []
})
if (problems.length > 0) {
throw new ApiError(
`${endpoint} writes ${expected}-scoped constants only: ${problems.join('; ')}`,
400
)
}
}

View file

@ -75,6 +75,20 @@ export async function refreshGenKvForRegion(regionId: number): Promise<void> {
}
}
/**
* Drops a bound's cached payload. Called when a bound is deleted so the stale blob cannot be
* served if that id is ever reused by a new bound.
*/
export async function deleteGenKvForBound(boundId: number): Promise<void> {
try {
const kv = getGenKvNamespace()
if (!kv) return
await kv.delete(genKvKeyForBound(boundId))
} catch (error) {
console.error(`deleteGenKvForBound failed for bound ${boundId}:`, error)
}
}
/**
* Client read path: serve the precomputed payload for a bound from KV. On a
* miss, build it from D1/env, backfill KV, and return.

View file

@ -1,6 +1,7 @@
import type { Buffer } from 'buffer'
import { AwsClient } from 'aws4fetch'
import { claimUploadUrlStatus, createUploadUrlStatus } from '@/src/dbService'
import { claimUploadUrlStatus, createUploadUrlStatus, getPendingUploadUrlKeys } from '@/src/dbService'
import { ApiError } from '@/src/lib/api-error'
import {
getS3AccessKeyId,
getS3Region,
@ -42,6 +43,47 @@ const buildObjectUrl = (bucket: string, key: string) => {
return `${normalizedEndpoint}/${bucket}/${normalizedKey}`
}
/**
* Reduce an image reference to the bucket-relative object key.
*
* Accepts a presigned URL, an asset-domain URL, a legacy value with a percent-encoded
* presigned query baked into it (`tags/x.png%3FX-Amz-...`), or an already-normalised key.
* `scaffoldAssetUrl` uses this, so scaffolding is idempotent and can never double-prefix:
*
* https://<account>.r2.cloudflarestorage.com/meatfarmer-dev/tags/1.png?X-Amz-... -> tags/1.png
* https://assets2.freshyo.in/tags/1.png -> tags/1.png
* tags/1.png%3FX-Amz-Signature=... -> tags/1.png
* tags/1.png -> tags/1.png
*/
export function normalizeAssetRef(input: string | null | undefined): string {
let value = (input ?? '').trim()
if (!value) {
return ''
}
// Legacy rows saved the presigned query percent-encoded as part of the value.
const encodedQuery = value.search(/%3[fF]/)
if (encodedQuery !== -1) {
value = value.slice(0, encodedQuery)
}
if (/^https?:\/\//i.test(value)) {
try {
value = decodeURIComponent(new URL(value).pathname)
} catch {
value = value.split('?')[0].replace(/^https?:\/\/[^/]+/i, '')
}
const parts = value.split('/').filter(Boolean)
// Drop the bucket segment when the URL carries one.
if (parts.length > 1 && parts[0] === getS3BucketName()) {
parts.shift()
}
value = parts.join('/')
}
return value.replace(/^\/+/, '')
}
export const imageUploadS3 = async(body: Buffer, type: string, key: string) => {
const client = getAwsClient()
const url = buildObjectUrl(getS3BucketName(), key)
@ -63,13 +105,16 @@ export const imageUploadS3 = async(body: Buffer, type: string, key: string) => {
// export async function deleteImageUtil(...keys:string[]):Promise<boolean>;
export async function deleteImageUtil({bucket = getS3BucketName(), keys}:{bucket?: string, keys: string[]}) {
if (keys.length === 0) {
// Stored values may be URLs, presigned URLs or legacy encoded keys — normalise first.
const objectKeys = keys.map((key) => normalizeAssetRef(key)).filter(Boolean)
if (objectKeys.length === 0) {
return true
}
try {
const client = getAwsClient()
await Promise.all(
keys.map(async (key) => {
objectKeys.map(async (key) => {
const url = buildObjectUrl(bucket, key)
const resp = await client.fetch(url, { method: 'DELETE' })
if (!resp.ok && resp.status !== 404) {
@ -96,7 +141,10 @@ export function scaffoldAssetUrl(input: string | null | (string | null)[]): stri
if (!input) {
return ''
}
const normalizedKey = input.replace(/^\/+/, '')
const normalizedKey = normalizeAssetRef(input)
if (!normalizedKey) {
return ''
}
const domain = assetsDomain.endsWith('/')
? assetsDomain.slice(0, -1)
: assetsDomain
@ -230,3 +278,52 @@ export async function claimUploadUrl(url: string): Promise<void> {
throw new Error('Failed to claim upload URL')
}
}
/**
* The upload URLs that cannot be claimed: unknown to the app (never issued here) or already
* used by another record. Keys are derived the same way `claimUploadUrl` derives them.
*/
export async function findUnclaimableUploadUrls(urls: string[]): Promise<string[]> {
const keys = [...new Set((urls || []).filter(Boolean).map((url) => extractKeyFromPresignedUrl(url)))]
if (keys.length === 0) {
return []
}
const pending = new Set(await getPendingUploadUrlKeys(keys))
return keys.filter((key) => !pending.has(key))
}
/**
* Guard to run *before* a write that references uploaded images. `upload_url_status` is a
* write-only ledger (nothing reads it), so a late claim failure never broke an image — but it
* did abort the request after the row was already committed, leaving orphans behind. Validating
* up front turns that into a clean 400 with nothing written.
*/
export async function assertUploadUrlsClaimable(urls: string[]): Promise<void> {
const unclaimable = await findUnclaimableUploadUrls(urls)
if (unclaimable.length > 0) {
throw new ApiError(
`These images were not uploaded through the app (unknown or already used): ${unclaimable.join(', ')}. Upload them again and retry.`,
400
)
}
}
/**
* Claims every upload URL without failing the caller: by the time this runs the rows are already
* written, so a claim failure is logged rather than surfaced as a 500 on committed work.
*/
export async function claimUploadUrls(urls: string[]): Promise<void> {
if (!urls || urls.length === 0) {
return
}
const results = await Promise.allSettled(urls.map((url) => claimUploadUrl(url)))
results.forEach((result, index) => {
if (result.status === 'rejected') {
console.error(`Failed to claim upload URL ${urls[index]}:`, result.reason)
}
})
}

View file

@ -83,6 +83,7 @@ export {
deleteProductGroup,
updateProductPrices,
toggleProductOutOfStock,
setProductSkusOutOfStock,
// Admin - Slots
getActiveSlotsWithProducts,
getSlotsAfterDate,
@ -277,6 +278,7 @@ export {
// Upload URL Helpers
createUploadUrlStatus,
claimUploadUrlStatus,
getPendingUploadUrlKeys,
// Superadmin / Region Helpers
getSuperadminByUsername,
getSuperadminById,
@ -289,6 +291,7 @@ export {
getBoundById,
createRegionBound,
updateRegionBound,
deleteRegionBound,
getBoundSettings,
upsertBoundSettings,
getEffectiveRegionSettings,

View file

@ -1,7 +1,7 @@
import { router, protectedProcedure, staffProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import { ApiError } from '@/src/lib/api-error'
import { scaffoldAssetUrl, claimUploadUrl, extractKeyFromPresignedUrl, deleteImageUtil } from '@/src/lib/s3-client'
import { scaffoldAssetUrl, claimUploadUrls, assertUploadUrlsClaimable, extractKeyFromPresignedUrl, deleteImageUtil, normalizeAssetRef } from '@/src/lib/s3-client'
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
import { createAvailabilityCacheFile } from '@/src/lib/cloud_cache'
import {
@ -16,6 +16,7 @@ import {
deleteProductGroup as deleteProductGroupInDb,
updateProductPrices as updateProductPricesInDb,
toggleProductOutOfStock as toggleProductOutOfStockInDb,
setProductSkusOutOfStock as setProductSkusOutOfStockInDb,
checkProductExistsByName,
createProduct as createProductInDb,
replaceTagProducts,
@ -110,26 +111,72 @@ export const productRouter = router({
toggleOutOfStock: protectedProcedure
.input(z.object({
id: z.number(),
// Optional: flip specific variants instead of the whole product (PD-06).
skuIds: z.array(z.number().int().positive()).min(1).optional(),
isOutOfStock: z.boolean().optional(),
}))
.mutation(async ({ input, ctx }): Promise<AdminToggleOutOfStockResult> => {
const { id } = input;
const regionId = ctx.staffUser!.regionId
const result = await toggleProductOutOfStockInDb(ctx.staffUser!.regionId, id)
let result: AdminToggleOutOfStockResult
if (!result) {
throw new ApiError('Product not found', 404)
if (input.skuIds) {
if (typeof input.isOutOfStock !== 'boolean') {
throw new ApiError('isOutOfStock is required when skuIds are given', 400)
}
const updated = await setProductSkusOutOfStockInDb(
regionId,
input.id,
input.skuIds,
input.isOutOfStock
)
if (!updated) {
throw new ApiError('Product not found', 404)
}
if (updated.ignoredSkuIds.length > 0) {
throw new ApiError(
`These variants do not belong to product ${input.id}: ${updated.ignoredSkuIds.join(', ')}`,
400
)
}
const outCount = updated.skus.filter((sku) => sku.isOutOfStock).length
const partial = outCount > 0 && outCount < updated.skus.length
result = {
productId: updated.id,
isOutOfStock: updated.isOutOfStock,
affectedSkuIds: updated.skus
.map((sku) => sku.id)
.filter((skuId) => input.skuIds!.includes(skuId)),
skus: updated.skus,
message: `Marked ${input.skuIds.length} variant(s) as ${
input.isOutOfStock ? 'out of stock' : 'in stock'
}${partial ? ' (other variants unchanged)' : ''}`,
}
} else {
const toggled = await toggleProductOutOfStockInDb(regionId, input.id)
if (!toggled) {
throw new ApiError('Product not found', 404)
}
result = {
productId: toggled.id,
isOutOfStock: toggled.isOutOfStock,
message: `Product marked as ${toggled.isOutOfStock ? 'out of stock' : 'in stock'}`,
}
}
// Only the availability cache needs regenerating for a stock flip.
await createAvailabilityCacheFile(ctx.staffUser!.regionId).catch((err) => {
await createAvailabilityCacheFile(regionId).catch((err) => {
console.error('Failed to regenerate availability cache after stock update:', err)
})
return {
productId: result.id,
isOutOfStock: result.isOutOfStock,
message: `Product marked as ${result.isOutOfStock ? 'out of stock' : 'in stock'}`,
}
return result
}),
createProduct: staffProcedure
@ -190,6 +237,10 @@ export const productRouter = router({
comboItems: (sku.comboItems || []).map((ci) => ({ skuId: ci.skuId })),
}))
// Validate every image upload before writing, so an unknown/reused upload URL cannot leave
// the product (and its SKUs) behind while the request fails.
await assertUploadUrlsClaimable(allUploadUrls)
const newProduct = await createProductInDb({
name,
shortDescription,
@ -200,9 +251,7 @@ export const productRouter = router({
skus: skuInputs,
} as any, ctx.staffUser!.regionId)
if (allUploadUrls.length > 0) {
await Promise.all(allUploadUrls.map((url) => claimUploadUrl(url)))
}
await claimUploadUrls(allUploadUrls)
await scheduleStoreInitialization(ctx.staffUser!.regionId)
@ -256,6 +305,9 @@ export const productRouter = router({
.mutation(async ({ input, ctx }): Promise<{ product: AdminProductWithRelations; message: string }> => {
const { id, name, shortDescription, longDescription, storeId, incrementStep, productType, skus, deletedImageKeys, newImageUrls } = input
// Before deleting any current image or writing the update: the new uploads must be real.
await assertUploadUrlsClaimable(newImageUrls)
if (deletedImageKeys.length > 0) {
await deleteImageUtil({ keys: deletedImageKeys })
}
@ -295,7 +347,7 @@ export const productRouter = router({
}
if (newImageUrls.length > 0) {
await Promise.all(newImageUrls.map((url) => claimUploadUrl(url)))
await claimUploadUrls(newImageUrls)
}
await scheduleStoreInitialization(ctx.staffUser!.regionId)
@ -346,15 +398,15 @@ export const productRouter = router({
.mutation(async ({ input, ctx }): Promise<AdminProductReviewResponse> => {
const { reviewId, adminResponse, adminResponseImages, uploadUrls } = input;
await assertUploadUrlsClaimable(uploadUrls)
const updatedReview = await respondToReviewInDb(ctx.staffUser!.regionId, reviewId, adminResponse, adminResponseImages)
if (!updatedReview) {
throw new ApiError('Review not found', 404)
}
if (uploadUrls && uploadUrls.length > 0) {
await Promise.all(uploadUrls.map(url => claimUploadUrl(url)))
}
await claimUploadUrls(uploadUrls)
return { success: true, review: updatedReview }
}),
@ -519,10 +571,12 @@ export const productRouter = router({
throw new ApiError('A tag with this name already exists', 400)
}
await assertUploadUrlsClaimable(uploadUrls)
const createdTag = await createProductTagInDb({
tagName: tagName.trim(),
tagDescription,
imageUrl: imageUrl ?? null,
imageUrl: imageUrl ? normalizeAssetRef(imageUrl) : null,
isDashboardTag,
relatedStores,
sortOrder: productIds,
@ -530,9 +584,7 @@ export const productRouter = router({
await replaceTagProducts(ctx.staffUser!.regionId, createdTag.id, productIds)
if (uploadUrls.length > 0) {
await Promise.all(uploadUrls.map((url) => claimUploadUrl(url)))
}
await claimUploadUrls(uploadUrls)
await scheduleStoreInitialization(ctx.staffUser!.regionId)
@ -567,16 +619,25 @@ export const productRouter = router({
throw new ApiError('Tag not found', 404)
}
if (imageUrl !== undefined && imageUrl !== currentTag.imageUrl) {
// Checked before the old image is cleaned up, so a bad new URL cannot delete it.
await assertUploadUrlsClaimable(uploadUrls)
const normalizedImageUrl = imageUrl ? normalizeAssetRef(imageUrl) : imageUrl
if (normalizedImageUrl !== undefined && normalizedImageUrl !== currentTag.imageUrl) {
if (currentTag.imageUrl) {
await deleteImageUtil({ keys: [currentTag.imageUrl] })
try {
await deleteImageUtil({ keys: [currentTag.imageUrl] })
} catch (err) {
console.error('Failed to clean up previous tag image, continuing with update:', err)
}
}
}
const updatedTag = await updateProductTagInDb(ctx.staffUser!.regionId, id, {
tagName: tagName?.trim(),
tagDescription: tagDescription ?? undefined,
imageUrl: imageUrl ?? undefined,
imageUrl: normalizedImageUrl ?? undefined,
isDashboardTag,
relatedStores,
sortOrder: productIds,
@ -590,9 +651,7 @@ export const productRouter = router({
await replaceTagProducts(ctx.staffUser!.regionId, id, productIds)
}
if (uploadUrls.length > 0) {
await Promise.all(uploadUrls.map((url) => claimUploadUrl(url)))
}
await claimUploadUrls(uploadUrls)
await scheduleStoreInitialization(ctx.staffUser!.regionId)
@ -617,7 +676,12 @@ export const productRouter = router({
}
if (tag.imageUrl) {
await deleteImageUtil({ keys: [tag.imageUrl] })
// Image cleanup must never block deleting the tag itself.
try {
await deleteImageUtil({ keys: [tag.imageUrl] })
} catch (err) {
console.error('Failed to delete tag image, continuing with tag deletion:', err)
}
}
const deleted = await deleteProductTagInDb(ctx.staffUser!.regionId, input.id)

View file

@ -2,6 +2,7 @@ import { router, staffProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import { TRPCError } from '@trpc/server'
import { ApiError } from '@/src/lib/api-error'
import { assertConstantKeysInScope } from '@/src/lib/const-keys'
import { refreshGenKvForRegion } from '@/src/lib/gen-store'
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
import {
@ -29,13 +30,10 @@ const constRows = z.array(z.object({
value: z.union([z.string(), z.number(), z.boolean(), z.null()]),
}))
// Region-level keys that are baked into the versioned cache files; changing them
// requires regenerating the store cache so the user app picks it up.
/** Region-level keys baked into the versioned cache files; changing them requires
* regenerating the store cache so the user app picks it up. */
const CACHE_AFFECTING_REGION_KEYS: string[] = ['tagsOrder']
// Version counters live in region_consts but are owned by the cache pipeline.
const isVersionKey = (key: string) => key.includes('version')
export const regionRouter = router({
current: staffProcedure.query(async ({ ctx }) => {
return getRegionById(ctx.staffUser!.regionId)
@ -61,12 +59,23 @@ export const regionRouter = router({
.input(z.object({ constants: constRows }))
.mutation(async ({ input, ctx }) => {
const regionId = ctx.staffUser!.regionId
const rows = input.constants
.filter((c) => !isVersionKey(c.key))
.map((c) => ({ key: c.key, value: c.value == null ? null : String(c.value) }))
// Null means "delete this row", which is also the escape hatch for cleaning up a key
// that was stored under the wrong scope before this check existed.
const keysToWrite = input.constants.filter((c) => c.value != null).map((c) => c.key)
assertConstantKeysInScope(keysToWrite, 'region', 'admin.region.updateRegionConstants')
const rows = input.constants.map((c) => ({
key: c.key,
value: c.value == null ? null : String(c.value),
}))
let updated = 0
let deleted = 0
if (rows.length > 0) {
await upsertRegionConstants(regionId, rows)
const result = await upsertRegionConstants(regionId, rows)
updated = result.updated
deleted = result.deleted
await refreshGenKvForRegion(regionId)
}
@ -74,7 +83,7 @@ export const regionRouter = router({
await scheduleStoreInitialization()
}
return { success: true, updatedCount: rows.length }
return { success: true, updatedCount: updated, deletedCount: deleted }
}),
getBoundSettings: staffProcedure
@ -95,8 +104,11 @@ export const regionRouter = router({
.mutation(async ({ input, ctx }) => {
const regionId = ctx.staffUser!.regionId
await assertBoundInRegion(input.boundId, regionId)
await upsertBoundSettings(input.boundId, input.settings)
const keysToWrite = input.settings.filter((s) => s.value !== null).map((s) => s.key)
assertConstantKeysInScope(keysToWrite, 'bound', 'admin.region.updateBoundSettings')
const { updated, deleted } = await upsertBoundSettings(input.boundId, input.settings)
await refreshGenKvForRegion(regionId)
return { success: true, updatedCount: input.settings.length }
return { success: true, updatedCount: updated, deletedCount: deleted }
}),
})

View file

@ -2,7 +2,8 @@ import { router, superadminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import { TRPCError } from '@trpc/server'
import { ApiError } from '@/src/lib/api-error'
import { refreshGenKvForRegion } from '@/src/lib/gen-store'
import { assertConstantKeysInScope } from '@/src/lib/const-keys'
import { refreshGenKvForRegion, deleteGenKvForBound } from '@/src/lib/gen-store'
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
import {
getAllRegions,
@ -13,6 +14,7 @@ import {
getBoundById,
createRegionBound,
updateRegionBound,
deleteRegionBound,
getBoundSettings,
upsertBoundSettings,
getRegionConstants,
@ -36,8 +38,6 @@ const geojsonSchema = z.object({
// Region-level keys baked into the versioned cache files (cache regen needed).
const CACHE_AFFECTING_REGION_KEYS: string[] = ['tagsOrder']
// Version counters live in region_consts but are owned by the cache pipeline.
const isVersionKey = (key: string) => key.includes('version')
export const superadminRegionsRouter = router({
list: superadminProcedure.query(async () => {
@ -157,6 +157,38 @@ export const superadminRegionsRouter = router({
}
}),
deleteBound: superadminProcedure
.input(z.object({ id: z.number().int().positive() }))
.mutation(async ({ input }) => {
const result = await deleteRegionBound(input.id)
if (!result.found) {
throw new ApiError(`Region bound ${input.id} not found`, 404)
}
if (!result.deleted) {
if (result.lastBound) {
throw new ApiError(
`Bound ${input.id} is the only bound of region ${result.regionId}. A region needs at least one bound so it can take orders.`,
409
)
}
throw new ApiError(
`Bound ${input.id} is used by ${result.addressCount} address(es). Move them to another bound first.`,
409
)
}
// Remaining bounds are re-mirrored; the removed bound's cached payload is dropped.
if (result.regionId != null) {
await refreshGenKvForRegion(result.regionId)
}
await deleteGenKvForBound(input.id)
return { success: true, deletedId: input.id, remainingBounds: result.remainingBounds }
}),
boundSettings: superadminProcedure
.input(z.object({ boundId: z.number().int().positive() }))
.query(async ({ input }) => {
@ -172,14 +204,19 @@ export const superadminRegionsRouter = router({
})),
}))
.mutation(async ({ input }) => {
await upsertBoundSettings(input.boundId, input.settings)
// Null means "delete this row", which is also the escape hatch for cleaning up a key
// that was stored under the wrong scope before this check existed.
const keysToWrite = input.settings.filter((s) => s.value !== null).map((s) => s.key)
assertConstantKeysInScope(keysToWrite, 'bound', 'superadmin.regions.updateBoundSettings')
const { updated, deleted } = await upsertBoundSettings(input.boundId, input.settings)
// Bound settings are served from KV (essentialConsts payload), so the
// region's mirror must be rebuilt or clients keep reading stale values.
const bound = await getBoundById(input.boundId)
if (bound) {
await refreshGenKvForRegion(bound.regionId)
}
return { success: true, updatedCount: input.settings.length }
return { success: true, updatedCount: updated, deletedCount: deleted }
}),
getRegionConstants: superadminProcedure
@ -198,12 +235,23 @@ export const superadminRegionsRouter = router({
})),
}))
.mutation(async ({ input }) => {
const rows = input.constants
.filter((c) => !isVersionKey(c.key))
.map((c) => ({ key: c.key, value: c.value == null ? null : String(c.value) }))
// Null means "delete this row", which is also the escape hatch for cleaning up a key
// that was stored under the wrong scope before this check existed.
const keysToWrite = input.constants.filter((c) => c.value != null).map((c) => c.key)
assertConstantKeysInScope(keysToWrite, 'region', 'superadmin.regions.updateRegionConstants')
const rows = input.constants.map((c) => ({
key: c.key,
value: c.value == null ? null : String(c.value),
}))
let updated = 0
let deleted = 0
if (rows.length > 0) {
await upsertRegionConstants(input.regionId, rows)
const result = await upsertRegionConstants(input.regionId, rows)
updated = result.updated
deleted = result.deleted
await refreshGenKvForRegion(input.regionId)
}
@ -211,7 +259,7 @@ export const superadminRegionsRouter = router({
await scheduleStoreInitialization()
}
return { success: true, updatedCount: rows.length }
return { success: true, updatedCount: updated, deletedCount: deleted }
}),
effectiveSettings: superadminProcedure

View file

@ -1,6 +1,7 @@
import { router, protectedProcedure } from "@/src/trpc/trpc-index";
import { z } from "zod";
import {
applyDiscountToUserOrder,
cancelUserOrderTransaction,
checkUserSuspended,
composeUnitNotation,
@ -544,28 +545,23 @@ export const orderRouter = router({
let couponData = null;
if (couponUsageData.length > 0) {
// The coupon discounts the item subtotal, not the paid total: orders.total_amount
// stores items − discount + delivery, so using it as the base inflated the discount.
const itemsSubtotal = order.orderItems.reduce(
(sum, item) =>
sum +
parseFloat(item.price.toString()) * parseFloat(item.quantity.toString()),
0
);
const proportion = Number(order.orderGroupProportion || 1);
let totalDiscountAmount = 0;
const orderTotal = parseFloat(order.totalAmount.toString());
for (const usage of couponUsageData) {
let discountAmount = 0;
if (usage.coupon.discountPercent) {
discountAmount =
(orderTotal *
parseFloat(usage.coupon.discountPercent.toString())) /
100;
} else if (usage.coupon.flatDiscount) {
discountAmount = parseFloat(usage.coupon.flatDiscount.toString());
}
if (
usage.coupon.maxValue &&
discountAmount > parseFloat(usage.coupon.maxValue.toString())
) {
discountAmount = parseFloat(usage.coupon.maxValue.toString());
}
const { discountAmount } = applyDiscountToUserOrder(
itemsSubtotal,
usage.coupon,
proportion
);
totalDiscountAmount += discountAmount;
}

View file

@ -1,6 +1,6 @@
import { router, publicProcedure, protectedProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import { claimUploadUrl, extractKeyFromPresignedUrl, scaffoldAssetUrl } from '@/src/lib/s3-client'
import { claimUploadUrls, findUnclaimableUploadUrls, extractKeyFromPresignedUrl, scaffoldAssetUrl } from '@/src/lib/s3-client'
import { ApiError } from '@/src/lib/api-error'
import { getProductById as getProductByIdFromCache } from '@/src/stores/product-store'
import dayjs from 'dayjs'
@ -111,18 +111,17 @@ export const productRouter = router({
throw new ApiError('Product not found', 404)
}
// Reviews keep their lenient contract: an upload URL that is unknown or already used is
// logged, not rejected, but the review is no longer written after a fatal claim error.
const unclaimableReviewUrls = await findUnclaimableUploadUrls(uploadUrls)
if (unclaimableReviewUrls.length > 0) {
console.error('Review images were not uploaded through the app (unknown or already used):', unclaimableReviewUrls)
}
const imageKeys = uploadUrls.map(item => extractKeyFromPresignedUrl(item))
const newReview = await createUserProductReviewInDb(userId, productId, reviewBody, ratings, imageKeys)
// Claim upload URLs
if (uploadUrls && uploadUrls.length > 0) {
try {
await Promise.all(uploadUrls.map(url => claimUploadUrl(url)));
} catch (error) {
console.error('Error claiming upload URLs:', error);
// Don't fail the review creation
}
}
await claimUploadUrls(uploadUrls)
return { success: true, review: newReview }
}),

View file

@ -1,6 +1,7 @@
import { router, publicProcedure } from "@/src/trpc/trpc-index"
import { z } from 'zod'
import dayjs from 'dayjs'
import { getAllSlotsWithProductsForCache, getUserActiveSlotsList as getUserActiveSlotsListInDb, getUserProductAvailability as getUserProductAvailabilityInDb, getAllRegions } from '@/src/dbService'
import { getAllSlotsWithProductsForCache, getUserActiveSlotsList as getUserActiveSlotsListInDb, getUserProductAvailability as getUserProductAvailabilityInDb } from '@/src/dbService'
import { scaffoldAssetUrl } from '@/src/lib/s3-client'
import type { UserSlotsListResponse, UserSlotsWithProductsResponse } from '@packages/shared'
@ -35,15 +36,32 @@ export async function scaffoldSlotsWithProducts(regionId: number): Promise<UserS
}
export const slotsRouter = router({
getSlots: publicProcedure.query(async (): Promise<UserSlotsListResponse> => {
// No-input shape preserved for existing callers (separate workstream):
// aggregate the per-region active slot lists.
const regions = await getAllRegions()
const perRegion = await Promise.all(regions.map((r) => getUserActiveSlotsListInDb(r.id)))
getSlots: publicProcedure
.input(z.object({
// The caller's selected region. Admin tools omit it and fall back to the
// staff user's own region; without either, no slots are returned.
regionId: z.number().int().positive().optional(),
}).optional())
.query(async ({ input, ctx }): Promise<UserSlotsListResponse> => {
const regionId = input?.regionId ?? ctx.staffUser?.regionId ?? null
return {
slots: perRegion.flat(),
count: perRegion.reduce((n, list) => n + list.length, 0),
}
}),
if (regionId == null) {
return { slots: [], count: 0 }
}
// Only this region's active slots that can still be ordered: a slot whose
// freeze time has passed is closed, and a different region's slots are not
// deliverable at all. Mirrors the checks placeOrder applies.
const now = Date.now()
const slots = (await getUserActiveSlotsListInDb(regionId)).filter(
(slot) =>
new Date(slot.deliveryTime).getTime() > now &&
new Date(slot.freezeTime).getTime() > now
)
return {
slots,
count: slots.length,
}
}),
});

View file

@ -8,7 +8,8 @@
"preview": "npm run build && wrangler dev",
"typecheck": "tsc --noEmit",
"deploy": "npm run build && wrangler deploy",
"cf-typegen": "wrangler types"
"cf-typegen": "wrangler types",
"test": "vitest run"
},
"dependencies": {
"@tailwindcss/vite": "^4.1.18",

View file

@ -0,0 +1,29 @@
import { describe, expect, it } from 'vitest'
import { LAST_BOUND_HINT, MIN_BOUNDS_PER_REGION, canDeleteBound } from './bound-rules'
describe('canDeleteBound', () => {
it('refuses a region\'s only bound', () => {
expect(canDeleteBound(1)).toBe(false)
})
it('refuses when the region has no bounds at all', () => {
expect(canDeleteBound(0)).toBe(false)
})
it('allows deleting a bound while another one remains', () => {
expect(canDeleteBound(2)).toBe(true)
expect(canDeleteBound(3)).toBe(true)
})
it('refuses non-numeric input', () => {
expect(canDeleteBound(Number.NaN)).toBe(false)
})
it('keeps at least one bound per region', () => {
expect(MIN_BOUNDS_PER_REGION).toBe(1)
})
it('explains the refusal', () => {
expect(LAST_BOUND_HINT).toMatch(/at least one bound/i)
})
})

View file

@ -0,0 +1,17 @@
/**
* Bound rules shared by the UI and its tests.
*
* A region resolves pricing/availability through its bounds, so removing the last one would
* leave the region unable to take orders (the UI already warns "Add at least one bound so this
* region can take orders"). The server enforces the same rule in
* `deleteRegionBound`; the UI must not offer the action either.
*/
export const MIN_BOUNDS_PER_REGION = 1
export const LAST_BOUND_HINT =
'A region needs at least one bound, so the last bound cannot be deleted.'
/** Only allow deleting a bound when at least one other bound will remain. */
export function canDeleteBound(boundCount: number): boolean {
return Number.isFinite(boundCount) && boundCount > MIN_BOUNDS_PER_REGION
}

View file

@ -4,6 +4,7 @@ import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-compo
import { ProtectedRoute } from '../components/ProtectedRoute'
import { AppShell } from '../components/AppShell'
import { trpc } from '../lib/trpc-client'
import { LAST_BOUND_HINT, canDeleteBound } from '../lib/bound-rules'
export const Route = createFileRoute('/regions')({
component: () => (
@ -325,7 +326,13 @@ function RegionDetail({ regionId }: { regionId: number }) {
address coordinates.
</MyText>
{activeBound && <BoundSettingsEditor boundId={activeBound.id} />}
{activeBound && (
<BoundSettingsEditor
boundId={activeBound.id}
canDelete={canDeleteBound(bounds.length)}
onDeleted={regionQuery.refetch}
/>
)}
</>
)}
</div>
@ -462,11 +469,22 @@ function RegionConstantsEditor({ regionId }: { regionId: number }) {
)
}
function BoundSettingsEditor({ boundId }: { boundId: number }) {
function BoundSettingsEditor({
boundId,
canDelete,
onDeleted,
}: {
boundId: number
canDelete: boolean
onDeleted: () => void
}) {
const settingsQuery = trpc.superadmin.regions.boundSettings.useQuery({ boundId })
const updateSettings = trpc.superadmin.regions.updateBoundSettings.useMutation({
onSuccess: () => settingsQuery.refetch(),
})
const deleteBound = trpc.superadmin.regions.deleteBound.useMutation({
onSuccess: () => onDeleted(),
})
const [draft, setDraft] = useState<Record<string, string>>({})
const [initialised, setInitialised] = useState<number | null>(null)
@ -494,6 +512,12 @@ function BoundSettingsEditor({ boundId }: { boundId: number }) {
})
}
const handleDelete = () => {
if (!canDelete) return
if (!window.confirm(`Delete bound #${boundId} and its settings?`)) return
deleteBound.mutate({ id: boundId })
}
return (
<div>
<MyText className="mb-3 block font-semibold text-gray-900">Bound settings</MyText>
@ -513,6 +537,24 @@ function BoundSettingsEditor({ boundId }: { boundId: number }) {
>
{updateSettings.isPending ? 'Saving...' : 'Save settings'}
</MyButton>
<div className="mt-3 flex items-center gap-3">
<MyButton
onClick={handleDelete}
disabled={!canDelete || deleteBound.isPending}
title={canDelete ? `Delete bound #${boundId}` : LAST_BOUND_HINT}
className="rounded-lg border border-red-200 px-4 py-2 text-red-700 disabled:cursor-not-allowed disabled:opacity-50"
>
{deleteBound.isPending ? 'Deleting...' : 'Delete bound'}
</MyButton>
{!canDelete && (
<MyText className="block text-xs text-gray-500">{LAST_BOUND_HINT}</MyText>
)}
</div>
{deleteBound.error && (
<MyText className="mt-2 block text-sm text-red-600">{deleteBound.error.message}</MyText>
)}
</div>
)
}

View file

@ -0,0 +1,11 @@
import { defineConfig } from 'vitest/config'
// Minimal config for the pure-logic tests in this app: the app's vite.config.ts pulls in
// TanStack Start / Cloudflare / Nitro plugins that are irrelevant (and unavailable) in a
// node test run. Keep this file out of the app build — vite only reads vite.config.ts.
export default defineConfig({
test: {
include: ['src/**/*.test.ts'],
environment: 'node',
},
})

View file

@ -12,6 +12,7 @@ import { useCentralProductStore } from '@/src/store/centralProductStore';
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
import { useGetCart } from '@/hooks/cart-query-hooks';
import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
import { useRegion } from '@/src/hooks/useRegion';
import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent';
import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay';
import { useAddressStore } from '@/src/store/addressStore';
@ -22,6 +23,10 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
const router = useRouter();
const { isAuthenticated } = useAuth();
// Slots are per-region and the order is placed with this same region
// (see PaymentAndOrderComponent), so scope the query to it.
const { regionId } = useRegion();
// Protect checkout route and preserve query params
useAuthenticatedRoute({
targetUrl: isFlashDelivery ? '/(drawer)/(tabs)/flash-delivery/checkout' : '/(drawer)/(tabs)/home/checkout',
@ -35,7 +40,10 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
undefined,
{ enabled: isAuthenticated }
);
const { data: slotsData, refetch: refetchSlots } = trpc.user.slots.getSlots.useQuery();
const { data: slotsData, refetch: refetchSlots } = trpc.user.slots.getSlots.useQuery(
{ regionId: regionId ?? undefined },
{ enabled: regionId != null }
);
const constsData = useRegionalConsts();
const products = useCentralProductStore((state) => state.products);
const productsById = useCentralProductStore((state) => state.productsById);

View file

@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
import { fetchJson } from '@/src/lib/fetch-json'
import { trpc } from '@/src/trpc-client'
import type { ProductPriceFlags } from '@packages/shared'
import { AllProductsApiType, StoresApiType, SlotsApiType, EssentialConstsApiType, StoreWithProductsApiType, AvailabilityApiType } from "@backend/trpc/router";
@ -163,8 +163,8 @@ export function useAllProducts() {
if (!cacheUrl) {
throw new Error('Cache URL not available')
}
const response = await axios.get<ProductsResponse>(cacheUrl)
return response.data
const response = await fetchJson<ProductsResponse>(cacheUrl)
return response
},
staleTime: 60000, // 1 minute
enabled: !!cacheUrl,
@ -219,8 +219,8 @@ export function useAvailability() {
if (!cacheUrl) {
throw new Error('Cache URL not available')
}
const response = await axios.get<AvailabilityResponse>(cacheUrl)
return response.data
const response = await fetchJson<AvailabilityResponse>(cacheUrl)
return response
},
staleTime: 60000, // 1 minute
enabled: !!cacheUrl,
@ -237,8 +237,8 @@ export function useStores() {
if (!cacheUrl) {
throw new Error('Cache URL not available')
}
const response = await axios.get<StoresResponse>(cacheUrl)
return response.data
const response = await fetchJson<StoresResponse>(cacheUrl)
return response
},
staleTime: 60000, // 1 minute
enabled: !!cacheUrl,
@ -255,8 +255,8 @@ export function useSlots() {
if (!cacheUrl) {
throw new Error('Cache URL not available')
}
const response = await axios.get<SlotsResponse>(cacheUrl + '?v=123')
return response.data
const response = await fetchJson<SlotsResponse>(cacheUrl + '?v=123')
return response
},
staleTime: 60000, // 1 minute
enabled: !!cacheUrl,
@ -282,8 +282,8 @@ export function useStoreWithProducts(storeId: number) {
if (!cacheUrl) {
throw new Error('Cache URL not available')
}
const response = await axios.get<StoreWithProductsResponse>(cacheUrl)
return response.data
const response = await fetchJson<StoreWithProductsResponse>(cacheUrl)
return response
},
staleTime: 60000, // 1 minute
enabled: !!cacheUrl,

View file

@ -0,0 +1,37 @@
import axios from 'axios'
/**
* Hard cap for catalogue / CDN JSON requests.
*
* `handleRefresh` on the home screen waits for the products/stores/slots/consts refetches and only then
* clears its pull-to-refresh indicator. Those fetches had no timeout, so a single stalled connection left
* the spinner turning until the app was relaunched. Failing (with an abort) is far better than hanging.
*/
export const JSON_FETCH_TIMEOUT_MS = 90_000
/** True for the errors an aborted/cancelled request produces (axios or fetch). */
export function isAbortError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false
const candidate = error as { name?: string; code?: string }
return (
candidate.name === 'CanceledError' ||
candidate.name === 'AbortError' ||
candidate.code === 'ERR_CANCELED'
)
}
/**
* GET a JSON document with a bounded lifetime. The timeout is per request and the controller is always
* disposed, so nothing leaks when the request settles early.
*/
export async function fetchJson<T>(url: string, timeoutMs: number = JSON_FETCH_TIMEOUT_MS): Promise<T> {
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), timeoutMs)
try {
const response = await axios.get<T>(url, { signal: controller.signal })
return response.data
} finally {
clearTimeout(timer)
}
}

View file

@ -5,6 +5,7 @@ import { BASE_API_URL } from "@packages/shared";
import { getAuthToken } from "@/hooks/useJWT";
import { DeviceEventEmitter } from "react-native";
import { FORCE_LOGOUT_EVENT } from "common-ui/src/lib/const-strs";
import { JSON_FETCH_TIMEOUT_MS } from "@/src/lib/fetch-json";
// Create tRPC React hooks without strict typing for now
export const trpc = createTRPCReact<AppRouter>();
@ -19,7 +20,22 @@ export const trpcClient = createTRPCProxyClient<AppRouter>({
return token ? { Authorization: `Bearer ${token}` } : {};
},
fetch: async (url, options) => {
const response = await fetch(url, options);
// Every tRPC call gets a bounded lifetime: the home refresh waits on this leg too, and a
// request that never settles would keep its loading state alive indefinitely.
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), JSON_FETCH_TIMEOUT_MS);
const upstreamSignal = (options as RequestInit | undefined)?.signal;
const forwardAbort = () => controller.abort();
upstreamSignal?.addEventListener?.("abort", forwardAbort);
let response: Response;
try {
response = await fetch(url, { ...options, signal: controller.signal });
} finally {
clearTimeout(timer);
upstreamSignal?.removeEventListener?.("abort", forwardAbort);
}
if (response.status === 401) {
const data = await response
.clone()

View file

@ -1,9 +1,11 @@
import { QueryClient } from '@tanstack/react-query';
import { isAbortError } from '@/src/lib/fetch-json';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 3,
// Aborted requests (our 90s request cap) fail fast instead of being retried 3 more times.
retry: (failureCount, error) => !isAbortError(error) && failureCount < 3,
refetchOnWindowFocus: false,
staleTime: 1200000,
},

View file

@ -2578,3 +2578,434 @@ user-ui
-> pi stdio `command` + `args`. Project-scoped, so it needs project trust.)
No source files touched. No migrations run. No tests run.
[2026-10-10 18:17:00 +0530] Fix A1: `admin.product.deleteProduct` (500, FK violation) by making it a soft delete.
Root cause: D1 enforces FK constraints; `deleteProduct` issued a bare `DELETE FROM product_info`
while `product_skus.product_id` (NOT NULL, ON DELETE no action) and its child rows still referenced it.
Decision (user): soft delete; order history must keep showing the product name + billed amount.
Planned diff: packages/db_helper_sqlite/src/admin-apis/product.ts
- import: add `type SQL` to the drizzle-orm import.
- replace hard delete with:
+ async function softDeleteProduct(where: SQL): Promise<AdminProduct | null> {
+ const product = await db.query.productInfo.findFirst({ where, with: { skus: { columns: { id: true } } } })
+ if (!product) return null
+ const skuIds = product.skus.map((sku) => sku.id)
+ if (skuIds.length > 0) {
+ await db.batch([
+ db.delete(productMarketStats).where(inArray(productMarketStats.skuId, skuIds)),
+ db.delete(cartItems).where(inArray(cartItems.skuId, skuIds)),
+ db.delete(couponApplicableProducts).where(inArray(couponApplicableProducts.skuId, skuIds)),
+ db.delete(productTags).where(inArray(productTags.productId, skuIds)),
+ db.delete(productGroupMembership).where(inArray(productGroupMembership.productId, skuIds)),
+ db.delete(productCombos).where(inArray(productCombos.skuId, skuIds)),
+ db.delete(productCombos).where(inArray(productCombos.comboSkuId, skuIds)),
+ db.delete(specialDeals).where(inArray(specialDeals.skuId, skuIds)),
+ db.update(productSkus).set({ isDeleted: true }).where(inArray(productSkus.id, skuIds)),
+ ] as any)
+ }
+ return mapProduct(product)
+ }
+ export async function deleteProduct(regionId, id) { return softDeleteProduct(and(eq(productInfo.id, id), eq(productInfo.regionId, regionId))) }
+ export async function deleteGlobalProduct(id) { return softDeleteProduct(and(eq(productInfo.id, id), isNull(productInfo.regionId))) }
- (old bodies: single db.delete(productInfo)...returning() for both)
(kept: product_skus + sku_features rows -> order_items join still renders the name/unit;
kept product_info row -> parent FK; removed: market stats, carts, coupon applicability,
tags, group membership, combos, special deals)
- getAllProducts(regionId): hide fully-deleted products
- return products.map((product) => ({
+ return products.filter((product) => product.skus.some((sku) => !sku.isDeleted)).map((product) => ({
- checkProductExistsByName(name): ignore fully-deleted products so names can be reused
- db.query.productInfo.findFirst({ where: eq(productInfo.name, name), columns: { id: true } })
+ db.select({ id: productInfo.id }).from(productInfo)
+ .innerJoin(productSkus, eq(productSkus.productId, productInfo.id))
+ .where(and(eq(productInfo.name, name), eq(productSkus.isDeleted, false))).limit(1)
No other files: customer/store/slot/banner read paths already filter `productSkus.isDeleted`
(user-apis/product.ts, user-apis/stores.ts, stores/store-helpers.ts, admin-apis/slots.ts,
admin-apis/vendor-snippets.ts) and the order router already rejects deleted SKUs at checkout
(apps/backend/src/trpc/apis/user-apis/apis/order.ts SEC-05). No migration. No tests run.
[2026-10-10 18:26:00 +0530] Implemented the A1 soft-delete fix exactly as planned (packages/db_helper_sqlite/src/admin-apis/product.ts).
Verified against the running dev server (hot reloaded):
- `deleteProduct {152}` -> {"message":"Product deleted successfully"}; same for 151. (was HTTP 500)
- `getProductById {152}` -> skus 153/154 `isDeleted: true`, marketStats 0, features ["500 g","1 kg"] KEPT
(order history composes name/unit from these rows, so historical lines keep the product name).
- `admin.product.getProducts` -> 150 items, max id 150; fixtures 151/152 hidden.
- `user.product.getProductDetails {153}` -> "Product not found" (customer catalog hides tombstones).
- Name reuse: `createProduct` with the deleted product's name + bogus storeId -> "Invalid store ID: 999999"
(i.e. the name check passed; nothing was created).
- `deleteProduct {999999}` -> "Product not found" (404 preserved); re-deleting 152 still succeeds.
- No cache/store-init errors in the wrangler log after the deletes.
Still stranded by other known blockers (not part of this change): region-2 product 153 (no region-2 staff token),
stores 11/12 (store guard counts products), tag 10 (F4 image delete), region 2 (no delete API).
No migration. No tests run.
[2026-10-10 18:41:00 +0530] Fix A2/F2 (option A): order-detail coupon discount must be computed on the item subtotal, not on the paid total.
Root cause: the discount is not stored; both order-detail read paths recompute it as
`order.totalAmount * pct / 100`, but `orders.total_amount` holds the final payable
(items − discount + delivery). For order 2495 that reported 10% × 473.6 = 47.36 instead of the
10% × 304 = 30.4 that was charged. Fix: base = Σ(order_items.price × quantity) for this order,
cap prorated by `orders.order_group_proportion` (mathematically identical to what placeOrder charged),
reusing the existing (previously unused) applyDiscountToOrder() helper.
Planned diff: packages/db_helper_sqlite/src/user-apis/order.ts
+ export type CouponDiscountFields = Pick<CouponValidationResult, 'discountPercent' | 'flatDiscount' | 'maxValue'>
export function applyDiscountToOrder(
orderTotal: number,
- appliedCoupon: CouponValidationResult | null,
+ appliedCoupon: CouponDiscountFields | null,
proportion: number
)
Planned diff: packages/db_helper_sqlite/src/admin-apis/order.ts (getOrderByIdWithFullData, ~line 161-197)
- const orderTotal = parseFloat((orderData.totalAmount ?? '0').toString())
+ const itemsSubtotal = orderData.orderItems.reduce((sum, item) =>
+ sum + parseFloat(item.price?.toString() || '0') * parseFloat(item.quantity?.toString() || '0'), 0)
+ const proportion = Number(orderData.orderGroupProportion || 1)
for (const usage of couponUsageData) {
- let discountAmount = 0
- if (usage.coupon.discountPercent) { discountAmount = (orderTotal * pct) / 100 }
- else if (usage.coupon.flatDiscount) { discountAmount = parseFloat(usage.coupon.flatDiscount) }
- if (maxValue && discountAmount > maxValue) { discountAmount = maxValue }
- totalDiscountAmount += discountAmount
+ const { finalOrderTotal } = applyDiscountToOrder(itemsSubtotal, usage.coupon, proportion)
+ totalDiscountAmount += itemsSubtotal - finalOrderTotal
}
(import { applyDiscountToOrder } from '../user-apis/order')
Planned diff: apps/backend/src/trpc/apis/user-apis/apis/order.ts (getOrderById, ~line 547-577)
- const orderTotal = parseFloat(order.totalAmount.toString())
- ... manual per-coupon percent/flat/cap math on orderTotal ...
+ const itemsSubtotal = order.orderItems.reduce((sum, item) =>
+ sum + parseFloat(item.price.toString()) * parseFloat(item.quantity.toString()), 0)
+ const proportion = Number(order.orderGroupProportion || 1)
+ const { finalOrderTotal } = applyDiscountToUserOrder(itemsSubtotal, usage.coupon, proportion)
+ totalDiscountAmount += itemsSubtotal - finalOrderTotal
(add `applyDiscountToUserOrder` to the @/src/dbService import list)
Out of scope, reported only: admin-apis/order.ts rebalanceSlots (~line 684) recomputes each order's
`totalAmount` from latest prices minus discount but never adds the delivery charge, so a rebalance
overwrites the payable with a delivery-exclusive value (separate defect, same money area).
No migration. No tests run.
[2026-10-10 18:47:00 +0530] Implemented the A2/F2 fix as planned (option A) and verified live.
Files: packages/db_helper_sqlite/src/user-apis/order.ts (helper: CouponDiscountFields param +
discountAmount in the return so callers don't re-subtract and get 30.399999999999977),
packages/db_helper_sqlite/src/admin-apis/order.ts (getOrderByIdWithFullData coupon block),
apps/backend/src/trpc/apis/user-apis/apis/order.ts (getOrderById coupon block + import
applyDiscountToUserOrder from @/src/dbService).
Verified:
- admin.order.getOrderDetails {2495}: totalAmount 273.6, deliveryCharge 200, discountAmount 30.4
(was 47.36); items 304 - 30.4 + 200 = 473.6 ✓
- user.order.getOrderById {2495}: orderAmount/totalAmount 473.6, deliveryCharge 200,
discountAmount 30.4 (was 47.36) ✓
- no-coupon regression, admin.order.getOrderDetails {2496}: discountAmount null, couponCode null,
233 + 69 = 302 ✓
- proration equivalence checked numerically: read-path formula == write-path formula for a 10%/cap-50
coupon over splits (304@1), (304@0.5+0.5), (950@0.4+0.6) and for a flat-20/cap-50 coupon at p=1/0.5.
Still open (separate, reported): rebalanceSlots (~line 684 of the admin order helper) recomputes
orders.total_amount as latestItems − discount with no delivery charge, so a rebalance overwrites the
payable and would reintroduce a mismatch at read time. Needs its own decision/fix.
No migration. No tests run.
[2026-10-10 19:12:00 +0530] Fix `user.slots.getSlots` returning every region's slots (incl. past ones).
Problem: the procedure looped over all regions and returned the raw active-slot rows with no time
filter, so the checkout page received thousands of ids across regions, including full and long-past
slots (verified live: response contained [8..2032] while only 2032 is a future-active region-1 slot).
Planned diff: apps/backend/src/trpc/apis/user-apis/apis/slots.ts
getSlots: publicProcedure
+ .input(z.object({
+ // Caller's selected region. Omitted by admin tools -> staff region is used.
+ regionId: z.number().int().positive().optional(),
+ }).optional())
- .query(async (): Promise<UserSlotsListResponse> => {
- const regions = await getAllRegions()
- const perRegion = await Promise.all(regions.map((r) => getUserActiveSlotsListInDb(r.id)))
- return { slots: perRegion.flat(), count: perRegion.reduce((n, list) => n + list.length, 0) }
- })
+ .query(async ({ input, ctx }): Promise<UserSlotsListResponse> => {
+ const regionId = input?.regionId ?? ctx.staffUser?.regionId ?? null
+ if (regionId == null) return { slots: [], count: 0 }
+ const now = Date.now()
+ const slots = (await getUserActiveSlotsListInDb(regionId)).filter(
+ (slot) => new Date(slot.deliveryTime).getTime() > now && new Date(slot.freezeTime).getTime() > now,
+ )
+ return { slots, count: slots.length }
+ })
Planned diff: apps/user-ui/components/checkout-page.tsx
+ import { useRegion } from '@/src/hooks/useRegion';
...
+ const { regionId } = useRegion();
- const { data: slotsData, refetch: refetchSlots } = trpc.user.slots.getSlots.useQuery();
+ const { data: slotsData, refetch: refetchSlots } = trpc.user.slots.getSlots.useQuery(
+ { regionId: regionId ?? undefined },
+ { enabled: regionId != null }
+ );
(same region the order itself is placed with: PaymentAndOrderComponent sends
`regionId: selectedRegionId` from the same useRegion() hook)
No migration. No tests run.
[2026-10-10 19:20:00 +0530] Implemented the `user.slots.getSlots` scoping fix (backend + checkout caller).
During implementation the worker was briefly down: the new input schema used `z.object` without
importing zod in apps/backend/src/trpc/apis/user-apis/apis/slots.ts (Uncaught ReferenceError: z is not
defined) — fixed by adding `import { z } from 'zod'`. Server reloaded cleanly afterwards.
Verified live (temporarily set fixture slot 2033 to a future window with skuIds [148], then restored it
to deliveryTime 2026-10-11T13:30:00Z / freezeTime 2026-10-11T13:00:00Z / isActive false / skuIds null):
- active + future (freeze +30m, delivery +2h): regionId=1 -> count 1 [2033]; regionId=2 -> count 0;
staff token without input -> count 1 (falls back to the staff's own region);
no auth without input -> count 0 (previously: thousands of ids from every region)
- active but freeze time passed (freeze -1h): regionId=1 -> count 0
- inactive with a future window: regionId=1 -> count 0
- after restore: no future slots in any region -> count 0 for every variant (correct)
Response shape unchanged ({ slots: UserDeliverySlot[], count }) so the admin vendor-snippet forms keep
working (they now get their own region instead of every region).
NOT fixed by this change: the stale `slots.json` version pointer consumed by AddToCartDialog
(`essentialConsts.slots_version_num` stuck at 13 while newer files exist) and the hide-vs-show decision
for full slots. No migration. No tests run.
[2026-10-10 19:45:00 +0530] Fix A4/F4: tag images — normalise on write, make scaffoldAssetUrl idempotent, make image cleanup non-fatal.
Root cause recap (re-verified live): createProductTag/updateProductTag store the caller's imageUrl verbatim
(tag 10 holds a presigned URL); the tag read endpoints run scaffoldAssetUrl() which blindly prefixed
ASSETS_DOMAIN (-> https://assets2.freshyo.in/https://<r2>/...); deleteProductTag passed that same string to
deleteImageUtil as an object key, S3 rejected it, and the mutation 500s ("Failed to delete image") before
the row is deleted, so tag 10 is undeletable. Legacy tags 1 and 4 carry `tags/<file>%3FX-Amz-...` (encoded
presigned query baked into the value).
Planned diff: apps/backend/src/lib/s3-client.ts
+ export function normalizeAssetRef(input: string | null | undefined): string
+ // trims, drops a real query (`?`) or an encoded one (`%3F`), and for absolute URLs keeps the
+ // path minus host/bucket, so it works for presigned URLs, asset-domain URLs, legacy encoded
+ // values and plain keys alike.
scaffoldAssetUrl: - const normalizedKey = input.replace(/^\/+/, '')
+ const normalizedKey = normalizeAssetRef(input)
deleteImageUtil: iterate `keys.map(normalizeAssetRef).filter(Boolean)` instead of raw keys
(404 already tolerated; real failures still throw, callers decide)
Planned diff: apps/backend/src/trpc/apis/admin-apis/apis/product.ts
- import: add normalizeAssetRef to the '@/src/lib/s3-client' import
createProductTag: imageUrl: imageUrl ? normalizeAssetRef(imageUrl) : null (was: imageUrl ?? null)
updateProductTag: normalize before compare/write, and make the old-image cleanup non-fatal:
+ const normalizedImageUrl = imageUrl ? normalizeAssetRef(imageUrl) : imageUrl
+ ... if (normalizedImageUrl !== undefined && normalizedImageUrl !== currentTag.imageUrl) {
+ if (currentTag.imageUrl) { try { await deleteImageUtil({ keys: [currentTag.imageUrl] }) }
+ catch (err) { console.error('Failed to clean up previous tag image:', err) } }
+ }
- imageUrl: imageUrl ?? undefined -> imageUrl: normalizedImageUrl ?? undefined
deleteProductTag: wrap deleteImageUtil in try/catch (log + continue) so the tag row is always deleted.
Data repair (same session, recorded values):
- delete fixture tag 10 "E2E Deals 1715" (its stored value was the presigned URL above)
- clear imageUrl on tag 1 (was .../tags/1770321659633-1763869265110-e22b6d94-...jpeg%3FX-Amz-...) and
tag 4 (was .../tags/1770323410499-1763869436182-bf82f7b4-...jpeg%3FX-Amz-...): both objects return 404
at the clean key, so they need a re-upload; clearing stops the broken image. Tags 2/5/8/9 untouched.
No migration. No tests run.
[2026-10-10 20:00:00 +0530] A4/F4 implemented and verified live.
- tag 10 read: now `https://assets2.freshyo.in/tags/1791632636038.png` (was
`https://assets2.freshyo.in/https://<r2>/...?X-Amz-...`) — scaffolding is idempotent.
- `deleteProductTag {id:10}`: now "Tag deleted successfully" and the tag is gone (was 500
"Failed to delete image"); image cleanup 404 is tolerated and can no longer block the delete.
- write path: created tag 11 with a presigned imageUrl -> read back `https://assets2.freshyo.in/tags/999-test.png`
(key normalised on write); deleted tag 11 successfully.
- legacy repair: tags 1 "Chicken" and 4 "Fish" imageUrl cleared via updateProductTag (their objects return
404 at the clean key, so they need a re-upload; the previous image cleanup of the corrupted value no
longer throws). Tags 2/5/8 keep their images, tag 9 had none.
- regression: product images still scope correctly (`https://assets2.freshyo.in/product-images/1788767922579.png`);
update/delete of a tag still call scheduleStoreInitialization, so the customer tag cache regenerates
(subject to the A3 cache-version caveat we agreed to leave).
Data left: tag 10 removed (it was an E2E fixture), tags 1/4 need new images from the admin UI.
[2026-10-10 20:20:00 +0530] A5/F5 option 1: pre-validate upload URLs before the write, then claim best-effort.
Plan:
- packages/db_helper_sqlite/src/helper_methods/upload-url.ts: add
getPendingUploadUrlKeys(keys: string[]): Promise<string[]>
(single inArray query for the keys that exist with status 'pending').
- export it from packages/db_helper_sqlite/index.ts and apps/backend/src/sqliteImporter.ts.
- apps/backend/src/lib/s3-client.ts: add
findUnclaimableUploadUrls(urls): Promise<string[]> // unknown or already-claimed keys
assertUploadUrlsClaimable(urls): Promise<void> // throws ApiError 400 naming them
claimUploadUrls(urls): Promise<void> // Promise.allSettled, logs failures
replacing the fatal Promise.all(...claimUploadUrl) pattern.
- call sites: assert before the write, claimUploadUrls after:
admin createProduct:204 (allUploadUrls), updateProduct:298 (newImageUrls),
respondToReview:356, createProductTag:534, updateProductTag:600 (uploadUrls)
and user createReview:120 — there the existing contract is lenient (claim failures were already
swallowed), so it only logs the unclaimable keys before writing instead of throwing.
- upload_url_status is a write-only ledger (no readers, no cleanup job), so a claim failure never broke
an image; the fix targets the orphaned record + misleading 500.
No migration. No tests run.
[2026-10-10 20:35:00 +0530] A5/F5 option 1 implemented and verified live.
- repro (was: 500 "Failed to claim upload URL" + product created):
`createProduct` with a never-uploaded image -> 400
"These images were not uploaded through the app (unknown or already used):
product-images/999-nonexistent.png. Upload them again and retry."
product count 150 before and after; retrying the same name still reports the upload problem
(not "already exists"), so nothing was written.
- positive path: generated a real pending URL, created tag 12 with it -> success, imageUrl normalised
to https://assets2.freshyo.in/tags/1791639791557.png; reused the same URL for a second tag -> 400
"unknown or already used: tags/1791639791557.png" and no tag created; deleted tag 12 -> clean
(tag list back to the 9 legacy tags, no ZZ leftovers).
- replaced the fatal `Promise.all(...claimUploadUrl)` pattern at all six sites
(createProduct, updateProduct, respondToReview, createProductTag, updateProductTag, user createReview);
assertions run before destructive steps (updateProduct's deletedImageKeys cleanup and
updateProductTag's old-image cleanup now happen only after the new uploads validate).
- user createReview keeps its lenient contract: unclaimable upload URLs are logged, not rejected.
No migration. No tests run.
[2026-10-10 20:55:00 +0530] A6/F6 fix: reject out-of-scope constant keys instead of silently storing them, and allow null to delete a key.
Problem: each constant resolves from the table its scope names (CONST_SCOPE), but four endpoints
upsert into their own table without checking: superadmin.regions.updateBoundSettings /
updateRegionConstants and admin.region.updateBoundSettings / updateRegionConstants. Writing
`isFlashDeliveryEnabled` (region scope) through a bound endpoint returns {success:true,updatedCount:1},
stores a row nobody reads, and leaves the effective value unchanged (verified live; bound 1 still holds
a stray row from the E2E run). The region endpoints additionally dropped version keys silently.
Plan:
- apps/backend/src/lib/const-keys.ts: add assertConstantKeysInScope(keys, expected, endpoint) ->
ApiError 400 naming the correct endpoint per key (and rejecting version counters on region writes).
- packages/db_helper_sqlite/src/superadmin-apis/regions.ts: upsertBoundSettings/upsertRegionConstants now
delete the row when value === null and return { updated, deleted }.
- the four procedures call the guard first and return { success, updatedCount, deletedCount }.
Then clean up the stray bound row via value: null.
No migration. No tests run.
[2026-10-10 21:10:00 +0530] A6/F6 implemented and verified live.
Validation (all four endpoints) — wrong scope now returns 400 with the right endpoint named:
- superadmin.regions.updateBoundSettings + isFlashDeliveryEnabled -> "writes bound-scoped constants only:
isFlashDeliveryEnabled is a region constant — use updateRegionConstants" (was {success:true})
- ... + versionNum -> "... is a global constant — use the global constants endpoint"
- superadmin.regions.updateRegionConstants + deliveryCharge -> "... is a bound constant — use updateBoundSettings"
- admin.region.updateRegionConstants + products_version_num -> "... is a version counter owned by the
cache pipeline and cannot be set here" (was silently dropped)
- unknown key -> "... is not a known constant"
Legit writes still work on both the superadmin and staff endpoints:
bound + bound key -> {success:true,updatedCount:1,deletedCount:0}
region + region key -> {success:true,updatedCount:1,deletedCount:0}
Cleanup — stray row from the E2E run removed with value:null (allowed even for a wrong-scope key, so
mistakes can be deleted; scope is still enforced for writes):
admin.region.updateBoundSettings {boundId:1, settings:[{key:"isFlashDeliveryEnabled", value:null}]}
-> {success:true, updatedCount:0, deletedCount:1}; boundSettings no longer lists it; second call
-> deletedCount:0; essentialConsts unchanged (isFlashDeliveryEnabled false, deliveryCharge 20,
freeDeliveryThreshold 300, flashDeliveryCharge 69).
One bug found and fixed during verification: the delete branch used `.returning({ id })` but
region_consts/region_bound_consts have no id column (composite PK) -> "Cannot convert undefined or null
to object"; changed to `.returning({ key })`.
No migration. No tests run.
[2026-10-10 21:35:00 +0530] Add bound deletion (region deletion stays unsupported by design).
Context: A7 is not a defect (regions are not deletable), but bounds should be removable — and the RG-01
fixture bound 3 (region 2) is exactly what keeps a test region able to capture addresses.
Plan:
- packages/db_helper_sqlite/src/superadmin-apis/regions.ts: add deleteRegionBound(boundId) ->
{ found, deleted, regionId, addressCount, remainingBounds }. Refuses (deleted:false) when
addresses.boundId references it; otherwise removes its region_bound_consts rows and the bound row in one
transaction. (addresses.boundId is the only user-data FK to a bound, region_bound_consts.boundId the other.)
- apps/backend/src/lib/gen-store.ts: add deleteGenKvForBound(boundId) to drop the
essentialConsts_<boundId> KV blob of the removed bound.
- superadmin.regions.deleteBound {id}: 404 when missing, 409 naming the address count when in use,
else refreshGenKvForRegion + deleteGenKvForBound and return { success, deletedId, remainingBounds }.
- export deleteRegionBound via packages/db_helper_sqlite/index.ts and src/sqliteImporter.ts.
Verify with the region-2 fixture bound 3 (deletable) and the region-1 bound 2 (referenced by address 879 ->
409). No migration. No tests run.
[2026-10-10 21:55:00 +0530] Bound deletion, round 2: a region must always keep at least one bound.
Requirement (user): the UI must not let a bound be deleted when it is the region's only bound.
Plan:
- packages/db_helper_sqlite/src/superadmin-apis/regions.ts: deleteRegionBound now counts the region's
bounds first and refuses with `lastBound: true` when only one exists (no transaction run).
- superadmin.regions.deleteBound maps that to a 409: "Region <id>'s only bound cannot be deleted; a region
needs at least one bound so it can take orders."
- apps/superadmin-ui/src/lib/bound-rules.ts (NEW): MIN_BOUNDS_PER_REGION, canDeleteBound(boundCount) and
LAST_BOUND_HINT — the rule in one place so the UI and the test share it.
- apps/superadmin-ui/src/lib/bound-rules.test.ts (NEW): vitest cases — refuses the only bound (1), refuses
none (0), allows when another remains (2+). apps/superadmin-ui/package.json: add "test": "vitest run".
- apps/superadmin-ui/src/routes/regions.tsx: BoundSettingsEditor gains a "Delete bound" button, disabled
(with the hint as tooltip) when canDeleteBound(bounds.length) is false; on success it refetches the region
and surfaces server refusals (last bound / addresses in use) as an inline error.
No migration. No drizzle migrations run.
[2026-10-10 22:05:00 +0530] Add apps/superadmin-ui/vitest.config.ts (minimal) so `npm test` can run the bound-rule
test without loading the app's vite.config plugins (tanstack start / cloudflare / nitro are not needed for a
pure-logic test and are not resolvable from the hoisted node_modules here).
No other source files touched beyond the entries logged above.
[2026-10-10 22:15:00 +0530] Verified live:
- deleteBound {id:3} (region 2's only bound) -> 409 "Bound 3 is the only bound of region 2. A region needs
at least one bound so it can take orders."
- deleteBound {id:2} (region 1, referenced by address 879) -> 409 "Bound 2 is used by 1 address(es)."
- deleteBound {id:99999} -> 404.
- success path: created temp bound 4 in region 2 (priority 99) then deleted it ->
{"success":true,"deletedId":4,"remainingBounds":1}; region 2 is back to only bound 3 (temp row + its
bound consts gone); region 1 bounds 1/2 untouched; essentialConsts(bound 1) unchanged.
- UI test: `npx vitest run` in apps/superadmin-ui -> 1 file, 6 tests passed (ran by temporarily linking the
npx vitest cache into apps/superadmin-ui/node_modules because the app has no installed node_modules here —
link removed afterwards; with deps installed it is a plain `npm test`).
[2026-10-10 22:40:00 +0530] F9 fix 1: bound every catalogue/CDN request with an AbortController (90s) so a stalled
fetch can no longer pin the home pull-to-refresh spinner (or any query) forever.
Plan:
- apps/user-ui/src/lib/fetch-json.ts (NEW): JSON_FETCH_TIMEOUT_MS = 90_000, fetchJson<T>(url, timeoutMs?) that
runs axios.get(url, { signal }) under an AbortController armed for the timeout and cleared in `finally`,
plus isAbortError(error) for CanceledError/AbortError/ERR_CANCELED detection.
- apps/user-ui/src/hooks/prominent-api-hooks.ts: replace the five axios.get calls (products.json,
availability.json, stores.json, slots.json, store-with-products) with fetchJson; drop the axios import.
- apps/user-ui/utils/queryClient.ts: retry: (failureCount, error) => !isAbortError(error) && failureCount < 3
so a timed-out request surfaces instead of retrying 3 x 90s.
- apps/user-ui/src/trpc-client.ts: the custom fetch (used for every tRPC call, incl. the refetchConsts leg of
handleRefresh) gets the same 90s AbortController, forwarding any upstream signal.
No server changes. No migrations. No tests run.
[2026-10-10 22:50:00 +0530] F9 fix 1 implemented and verified.
Files: apps/user-ui/src/lib/fetch-json.ts (new), apps/user-ui/src/hooks/prominent-api-hooks.ts (5 call sites),
apps/user-ui/utils/queryClient.ts (retry skips aborts), apps/user-ui/src/trpc-client.ts (90s AbortController on
the shared fetch, forwarding the upstream signal).
Verification (the real helper bundled with esbuild, axios replaced by a faithful stub that turns an abort into
CanceledError/ERR_CANCELED; node http server with one instant route and one that never answers):
- JSON_FETCH_TIMEOUT_MS = 90000 (the requested cap)
- GET /fast -> resolves with the parsed JSON
- GET /stall with a 500 ms injected cap -> rejects after 504 ms, name CanceledError, isAbortError true
=> a hung request now fails at 90 s instead of hanging forever, so handleRefresh's `finally` runs and the
pull-to-refresh indicator clears
- isAbortError(new Error(...)) -> false (genuine failures are still retried 3x)
Not run here: the app's tsc/Metro build (apps/user-ui has no installed node_modules) and RN runtime behaviour.
AbortController is a platform global in RN 0.79 / Expo 53.
[2026-10-10 23:05:00 +0530] A11/F11 fix: per-variant out-of-stock, chosen from a BottomDialog in the admin app.
Plan:
- packages/db_helper_sqlite/src/admin-apis/product.ts: add
setProductSkusOutOfStock(regionId, productId, skuIds, isOutOfStock) ->
{ id, ignoredSkuIds, skus: [{id, name, isOutOfStock}], isOutOfStock } | null
(rejects skuIds that are not the product's; writes only those product_market_stats rows for the region;
leaves the existing all-variants toggleProductOutOfStock untouched).
- export it from packages/db_helper_sqlite/index.ts and apps/backend/src/sqliteImporter.ts.
- packages/shared/types/admin.ts: AdminToggleOutOfStockResult gains optional affectedSkuIds? and skus?.
- admin-apis/apis/product.ts toggleOutOfStock: input += skuIds? + isOutOfStock?; with skuIds it sets exactly
those variants (400 when a target state is missing or an id is not a variant), without skuIds it keeps the
current all-variants toggle. Availability cache is regenerated in both paths.
- NEW apps/admin-ui/src/components/VariantStockDialog.tsx: BottomDialog listing the variants with checkboxes
(select all / none) and two actions, "Mark out of stock" / "Mark in stock", calling the mutation with the
selected skuIds. Shows a partial-state note when variants disagree.
- apps/admin-ui/app/(drawer)/dashboard/products/index.tsx: the row's stock button now opens that dialog instead
of toggling blindly; the In/Out chip and the in-stock/out-of-stock filters/counters now use an aggregate over
all variants (In / Partial / Out) instead of only skus[0].
Verification: flip one variant of a real multi-SKU product out, assert the sibling stays in stock, then restore.
No migration. No drizzle migrations run.
[2026-10-10 23:20:00 +0530] A11/F11 implemented and verified (backend live; UI parse-checked only).
Verification (temp product 154 with SKUs 156/157, created for the test and soft-deleted afterwards):
- toggleOutOfStock {id, skuIds:[156], isOutOfStock:true} -> "Marked 1 variant(s) as out of stock (other
variants unchanged)", affectedSkuIds [156], aggregate isOutOfStock true, states (156:true, 157:false)
=> a single variant can be taken out while its sibling stays in stock (impossible before).
- toggleOutOfStock {id, skuIds:[157], isOutOfStock:false} -> both unchanged, targeting respected.
- toggleOutOfStock {id, skuIds:[999999], ...} -> 400 "These variants do not belong to product 154: 999999"
- toggleOutOfStock {id, skuIds:[156]} (no target) -> 400 "isOutOfStock is required when skuIds are given"
- toggleOutOfStock {id} (legacy) -> all variants out, pressing again -> all in (behaviour unchanged)
- admin.product.deleteProduct {154} -> "Product deleted successfully" (cleanup)
UI (apps/admin-ui): new VariantStockDialog (BottomDialog + Checkbox) opened from each row's Stock button; the
In/Out chip, the in-stock/out-of-stock filters and the counters now aggregate over all variants
(In / Partial / Out) instead of reading skus[0]. Both files parse with esbuild; the app itself was not built
or run here (apps/admin-ui has no installed node_modules in this environment).

View file

@ -1,6 +1,10 @@
# Freshyo cross-app E2E sanity and regression plan
Status: proposed checklist from code inspection; these cases have NOT been executed as part of this review.
Status: proposed checklist from code inspection. Partially executed since — see
`docs/test reports/e2e-sanity-test-results-2026-10-10-1310.md` and
`docs/test reports/e2e-sanity-test-results-2026-10-10-1650.md`, with the defect register in
`docs/test reports/e2e-errors-2026-10-10.md` and per-defect detail in
`docs/test reports/e2e-findings-2026-10-10.md`.
## Scope and approach
@ -19,6 +23,32 @@ A success toast alone is not proof. Check the result in the other app, and for
money/ownership tests also check authoritative API data. Do not mock the backend
in these E2E journeys. Mocked screen/component tests remain a separate layer.
### Assertion rules (apply to every case)
- **Money** — for any case that touches a total, assert the identity
`items − discount + fees = payable` on the *persisted* order payload, and again on the order-detail
response the customer/admin actually reads (not only the cart preview or the success screen).
- **Cache/config** — before asserting a served value, record the DB value and the served
version/timestamp so "stale" can be told apart from "wrong". A stale read inside the publication deadline
is not a defect; a stale read after it is.
- **Mutations** — assert the *absence* of unintended writes (row counts, name lookups, sibling rows), not only
the response body or a toast.
- **Failures** — a request that fails must leave no partial write; a request that is merely slow must not leave
any screen in a permanent loading state.
- **UI defects** — before filing one, confirm from the screenshot/hierarchy that the expected screen was really
open (a bottom sheet dims the background; no backdrop means it never opened).
### Fixture lifecycle (confirmed policies)
- **Regions cannot be deleted** (by design). Reuse one long-lived test region per environment, or neutralise a
throwaway one by renaming it and shrinking its bound polygon. Do not plan cleanup around region deletion.
- **Bounds are deletable** (`superadmin.regions.deleteBound`) but are refused when it is the region's only
bound or when addresses still reference it. A region must always keep at least one bound.
- **Deleting a product is a soft delete**: it disappears from catalog/cart/slots/availability while its rows
remain, so order history keeps the original product name and billed amount, and the name becomes reusable.
- **An address may exist without a bound** and is then served by the active bound for the region (see `G`/`BL`
cases); missing coordinates are an address-quality warning, not a bound error.
### Test fixtures
- Dedicated staging backend, DB, KV, assets, queues and notification destinations.
@ -52,6 +82,12 @@ in these E2E journeys. Mocked screen/component tests remain a separate layer.
add item, place COD order, find order by ID, cancel disposable order.
- Prefer stable `testID`/accessible labels, including dynamic IDs based on entity
IDs. Avoid percentage taps and matching the first product/address in a list.
- Form entry: type one field at a time with the repo pattern
(`tapOn` → `inputText` → `hideKeyboard` → `scrollUntilVisible` → `tapOn`), as in `tests/e2e/add-product.yaml`.
Never type into a field that may sit behind the keyboard; verify each field's value before the next.
- Stalled vs failed requests: catalogue/consts requests are capped at 90 seconds. A stalled request must
surface as an error/retry within that bound — an eternal spinner is a FAIL, and the report should say whether
the request was still pending. Retrying after an ambiguous failure must not create a duplicate.
- Wait for business state with a bounded deadline. Catalog regeneration is
debounced by roughly 30 seconds (`CacheCreator`), and constants polling is
60 seconds; allow a configurable staging deadline, initially 120 seconds.
@ -65,14 +101,18 @@ in these E2E journeys. Mocked screen/component tests remain a separate layer.
## Recommended daily sanity subset
Start with these 20 cases, reusing safe baseline fixtures where possible:
Start with these 24 cases, reusing safe baseline fixtures where possible:
`RG-01`, `RG-03`, `RG-06`, `AU-01`, `AU-02`, `PD-01`, `PD-02`, `PD-05`,
`DS-01`, `SL-01`, `SL-05`, `CT-01`, `CT-04`, `AD-01`, `AD-05`, `BL-01`,
`CP-01`, `OR-01`, `OR-04`, `FL-01`.
`CP-01`, `OR-01`, `OR-04`, `FL-01`, plus one case from each of the newer
high-yield classes: `P-01` (write atomicity), `Q-01` (config/cache propagation),
`R-01` (4xx contract), `S-01` (post-delete order history).
These cover startup, authentication, publication, region isolation, availability,
cart persistence, addresses/bounds, money, coupons, COD, fulfillment and flash.
cart persistence, addresses/bounds, money, coupons, COD, fulfillment and flash —
and now also the failure-atomicity, cache-propagation, error-contract and
destructive-lifecycle classes where real defects have been found.
Run the full checklist before release; mandatory API security checks should also
be a release gate. High-risk financial cases deserve priority even if slower.
@ -115,7 +155,7 @@ be a release gate. High-risk financial cases deserve priority even if slower.
| PD-02 | With P published in A, customer selects B; admin B opens product/store/slot lists and selectors. | P/A's store and slot do not appear anywhere in B. |
| PD-03 | Admin edits P's name/descriptions/features/variant image → customer refreshes list and detail. | Latest content is consistent in Home/search/store/detail; replaced images do not stay stale or break other variants. |
| PD-04 | Create duplicate product name, missing SKU features, missing store or nonpositive price → then submit valid product. | Invalid save is rejected without partial product/SKU rows; valid retry creates exactly one product. |
| PD-05 | Put P in customer cart → admin marks its SKU out of stock → customer refreshes → admin restores stock. | Unavailable state propagates, blocked item is not ordered/charged; restoration makes the SKU usable without reinstalling. |
| PD-05 | Put P in customer cart → admin opens the product's Stock dialog and marks **one** variant of multi-SKU P out of stock (leaving the other in stock) → customer refreshes → admin restores it. | Unavailable state propagates for that variant only; the sibling variant stays in stock and orderable; the product list shows it as *Partial*, not In or Out; restoration works without reinstalling. |
| PD-06 | Admin suspends or soft-deletes one SKU of multi-SKU P → browse/search/detail and existing cart. | Removed SKU is no longer purchasable; sibling SKU remains usable; no phantom payable cart line or crash. |
| PD-07 | Admin adds a third SKU → assigns it to a slot → later removes that SKU. | New variant is discoverable and orderable; removal does not corrupt old orders or remaining variants. |
| PD-08 | Admin changes regular/MRP/flash prices via Prices Overview → customer with P already in cart refreshes. | Availability-only publication updates card/detail/cart prices; flash uses flash price; B is unchanged. |
@ -191,8 +231,8 @@ regular/flash prices, and at least one two-slot cart. Equal fixture values can h
| BL-01 | Set bound delivery threshold T and fee D → order subtotal T−1, T and T+1 without coupon. | Same fee rule in floating bar, Cart, Checkout, success, persisted order and admin details; exact threshold boundary is correct. |
| BL-02 | Set regular minimum M different from free threshold T → try totals below M, between M/T and above both. | Intended minimum-order policy is explicit and enforced; free-delivery threshold is not accidentally replaced by minimum order. |
| BL-03 | Coupon lowers subtotal from above T to below T → repeat with post-coupon total exactly T. | Agreed pre/post-discount fee policy holds on client and backend, including boundary. |
| BL-04 | P/Q in S1/S2, paid delivery and coupon → place order → sum all generated order totals and fees. | One checkout creates expected slot suborders; total fee is charged only once, coupon is allocated correctly, summed total equals displayed To Pay. |
| BL-05 | Use noninteger prices/percentage discounts and several quantities → compare previews and persisted amounts. | Consistent rounding/currency precision; truncation in labels does not conceal overcharge or contradictory success totals. |
| BL-04 | P/Q in S1/S2, paid delivery and coupon → place order → sum all generated order totals and fees. | One checkout creates expected slot suborders; total fee is charged only once, coupon is allocated correctly, summed total equals displayed To Pay, **and the order-detail payload's item/discount/fee components reconstruct that same amount**. |
| BL-05 | Use noninteger prices/percentage discounts and several quantities → compare previews and persisted amounts. Include a **capped** percentage coupon and a multi-slot split (the cap is prorated per suborder). | Consistent rounding/currency precision; truncation in labels does not conceal overcharge or contradictory success totals; the discount reported by the order-detail endpoint equals the discount actually deducted for the same suborder. |
| BL-06 | Select A1 then A2, with visibly different charges/thresholds → repeat regular and flash checkout. | Correct bound's fees and nudges are used, including free crossed-out fee; no undefined/NaN/negative totals. |
| BL-07 | Customer opens Checkout → admin changes SKU price or selected-bound fee → submit. | No silent difference between quoted and authoritative total; agreed reprice/refresh/confirmation policy is followed. |
@ -225,7 +265,7 @@ regular/flash prices, and at least one two-slot cart. Equal fixture values can h
| OR-07 | Admin cancels pending order with reason → customer history/detail and next-order glimpse refresh. | Cancellation is attributed to admin and visible to customer; next-order summary no longer treats it as upcoming. |
| OR-08 | Try blank reason, second cancellation and cancellation after Delivered; cancel one of two slot suborders. | Invalid cancellations reject without duplicate refund records; other suborder stays intact. |
| OR-09 | Admin removes delivery charge from order → customer/admin details refresh. | Saved payable total and fee update together, exactly once; unrelated suborders stay unchanged. |
| OR-10 | Place order → admin changes prices → verify old order unchanged → run explicit Rebalance on chosen slot(s). | Normal catalog edits do not reprice historical orders; explicit rebalance affects only intended orders and preserves agreed fees/coupon allocations. Define eligibility for delivered/cancelled orders. |
| OR-10 | Place order → admin changes prices → verify old order unchanged → run explicit Rebalance on chosen slot(s). | Normal catalog edits do not reprice historical orders; explicit rebalance affects only intended orders and preserves agreed fees/coupon allocations — **after rebalancing, each touched order's stored total + delivery charge still reconcile to its items and coupon allocation**. Define eligibility for delivered/cancelled orders. |
| OR-11 | Create many A/B orders → exercise admin filters and pagination and customer My Orders pagination. | No missing/duplicate A orders due to B's high IDs; filters match actual statuses; customer sees own orders across regions with region labels. |
| OR-12 | Double-tap Place Order; simulate response loss after server commit → relaunch and retry only after checking history. | Exactly one intended order group; no duplicates or lost order; loading lock and reconciliation work. Backend idempotency is a requirement to verify, not assumed. |
@ -258,9 +298,9 @@ regular/flash prices, and at least one two-slot cart. Equal fixture values can h
| ID | Steps / journey | Required result |
|---|---|---|
| RC-01 | Customer already open while admin rapidly edits product/price/slot in A and B → wait/refetch discovery and catalog. | Final changes publish for both regions; one pending region does not overwrite another; clients do not mix catalog/availability/slot versions. |
| RC-02 | Cold-launch with saved cart/config and slow catalog/availability/slot responses; temporarily fail asset requests then restore network. | Recoverable loading/error state, no permanent zero-priced items, cart deletion or endless spinner. No offline order submission. |
| RC-02 | Cold-launch with saved cart/config and slow catalog/availability/slot responses; temporarily fail asset requests then restore network. Also **stall** (accept but never answer) one catalogue endpoint. | Recoverable loading/error state, no permanent zero-priced items, cart deletion or endless spinner; a stalled request must fail within the 90 s request cap and clear the loading indicator. No offline order submission. |
| RC-03 | In controlled staging, remove a bound's KV payload or return corrupt local config → customer opens region. | Backend rebuild/backfill and client cache recovery work; foreign bound's cached config is never reused. |
| RC-04 | Disconnect during product/image/address save and before/during order request → reconnect and inspect stored result before retry. | Error is recoverable; no half-uploaded published image, duplicate address/product/order, or false success. Distinguish precommit from postcommit request loss. |
| RC-04 | Disconnect during product/image/address save and before/during order request → reconnect and inspect stored result before retry. | Error is recoverable; no half-uploaded published image, duplicate address/product/order, or false success; **retrying an ambiguous failure reports the existing record instead of creating a second one**. Distinguish precommit from postcommit request loss. |
| RC-05 | Run critical customer/admin flows on iOS and Android; admin-web/customer-web in Chromium, including refresh/direct links/back. | Same business results with platform-specific storage, permissions, pickers and routing. Web is a separate implementation, not assumed equivalent because APIs are shared. |
| RC-06 | Superadmin changes supported internal version/store URLs → open older/newer app builds; cancel image/location permissions and retry. | Update behavior matches version policy and OS URL; permission denial is recoverable. Verify regional support/welcome text rather than hardcoded Mahabubnagar copy in B. |
@ -296,6 +336,69 @@ online payment/refund journeys as supported or passing today.
| PAY-04 | Paid customer order cancellation → admin partial/full refund → gateway settles → customer views status; retry refund. | Amount never exceeds collected payment, authorization enforced and no duplicate refund; COD does not enter online-refund flow. |
| PAY-05 | Forged signature, another customer's merchant order ID, duplicate callback and mismatched amount/currency. | Backend rejects forged/foreign payment, verifies authoritative ownership/amount and handles callbacks idempotently. |
## P. Write-path integrity, atomicity and idempotency
Every case here asserts the **absence of unintended writes** on failure, using row counts, name lookups and
sibling rows — not just the response. These come from defects where a request failed *after* committing.
| ID | Steps / journey | Required result |
|---|---|---|
| P-01 | `createProduct` where one image URL is valid and the other was never uploaded (previously: 500 "Failed to claim upload URL" with the product already stored). | 4xx naming the offending key; **no** product/SKU/market-stats rows exist (verify by name lookup and counts); retrying with the same name does not report "already exists". |
| P-02 | `updateProduct` with a bad new image while also deleting an old image. | Rejected before any change: old images still present, name/prices/variants unchanged. |
| P-03 | Bad upload URL on tag create, tag update, review create and review response. | Target row absent (tag/review not created, tag not modified) and the old image cleanup has not run. |
| P-04 | Double-submit each admin create form (rapid double tap) and retry after an ambiguous 5xx. | Exactly one record; the second attempt returns a clean conflict/validation error, never a duplicate. |
| P-05 | Kill the client mid-save (background the app, force-quit, or abort the request). | Either nothing was written or the record is complete — never a half-created product/tag/slot/address; the UI recovers on relaunch. |
| P-06 | Delete a tag/group/banner whose stored image cannot be cleaned up (missing or malformed object key). | The DB delete still happens (cleanup failure is logged, not fatal); no undeletable row remains. |
## Q. Config and cache propagation (same region)
Publication of a write to the customer app is a first-class assertion. Record the served
version/timestamp and the DB value so *stale* and *wrong* can be distinguished; the staging deadline is 120 s.
| ID | Steps / journey | Required result |
|---|---|---|
| Q-01 | Admin marks a future slot full (and later clears it) → customer slot list, product next-delivery and checkout slot picker. | The change reaches every surface inside the deadline; the served catalogue version advances; the slot cannot be selected anywhere while full, and reappears after clearing. |
| Q-02 | Write a region-scoped key through `updateRegionConstants` (must take effect) and through the bound-settings endpoint (must be rejected). | Correct endpoint changes the effective value; wrong endpoint returns 4xx naming the right endpoint and stores no stray row; the resolved payload contains the value from its own table. |
| Q-03 | Change a bound's charge/threshold → floating bar, cart, checkout and the next order. | All surfaces and the next order use the new fee after the deadline; a stale value after the deadline is a FAIL with the version evidence attached. |
| Q-04 | Create/edit a tag image (fresh upload) → customer tag surface and the tag list. | The stored image reference is a key/normalised URL: no double asset-domain prefix, no `%3F…` leftovers; the image request returns 200; deleting the tag succeeds. |
## R. API contract enforcement
UI filtering is not protection. These cases call the API directly and assert the *shape* of failures.
| ID | Steps / journey | Required result |
|---|---|---|
| R-01 | Trigger each business rejection directly: out-of-stock SKU, full slot, delete store with products, delete default address, delete the region's only bound, address attached to an ongoing order. | 4xx with the specific message (not 500/INTERNAL_SERVER_ERROR); the resource is unchanged. |
| R-02 | Send unknown keys, out-of-scope keys, wrong-type values and foreign ids to product/tag/slot/order/const mutations. | 400 that names the offending key/id; no partial write and no misleading `success: true`. |
| R-03 | Multi-SKU product P: mark one variant out of stock via the API, then order it and its sibling. | Only the targeted variant is refused; the sibling still orders; the persisted product state matches the per-variant call. |
| R-04 | Repeat identical deletes/toggles/cancellations twice. | Idempotent or a consistent 404/409 (never a 500, duplicate side effect, or resurrection of the row). |
## S. Destructive lifecycle and post-delete semantics
| ID | Steps / journey | Required result |
|---|---|---|
| S-01 | Create product P, order it (COD), then admin deletes P → customer catalog/cart/slot/availability and the historical order detail. | P disappears from every live surface; the old order still shows the original product name and billed amount; P's name can be reused for a new product; deleting again is a clean 404/conflict. |
| S-02 | Delete a tag with products/images, a group with members, a banner with images, and a slot assigned to a product. | Either the children are handled (cascade) or the response is a clear 4xx naming the dependency; no orphan child rows remain in any case. |
| S-03 | Delete the only bound of a region, then delete a bound that an address references. | Both refused with a clear message; the region keeps taking orders and the existing address/bound still resolves. |
| S-04 | Attempt region deletion (superadmin) and then neutralise a throwaway region (rename + shrink its bound polygon). | Region deletion is not available (by design); the neutralised region stops capturing addresses and its customers are unaffected. |
| S-05 | Suspend and soft-delete a product and a variant, then reopen past orders, invoices and admin order detail. | Historical orders render unchanged (names, amounts, packaging state); only live surfaces change. |
| S-06 | Delete a store that still has products; delete a product's last remaining variant; delete an address used by an open order. | Each refused with the specific blocker and no partial delete of related rows. |
## T. Permanent regression seeds for fixed defects
One permanent row per fixed defect so a regression is caught by the daily subset, not by chance.
| ID | Steps / journey | Required result |
|---|---|---|
| T-01 | Delete a product that has order history, then open that order. | Soft delete semantics: hidden from live surfaces, original name/amount still rendered, name reusable. |
| T-02 | Create a tag with a freshly uploaded image, read it back, then delete the tag. | Normalised image reference and a successful delete (no "Failed to delete image"). |
| T-03 | `createProduct` with a never-uploaded image. | 4xx and no product/SKU rows (formerly a 500 with an orphan). |
| T-04 | Write a region-scoped const key through the bound endpoint. | 4xx naming the correct endpoint (formerly `success: true` with no effect). |
| T-05 | Mark one variant of a multi-SKU product out of stock. | Sibling stays orderable (formerly both flipped). |
| T-06 | Request the slot list for region A. | Only region A's future, orderable slots are returned (formerly every region, including past ones). |
| T-07 | Stall one catalogue/consts request. | Fails within the 90 s cap and clears the loading state (formerly an eternal spinner). |
| T-08 | After a region switch, open the region sheet from the home bar. | Sheet opens with the region list (formerly a spinner/no-op path). |
## Code observations that should influence priority
These are static observations, not executed bug reports. Where desired behavior
@ -338,8 +441,44 @@ is not yet defined, agree the contract rather than write a test that endorses a
placement (automatic login route and checkout address selection), and needs
alignment with current Cart/Me login walls and read-only Checkout. Add
regional selection and persisted-order/admin assertions.
9. **Writes that fail after committing.** Several endpoints perform the DB write first and a follow-up step
(upload-URL claim, image cleanup, KV mirror) afterwards, so a failing follow-up used to abort the request
with the row already stored (product, tag, review). Pre-validate, then write, then treat follow-ups as
best-effort — see section `P`.
10. **"Delete" means different things per entity.** Product deletes are soft (rows kept for order history and
the name freed for reuse); tags/groups/banners/slots delete rows but must not be blocked by image cleanup;
bounds delete but never the last one and never while referenced; regions cannot be deleted at all. Cases
must assert the agreed semantics, not a generic "it is gone" — see `S`.
11. **Config writes can be silently ignored.** Each constant is resolved from its own table, but the write
endpoints accept any key, so a wrong-scope write returns success and changes nothing (and leaves a stray
row). Scope validation now rejects those; keep a case for it — see `Q-02`/`R-02`.
12. **Request lifetime matters as much as correctness.** Catalogue/consts requests have no natural bound, and a
request that hangs leaves loading states (e.g. the home refresh indicator) alive indefinitely. A 90 s
AbortController cap is in place on the customer app; assertions must distinguish *stalled* from *failed* —
see `RC-02`/`T-07`.
13. **Stock granularity is per SKU per region.** The all-variants toggle cannot express one variant being out
and destroys a partial state; the admin app now chooses variants in a stock dialog. Assert per-variant
behaviour and the sibling staying orderable — see `PD-05`/`R-03`.
## Policies to settle before turning every row into a hard assertion
## Policies settled (assert these; do not re-litigate)
- **Regions are not deletable** — by product decision. Bounds *are* deletable, refused when it is the region's
only bound or when addresses reference it.
- **An address may exist without a bound** and is then served by the active bound: the least-priority bound
among the customer's addresses in that region, else the region's effective (lowest-priority) bound. Missing
coordinates are an address-quality warning, not a bound error.
- **Product deletion is a soft delete** — the product leaves live surfaces but its rows stay, so order history
keeps the original name and billed amount, and the name becomes reusable.
- **Money basis** — the coupon discounts the item subtotal; the free-delivery threshold is decided on the
post-discount subtotal; the delivery fee is added after the discount. Order-detail components must reconstruct
the paid amount (see `BL-04`/`BL-05`).
- **Constant scope** — every key belongs to one table (global/region/bound/legacy); writes through the wrong
endpoint are rejected, never silently accepted.
- **Slot listing** — the customer slot list is region-scoped and future-only (a frozen slot is not orderable).
- **Request cap** — the customer app aborts catalogue/consts requests after 90 seconds so a stalled request
surfaces instead of hanging.
## Policies still open before turning every row into a hard assertion
- Is `minRegularOrderValue` a hard order minimum or only informational? Which
subtotal controls free delivery: pre- or post-coupon?
@ -356,8 +495,7 @@ is not yet defined, agree the contract rather than write a test that endorses a
- Do cancelled first orders restore first-order coupon eligibility?
- Are customer/admin notifications regional or intentionally global? Current
broadcast/admin-notify paths should not be assumed regional by UI labels.
- How are missing address coordinates, overlapping regions and legacy null
region/bound addresses handled?
- How are overlapping regions handled (legacy null region/bound addresses are now settled above)?
Keep these as explicitly named policy checks; do not silently mark ambiguous
behavior PASS. Recommended report columns: **case, platform, run ID, status

View file

@ -166,15 +166,50 @@ Maestro `permissions: { location: allow }` is rejected on iOS
(`wrong argument value 'allow'`). Handle the OS permission alert manually, or rely
on the already-granted permission in the dev build.
### 4.8 Simulated location
### 4.8 Simulated location (change it from the CLI)
Set the iOS simulator's GPS location with `xcrun simctl location` — no Xcode UI,
no Maestro flow. The device is addressed by UDID, or the literal `booted` for the
currently booted sim:
```bash
xcrun simctl location <device_id> set 16.7489,77.9856 # inside region A
xcrun simctl location <device_id> set 0.0,0.0 # outside every bound
xcrun simctl location <device_id> list # scenarios
xcrun simctl location booted set 16.7489,77.9856 # inside region A (Mahabubnagar)
xcrun simctl location booted set 0.0,0.0 # outside every bound
xcrun simctl location booted set 17.3850,78.4867 # inside region B (Hyderabad) — if its polygon exists
```
A location outside all bounds keeps the saved region (no hang) — good for RG-04.
There is no continuous region tracking while the app is open; resolution is a
one-shot startup check.
`set <lat>,<lon>` is the everyday command. The full action list:
| Action | What it does |
|---|---|
| `set <lat>,<lon>` | Pin a fixed coordinate (persists until changed/cleared). |
| `clear` | Stop any scenario and remove the simulated location (device falls back to none). |
| `list` | List built-in simulation **scenarios** (e.g. City Run, Freeway Drive, custom). |
| `run <scenario>` | Run a named scenario from `list`. |
| `start [--speed=<m/s>] [--distance=<m>|--interval=<s>] <lat,lon> <lat,lon> …` | Walk through waypoints, interpolating over time (≥2 waypoints; `-` reads from stdin). Good for a GPS "move across bounds" / region-race test. |
```bash
xcrun simctl location booted clear # reset before/after a test
xcrun simctl location booted list # see scenarios
xcrun simctl location booted run 'City Run' # simulate movement
# move A → B over ~5 min, an update every 250 m:
xcrun simctl location booted start --speed=20 --distance=250 16.7489,77.9856 17.3850,78.4867
```
Notes:
- **Format:** decimal separator must be `.`, field separator `,` (`16.7489,77.9856`);
do not use a locale comma-decimal or a space.
- **Availability:** the `location` subcommand needs a recent Xcode (present on
Xcode 16.4 here). Confirm with `xcrun simctl help | grep -i location`; if it is
missing, use Xcode → Simulator → **Features ▸ Location** (GUI) instead.
- **Target the right sim:** if more than one is booted, `booted` is ambiguous — use
the UDID from `xcrun simctl list devices booted` (or `tools.maestro.list_devices()`).
- **Persistence:** the setting survives app relaunch, so it must be set *before*
the app's startup region resolution. `clear` restores "no location" — do this
after a location-dependent test so later runs are not biased.
- A location outside all bounds keeps the saved region (no hang) — good for RG-04.
- There is no continuous region tracking while the app is open; resolution is a
one-shot startup check, so change location then **relaunch** to re-resolve.
---

View file

@ -0,0 +1,114 @@
# Freshyo E2E — complete error log (run 2026-10-10 16:30 IST)
Every error, failure, rejection and exception observed during the run (and during the setup work in
the same session), with the exact message, where it came from, whether it is an **app/API defect**, a
**harness limitation**, or **my own input**, and what happened next.
Companion files: `e2e-sanity-test-results-2026-10-10-1650.md` (case outcomes),
`e2e-findings-2026-10-10.md` (curated defects F1–F14).
Counts: **18 app/API defects** (A) · **9 API-contract/validation errors caused by my inputs** (B) ·
**3 response quirks that are not defects** (C) · **11 harness/tooling errors** (D) ·
**7 mistakes of mine in scripts/inspection** (E) · **4 false alarms retracted** (F).
---
## A. App / API defects reproduced in this run
| # | Where / trigger | Exact message | Root cause | Ref |
|---|---|---|---|---|
| A1 | `admin.product.deleteProduct {id:152}` and `{id:151}` (region 1) | `Failed query: delete from "product_info" where ("product_info"."id" = ? and "product_info"."region_id" = ?) returning "id", … params: 152,1` → HTTP 500 `INTERNAL_SERVER_ERROR` | D1 enforces FKs; `product_skus.product_id` (NOT NULL, `ON DELETE no action`) still referenced the row. Fixed as a soft delete — see F1 | **FIXED 2026-10-10 18:26** (soft delete) |
| A2 | Order #2495 (₹473.6 payable = ₹304 items − ₹30.4 coupon + ₹200 fee, coupon 10 %) | both order-detail APIs reported `discountAmount: 47.36` while the charge applied `₹30.4` | Discount is recomputed at read time on the wrong base: read paths used `order.totalAmount` (473.6, the paid total) instead of the items subtotal (304) | **FIXED 2026-10-10 18:47** (both paths now report 30.4) |
| A3 | `updateSlotCapacity {slotId:2033,isCapacityFull:true}` then app → product → `ADD TO CART` | UI: slot `Sun, 11 Oct • 7-8 PM` still listed, checkbox enabled, `Add to Cart` accepted (bar `₹199 • 1 Item`) | Three disagreeing slot sources: `AddToCartDialog` reads the cached `slots.json` at a version pointer stuck at 13 (`essentialConsts` KV blob) while newer files exist; checkout's `user.slots.getSlots` returned an unfiltered multi-region list; only `user.cart.getCartSlots` (live DB) and `placeOrder` filter capacity. The app never reads `isCapacityFull` | F3 (open; `getSlots` scoping **FIXED 2026-10-10 19:20**; stale-pointer part closed as KV delay, by decision) |
| A4 | `admin.product.createProductTag` with a presigned `imageUrl`; read back via `getProductTags` then `deleteProductTag {id:10}` | read returns `"imageUrl": "https://assets2.freshyo.in/https://da9b1aa7…r2.cloudflarestorage.com/meatfarmer-dev/tags/…?X-Amz-…"`; delete → `Failed to delete image` (500) and tag 10 still exists | Write stores the caller's string verbatim (`createProductTag`/`updateProductTag`), reads run `scaffoldAssetUrl` which blind-prefixes the assets domain, and delete passes that same string to `deleteImageUtil` as an object key → S3 rejects, the mutation throws before the row is deleted. Legacy tags 1/4 are already corrupted in the same way (`…jpeg%3FX-Amz-…`) | **FIXED 2026-10-10 20:00** — normalise on write, idempotent scaffolding, non-fatal image cleanup; legacy tags 1/4 images cleared pending re-upload |
| A5 | `admin.product.createProduct` with a never-uploaded image URL | `Failed to claim upload URL` (500) — but product **151 + 2 SKUs were created** | Claim runs after the insert transaction commits and is unguarded (`claimUploadUrl` throws when no `pending` row exists for the key). Same pattern at 6 sites: createProduct/updateProduct/respondToReview/createProductTag/updateProductTag + user createReview. `upload_url_status` has no readers, so the image itself is fine — the damage is the orphaned row, the misleading 500 and the retry collision | **FIXED 2026-10-10 20:35** — validate the upload URLs before the write (400 naming the keys), claim afterwards without failing the request |
| A6 | `superadmin.regions.updateBoundSettings {boundId:1,settings:[{key:"isFlashDeliveryEnabled",value:"true"}]}` | `{"success":true,"updatedCount":1}` yet `essentialConsts.isFlashDeliveryEnabled` stays `false`; a stray `isFlashDeliveryEnabled:"true"` row now sits in bound 1's settings | Neither superadmin const endpoint validates key scope: `scaffoldEssentialConsts` resolves each key from its own table (`isFlashDeliveryEnabled` from `region_consts`) and never reads bound rows wholesale, while `updateBoundSettings`/`updateRegionConstants` upsert any key into their own table. `CONST_SCOPE` exists and is enforced by `admin.const.updateConstants` only. The superadmin UI is scope-correct, so this traps scripts/agents (mirror case: bound keys into `region_consts`) | **FIXED 2026-10-10 21:10** — `CONST_SCOPE` validation in all four const endpoints (400 naming the right endpoint); `value: null` now deletes a row, so the stray bound row was removed |
| A7 | `superadmin.regions.delete {id:2}` | `No procedure found on path "superadmin.regions.delete"` (404) — no region/bound delete and no region status flag; region 2 stays in `common.listRegions` | **Not a defect** — deleting a region is not an allowed action (confirmed by the product owner). The consequence is process-level: the test plan's RG-01 cleanup step is unactionable and a created region is permanent/customer-visible, so fixtures should reuse one long-lived test region or be renamed and have their bound polygon shrunk. **Bounds are deletable** (`deleteBound`, added 2026-10-10 22:15) subject to two guards: not the region's only bound, and no address referencing it | F7 (by design) |
| A8 | `user.address.createAddress` without lat/lng (fresh customer 1314, first address); then the app's own `+ Attach Current Location` flow; then the active-bound rule for a mixed address set | create → `{id:881, boundId:null}`; attach-location (coords only) → coords set, `boundId` still null. Active bound observed live: with the user's only bounded address on bound 2, `common.activeBound` returns **2** while region 1's least-priority bound is **1** | **Not a defect (by design, confirmed 2026-10-10):** an address may exist without a bound and is served by the active bound (`common.activeBound` = least-priority bound of the user's addresses in the region, region's effective bound when they have none); `placeOrder` uses `params.boundId ?? getEffectiveBoundId(regionId)` and verifies the bound belongs to the region. Kept for reference only: the charge for a bound-less address follows the client's `params.boundId`, and `orders` has no `boundId` column | F8 (by design) |
| A9 | Home screen, region-switch attempts (customer app) — captured 5:02/5:02/5:03 | endless centred spinner **above the `DELIVER TO` bar**, no sheet and no backdrop, content fully loaded; `common.listRegions` answered normally over curl; cleared only by relaunch | Re-read from the screenshots (not the reported cause): this is the home list's `RefreshControl` (`home/index.tsx:758-764`), whose `isRefreshing` state (`:504`) is cleared only when all four refetches in `handleRefresh` (`:603-621`) settle. `products/stores/slots.json` are fetched with plain `axios.get(cacheUrl)` with **no timeout** (`prominent-api-hooks.ts:160-171`) under a query client with `retry: 3` and no fetch timeout, so one hanging request pins the spinner until relaunch. The region sheet was **never open** in those captures (a presented `BottomDialog` dims the screen with `rgba(0,0,0,0.3)`), so the original "region sheet hangs" wording was a misread of the harness screen. Separately confirmed by code: the region gate can strand forever on `LoadingScreen("Finding your region...")` when location is denied and no region is saved (`useRegion.ts:180-191`), with `refreshLocation` wired nowhere | F9 |
| A10 | Add-Product form on iOS via Maestro testIDs | Product Name ended up `E2E Sanity 1655n500 g199249 1 kg`; variant quantity/price fields left empty; keyboard never dismissed | **Not an app defect (harness/flow).** `MyTextInput` is a passthrough to react-native-paper's `TextInput` with no focus logic (`packages/ui/src/components/textinput.tsx`), and the repo's own `tests/e2e/add-product.yaml` shows the required pattern (`inputText` → `hideKeyboard` → `scrollUntilVisible` → tap per field). My exploratory flow skipped that, so with the keyboard up the lower fields sat behind it, taps hit the keyboard, focus stayed on Product Name and every `inputText` appended there. Minor genuine gap kept in the report: `ProductForm` is a bare `ScrollView` and admin-ui has no `KeyboardAvoidingView`/auto-scroll | F10 (reclassified) |
| A11 | `admin.product.toggleOutOfStock {id:152}` then `placeOrder {skuId:153}` and `{skuId:154}` | both rejected: `Product 153 is unavailable`, `Product 154 is unavailable` | Stock lives per SKU per region (`product_market_stats.is_out_of_stock`), but `toggleProductOutOfStock(regionId, productId)` writes one computed value to **all** of the product's SKU rows for the region — no `skuId` input. PD-06 (one variant out) is only expressible via `updateProduct`/`createProduct` (or the global-product form), and the toggle collapses a partial state (one out + one in → press 1 = all in, press 2 = all out). The admin list switch reads only the default SKU, so a partially-out product can show as in stock | **FIXED 2026-10-10 23:20** — `toggleOutOfStock` accepts optional `skuIds` + `isOutOfStock` (per-variant, validated) while `{id}` alone keeps the all-variants toggle; the admin app picks variants in a new `VariantStockDialog` (BottomDialog) and the row chip/filters/counters now aggregate over all variants (In / Partial / Out) |
| A12 | All business rejections (OOS, full slot, guards) | HTTP **500** `INTERNAL_SERVER_ERROR` with a correct message — e.g. `Selected delivery slot is at full capacity…`, `Cannot delete a store that still has products…`, `Address is attached to an ongoing order…`, `Cannot delete default address…` | ApiError statuses flattened to 500 | F12 |
| A13 | My Orders list for delivered order #2495 | `SHIPPING STATUS: success` (detail screen shows `DELIVERED`) | Internal status string rendered in the list | F13 |
| A14 | Cart, first selection of the A2 address | screen rendered `Your cart is empty / Looks like you haven't added anything…` with A2 checked; the same cart came back with the A2 fee on the next attempt | Unconfirmed client flap | F14 |
| A15 | `common.essentialConsts?boundId=1` with a **staff** token | values came back `null` (`products_version_num: null`, `deliveryCharge: null`) while the same call with a superadmin token returned real values | Mixed/absent tenant resolution for staff context on a customer-facing endpoint | — |
| A16 | `pi mcp list` in the project | `…/freshyo/.pi/mcp.json is ignored because the project is not trusted` although `~/.pi/agent/trust.json` contains `{"/Users/…/freshyo": true}` | Trust decision honoured by sessions but not by the shell subcommand | — |
| A17 | Maestro MCP handshake against `maestro mcp` | `{"code":-32601,"message":"Server does not support resources/list"}` | Server advertises tools only — informational, listed for completeness | — |
| A18 | `maestro mcp --help` | `Unknown option: '--help'` + usage text | CLI accepts no help flag | — |
## B. Errors caused by my inputs (API contract / validation)
| # | Call | Exact message | What I did wrong / fix |
|---|---|---|---|
| B1 | `superadmin.regions.updateBoundSettings {"bounds…","settings":{…}}` | zod: `expected: "array", code: "invalid_type", path: ["settings"], "Invalid input: expected array, received object"` | `settings` is an **array** of `{key,value}` — corrected and retried |
| B2 | `user.order.getOrderById {"orderId":2495}` | zod: `expected: "string"`, path `orderId`, `Invalid input: expected string, received number` | this endpoint takes the id as a **string** (`"2495"`) |
| B3 | `admin.order.updatePackaged {"orderId":2495}` / `updateDelivered {"orderId":2495}` | same zod string/number error | ids are strings for these mutations |
| B4 | `admin.order.getAll {"flashDeliveryFilter": true}` | zod: `invalid_value`, `values: ["all","flash","regular"]`, path `flashDeliveryFilter` | the filter is an **enum**, not a boolean. With `"flash"` it correctly returned orders 2496/2474/2473 — **my earlier "filter defect" claim is retracted** |
| B5 | `superadmin.staff.create` (region B admin) | `"Unexpected token '}', ...\"regionId\":}\" is not valid JSON"` | my shell variable for `regionId` was empty (bad jq path) → invalid JSON body |
| B6 | `admin.product.updateProduct` for the region-2 product | `Store belongs to a different region` (500) | I passed region-1 `storeId:1` for a region-2 product; must use store 12 (and later the staff-B token was already deleted) |
| B7 | `superadmin.staff.remove {"id":12}` | `Staff user not found` (500) | wrong id — the created staff was id **7**; removed correctly afterwards |
| B8 | `admin.staff.list`, `user.address.list`, `user.addresses.list`, `user.address.getAddresses`, `common.getRegions`, `common.regions`, `common.regionList`, `user.region.list` | `No procedure found on path "…"` (404) | guessed procedure names; correct ones are `admin.staffUser.*`, `user.address.getUserAddresses`, `common.listRegions` |
| B9 | `admin.staffUser.login {name:"e2eadminA"}` (first attempt) | `UNAUTHORIZED` (401) | the 13:10 fixture staff no longer existed — expected, not a defect |
## C. Response quirks that are **not** defects
| # | Observation | Why it is not a bug |
|---|---|---|
| C1 | `GET /` → 404; `superadmin.regions.list` without a token → 401 | expected for a tRPC-only worker and an authenticated procedure |
| C2 | `admin.order.getOrderDetails {orderId:2495}` with the **region-B** token → `Order not found`; `admin.product.getProductById {id:152}` with the B token → `Product not found` | correct cross-region isolation (SEC-02/OR-01 evidence) |
| C3 | Cart moves the ₹20 delivery fee back on **after** a coupon drops the subtotal below ₹300; "Add products worth ₹26 for free delivery" | internally consistent post-discount policy (the discrepancy is in what gets *persisted* — A2) |
## D. Harness / tooling errors
| # | Where | Exact message | Cause / workaround |
|---|---|---|---|
| D1 | `run` without an `appId` header | `Failed to run flow: Config Section Required at /var/folders/…/maestro-flow….yaml:1:1` | flows need `appId: …` + `---`; fixed each time |
| D2 | `run` while a second `maestro mcp` server was attached | `Failed to run flow: Device became unreachable during viewHierarchy` | two MCP servers (opencode's + mine) competing for the same iOS driver; killed my orphans and switched to `detached: true` + `killpg` |
| D3 | `tapOn: "Home"` in a flow | `Failed to run flow: Element not found: Text matching regex: Home` | Maestro text matching is **full-string regex**; the tab node is `Home, tab, 1 of 5` → use `"Home, tab, 1 of 5"`, `"Home.*"` or a point tap |
| D4 | `assertVisible: "DELIVER TO"` | `Failed to run flow: Assertion is false: "DELIVER TO" is visible` | the customer home is one a11y node with `txt: ""`; fragments of the concatenated blob never match |
| D5 | Long chained flow (region switch with two waits + 45 s `extendedWaitUntil`) | `Error: MCP request timed out after 60000ms` (codemode `Script failed`) | per-request MCP ceiling is 60 s; flows must be split or `timeout` raised in `.pi/mcp.json` |
| D6 | `run` on the flash flow | `Failed to run flow: Assertion is false: ".*Order Placed Successfully.*" is visible` | my `Checkout`/`Place Order` coordinates were stale (screen had grown); retried at 72 %,77 % and 50 %,69 % |
| D7 | Reusing `clearState` to log out | *(no error raised)* the session simply survived | `launchApp: {clearState:true}` is a no-op on iOS; log out through the UI |
| D8 | After the first region switch, `DELIVER TO` taps | *(no error raised)* endless spinner, sheet never opens | see A9; workaround = relaunch the app |
| D9 | Killing my helper client | orphaned `java … maestro.cli.AppKt mcp` processes remained (driver contention) | SIGTERM to the `maestro` wrapper does not kill the JVM; spawn detached and kill the process group |
| D10 | `pi --approve mcp list` | *(no error raised)* it started a full agent session with the prompt "mcp list" instead of listing servers | put flags after the subcommand; it did prove the MCP server was reachable |
| D11 | `curl …/superadmin.regions.bounds` (bounds of region 1) | response body cut mid-JSON in my capture (`{"id":2,…` truncated by my own `head -c`) | display artefact only |
## E. Mistakes of mine in scripts/inspection (no product impact)
| # | Where | Exact message | Fix |
|---|---|---|---|
| E1 | codemode script | `TypeError: tools.describeNamespace does not exist. Available: read, bash, …, mcp__maestro__*` | in codemode, MCP tools are `tools.mcp__maestro__run(...)` etc.; namespace description is not exposed |
| E2 | codemode script with `dev.structuredContent?.devices ?? JSON.parse(...)` | `TypeError: not a function` | `list_devices` returns only `content[0].text` as JSON — parse that instead |
| E3 | codemode script using `typeof ''.includes` inside a single-quoted string | `SyntaxError: Unexpected string` | quoting bug in my own probe |
| E4 | codemode script | `TypeError: cannot read property 'slice' of undefined` | guarded the optional field afterwards |
| E5 | codemode options line typo | `@options must be valid JSON with supported fields 'max_output_tokens' and 'timeout_ms': Expected ':' after property name…` | corrected JSON |
| E6 | `sqlite3 apps/backend/dumps/latest.sqlite "select … from regions"` | `Error: in prepare, no such table: regions` | that dump is not the live DB; no SQLite ground truth is reachable (`.wrangler/` empty; `find` over `~/Library` timed out at 180 s) |
| E7 | `cat ~/.nvm/alias/lts` (unrelated shell work) | `cat: …/alias/lts: Is a directory` (exit 1) | it is a directory of LTS codenames, not a file |
## F. Retracted / false alarms (kept so nobody re-chases them)
| # | Earlier claim | Verdict |
|---|---|---|
| F1 | "`admin.order.getAll {flashDeliveryFilter:true}` returns nothing → filter defect" | **Not a bug.** The schema wants `"all" | "flash" | "regular"`; with `"flash"` it returned orders 2496, 2474, 2473. My boolean input produced a zod error that my jq rendered as `[]` |
| F2 | "Selecting the A2 address wipes the cart" | **Unconfirmed.** The empty-cart render occurred once; the very next attempt kept both lines and the coupon. Logged as A14 |
| F3 | "`common.essentialConsts` is broken" | **Wrong.** It returns data for a superadmin token; the `null` payload was reproduced only with a staff token (A15) |
| F4 | "`admin.store.deleteStore` is broken" | **Not a bug.** Both stores refused with `Cannot delete a store that still has products…` — correct guard; my fixtures simply still had products (and products cannot be deleted because of A1) |
## Cross-reference: which case IDs these errors affected
`RG-01` (A7) · `RG-06`/`AD-05` (A9, A14) · `PD-01` (A5, A10) · `PD-13` (A1, F4) · `SL-05` (A3, A12) ·
`CP-01`/`BL-01`/`BL-03`/`BL-04` (A2) · `DS-01` (A4) · `AD-01`/`AD-04` (A8) · `OR-01`/`OR-04` (A13) ·
`FL-01` (A6) · `PD-06`/`PD-11` (A11) · all API cases (A12) · whole run (D1–D11).
## Data still stranded because of A4 (A1 fixed, A7 by design)
Region 2 + bound 3 (**by design — region deletion is not an allowed action**) · stores 11 and 12 ·
region-2 product 153 · customer `9000011715` + default address 880 · address 879 (tied to order #2495) ·
slots 2033/2034 (deactivated) · orders #2495 (delivered), #2496 (flash, pending). Everything else was
restored: staff B removed, coupon 43 invalidated, flash `false`, bound-1 constants 300/20, slot 2033
capacity cleared, tag 10 deleted, tags 1/4 images cleared.
**A1 fix (2026-10-10 18:26):** products 152/151 were soft-deleted and disappeared from the catalog; their
rows remain as tombstones so order lines keep the product name. Store 11/12 are still blocked by region-2
product 153, and tag 10 by the image-delete bug (A4).

View file

@ -0,0 +1,586 @@
# Freshyo E2E — defects & problems found (run 2026-10-10 16:30)
Source: `docs/test reports/e2e-sanity-test-results-2026-10-10-1650.md` (20-case daily subset +
incidental checks). Every entry lists the exact request or flow used, so each one can be re-run.
Screenshots: `/tmp/freshyo-e2e/*.jpg`. Backend: local `wrangler dev` @ `:8787`, D1.
Severity is my judgement, not a formal triage.
| # | Area | Problem | Severity | Confidence |
|---|---|---|---|---|
| F1 | Products API | `admin.product.deleteProduct` always fails on D1 | High | Confirmed · **FIXED 2026-10-10 18:26** (soft delete) |
| F2 | Coupons / money | Order detail reports a discount computed on the paid total (₹47.36 vs ₹30.4 charged) | High | Confirmed · **FIXED 2026-10-10 18:47** |
| F3 | Slots / UI | A full-capacity slot is still offered and addable in the app | High | Confirmed · root cause refined (stale slot cache pointer + no client-side capacity check) |
| F4 | Tags | Tag images: stored as a URL, scaffolded as a key at read, deleted as a key → broken image + undeletable tag | High | Confirmed · **FIXED 2026-10-10 20:00** |
| F5 | Products API | `createProduct` (and 5 more write paths) commit the row, then fail on the upload-URL claim | Medium | Confirmed · **FIXED 2026-10-10 20:35** |
| F6 | Region config API | Both superadmin const endpoints accept out-of-scope keys and report success while changing nothing | Medium | Confirmed · **FIXED 2026-10-10 21:10** |
| F7 | Regions API | Region deletion is intentionally unsupported, so region fixtures are permanent and customer-visible | — | **Not a defect (by design)** — plan guidance is the thing to change. Bounds **are** deletable: `deleteBound` added with last-bound + address guards (2026-10-10 22:15) |
| F8 | Addresses | Bound-less addresses inherit an active bound rather than a per-address bound | — | **Not a defect (by design)** — policy: an address may exist without a bound; the active bound applies |
| F9 | Customer UI | Home pull-to-refresh spinner can stick forever; region gate can strand with no escape | Medium | Diagnosis corrected from screenshots · **spinner fix DONE 2026-10-10 22:50** (90 s abort cap); gate dead end open |
| F10 | Admin UI (iOS) | Typing during automation landed in the first field | — | **Not an app defect (harness flow)** — the repo flow hides the keyboard and scrolls per field; minor gap: no keyboard avoidance/auto-scroll in the form |
| F11 | Products / admin | OOS toggle was product-wide only and collapsed partial state | Low | Confirmed · **FIXED 2026-10-10 23:20** (per-variant API + BottomDialog picker) |
| F12 | Orders API | Business rejections surface as HTTP 500 / `INTERNAL_SERVER_ERROR` | Low | Confirmed |
| F13 | Customer UI | Order list shows shipping status `success` (not `Delivered`) for a delivered order | Low | Confirmed |
| F14 | Customer UI | One address-selection switch rendered an empty cart before restoring it | Low | Unconfirmed (single occurrence) |
| — | Orders API | ~~`flashDeliveryFilter` returns nothing~~ | — | **Retracted — my input error** (see below) |
---
## F1 — `admin.product.deleteProduct` always fails (High)
**Request**
```
POST /api/trpc/admin.product.deleteProduct {"id":152} (also tried {"id":151})
```
**Observed**
```
{"error":{"message":"Failed query: delete from \"product_info\" where (\"product_info\".\"id\" = ? and
\"product_info\".\"region_id\" = ?) returning \"id\", \"region_id\", \"name\", \"short_description\",
\"long_description\", \"store_id\", \"increment_step\", \"created_at\", \"product_type\"\nparams: 152,1",
"code":-32603,"httpStatus":500}}
```
Reproduced for the fixture product (2 SKUs) and for an orphan product with no slot association, so it is
not limited to products referenced by slots. The message exposes the SQL but **not the underlying cause**
(no D1/driver error text), which is itself worth fixing for diagnosability.
**Impact** — no product can be removed through the admin API/UI. Cleanup of bad or test data is impossible;
PD-13-class deletion flows cannot pass. Workaround used in this run: `updateProduct` with
`isSuspended: true` on every SKU plus a rename.
**Where** — `apps/backend/src/trpc/apis/admin-apis/apis/product.ts` (`deleteProduct`) → `deleteProductInDb`.
**Suggested fix** — surface the driver error (`cause`), then resolve the FK/`returning` issue (delete or
cascade the child rows: SKU/features, slot associations, market stats, reviews) and return a proper 4xx with
a dependency reason instead of a 500.
> **FIXED (2026-10-10 18:26)** — `deleteProduct`/`deleteGlobalProduct` are now a **soft delete**
> (`packages/db_helper_sqlite/src/admin-apis/product.ts`): product + SKU rows stay so `order_items.sku_id`
> and order-history name rendering keep working (`product_skus.is_deleted = true`, `sku_features` kept);
> market stats, cart items, coupon applicability, tags, group membership, combos and special deals are
> removed in one atomic `db.batch`. The admin product list hides products whose SKUs are all deleted, and
> `checkProductExistsByName` ignores tombstones so names can be reused. Verified by deleting fixtures
> 151/152 (both returned success where they previously 500'd); a deleted-SKU detail lookup returns
> "Product not found". Root cause of the old 500: the single `DELETE FROM product_info … RETURNING` hit
> D1's FK enforcement (`product_skus.product_id` is NOT NULL, `ON DELETE no action`).
---
## F2 — Coupon discount is reported on a different basis than it is charged (High)
**Evidence (order #2495)** — cart/checkout preview and the success screen: item total ₹304, coupon
`E2E10PCT` 10% (max ₹50), delivery fee ₹200, **To Pay ₹473.6**. Stored row: `total_amount = 473.6`
(the final payable), `delivery_charge = 200`. Both order-detail APIs report **`discountAmount: 47.36`**
(customer `user.order.getOrderById`, admin `admin.order.getOrderDetails` — the latter verified live):
`47.36 = 10% × 473.6` (the payable, which already includes the ₹200 fee and the ₹30.4 discount), while the
amount actually deducted was `30.4 = 10% × 304` (items only). The reported components therefore do not
reconstruct the paid total: `304 − 47.36 + 200 = 456.64 ≠ 473.6`.
**Where** — the discount is **recomputed at read time** (it is not stored anywhere): both read paths use
`order.totalAmount` as the base — `apps/backend/src/trpc/apis/user-apis/apis/order.ts` `getOrderById`
(~line 547-577) and `packages/db_helper_sqlite/src/admin-apis/order.ts` `getOrderDetails` (~line 171-197).
The write path is correct and uses the items subtotal — `apps/backend/src/trpc/apis/user-apis/apis/order.ts`
(~line 213-231) and the app's checkout (`apps/user-ui/components/checkout-page.tsx` ~line 205-215) both
compute `10% × 304 = 30.4`, which matches the charge. The cap (₹50) is above the inflated figure, so it
never clamped and never exposed the error.
> **FIXED (2026-10-10 18:47)** — both order-detail paths now compute the discount from the order's item
> subtotal (`Σ price × quantity`) with the cap prorated by `orders.order_group_proportion`, reusing
> `applyDiscountToOrder()` (`packages/db_helper_sqlite/src/user-apis/order.ts:158`, parameter narrowed to
> `CouponDiscountFields`, now also returns `discountAmount` so callers do not re-subtract and hit float
> noise). Order #2495 now reports **30.4** on both the admin and customer detail endpoints and reconciles:
> `304 − 30.4 + 200 = 473.6`. No-coupon orders still return `null` (verified on #2496). Numerical check:
> the read-path formula equals the write-path formula for percentage and flat coupons across single- and
> multi-slot splits.
>
> **Still open in the same area:** `rebalanceSlots`
> (`packages/db_helper_sqlite/src/admin-apis/order.ts` ~line 684) recomputes `orders.total_amount` as
> latest-prices − discount **without adding the delivery charge**, so a slot rebalance overwrites the paid
> total and would make the detail endpoints disagree again.
**Impact** — refunds, coupon accounting, admin totals and any downstream reporting will disagree with what
the customer paid; the plan's own "money parity is a high-risk gap" note (BL-03/BL-04/BL-05) is confirmed
with a live order.
**Suggested fix** — compute the discount once, in the same function used for the quote, and persist that
value; add an invariant check (`items − discount + fees == payable`) in the order write path.
---
## F3 — Full-capacity slot still offered and addable in the app (High)
**Steps** — `updateSlotCapacity {slotId: 2033, isCapacityFull: true}` → in the app: product → `ADD TO CART`
→ the dialog still lists **“Sun, 11 Oct • 7-8 PM”** with an enabled checkbox; selecting it and pressing
`Add to Cart` succeeded (floating bar `₹199 • 1 Item`).
**Backend is correct**: a direct `placeOrder` with that slot returned
`Selected delivery slot is at full capacity. Please choose another slot.` (403).
**Impact** — the customer is allowed to build a cart that cannot be ordered; the failure only appears at
submission (SL-05 requires the option to be removed/disabled). Evidence:
`SL-05-full-slot-dialog.jpg`, `SL-05-full-slot-accepted-into-cart.jpg`.
**Root cause refined 2026-10-10 19:0x (live re-test):** it is *not* that the list query forgets to filter —
three different slot sources disagree:
| source | used by | capacity-aware? |
|---|---|---|
| `slots.json` CDN cache at `regions/<r>/slots/v-<slots_version_num>/slots.json`, version from `common.essentialConsts` (which reads the **KV blob**, `readEssentialConstsFromKv`) | `AddToCartDialog` (`useSlots()` in `apps/user-ui/src/hooks/prominent-api-hooks.ts`) | filtered when generated, but the app keeps reading the **stale version** |
| `user.slots.getSlots` | checkout page (`apps/user-ui/components/checkout-page.tsx:38`) | **Fixed 2026-10-10 19:20** — was unfiltered and multi-region (thousands of ids incl. past/full slots); now scoped to the caller's region and filtered to future, orderable slots |
| `user.cart.getCartSlots` → `getMultipleProductsSlots` (live DB) | cart page | **Yes** — returned `{"148": []}` while the slot was full |
The app also never reads the flag at all: `isCapacityFull` appears nowhere under `apps/user-ui`, and
`AddToCartDialog` filters only `freezeTime > now` (`availableSlots` ~line 106-109), so a slot reported as
full is still selectable.
**Live evidence of the stale pointer (slot 2032, the only future-active slot; capacity was flipped and
reverted during the test):**
- DB after revert: `isActive: true, isCapacityFull: false`.
- Files produced by `createSlotsCacheFile`: `v-13` contains `[2032]`; `v-14`…`v-17` do **not** contain 2032.
- `common.essentialConsts {boundId:1}` still advertises **`slots_version_num: 13`** → the app keeps fetching
the old file that still lists the slot, while the new files are never requested.
- `updateSlotCapacity` regenerates only the slots file (`createSlotsCacheFile`) — the **products** cache
(`products.json`, which carries each product's `nextDeliveryDate` computed with the capacity filter, and
whose `products_version_num` also stayed at 7) is not regenerated at all.
- Secondary inconsistency: `slots.json` content churns across versions (`v-13: [2032]`, `v-14: [2012,2014]`,
`v-15: [2012,2014,2016]`) although only capacity changed — the generated slot set does not match the
future-active slots the admin API reports (`[2032]`).
**Suggested fix** — (1) make the capacity flip reach the app: ensure the version pointer is refreshed
(`refreshGenKvForRegion` → KV `putBound` appears not to take effect) and regenerate the products cache too;
(2) have `AddToCartDialog`/checkout use the capacity-aware live source (`getCartSlots`) or re-validate at
submit; (3) honour the flag in the UI (disable/label `Full`); (4) fix `user.slots.getSlots` to be
region-scoped and capacity/freeze filtered; and (5) keep the server-side rejection (already correct) as the
backstop, ideally with a message that tells the user the slot just filled.
> **Partially fixed (2026-10-10 19:20)** — `user.slots.getSlots` is now region-scoped and future-only
> (`apps/backend/src/trpc/apis/user-apis/apis/slots.ts`): optional `regionId` input falling back to the
> caller's staff region, filtering `deliveryTime`/`freezeTime` against now. Verified: region 1 → 1 slot,
> region 2 → 0, staff without input → own region 1, anonymous without input → 0; a passed freeze time or an
> inactive slot is excluded. The checkout page passes `useRegion().regionId` — the same region the order is
> placed with. Capacity filtering is deliberately **not** included yet (that is the hide-vs-show decision),
> and the stale `slots.json` pointer that `AddToCartDialog` reads is still open.
>
> **Closed by decision (2026-10-10)** — the stale `slots_version_num` pointer is treated as a KV
> propagation/cache delay and left as-is; not investigated further. If it ever outlives a refresh cycle
> (i.e. still stale minutes later), the next suspects are the `refreshGenKvForRegion` write path and the
> app's react-query cache of `essentialConsts`.
---
## F4 — Tag images: written as a URL, read as a key, deleted as a key (High)
**Steps** — presigned upload (`user.fileUpload.generateUploadUrls {contextString:'tags'}`) → `PUT` 200 →
`admin.product.createProductTag {…, imageUrl, uploadUrls:[url]}` → 201.
**Observed** — `admin.product.getProductTags` / `getProductTagById` return
`"imageUrl": "https://assets2.freshyo.in/https://da9b1aa7c1951c23e2c0c3246ba68a58.r2.cloudflarestorage.com/meatfarmer-dev/tags/1791632636038.png?X-Amz-Expires=180&X-Amz-Signature=…"`
and `admin.product.deleteProductTag {id:10}` fails with **`Failed to delete image`** (500) while tag 10 keeps
existing (both re-verified 2026-10-10 ~19:35).
**Root cause — three inconsistent conventions for the same field:**
1. **Write** stores whatever it is given. `createProductTag` (`packages/db_helper_sqlite/src/admin-apis/product.ts:849`)
— and `updateProductTag` at `:905` — insert `imageUrl` verbatim, with no key normalisation, unlike banners
(`admin-apis/banner.ts:97`), stores and products which call `extractKeyFromPresignedUrl()`. So API-created
tag 10 stored a **presigned URL** (expiring signature) while seeded tags 2/5/8 store plain object keys
(`tags/<key>.png`).
2. **Read** scaffolds unconditionally. Both tag endpoints run `scaffoldAssetUrl(stored)`
(`admin-apis/product.ts:475` and `:494`), and `scaffoldAssetUrl` merely strips leading slashes and prefixes
`ASSETS_DOMAIN` (`lib/s3-client.ts:96-107`) — it does not detect an absolute URL. A URL therefore becomes
`https://assets2.freshyo.in/https://…?X-Amz-…` (broken image). The customer cache path scaffolds the same
way (`apps/backend/src/stores/product-tag-store.ts`), and `products.json` already contains the same class of
corruption in production data: tags **1** and **4** carry `…/tags/<key>.jpeg%3FX-Amz-Algorithm…` (an encoded
presigned query baked into the object key), while 2/5/8/9 are clean.
3. **Delete** treats the stored value as an object key. `deleteProductTag`
(`admin-apis/apis/product.ts:619-621`) calls `deleteImageUtil({ keys: [tag.imageUrl] })`; `deleteImageUtil`
builds `buildObjectUrl(bucket, key)` and DELETEs it (`lib/s3-client.ts:65-87`). For a URL the path is
nonsense → S3 responds non-2xx → it throws `Failed to delete image` → the mutation 500s **before**
`deleteProductTagInDb`, so the row is never removed: any tag whose image is not a clean key is undeletable.
**Impact** — tag images are broken on the customer home for every API-created tag (plus legacy 1 and 4), and
the tag cannot be deleted afterwards, which also blocks store/region cleanup (tag 10 is stuck).
**Suggested fix** — (1) normalise on write: `imageUrl: extractKeyFromPresignedUrl(imageUrl)` in
`createProductTag`/`updateProductTag` (and for the `uploadUrls` claim, store the derived key); (2) make the
asset helper defensive — detect absolute/protocol-relative URLs and strip `?X-Amz-…` instead of blind
prefixing (used by tags, products, banners, stores); (3) make cleanup non-fatal: normalise each key in
`deleteImageUtil`, treat a missing object as success, and delete the tag row even if image cleanup fails;
(4) repair data: re-upload or null the images for tags 10 (and legacy 1/4).
> **FIXED (2026-10-10 20:00)** — (1) `normalizeAssetRef()` added to `apps/backend/src/lib/s3-client.ts`
> (trims, drops a real or `%3F`-encoded query, and for absolute URLs keeps the path minus host/bucket);
> `scaffoldAssetUrl` now uses it, so scaffolding is idempotent; `deleteImageUtil` normalises every key first.
> (2) `createProductTag`/`updateProductTag` store `normalizeAssetRef(imageUrl)`. (3) Image cleanup in both
> the delete and update tag procedures is wrapped in try/catch and can no longer block the DB write.
> Verified: tag 10 read → `https://assets2.freshyo.in/tags/1791632636038.png` (was the double prefix);
> `deleteProductTag {id:10}` → "Tag deleted successfully" (was 500) and the tag is gone; a tag created with a
> presigned URL stores the key; product images still render normally; tags 2/5/8 unchanged.
> **Data repair:** tags **1 "Chicken"** and **4 "Fish"** had their `imageUrl` cleared — their objects return
> 404 at the clean key (the upload never landed there), so they need a fresh image from the admin UI. Tag 10
> was an E2E fixture and is now deleted.
---
## F5 — Write-then-claim: the request fails *after* the row is committed (Medium)
**Steps** — `createProduct` with an image URL that was never uploaded returned HTTP 500
(`Failed to claim upload URL`), but product 151 and its two SKUs existed afterwards, including the bogus
image path (re-confirmed by reading the current code, 2026-10-10).
**Root cause** — the order of operations in the `createProduct` procedure
(`apps/backend/src/trpc/apis/admin-apis/apis/product.ts:204`) is:
1. `createProductInDb(...)` — inserts product + SKUs (+ per-region market stats) inside a `db.transaction`;
2. `await Promise.all(allUploadUrls.map((url) => claimUploadUrl(url)))` — **after** the transaction;
3. `scheduleStoreInitialization(...)`.
`claimUploadUrl` (`apps/backend/src/lib/s3-client.ts:264-276`) calls `claimUploadUrlStatus`, which only
updates a row whose `status = 'pending'` (`packages/db_helper_sqlite/src/helper_methods/upload-url.ts:12-20`),
and throws when nothing was updated. The claim is outside the insert transaction and unguarded, so any
non-pending/unknown key aborts the request **with the product already committed**. Partial failure is also
possible: `Promise.all` may claim some keys before a sibling throws.
**Scope — six call sites share the pattern:** `createProduct:204`, `updateProduct:298`, `respondToReview:356`,
`createProductTag:534`, `updateProductTag:600` (all `apps/backend/src/trpc/apis/admin-apis/apis/product.ts`)
and `createReview` (`apps/backend/src/trpc/apis/user-apis/apis/product.ts:120`).
**What `upload_url_status` actually means** — verified repo-wide: the table is written when a presigned
upload URL is generated (`createUploadUrlStatus`) and flipped here; **nothing reads it** (no render-time
validation, no cleanup job) and no migration adds a reader. So a failed claim does **not** break the uploaded
image — the object is in R2 regardless. The real damage is the orphaned record, a misleading 500, a ledger
row that stays `pending` although the upload was used, and an awkward retry (the product now exists, so the
next attempt hits "A product with this name already exists", or the now-claimed URL gives "already claimed").
**Impact** — silent data pollution across six write paths; the E2E left policy-owner debris behind this way.
Since F1 was fixed (`deleteProduct` is now a soft delete), such debris is at least removable again.
**Suggested fix** — pre-validate before writing: one query for every key (they must exist and be `pending`),
throw a 400 listing the offending keys *before* the insert, then insert, then treat the claim as best-effort
(log instead of failing the request) — or claim inside the insert transaction (needs
`claimUploadUrlStatus` to accept a `tx`). That removes the orphan window for the common case (bad, foreign or
reused upload URL, which is exactly what produced product 151) without consuming claims for writes that fail.
> **FIXED (2026-10-10 20:35)** — option 1, applied at all six sites. New helpers in
> `apps/backend/src/lib/s3-client.ts`: `findUnclaimableUploadUrls()`,
> `assertUploadUrlsClaimable()` (throws `ApiError` 400 naming the keys) and `claimUploadUrls()`
> (`Promise.allSettled`, logs failures instead of aborting), backed by `getPendingUploadUrlKeys()` in
> `packages/db_helper_sqlite/src/helper_methods/upload-url.ts`. Each write now validates first and claims
> afterwards; in `updateProduct` and `updateProductTag` the check runs *before* any image is deleted.
> Verified: the original repro returns **400 with nothing written** (product count unchanged, retry no longer
> hits "name already exists"); a legitimately generated upload URL still creates the record (tag 12, image
> normalised) and reusing it is rejected with 400 and no row.
> `createReview` keeps its deliberate leniency: unclaimable URLs are logged, not rejected.
---
## F6 — Both superadmin const endpoints accept out-of-scope keys and silently no-op (Medium)
```
POST superadmin.regions.updateBoundSettings {"boundId":1,"settings":[{"key":"isFlashDeliveryEnabled","value":"true"}]}
→ {"success":true,"updatedCount":1}
GET common.essentialConsts?boundId=1 → "isFlashDeliveryEnabled": false # unchanged
POST superadmin.regions.updateRegionConstants {"regionId":1,"constants":[{"key":"isFlashDeliveryEnabled","value":"true"}]}
→ essentialConsts "isFlashDeliveryEnabled": true # works
```
Re-verified live (2026-10-10 ~19:50, with the flash state restored afterwards):
- `superadmin.regions.boundSettings {boundId:1}` returns a **stray**
`isFlashDeliveryEnabled: "true"` — the row my E2E run wrote through the bound endpoint.
- `common.essentialConsts {boundId:1}` reports `isFlashDeliveryEnabled: false` (the `region_consts`
value), so the stored bound row is ignored.
- Writing it again returns `{success:true,updatedCount:1}` and the effective value stays `false`.
- A genuine bound key still works: `flashFreeDeliveryThreshold` 500 → 501 → `essentialConsts` 501 → restored 500.
**Root cause** — the resolved payload takes each key from its own table: `scaffoldEssentialConsts`
(`apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts:47-135`) reads `isFlashDeliveryEnabled` from
`getRegionConstValues()`, bound keys from `getBoundConstValues()`, and never spreads bound rows wholesale.
`apps/backend/src/lib/const-keys.ts` already owns the mapping (`CONST_SCOPE`, built from
`GLOBAL/REGION/BOUND/LEGACY_CONST_KEYS`) and `admin.const.updateConstants` enforces it — but
`updateBoundSettings` (`superadmin-apis/apis/regions.ts:166-183`) and `updateRegionConstants` (`:192-216`)
validate nothing (the latter only filters version keys) and their helpers (`upsertBoundSettings` /
`upsertRegionConstants`, `packages/db_helper_sqlite/src/superadmin-apis/regions.ts:276-324`) upsert any key
into their own table.
**Blast radius** — the superadmin UI is scope-correct (it keeps `BOUND_SETTING_KEYS` and
`REGION_SETTING_KEYS` apart and calls the matching mutation in `apps/superadmin-ui/src/routes/regions.tsx`),
so this is an API-contract trap for scripts, agents and testers — the plan's own guidelines tell testers to
use `updateRegionConstants`, and the false `success` cost me a debugging cycle plus one stray row. The mirror
case is equally possible: `updateRegionConstants` would happily write a bound/global key into `region_consts`
(none present today — checked). Stray rows are inert but cannot be removed: the endpoints are upsert-only.
**Suggested fix** — validate against `CONST_SCOPE` in both endpoints and reject mismatches with a 400 that
names the correct endpoint (optionally also accept any key and route it to the right table, and/or allow
`value: null` to delete a row so existing strays can be cleaned).
> **FIXED (2026-10-10 21:10)** — `assertConstantKeysInScope(keys, expected, endpoint)` added to
> `apps/backend/src/lib/const-keys.ts` (uses `CONST_SCOPE`, also rejects version counters on region writes)
> and called first by **all four** endpoints — the superadmin pair and the staff pair in
> `admin-apis/apis/region.ts`. `value: null` now **deletes** the row instead of storing NULL
> (`upsertBoundSettings`/`upsertRegionConstants` return `{ updated, deleted }`, and the endpoints return
> `deletedCount`); null is allowed even for a wrong-scope key so old mistakes can be removed while writes
> stay validated. Verified: wrong scope → 400 naming the target endpoint, version keys → 400, unknown keys
> → 400, legit writes unchanged, and the leftover bound-1 `isFlashDeliveryEnabled` row was deleted
> (`deletedCount: 1`, idempotent afterwards) with `essentialConsts` unaffected. One fix during verification:
> the delete branch's `.returning({ id })` failed because these tables have no `id` column.
---
## F7 — Region deletion is intentionally not supported (not a defect)
**Verdict (confirmed by the product owner, 2026-10-10): deleting a region is not an allowed action.** So this
is not a bug — but it does make one instruction in the test plan unactionable and leaves permanent fixtures.
Observed behaviour (kept as context, re-verified live 2026-10-10 ~20:15):
- `superadmin.regions.delete` → `No procedure found on path "superadmin.regions.delete"` (404); there is no
`deleteBound` either.
- `regions` has only `id, name, description, createdAt` — no `isActive`/`isDeleted` — and `updateRegion`
changes `name`/`description` only, so a region cannot be disabled.
- The superadmin UI offers no delete affordance for regions (the only `removeBound` is client-side draft
editing in the create form).
- `common.listRegions` returns every region, including fixtures (region 2 `E2E Testnagar 1702`), and bound
polygons participate in address resolution (`addresses.boundId → region_bounds.regionId`).
**Residual (process) issues, not bugs:**
1. The plan's RG-01 cleanup step ("delete the extra regions you created") cannot be followed. It should say to
**reuse one long-lived test region** instead of creating new ones.
2. A created region is permanent and customer-visible. The sanctioned ways to neutralise one are `update`
(rename it clearly, e.g. `ZZ DO NOT USE`) and `updateBound` (shrink/move its `geojson` so its polygon cannot
capture addresses).
3. Content inside another region can only be cleaned with a **temporary staff user for that region**
(`superadmin.staff.create` → use the `admin.*` endpoints → `superadmin.staff.remove`), because `staffProcedure`
requires `ctx.staffUser` and a superadmin token cannot call `admin.*`.
The RG-01 fixture (region 2, bound 3) therefore stays, by design, along with anything created inside it.
> **Bounds, by contrast, are deletable (2026-10-10 22:15)** — `superadmin.regions.deleteBound` was added with
> two guards: it refuses when the bound is the region's **only** bound (409: *"A region needs at least one
> bound so it can take orders"*) and when any address still points at it (409, with the address count); the
> package helper `deleteRegionBound` removes the bound's `region_bound_consts` rows and the row itself, then
> the router re-mirrors the region's remaining bounds and drops the removed bound's `essentialConsts_<id>` KV
> blob. The superadmin UI gets a **Delete bound** button that is disabled (with the same hint) when
> `canDeleteBound(bounds.length)` is false — the rule lives in `apps/superadmin-ui/src/lib/bound-rules.ts`
> with a vitest test (`bound-rules.test.ts`, 6 cases, `npm test`) so the UI cannot offer the last-bound delete
> and the server cannot be bypassed by a script.
---
## F8 — Bound-less addresses (by design, closed)
**Business policy (confirmed 2026-10-10):** an address may exist without a bound; such an address is served by
an **active bound** rather than one tied to the address. **Verdict: not a defect** — the report below is kept as
behavioural reference, not as work.
How it actually resolves (for future reference):
- `common.activeBound` (`apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts:247-265`) returns the
least-priority bound among the **user's** addresses in the region, and the region's effective
(least-priority) bound when they have none. Verified live: with the user's only bounded address on bound 2,
it returns `boundId: 2` while region 1's least-priority bound is 1. (Address 285 was moved to bound 2 for the
test and restored; state confirmed back to `285→1`, `879→2`.)
- The app uses that value whenever the selected address has no bound (`useGetEssentialConsts`,
`prominent-api-hooks.ts:32-36`; `useRegion.ts:96-113`).
- `placeOrder` prices with `params.boundId ?? getEffectiveBoundId(regionId)` and verifies via
`getRegionSettingsForBound` that the bound belongs to the region (otherwise it falls back to the region's
effective settings), so no cross-region pricing is possible.
- Coordinates are irrelevant to this policy: `+ Attach Current Location` stores lat/lng and leaving `boundId`
null is expected; the "No Location is attached" banner is an address-quality nudge.
Two notes kept for the record (no action requested): the client's `params.boundId` is what decides the charge
for a bound-less address, and `orders` has no `boundId` column, so the applied bound is not stored on the order.
---
## F9 — Home pull-to-refresh spinner can stick forever (corrected; the "region sheet hang" was a misread) (Medium)
**What the evidence actually shows.** All three E2E captures (`RG-06-region-sheet.jpg`, `RG-06-region-sheet2.jpg`,
`RG-06-region-sheet3.jpg`, 5:02–5:03) are the **home screen** with the catalogue and cart fully rendered and a
small centred spinner **above the `DELIVER TO` bar** — no sheet and **no dark backdrop**, which a presented
`BottomDialog` (its backdrop is `rgba(0,0,0,0.3)`) would show. So the sheet was never open in those minutes and
my original note ("the sheet never renders the region list") was a misreading of the harness screen; the taps
just did not open it. The spinner itself is the home list's `RefreshControl`
(`apps/user-ui/app/(drawer)/(tabs)/home/index.tsx:758-764`), which renders exactly there because `LocationBar`
is the `ListHeaderComponent`.
**Why it can never clear.** `isRefreshing` is a local `useState` (`home/index.tsx:504`) reset only in
`handleRefresh`'s `finally` (`:603-621`), after
`await Promise.all([refetchProducts?, refetchSlots, refetchStores, refetchConsts])`. Those refetches hit the
versioned CDN JSON (`products.json`, `stores.json`, `slots.json`) through plain `axios.get(cacheUrl)` with **no
timeout** (`prominent-api-hooks.ts:160-171`) and a global query client with `retry: 3` and no fetch timeout
(`utils/queryClient.ts`). A request that *fails* eventually rejects and clears the spinner; a request that
**hangs** never settles, so `finally` never runs and the indicator spins until the app is relaunched — matching
the captures, which are a minute apart with the spinner still going. `handleRefresh` is also invoked without a
pull, via `useManualRefresh`/`useMarkDataFetchers` (`:623-629`), so it can start on its own after other screens
refresh (e.g. the region switch clearing the central stores and invalidating every query — `region-switch.ts`).
**Separate confirmed issue in the same area (region gate dead end).** Independent of the sheet:
`isResolvingRegion` = `regionId == null && !startupResolved` (`useRegion.ts:191`), and the 8 s safety net that
unsticks the first-run spinner is armed only when `shouldResolve` is true, which requires `coords != null`
(`useRegion.ts:180-189`). With location denied/off, `locationStore` keeps `coords: null`
(`status: 'denied' | 'unavailable'`), so the timer never arms and `startupResolved` never flips →
`LoadingScreen("Finding your region...")` forever, with the manual chooser unreachable because it is rendered
after that branch. The only resets are a reload or `refreshLocation()`, and **no component calls
`refreshLocation`** (checked repo-wide).
**Suggested fix** — (1) give the catalogue fetches a timeout/`AbortController` and derive the home
`refreshing` state from real query state (or force-reset after a bounded time) so a stalled request cannot pin
the UI; (2) gate: arm the timeout even without coords, route `denied`/`unavailable` straight to the manual
chooser, and wire an escape (`refreshLocation` / "Choose region manually"); (3) don't `await` a global
`invalidateQueries()` inside the region switch.
> **FIXED (item 1) 2026-10-10 22:50** — every catalogue/CDN request is now bounded by an `AbortController` with
> a **90 s** cap: new `apps/user-ui/src/lib/fetch-json.ts` (`JSON_FETCH_TIMEOUT_MS`, `fetchJson<T>()`,
> `isAbortError()`), used by all five fetches in `prominent-api-hooks.ts` (products, availability, stores, slots,
> store-with-products); the shared tRPC `fetch` gets the same guard (covers `refetchConsts`, the other leg of
> `handleRefresh`); and the query client no longer retries aborted requests (`retry: (n, e) =>
> !isAbortError(e) && n < 3`) so a timeout surfaces instead of repeating 3×90 s. Verified with the real helper
> bundled for node against a server with one instant route and one that never answers: `90000` constant, fast
> route resolves, stalled route rejects after the injected cap as `CanceledError` with `isAbortError` true, and
> a plain error is not treated as an abort (still retried). Items (2) and (3) are still open.
**Suggested fix** — (1) gate: arm the timeout even without coords (or route `denied`/`unavailable` straight to the
manual chooser) and wire an escape (`refreshLocation` / "Choose region manually") — removes a hard dead end;
(2) sheet: keep `listRegions` warm (prefetch) and show a retry instead of an endless spinner when data is
absent; (3) switch: don't await a global `invalidateQueries()`, and dismiss Alert/modal before mounting the next
one; (4) validation: only `clearRegion()` when a non-empty list genuinely lacks the id.
---
## F10 — Admin form typing: harness/flow issue, not a focus bug (reclassified)
What happened: filling the Add-Product form by tapping testIDs and calling `inputText` left the Product Name as
`E2E Sanity 1655n500 g199249 1 kg` — every later value was appended to the name field while the variant fields
stayed empty.
Why, from the code:
- `MyTextInput` is a thin passthrough to react-native-paper's `TextInput`
(`packages/ui/src/components/textinput.tsx`): it spreads `{...props}` (so `testID` reaches the real input and
became its `accessibilityLabel`) and adds **no** focus logic. There is no wrapper that could swallow a tap.
- `ProductForm` is a bare `ScrollView` with `keyboardShouldPersistTaps="handled"`
(`apps/admin-ui/src/components/ProductForm.tsx:256`) and **`KeyboardAvoidingView` appears nowhere in
admin-ui** (grepped). Once the keyboard is up after focusing Product Name, the variant/price fields sit behind
it; a coordinate tap lands on the keyboard, focus never moves, and Maestro's `inputText` (which types into the
focused element) keeps appending to the name.
- The repo's own flow shows the intended pattern: `tests/e2e/add-product.yaml` does `inputText` →
`hideKeyboard` → `scrollUntilVisible` → tap, per field. My exploratory flow skipped the hide/scroll because
`hideKeyboard` fails on this build (noted in the guidelines).
**Verdict** — primarily a harness/flow problem (the sanctioned flow exists in-repo), with a genuine but minor
ergonomics gap: the long form has no keyboard avoidance or auto-scroll-to-focused-field, so on iOS a human must
scroll manually and automation is fragile. Not a functional defect.
---
## F11 — Out-of-stock can only be set for a whole product through the toggle (Low)
`admin.product.toggleOutOfStock {id: 152}` reports `{"productId":152,…}` and marks **all** SKUs unavailable;
`placeOrder` then rejects both SKUs ("Product 153 is unavailable", "Product 154 is unavailable").
Where the state lives and what the endpoint does:
- Stock is per **SKU per region**: `product_market_stats.is_out_of_stock`
(`packages/db_helper_sqlite/src/db/schema.ts:216`).
- `toggleProductOutOfStock(regionId, productId)` (`packages/db_helper_sqlite/src/admin-apis/product.ts:1270-1302`)
loads every SKU of the product, computes `nextIsOutOfStock = !skus.some(sku => marketStats.isOutOfStock)`
("out if **any** variant is out") and writes that single value to **all** of the product's market-stats rows
for the region. The input has no `skuId`.
Consequences:
1. The endpoint cannot express PD-06 (one variant out of a multi-SKU product). Per-SKU control exists only in the
full `updateProduct`/`createProduct` payloads (per-SKU `isOutOfStock`) and, for global products, in
`GlobalProductForm`'s per-variant "Out of stock" checkbox.
2. It **destroys partial state**: with one SKU out and one in (set via `updateProduct`), `some(...)` is true, so
one press sets everything back in stock and the next press takes everything out — a partial state can never
survive the toggle.
3. The admin product list switch (`apps/admin-ui/app/(drawer)/dashboard/products/index.tsx:148,57`) renders from
the **default SKU's** flag, so a partially-out product can display as "in stock".
**Suggested fix** — give the toggle an optional `skuIds` (or add `setVariantOutOfStock`) that writes only those
market-stats rows, keep the product-level action as an explicit "all variants" operation, and show a partial
state in the list. No migration: the data model already supports it.
> **FIXED (2026-10-10 23:20)** — `toggleOutOfStock` now takes optional `skuIds` + `isOutOfStock`
> (`apps/backend/src/trpc/apis/admin-apis/apis/product.ts`), backed by a new
> `setProductSkusOutOfStock(regionId, productId, skuIds, isOutOfStock)`
> (`packages/db_helper_sqlite/src/admin-apis/product.ts`) that writes exactly those
> `product_market_stats` rows, rejects ids that are not the product's variants (400) and requires the target
> state (400). The all-variants path is untouched (400/`{id}` only). The admin app gets a new
> **`VariantStockDialog`** (`apps/admin-ui/src/components/VariantStockDialog.tsx`) built on `BottomDialog`: the
> row's Stock button opens it, each variant has a checkbox (default all selected, with Select all / Clear),
> current state is shown per row (In/Out), a banner appears when the product is partially out, and two actions
> apply "Mark out of stock" / "Mark in stock" to the selection. The row chip and the in-stock/out-of-stock
> filters/counters now aggregate over all variants (In / Partial / Out) instead of reading `skus[0]`.
> Verified live: with a temp 2-SKU product, marking one variant out left the sibling in stock
> (`(156:true, 157:false)`), targeting the sibling was a no-op, a foreign id returned 400, a missing target
> returned 400, and the legacy `{id}` toggle still flipped all variants both ways. UI files parse with esbuild;
> the admin app was not built or run here (no installed node_modules in this environment).
---
## F12 — Rejections are 500s (Low)
Correct business rejections come back as `INTERNAL_SERVER_ERROR` / HTTP 500, e.g. out-of-stock
(`Product 153 is unavailable`), full slot, `Cannot delete a store that still has products`,
`Address is attached to an ongoing order. Please cancel the order first.`,
`Cannot delete default address…`, `Failed to delete image`. Consistent with the already-known
"ApiError statuses are flattened" quirk, but it makes monitoring and client error handling harder
(the client has to parse messages).
---
## F13 — Delivered orders still show `success` (Low)
In My Orders the delivered order #2495 renders `SHIPPING STATUS: success`; the order *detail* screen shows
the `DELIVERED` badge and all three stepper nodes. The list label reads like an internal status string rather
than a customer-facing state.
---
## F14 — One empty-cart flap when selecting an address (Low, unconfirmed)
Selecting the A2 address on the cart once rendered "Your cart is empty / Start Shopping" with the A2 address
checked (`AD-05-bill-with-A2.jpg` captured just after). Selecting it again showed the cart intact with the
A2 fee (₹200) and both lines. Single occurrence; recorded so it can be watched during CT-04/AD-09-class work.
---
## Retracted — not a defect
- **`admin.order.getAll {flashDeliveryFilter: true}` returning an empty list.** The schema expects the enum
`"all" | "flash" | "regular"` (`apps/backend/src/trpc/apis/admin-apis/apis/order.ts:67-87`). With
`{"flashDeliveryFilter":"flash"}` the endpoint correctly returned the flash orders (2496, 2474, 2473);
with a boolean it returns a zod `invalid_value` error, which my filter had silently rendered as `[]`.
**No bug.**
## Harness problems also worth fixing (they cost most of the run's time)
1. `launchApp: {clearState: true}` does not sign the iOS app out — every "signed-out" case needs a manual
logout path.
2. MCP request ceiling of 60 s kills long chained flows mid-way, leaving the app in an arbitrary state.
3. Maestro percentage coordinates go stale as soon as a screen grows (the coupon row moved 51 % → 61 % when
the cart gained a line). The repo's `tests/e2e` flows correctly use `id:`; the exploratory flows this run
mostly could not, because the customer app exposes few testIDs outside login/search/cart.
4. `hideKeyboard` fails on this build, so numeric inputs need a neutral tap that often does not dismiss the
keyboard either (F10).
5. No SQLite/D1 file is reachable from the workspace (`apps/backend/.wrangler/` is empty and
`dumps/latest.sqlite` has no `regions` table), so the plan's "authoritative DB read" layer was
unavailable and every money/usage claim had to be made through the API.
## Suggested fix order
1. **F1** (no product deletion) and **F4** (tags: broken image + undeletable) — both block cleaning up the
data this and the previous run created.
2. **F2** (discount basis) — money correctness, affects refunds and reporting.
3. **F3** (full slot selectable) — customers can build unplaceable carts.
4. **F6** + **F7** (silent no-op config write, no region delete) — they make staging cleanup and config tests
unreliable.
5. **F5**, then **F9/F10** (app behaviour that also blocks automation), then the Low items.
## Data left behind because of F4/F7 (F1 removed)
Region 2 + bound 3 (F7: no region delete API) · stores 11 and 12 (guard: products exist) · tag 10 (F4) ·
region-2 product 153 (needs a region-2 staff token) · customer `9000011715` + default address 880 ·
address 879 (tied to order 2495) · slots 2033/2034 (deactivated) · orders #2495 (delivered) and
#2496 (flash, pending).
**Cleared by the F1 fix (2026-10-10 18:26):** products 152 and 151 are gone from the catalog; their rows
remain only as tombstones (`product_skus.is_deleted = true`) so order history keeps its names. Store 11/12
deletion is still blocked by region-2 product 153, not by F1.

View file

@ -0,0 +1,199 @@
# Freshyo E2E sanity — results (run 2026-10-10 16:30, final)
Companion to `docs/e2e-sanity-test-plan.md`. Maestro MCP drove the iOS simulator
(`B1F98A94-…`, `com.freshyotrial.app` / `in.freshyo.adminui`); authoritative assertions were
made over tRPC (sanctioned by the plan). Screenshots: `/tmp/freshyo-e2e/*.jpg`.
Maestro viewer used: `http://127.0.0.1:10000/`.
Scope actually executed: the plan's **recommended daily sanity subset** (20 cases).
Every case below with a status was *executed in this run*; the remaining plan cases are
marked **NOT RUN (this run)** — the 13:10 report (`e2e-sanity-test-results-2026-10-10-1310.md`)
remains the record for those.
## Environment
| Item | Value |
|---|---|
| Backend | `wrangler dev --config wrangler.dev.toml` @ `:8787` (workerd PID 96583, started 15:15:48) |
| Metro | `:8081` (pre-existing, untouched) |
| Web | `:4174` customer · `:4175` superadmin · `:4176` admin |
| GPS | `16.7489,77.9856` → region 1, bound 1 |
| Baseline (before) | regions: only 1 (Mahabubnagar); bound 1 charge 20 / threshold 300 / min 300; flash off; versions 2/2/2; 20 products; staff `shafi` (id 6); customer 388 `9676651496` |
| Credentials used | superadmin `superadmin`/`superadmiN123`; staff `shafi`/`shafI123`; customer 388; (created) staff B `e2eadminB1702`; (created) fresh customer `9000011715` |
## Harness notes discovered (add to `maestro-mcp-agent-guidelines.md`)
1. **`launchApp: {clearState: true}` is a no-op on iOS** — the session survived; log out through
the UI (Me `90%,92%` → gear `89%,21%` → swipe `50%,80%→50%,30%` → `Logout` `50%,78%`).
2. **Pushed routes have no tab bar** (cart, checkout, login walls, order success, search results):
tab taps are ignored; leave with the back chevron `7%,7%` / `Go Back` / `Continue Shopping`.
3. **MCP requests die at 60 s** — long chained flows abort mid-way. Either keep flows short or raise
`timeout` in `.pi/mcp.json` (not done here).
4. **The region sheet stops responding after first use** — the sheet's list query shows an endless
top-center spinner; `stopApp`/`launchApp` clears it. Cold launch re-resolves GPS and restores the
GPS region (that is how the run returned from region B to A).
5. **Cart item removal asks for confirmation** ("Remove Item … Cancel / Remove").
6. `yaml` flows need `appId: com.freshyotrial.app` + `---`, and admin flows need the app's own
`appId: in.freshyo.adminui`; the repo's `tests/e2e` testIDs all work on iOS (name/store/type/
variant fields), but **typing into those fields on iOS routes text into the wrong input**
(keyboard focus) — creation was therefore done through the same tRPC mutations the UI calls,
as the 13:10 run did.
7. QR/percentage coordinates that shifted this run: coupon row 61% (not 51%), flash `Checkout`
72%,77%, `Place Order` 50%,70%, `Get in 1 Hour` 74%,75%.
8. Customer home is a single a11y blob (`txt: ""`), so evidence = screenshots + blob substring checks.
9. An "Open in Freshyo?" alert did not appear this run (no deep links used).
---
## Results — the 20-case daily subset
### A. Regions, bounds, configuration
| ID | Status | Evidence |
|---|---|---|
| RG-01 | **PASS** | Created region 2 "E2E Testnagar 1702" + bound (priority 1) + admin `e2eadminB1702` through the same APIs the UI calls (`superadmin.regions.create`, `superadmin.staff.create`). `common.listRegions` (used by `apps/user-ui/src/components/RegionSelector.tsx`) returns both regions with `effectiveBoundId`; the app's Delivery Region sheet lists the new region with its description; after switching, the region loads with **no undefined amounts** — ₹500 threshold from bound 3, its own stores/catalog (`/tmp/freshyo-e2e/RG-06-region-sheet4.jpg`, `RG-06-region-B-home.jpg`). |
| RG-03 | **PASS** | Cold launch **signed out** → `DELIVER TO Mahabubnagar`, catalog (Popular rail with prices) and `₹300 more for FREE Delivery` with **no login** (`RG-03-signedout-home-relaunch.jpg`); signed-in repeat identical plus `UPCOMING ORDER #ORD2466` and `₹235 • 1 Item / ₹65 more` (235+65=300 ✓) (`RG-03-signedin-home2.jpg`). Resolved once, no flip. |
| RG-06 | **PARTIAL → effectively PASS** | A: fixture products/stores visible; B: same search → "No products found", B's own store/item/threshold visible, cart cleared on switch; API isolation: admin B → A product 152 "Product not found", admin A → B product 153 "Product not found", admin B stores/slots contain only B's. **The B→A leg could not be completed through the sheet** (harness: sheet hang) — it was exercised only indirectly via cold launch re-resolution, so the "browse A → B → A" sequence is one leg short of the plan's wording. |
### B. Authentication
| ID | Status | Evidence |
|---|---|---|
| AU-01 | **PASS** | Signed out: browse/search/product detail work (`AU-01-search-chicken-signedout.jpg`, `AU-01-product-detail-signedout.jpg`); Cart → "Please log in / Log in to view your cart and continue to checkout." + Log In/Go Back (`AU-01-cart-login-wall.jpg`); Me → "Please log in / Log in to view your profile, orders and more."; no forced redirects; tabs usable after leaving the wall. |
| AU-02 | **PASS** | Item added while signed out (₹235 • 1 Item, ₹65 more) → cart wall → Log In → `user-login-mobile` 9676651496 → `user-login-other-ways` (password path, **no OTP**) → `user-login-password` → Login → returned to the Scheduled Delivery Cart with the line intact, address "Shafi" (`AU-02-after-login-return.jpg`). |
### C. Stores, products, variants
| ID | Status | Evidence |
|---|---|---|
| PD-01 | **PASS** (creation via API; results via UI) | Store 11 with image; product 152 with SKUs 153 (500 g ₹199/249) and 154 (1 kg ₹349/399, flash ₹299), genuine uploaded images (presigned PUT + claim), unit features; slot 2033 with both SKUs. Customer: both variants with correct price/MRP/unit/images; add-dialog offers **only** the assigned slot; item added; store detail "E2E Store 1657 · 2 ITEMS" (`PD-01-customer-search-after-cache.jpg`, `PD-01-SL-slot-dialog-options.jpg`, `PD-01-store-detail.jpg`). Cache verified directly: `products.json` v-4 contains the fixture; versions bumped 2→4. **Caveat:** admin-app form creation could not be driven on iOS (keyboard focus) — see harness note 6. |
| PD-02 | **PASS** (API) | Cross-region product/store/slot lookups all denied; admin B list/slots contain only B entities (see RG-06). |
| PD-05 | **PASS** | `toggleOutOfStock{152}` → both SKUs UNAVAILABLE in search + red "Out of Stock" badge on the cart line while the other line stays valid (`PD-05-sku-oos-customer.jpg`, `PD-05-cart-with-oos-line.jpg`); `placeOrder` with SKU 153 → **"Product 153 is unavailable"**, with 154 → **"Product 154 is unavailable"** (product-level OOS). Stock restored. |
### D. Discovery
| ID | Status | Evidence |
|---|---|---|
| DS-01 | **PASS (renders) / FAIL (image)** | Dashboard tag 10 "E2E Deals 1715" (image + store 11 + product 152) appears in the customer home tab strip (`DS-01-home-tag.jpg`). **But the stored image URL is malformed**: `https://assets2.freshyo.in/https://<r2-host>/meatfarmer-dev/tags/…` (double-prefixed) — `createProductTag` passes the presigned URL through `scaffoldAssetUrl()` instead of extracting the key. |
### E. Slots
| ID | Status | Evidence |
|---|---|---|
| SL-01 | **PASS** | The add dialog for SKU 153 offered exactly the assigned slot with the admin's window (`Sun, 11 Oct • 7-8 PM`, slot 2033) and not the unrelated same-day slots — membership + local-time display correct. |
| SL-05 | **FAIL (UI) / PASS (backend)** | With `updateSlotCapacity{2033,isCapacityFull:true}`: **backend rejects a stale submit** — `placeOrder` → "Selected delivery slot is at full capacity. Please choose another slot." — but the **customer UI still offers the full slot as selectable** and happily put the item in the cart (`SL-05-full-slot-dialog.jpg`, `SL-05-full-slot-accepted-into-cart.jpg`). Capacity restored afterwards. |
### F. Cart / checkout summary
| ID | Status | Evidence |
|---|---|---|
| CT-01 | **PASS** | Same SKU from Home and from Search: floating bar `₹235 • 1 Item`, expanded sheet subtitle `SUBTOTAL ₹235` + `FREE DELIVERY PROGRESS 78% / Needed +₹65`, full cart line ₹235 with slot — identical identities/quantities/subtotals across all three surfaces (`CP-01-BL-01-cart-304-pre-coupon.jpg` sequence). |
| CT-04 | **PASS** | 2-line cart (₹434) survived a cold relaunch; the floating bar rendered `₹434 • 2 Items` right after relaunch (before/after catalog load), no empty-cart flash, quantities intact. |
### G. Addresses / bounds
| ID | Status | Evidence |
|---|---|---|
| AD-01 | **PARTIAL** | Fresh customer 1314 created; first address submitted **without** the Default flag → stored with `isDefault: true` (correct "first address becomes default"), `regionId: 1`. **But `boundId: null`** — with no coordinates the address has no bound (`PD-01`-adjacent note; relates to AD-04's "No Location is attached to address" prompt, which the app does show: `+ Attach Current Location`). Cart/checkout contact display for that account was not exercised (would need switching the sim's session). |
| AD-05 | **PASS** | A1 selected: Delivery Fee **₹20**, nudge "Add products worth ₹26", To Pay **₹293**. A2 selected: Delivery Fee **₹200**, nudge "Add products worth **₹526**" (= 800 − 274), To Pay **₹473** — cart lines + coupon preserved across the switch (`AD-05-bill-with-A2.jpg`). Order placed with A2: **#2495, Total ₹473.6** matching the preview, and the persisted order carries `deliveryCharge 200` (below). Observed flap: one selection of A2 briefly rendered "Your cart is empty" before restoring — recorded as an inconsistency, not reproducible on the second attempt. |
### H. Bill arithmetic
| ID | Status | Evidence |
|---|---|---|
| BL-01 | **PASS (parity) / PARTIAL (exact boundary)** | Below threshold: bar/cart/checkout all show the ₹20 fee with the correct nudge (235 → +₹65; 268 → +₹26 basis post-discount). Above threshold: ₹304 → `FREE DELIVERY UNLOCKED`, fee ₹0 in cart and checkout. Persisted order #2495 keeps `deliveryCharge: 200` (A2) matching the quote, and the success screen shows the same `₹473.6`. The plan's exact **T−1/T/T+1** triple was not constructed (catalogue-specific totals); the coupon-crossing case below covers the interesting boundary. |
### I. Coupons
| ID | Status | Evidence |
|---|---|---|
| CP-01 | **PASS (flow) / FAIL (accounting)** | Coupon 43 `E2E10PCT` (10%, max ₹50, min ₹200) offered to the customer ("E2E10PCT … Save ₹30.4"), applied in cart, carried into checkout ("Coupon E2E10PCT 10% off"), order #2495 created with total **₹473.6 = preview** (cap/min respected, single use recorded server-side; coupon then invalidated by cleanup). **Accounting defect:** the persisted order stores `discountAmount: 47.36` (= 10% of the ₹473.6 *payable*, i.e. including the ₹200 delivery fee) while the actually applied discount was ₹30.4 on items — persisted components (item 304 − 47.36 + 200) do **not** reconstruct the stored total 473.6. Matches the plan's "money parity is a high-risk gap" observation. |
### J. Orders / fulfillment
| ID | Status | Evidence |
|---|---|---|
| OR-01 | **PASS** | #2495 (2 items, COD, coupon, address A2, region 1): success screen `Order #2495 Total ₹473.6`; My Orders shows `#ORD2495` with items/prices, `SHIPPING STATUS: success`, `Delivery: ₹200`, `₹473.6`; admin A `getOrderDetails` returns the order with items 8374/8375; **admin B → "Order not found"**. |
| OR-04 | **PASS** | Package item 8374 → `updateOrderItemPackaging` ok; whole order packaged; `updateDelivered` → admin detail `isPackaged: true, isDelivered: true`, both items packaged; customer detail shows the **DELIVERED** badge, all three stepper nodes green (`Placed → Packed → Delivered`), COD/`Delivered on 10 Oct 2026, 6:00 PM` (`OR-04-order-detail-status.jpg`). (Admin actions were driven through the same mutations the admin UI calls; the admin app's own tap-through was not repeated.) |
### K. Flash delivery
| ID | Status | Evidence |
|---|---|---|
| FL-01 | **PASS** | Flash enabled for region 1 via `superadmin.regions.updateRegionConstants` (`isFlashDeliveryEnabled: true`; note: writing the key through `updateBoundSettings` did **not** propagate — only the region-constants path did). Flash surface activated (`1 Hr Delivery`, notice text, flash bar `No Flash Items / ₹500 more`). Added a flash-eligible item, flash cart showed `Item ₹233 / Delivery Fee ₹69 / Add products worth ₹267 / To Pay ₹302`; checkout → **"1 Hr Order Placed! 1 Hr Order #2496 Total: ₹302"**. Admin: order 2496 has `isFlashDelivery: true`, `deliveryCharge: 69`, **no slot**, item ₹233. Flash restored to `false`. **FL-02 incidentally verified**: `placeOrder` with non-flash SKU 153 + `isFlashDelivery: true` → "Product 153 is not available for flash delivery". **Suspected filter defect:** `admin.order.getAll {flashDeliveryFilter: true}` returned an empty list although 2496 is a flash order (input shape may differ; needs confirmation). |
### O. Payments (incidental)
| ID | Status | Evidence |
|---|---|---|
| PAY-01 | **PASS** | Checkout shows "Pay Online (Coming Soon) — UPI, Cards, Netbanking" greyed out with no radio selection; COD works end to end (two orders). |
---
## Full-plan cases NOT executed in this run
Everything below is **NOT RUN by this session** (the 13:10 report covers them; several were
re-verified incidentally and are noted):
- **RG-02, RG-04, RG-05, RG-07, RG-09, RG-10, RG-11** — not run. Related observations from this
run: no `superadmin.regions.delete` procedure exists (region 2 created for RG-01 cannot be removed
through the API); cold launch re-resolves GPS and resets regional state (RG-08 evidence);
the A2-select flap (AD-05) hints at the same reconciliation area as RG-07.
- **AU-03…AU-10** — not run in this session (password-path login verified for AU-02; no OTP triggered
anywhere). The fresh customer `9000011715` (+ default address) was left in place for AU-05/AU-10 work.
- **PD-03, PD-04, PD-06…PD-13** — not run. Related: **`admin.product.deleteProduct` is broken**
(`Failed query: delete from "product_info" … returning …`, 500) — PD-13-relevant;
`admin.store.deleteStore` correctly refuses while products exist; `createProduct` is not atomic
with the upload claim (left product 151 behind).
- **DS-02…DS-08** — not run. DS-01 bug documented above; `deleteProductTag` also fails
("Failed to delete image", 500) once a tag has an image (tag 10 could not be removed).
- **SL-02, SL-03, SL-04, SL-06, SL-07, SL-08** — not run (SL-05 above).
- **CT-02, CT-03, CT-05…CT-11** — not run. Incidental: quantity steppers work on cards and in the
dialog; removal asks for confirmation; checkout is read-only and has "Back to Cart"; the expanded
sheet shows progress vs threshold.
- **AD-02, AD-03, AD-04, AD-06…AD-09** — not run. Incidental: deleting an address attached to an
order is correctly refused ("Address is attached to an ongoing order. Please cancel the order
first."); deleting the only/default address is refused ("Cannot delete default address. Please set
another address as default first."); the app shows "No Location is attached to address" with an
attach action.
- **BL-02…BL-07** — not run except the BL-01 notes above; the coupon accounting mismatch is direct
evidence for BL-03/BL-04/BL-05.
- **CP-02…CP-11** — not run (coupon create/apply/order path verified for CP-01; user-based and
region-scoped variants untouched).
- **OR-02, OR-03, OR-05…OR-12** — not run except OR-01/OR-04 above; multi-slot suborders were not
exercised (both orders used a single slot / flash).
- **FL-02…FL-06** — FL-02 negative path verified via API; the rest not run (flash was disabled again).
- **OP-01…OP-08, RC-01…RC-06, SEC-01…SEC-08, PAY-02…PAY-05** — not run this session. Incidental
security observations: cross-region order/product/store/slot access denied; staff B removed
mid-run — its token subsequently failed (consistent with SEC-08's expectation).
## Findings summary (new, this run)
1. **`admin.product.deleteProduct` fails on D1** — `Failed query: delete from "product_info" … returning …` (500). No workaround except suspend.
2. **`admin.product.deleteProductTag` fails with an image** — `Failed to delete image` (500); the tag stays.
3. **`createProductTag` stores a malformed image URL** — `https://assets2.freshyo.in/https://<r2>/…` (double prefix).
4. **Full slot remains selectable in the customer UI** (SL-05): only the backend rejects it.
5. **Coupon accounting mismatch** (CP-01/BL-03/05): `discountAmount 47.36` recorded vs ₹30.4 applied; stored components don't reconstruct the stored total.
6. **`createProduct` is not atomic** with the image claim — a failed claim leaves a half-created product (and its SKUs) behind.
7. **Flash enable via `updateBoundSettings` doesn't propagate** to `essentialConsts`; `updateRegionConstants` does. Suspected `admin.order.getAll {flashDeliveryFilter:true}` filter defect.
8. **Address without coordinates gets `boundId: null`**, and the active browsing bound then falls back to the address's bound (A2 → ₹800 threshold) after selection — consistent with the guidelines' "explicit address selection isn't persisted" note, and the app flaps ("cart empty") once during that switch.
9. Rejected OOS/full-slot submissions surface as HTTP 500 / `INTERNAL_SERVER_ERROR` with a correct message (known ApiError flattening).
10. Harness: iOS `clearState` no-op; region sheet hangs on reuse; MCP 60 s request ceiling.
## Fixture state after the run (cleanup performed)
Removed/neutralised: staff B removed · coupon 43 invalidated · fixture slots 2033/2034 deactivated ·
region-1 fixture products 152 and orphan 151 suspended (renamed `ZZ … (delete-me)`) ·
flash reverted to `false` · bound 1 constants back to 300/20 · slot 2033 capacity restored ·
order 2495 delivered, order 2496 left as placed.
Left behind (blocked by missing/broken APIs): **region 2 + bound 3** (no delete endpoint),
stores 11 "E2E Store 1657" and 12 "E2E B Store 1702" (refuse while products exist, products only
suspendable), **tag 10** (delete broken), region-2 product 153 (region-1 admin can't touch it),
fresh customer `9000011715` + its default address 880, address 879 (attached to order 2495).
Bound-2 settings are charge 200 / threshold 800, which matches the configuration documented in the
13:10 report.
## Suggested report columns for the next run
case · platform · run ID · status (PASS/FAIL/PARTIAL/BLOCKED/NOT RUN/NEEDS-POLICY) · expected/actual ·
evidence (screenshot name + API probe) · entity IDs · follow-up owner.

View file

@ -96,6 +96,7 @@ export {
deleteProductGroup,
updateProductPrices,
toggleProductOutOfStock,
setProductSkusOutOfStock,
} from './src/admin-apis/product'
export {
@ -370,6 +371,7 @@ export {
export {
createUploadUrlStatus,
claimUploadUrlStatus,
getPendingUploadUrlKeys,
} from './src/helper_methods/upload-url'
// Seed Helpers
@ -405,6 +407,7 @@ export {
getBoundById,
createRegionBound,
updateRegionBound,
deleteRegionBound,
getBoundSettings,
upsertBoundSettings,
getRegionConstants,

View file

@ -11,6 +11,7 @@ import {
refunds,
} from '../db/schema'
import { and, desc, eq, gt, inArray, lt, SQL } from 'drizzle-orm'
import { applyDiscountToOrder } from '../user-apis/order'
import type {
AdminOrderDetails,
AdminOrderRow,
@ -167,27 +168,19 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
let couponData = null
if (couponUsageData.length > 0) {
// The coupon discounts the item subtotal, not the paid total: orders.total_amount
// stores items − discount + delivery, so using it as the base inflates the discount.
const itemsSubtotal = orderData.orderItems.reduce(
(sum: number, item: any) =>
sum +
parseFloat(item.price?.toString() || '0') * parseFloat(item.quantity?.toString() || '0'),
0
)
const proportion = Number(orderData.orderGroupProportion || 1)
let totalDiscountAmount = 0
const orderTotal = parseFloat((orderData.totalAmount ?? '0').toString())
for (const usage of couponUsageData) {
let discountAmount = 0
if (usage.coupon.discountPercent) {
discountAmount =
(orderTotal * parseFloat(usage.coupon.discountPercent.toString())) /
100
} else if (usage.coupon.flatDiscount) {
discountAmount = parseFloat(usage.coupon.flatDiscount.toString())
}
if (
usage.coupon.maxValue &&
discountAmount > parseFloat(usage.coupon.maxValue.toString())
) {
discountAmount = parseFloat(usage.coupon.maxValue.toString())
}
const { discountAmount } = applyDiscountToOrder(itemsSubtotal, usage.coupon, proportion)
totalDiscountAmount += discountAmount
}

View file

@ -25,7 +25,7 @@ import {
keyValStore,
couponApplicableProducts,
} from '../db/schema'
import { and, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm'
import { and, desc, eq, inArray, isNull, or, sql, type SQL } from 'drizzle-orm'
import { runBatched } from '../lib/run-batched'
import { marketStatsForRegion, isSkuSuspended } from '../lib/market-stats'
import type { InferSelectModel } from 'drizzle-orm'
@ -250,7 +250,10 @@ export async function getAllProducts(regionId: number): Promise<AdminProductWith
},
}) as ProductWithRelationsRow[]
return products.map((product) => ({
// Soft-deleted products keep their rows for order history but are hidden here.
return products
.filter((product) => product.skus.some((sku) => !sku.isDeleted))
.map((product) => ({
...mapProduct(product),
store: product.store ? mapStore(product.store) : null,
skus: product.skus.map((sku) => {
@ -333,30 +336,50 @@ export async function getProductById(regionId: number, id: number): Promise<Admi
}
}
export async function deleteProduct(regionId: number, id: number): Promise<AdminProduct | null> {
const [deletedProduct] = await db
.delete(productInfo)
.where(and(eq(productInfo.id, id), eq(productInfo.regionId, regionId)))
.returning()
/**
* Soft delete. `order_items.sku_id` is a NOT NULL FK and order history renders
* each line by joining order_items -> product_skus -> product_info (+ sku_features),
* so the product and its SKUs are kept: the SKU is flagged `is_deleted` and only the
* state that keeps the product orderable/visible is removed. Deleting the rows instead
* would either trip D1's FK enforcement or blank out historical order lines.
*/
async function softDeleteProduct(where: SQL): Promise<AdminProduct | null> {
const product = await db.query.productInfo.findFirst({
where,
with: { skus: { columns: { id: true } } },
})
if (!deletedProduct) {
if (!product) {
return null
}
return mapProduct(deletedProduct)
const skuIds = product.skus.map((sku) => sku.id)
if (skuIds.length > 0) {
await db.batch([
db.delete(productMarketStats).where(inArray(productMarketStats.skuId, skuIds)),
db.delete(cartItems).where(inArray(cartItems.skuId, skuIds)),
db.delete(couponApplicableProducts).where(inArray(couponApplicableProducts.skuId, skuIds)),
// product_tags / product_group_membership store SKU ids in their `product_id` column
db.delete(productTags).where(inArray(productTags.productId, skuIds)),
db.delete(productGroupMembership).where(inArray(productGroupMembership.productId, skuIds)),
db.delete(productCombos).where(inArray(productCombos.skuId, skuIds)),
db.delete(productCombos).where(inArray(productCombos.comboSkuId, skuIds)),
db.delete(specialDeals).where(inArray(specialDeals.skuId, skuIds)),
// sku_features are deliberately kept: order history composes the name/unit from them.
db.update(productSkus).set({ isDeleted: true }).where(inArray(productSkus.id, skuIds)),
] as any)
}
return mapProduct(product)
}
export async function deleteProduct(regionId: number, id: number): Promise<AdminProduct | null> {
return softDeleteProduct(and(eq(productInfo.id, id), eq(productInfo.regionId, regionId)))
}
export async function deleteGlobalProduct(id: number): Promise<AdminProduct | null> {
const [deletedProduct] = await db
.delete(productInfo)
.where(and(eq(productInfo.id, id), isNull(productInfo.regionId)))
.returning()
if (!deletedProduct) {
return null
}
return mapProduct(deletedProduct)
return softDeleteProduct(and(eq(productInfo.id, id), isNull(productInfo.regionId)))
}
export async function createProduct(input: CreateProductInput, regionId: number | null): Promise<AdminProductWithRelations> {
@ -1276,18 +1299,87 @@ export async function toggleProductOutOfStock(
return { id: productId, isOutOfStock: nextIsOutOfStock }
}
/**
* Set the stock flag for specific variants of a product (per SKU, per region).
*
* The all-variants `toggleProductOutOfStock` cannot express "one variant is out" (the plan's PD-06
* case) and collapses a partial state on the next press. This writes exactly the given SKUs'
* `product_market_stats` rows for the region and reports their resulting states.
*/
export async function setProductSkusOutOfStock(
regionId: number,
productId: number,
skuIds: number[],
isOutOfStock: boolean
): Promise<{
id: number
/** Requested ids that are not variants of this product (caller should reject the request). */
ignoredSkuIds: number[]
skus: Array<{ id: number; name: string | null; isOutOfStock: boolean }>
isOutOfStock: boolean
} | null> {
const product = await db.query.productInfo.findFirst({
where: and(eq(productInfo.id, productId), eq(productInfo.regionId, regionId)),
columns: { id: true },
})
if (!product) {
return null
}
const skus = await db.query.productSkus.findMany({
where: eq(productSkus.productId, productId),
with: { marketStats: true },
})
if (skus.length === 0) {
return null
}
const owned = new Set(skus.map((sku) => sku.id))
const requested = [...new Set(skuIds)]
const ignoredSkuIds = requested.filter((skuId) => !owned.has(skuId))
const targets = requested.filter((skuId) => owned.has(skuId))
if (targets.length > 0) {
await db
.update(productMarketStats)
.set({ isOutOfStock })
.where(and(inArray(productMarketStats.skuId, targets), eq(productMarketStats.regionId, regionId)))
}
const targetSet = new Set(targets)
const skuStates = skus.map((sku) => ({
id: sku.id,
name: sku.name ?? null,
isOutOfStock: targetSet.has(sku.id)
? isOutOfStock
: (marketStatsForRegion(sku.marketStats, regionId)?.isOutOfStock ?? false),
}))
return {
id: productId,
ignoredSkuIds,
skus: skuStates,
// Same convention as the all-variants toggle: out when any variant is out.
isOutOfStock: skuStates.some((sku) => sku.isOutOfStock),
}
}
// ==========================================================================
// Product Helpers for Admin Controller
// ==========================================================================
export async function checkProductExistsByName(name: string): Promise<boolean> {
const product = await db.query.productInfo.findFirst({
where: eq(productInfo.name, name),
columns: { id: true },
})
// Ignore soft-deleted products so a deleted name can be reused.
const product = await db
.select({ id: productInfo.id })
.from(productInfo)
.innerJoin(productSkus, eq(productSkus.productId, productInfo.id))
.where(and(eq(productInfo.name, name), eq(productSkus.isDeleted, false)))
.limit(1)
return !!product
return product.length > 0
}
export async function replaceTagProducts(regionId: number, tagId: number, productIds: number[]): Promise<void> {

View file

@ -1,4 +1,4 @@
import { and, eq } from 'drizzle-orm'
import { and, eq, inArray } from 'drizzle-orm'
import { db } from '../db/db_index'
import { uploadUrlStatus } from '../db/schema'
@ -18,3 +18,23 @@ export async function claimUploadUrlStatus(key: string): Promise<boolean> {
return result.length > 0
}
/**
* Of the given keys, the ones that still exist with status 'pending' — i.e. uploads that
* were issued by the app and have not been attached to anything yet. Callers use this to
* reject unknown/reused upload URLs *before* writing rows that would otherwise be orphaned
* when the later claim fails.
*/
export async function getPendingUploadUrlKeys(keys: string[]): Promise<string[]> {
const unique = [...new Set(keys.filter(Boolean))]
if (unique.length === 0) {
return []
}
const rows = await db
.select({ key: uploadUrlStatus.key })
.from(uploadUrlStatus)
.where(and(inArray(uploadUrlStatus.key, unique), eq(uploadUrlStatus.status, 'pending')))
return rows.map((row) => row.key)
}

View file

@ -1,5 +1,5 @@
import { db } from '../db/db_index'
import { regions, regionBounds, regionConsts, regionBoundConsts, productMarketStats } from '../db/schema'
import { regions, regionBounds, regionConsts, regionBoundConsts, productMarketStats, addresses } 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 {
@ -223,6 +223,89 @@ export async function getBoundsForRegion(regionId: number): Promise<RegionBoundD
return rows.map(toBoundDto)
}
export interface DeleteRegionBoundResult {
found: boolean
deleted: boolean
regionId: number | null
/** Addresses pointing at the bound; when > 0 the delete is refused. */
addressCount: number
/** True when this is the region's only bound, which may not be removed. */
lastBound: boolean
/** Bounds left in the region (unchanged when the delete was refused). */
remainingBounds: number
}
/**
* Removes a delivery bound and its settings. Refused when it is the region's only bound (a
* region needs at least one to take orders) and while any address still points at it
* (`addresses.boundId` is the only user-data FK to a bound).
*/
export async function deleteRegionBound(boundId: number): Promise<DeleteRegionBoundResult> {
const bound = await db.query.regionBounds.findFirst({
where: eq(regionBounds.id, boundId),
columns: { id: true, regionId: true },
})
if (!bound) {
return {
found: false,
deleted: false,
regionId: null,
addressCount: 0,
lastBound: false,
remainingBounds: 0,
}
}
const [boundCountRow] = await db
.select({ count: sql<number>`count(*)` })
.from(regionBounds)
.where(eq(regionBounds.regionId, bound.regionId))
const boundCount = Number(boundCountRow?.count ?? 0)
if (boundCount <= 1) {
return {
found: true,
deleted: false,
regionId: bound.regionId,
addressCount: 0,
lastBound: true,
remainingBounds: boundCount,
}
}
const [addressRow] = await db
.select({ count: sql<number>`count(*)` })
.from(addresses)
.where(eq(addresses.boundId, boundId))
const addressCount = Number(addressRow?.count ?? 0)
if (addressCount > 0) {
return {
found: true,
deleted: false,
regionId: bound.regionId,
addressCount,
lastBound: false,
remainingBounds: boundCount,
}
}
await db.transaction(async (tx) => {
await tx.delete(regionBoundConsts).where(eq(regionBoundConsts.boundId, boundId))
await tx.delete(regionBounds).where(eq(regionBounds.id, boundId))
})
return {
found: true,
deleted: true,
regionId: bound.regionId,
addressCount: 0,
lastBound: false,
remainingBounds: boundCount - 1,
}
}
export async function getBoundById(id: number): Promise<RegionBoundDto | null> {
const row = await db.query.regionBounds.findFirst({ where: eq(regionBounds.id, id) })
return row ? toBoundDto(row) : null
@ -276,16 +359,29 @@ export async function getBoundSettings(boundId: number): Promise<Record<string,
export async function upsertBoundSettings(
boundId: number,
settings: Array<{ key: string; value: string | null }>
): Promise<void> {
): Promise<{ updated: number; deleted: number }> {
const bound = await db.query.regionBounds.findFirst({
where: eq(regionBounds.id, boundId),
columns: { id: true, regionId: true },
})
if (!bound) throw new Error(`Region bound ${boundId} not found`)
let updated = 0
let deleted = 0
await db.transaction(async (tx) => {
for (const { key, value } of settings) {
const nextValue = value === null ? null : String(value)
// A null value means "remove this setting" so a bound falls back to the default.
if (value === null) {
const removed = await tx
.delete(regionBoundConsts)
.where(and(eq(regionBoundConsts.boundId, boundId), eq(regionBoundConsts.key, key)))
.returning({ key: regionBoundConsts.key })
deleted += removed.length
continue
}
const nextValue = String(value)
await tx
.insert(regionBoundConsts)
.values({ regionId: bound.regionId, boundId, key, value: nextValue })
@ -293,8 +389,11 @@ export async function upsertBoundSettings(
target: [regionBoundConsts.boundId, regionBoundConsts.key],
set: { value: nextValue, regionId: bound.regionId },
})
updated += 1
}
})
return { updated, deleted }
}
/** Region-scoped consts (region_consts) for one region. */
@ -308,10 +407,23 @@ export async function getRegionConstants(regionId: number): Promise<Record<strin
export async function upsertRegionConstants(
regionId: number,
settings: Array<{ key: string; value: string | null }>
): Promise<void> {
): Promise<{ updated: number; deleted: number }> {
let updated = 0
let deleted = 0
await db.transaction(async (tx) => {
for (const { key, value } of settings) {
const nextValue = value === null ? null : String(value)
// A null value means "remove this constant" so the reader falls back to its default.
if (value === null) {
const removed = await tx
.delete(regionConsts)
.where(and(eq(regionConsts.regionId, regionId), eq(regionConsts.key, key)))
.returning({ key: regionConsts.key })
deleted += removed.length
continue
}
const nextValue = String(value)
await tx
.insert(regionConsts)
.values({ regionId, key, value: nextValue })
@ -319,8 +431,11 @@ export async function upsertRegionConstants(
target: [regionConsts.regionId, regionConsts.key],
set: { value: nextValue },
})
updated += 1
}
})
return { updated, deleted }
}
/** The region's lowest-numbered-priority bound id, if any. */

View file

@ -155,16 +155,31 @@ export async function validateAndGetCoupon(
return coupon as CouponValidationResult
}
/** The discount fields a coupon row carries. `CouponValidationResult` and the coupon rows
* loaded for order history both satisfy this, so callers never need a cast. */
export type CouponDiscountFields = Pick<
CouponValidationResult,
'discountPercent' | 'flatDiscount' | 'maxValue'
>
/**
* Applies a coupon to an order/sub-order and returns the post-discount total.
*
* `orderTotal` must be the item subtotal (sum of price × quantity) — not the paid total, which
* already includes the discount and the delivery charge. The cap is prorated by `proportion`
* so a multi-slot cart's per-sub-order discount is the same share placeOrder charged.
*/
export function applyDiscountToOrder(
orderTotal: number,
appliedCoupon: CouponValidationResult | null,
appliedCoupon: CouponDiscountFields | null,
proportion: number
): { finalOrderTotal: number; orderGroupProportion: number } {
): { finalOrderTotal: number; discountAmount: number; orderGroupProportion: number } {
let finalOrderTotal = orderTotal
let discountAmount = 0
if (appliedCoupon) {
if (appliedCoupon.discountPercent) {
const discount = Math.min(
discountAmount = Math.min(
(orderTotal *
parseFloat(appliedCoupon.discountPercent.toString())) /
100,
@ -172,19 +187,18 @@ export function applyDiscountToOrder(
? parseFloat(appliedCoupon.maxValue.toString()) * proportion
: Infinity
)
finalOrderTotal -= discount
} else if (appliedCoupon.flatDiscount) {
const discount = Math.min(
discountAmount = Math.min(
parseFloat(appliedCoupon.flatDiscount.toString()) * proportion,
appliedCoupon.maxValue
? parseFloat(appliedCoupon.maxValue.toString()) * proportion
: finalOrderTotal
: orderTotal
)
finalOrderTotal -= discount
}
finalOrderTotal -= discountAmount
}
return { finalOrderTotal, orderGroupProportion: proportion }
return { finalOrderTotal, discountAmount, orderGroupProportion: proportion }
}
export async function getAddressByIdAndUser(

View file

@ -438,6 +438,10 @@ export interface AdminToggleOutOfStockResult {
productId: number;
isOutOfStock: boolean;
message: string;
/** Variants targeted by this call (only set when the caller passed `skuIds`). */
affectedSkuIds?: number[];
/** Per-variant state after the call (only set when the caller passed `skuIds`). */
skus?: Array<{ id: number; name: string | null; isOutOfStock: boolean }>;
}
export interface AdminUpdateSlotProductsResult {

7
test-creds.txt Normal file
View file

@ -0,0 +1,7 @@
superadmin ui:
username: superadmin
password: superadmiN123
user ui: (use login with password, not otp)
username: 9676651496
password: meatfarmer@123