tests addition

This commit is contained in:
shafi54 2026-09-26 22:29:54 +05:30
parent 677778ab33
commit 9844cd9900
35 changed files with 1065 additions and 1045 deletions

View file

@ -9,20 +9,7 @@ export default function CreateCoupon() {
const router = useRouter();
const createCoupon = trpc.admin.coupon.create.useMutation();
const createReservedCoupon = trpc.admin.coupon.createReservedCoupon.useMutation();
const { refetch: refetchCoupons } = trpc.admin.coupon.getAll.useInfiniteQuery(
{ limit: 20, search: '' },
{
enabled: false,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
)
const { refetch: refetchReservedCoupons } = trpc.admin.coupon.getReservedCoupons.useInfiniteQuery(
{ limit: 20, search: '' },
{
enabled: false,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
)
const utils = trpc.useUtils();
const handleCreateCoupon = async (values: any) => {
const { isReservedCoupon, couponCodes, ...rest } = values;
@ -47,8 +34,9 @@ export default function CreateCoupon() {
const mutation = isReservedCoupon ? createReservedCoupon : createCoupon;
try {
await mutation.mutateAsync({ ...payload, couponCodes: codes });
await refetchCoupons()
await refetchReservedCoupons()
// Invalidate by path so the list refreshes whatever search term it holds.
utils.admin.coupon.getAll.invalidate()
utils.admin.coupon.getReservedCoupons.invalidate()
Alert.alert('Success', `${codes.length} coupon${codes.length > 1 ? 's' : ''} created successfully`, [
{ text: 'OK', onPress: () => router.back() }
]);

View file

@ -13,21 +13,8 @@ export default function EditCoupon() {
const couponId = parseInt(id as string);
const { data: coupon, isLoading, refetch } = trpc.admin.coupon.getById.useQuery({ id: couponId });
const { refetch: refetchCoupons } = trpc.admin.coupon.getAll.useInfiniteQuery(
{ limit: 20, search: '' },
{
enabled: false,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
)
const { refetch: refetchReservedCoupons } = trpc.admin.coupon.getReservedCoupons.useInfiniteQuery(
{ limit: 20, search: '' },
{
enabled: false,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
)
const updateCoupon = trpc.admin.coupon.update.useMutation();
const utils = trpc.useUtils();
const handleUpdateCoupon = (values: CreateCouponPayload & { isReservedCoupon?: boolean }) => {
// Transform targetUsers array to targetUser for backend compatibility
@ -45,8 +32,9 @@ export default function EditCoupon() {
updateCoupon.mutate({ id: couponId, updates }, {
onSuccess: async () => {
await refetch()
await refetchCoupons()
await refetchReservedCoupons()
// Invalidate by path so the list refreshes whatever search term it holds.
utils.admin.coupon.getAll.invalidate()
utils.admin.coupon.getReservedCoupons.invalidate()
Alert.alert('Success', 'Coupon updated successfully', [
{ text: 'OK', onPress: () => router.back() }
]);

View file

@ -21,7 +21,6 @@ import {
import { useRouter } from "expo-router";
import { trpc } from "../../../../src/trpc-client";
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { useQueryClient } from "@tanstack/react-query";
const { width: screenWidth } = Dimensions.get("window");
// Item takes full width minus padding
@ -88,7 +87,7 @@ const ProductItem: React.FC<DragOrderItemProps<Product>> = ({
export default function AllItemsOrder() {
const router = useRouter();
const queryClient = useQueryClient();
const utils = trpc.useUtils();
const [products, setProducts] = useState<Product[]>([]);
const [hasChanges, setHasChanges] = useState(false);
@ -177,7 +176,7 @@ export default function AllItemsOrder() {
onSuccess: () => {
setHasChanges(false);
Alert.alert('Success', 'All items order updated successfully!');
queryClient.invalidateQueries({ queryKey: ['const.getConstants'] });
utils.admin.const.getConstants.invalidate();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update items order. Please try again.');

View file

@ -23,7 +23,6 @@ import ProductsSelector from "../../../../components/ProductsSelector";
import { useRouter } from "expo-router";
import { trpc } from "../../../../src/trpc-client";
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { useQueryClient } from "@tanstack/react-query";
import type { StoreProductCard } from '@packages/shared';
import type { DragOrderItemProps } from '@/types/drag-order-item';
@ -113,7 +112,7 @@ const ProductItem: React.FC<ProductItemProps> = ({
export default function CustomizePopularItems() {
const router = useRouter();
const queryClient = useQueryClient();
const utils = trpc.useUtils();
const [popularProducts, setPopularProducts] = useState<PopularProduct[]>([]);
const [hasChanges, setHasChanges] = useState(false);
const [showAddDialog, setShowAddDialog] = useState(false);
@ -211,7 +210,7 @@ export default function CustomizePopularItems() {
onSuccess: () => {
setHasChanges(false);
Alert.alert('Success', 'Popular items updated successfully!');
queryClient.invalidateQueries({ queryKey: ['const.getConstants'] });
utils.admin.const.getConstants.invalidate();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update popular items. Please try again.');

View file

@ -36,6 +36,7 @@ export default function EditBanner() {
enabled: false,
});
const [banner, setBanner] = useState<typeof bannerData>(undefined);
const utils = trpc.useUtils();
useEffect(() => {
@ -105,6 +106,8 @@ export default function EditBanner() {
});
await refetchBanners()
// This screen renders getBanner (and mirrors it into local state).
utils.admin.banner.getBanner.invalidate();
Alert.alert('Success', 'Banner updated successfully', [
{
text: 'OK',

View file

@ -148,6 +148,9 @@ export default function DashboardBanners() {
serialNum: null
});
// getBanners carries the serialNum -> slot labels this list renders.
refetch();
// Update local state
setSlotAssignments(prev => ({
...prev,

View file

@ -449,6 +449,10 @@ export default function DeliverySequences() {
onSuccess: () => {
setHasSequenceChanged(false);
Alert.alert("Success", "Delivery sequence updated successfully");
// The saved sequence lives in getDeliverySequence / getSlotOrders, both of which
// stay mounted on this screen.
refetchSequence();
refetchOrders();
},
onError: (error: any) => {
Alert.alert(
@ -763,7 +767,10 @@ export default function DeliverySequences() {
setShowOrderMenu(false);
setCancelDialogOpen(true);
}}
onAttachLocation={() => {}}
onAttachLocation={() => {
refetchOrders();
refetchSequence();
}}
onWhatsApp={() => {}}
onDial={() => {}}
/>

View file

@ -48,6 +48,7 @@ export default function OrderDetails() {
: "N/A"
}`
);
refetch();
setGenerateCouponDialogOpen(false);
},
onError: (error: any) => {
@ -66,6 +67,7 @@ export default function OrderDetails() {
`Refund initiated successfully!\n\nAmount: `
// `Refund initiated successfully!\n\nAmount: ₹${result.amount}\nStatus: ${result.status}`
);
refetch();
setInitiateRefundDialogOpen(false);
},
onError: (error: any) => {

View file

@ -23,6 +23,7 @@ export default function EditTag() {
enabled: false,
});
const updateTag = trpc.admin.product.updateProductTag.useMutation();
const utils = trpc.useUtils();
const { data: storesData } = trpc.admin.store.getStores.useQuery();
const { upload, isUploading } = useUploadToObjectStorage();
@ -59,6 +60,8 @@ export default function EditTag() {
})
await refetchTags()
// The detail query this screen was seeded from is not the list.
utils.admin.product.getProductTagById.invalidate();
Alert.alert('Success', 'Tag updated successfully', [
{
text: 'OK',

View file

@ -20,7 +20,6 @@ import {
import { useRouter } from 'expo-router';
import { trpc } from '../../../../src/trpc-client';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useQueryClient } from '@tanstack/react-query';
import type { DragOrderItemProps } from '@/types/drag-order-item';
const { width: screenWidth } = Dimensions.get('window');
@ -79,7 +78,7 @@ const TagItem: React.FC<DragOrderItemProps<Tag>> = ({ item, drag, isActive }) =>
export default function TagOrders() {
const router = useRouter();
const queryClient = useQueryClient();
const utils = trpc.useUtils();
const [tags, setTags] = useState<Tag[]>([]);
const [hasChanges, setHasChanges] = useState(false);
@ -166,7 +165,7 @@ export default function TagOrders() {
onSuccess: () => {
setHasChanges(false);
Alert.alert('Success', 'Tag order updated successfully!');
queryClient.invalidateQueries({ queryKey: ['const.getConstants'] });
utils.admin.const.getConstants.invalidate();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update tag order. Please try again.');

View file

@ -26,6 +26,7 @@ const ReviewResponseForm: React.FC<ReviewResponseFormProps> = ({ reviewId, onClo
const [displayImages, setDisplayImages] = useState<{ uri?: string }[]>([]);
const respondToReview = trpc.admin.product.respondToReview.useMutation();
const utils = trpc.useUtils();
const { upload } = useUploadToObjectStorage();
const handleImagePick = usePickImage({
@ -74,6 +75,8 @@ const ReviewResponseForm: React.FC<ReviewResponseFormProps> = ({ reviewId, onClo
uploadUrls: presignedUrls,
});
// The parent screen's reviews list stays mounted behind this dialog, so refresh it.
utils.admin.product.getProductReviews.invalidate();
Alert.alert('Success', 'Response submitted');
onClose();
setAdminResponse('');

View file

@ -17,11 +17,14 @@ export default function EditStore() {
);
const updateStoreMutation = trpc.admin.store.updateStore.useMutation();
const utils = trpc.useUtils();
const handleSubmit = (values: StoreFormData) => {
updateStoreMutation.mutate({ id: storeId, ...values }, {
onSuccess: (data) => {
refetch();
// The stores list is still mounted behind this screen.
utils.admin.store.getStores.invalidate();
Alert.alert('Success', data.message);
router.push('/(drawer)/dashboard/stores' as any);
},

View file

@ -29,6 +29,7 @@ const ProductGroupForm: React.FC<ProductGroupFormProps> = ({
const createGroup = trpc.admin.product.createGroup.useMutation();
const updateGroup = trpc.admin.product.updateGroup.useMutation();
const utils = trpc.useUtils();
const isEditing = !!group;
@ -67,6 +68,8 @@ const ProductGroupForm: React.FC<ProductGroupFormProps> = ({
product_ids: values.product_ids,
});
}
// The groupings list/detail screens render getGroups.
utils.admin.product.getGroups.invalidate();
onSuccess();
} catch (error: any) {
Alert.alert('Error', error.message || 'Failed to save group');

View file

@ -51,6 +51,7 @@ export default function SlotForm({
const { mutate: createSlot, isPending: isCreating } = trpc.admin.slots.createSlot.useMutation();
const { mutate: updateSlot, isPending: isUpdating } = trpc.admin.slots.updateSlot.useMutation();
const utils = trpc.useUtils();
const isEditMode = !!slotId;
const isPending = isCreating || isUpdating;
@ -87,6 +88,8 @@ export default function SlotForm({
{
onSuccess: () => {
Alert.alert('Success', 'Slot updated successfully!');
// Nothing else refreshes the slot list/detail the admin came from.
utils.admin.slots.invalidate();
onSlotAdded?.();
},
onError: (error: any) => {

View file

@ -5,7 +5,7 @@ real credentials, create data through the API, and pull the generated static JSO
cache the apps consume.
- **Runner**: jest + ts-jest, node environment, serial (`--runInBand`)
- **Total**: **21 suites / 103 tests** — all green (`bun run test:api`, ~2.5 min)
- **Total**: **22 suites / 107 tests** — all green (`bun run test:api`, ~2.5 min)
- Tests live in `apps/backend/tests/`; they do not import server runtime code beyond
the `AppRouter` type.
@ -106,6 +106,21 @@ bun run test:api:typecheck # tsc over tests/
`cacheVersion` advances on every admin write while the ~30 s rebuild writes the per-store files
separately, so the store-detail test resolves the current version on each poll attempt instead
of pinning it.
- **A presigned upload URL is usable by any client, with no R2 credentials.** The signature
travels in the query string and `Content-Type` is deliberately left unsigned (see the comment
in `generateUploadUrl`), so the test process can PUT bytes straight to R2 and read the object
back from the public assets domain. `X-Amz-Expires` is 180 s.
- **The object key is `${folder}/${Date.now()}${extension}`** (`common.generateUploadUrls`), with
the folder chosen from `contextString` (product-images, tags, store-images, review-images,
review-response-images, complaint-images, profile-images) and the extension from the mime type
(jpg/png/gif, jpg fallback). Two files with the *same* mime type in one call share a
millisecond and therefore a key — one pending-status row, two URLs, one object. Deliberately
not covered here.
- **Every presign writes a `pending` status row** (`createUploadUrlStatus`), and `claimUploadUrl`
flips it to claimed — throwing `Failed to claim upload URL` when the row is absent or already
claimed. The admin create paths that accept `uploadUrls` (product SKU images, tag image,
review response) depend on it. Not covered here: claim/re-claim, and `deleteImageUtil` on image
replacement (store update, tag update/delete, product update).
## Suites
@ -297,6 +312,18 @@ Uses a tiny-priced SKU (5) so one unit is below `minRegularOrderValue`.
| 102 | deletes a store | `store.createStore` → `deleteStore({ storeId })` → `getStoreById` no longer resolves |
| 103 | places two concurrent orders for different slots | two `placeOrder` calls in parallel → two distinct, persisted order ids |
### `api/uploads.test.ts` — 4 (image upload round trip)
The presigned PUT is self-signed, so these cases upload real bytes without any R2 credentials and
read them back from the public assets domain (`common.essentialConsts.assetsDomain`, the same
source the app renders from). Objects stay in the dev bucket.
| # | Test | Request → assert |
| --- | --- | --- |
| 104 | stores exactly the bytes that were uploaded | `common.generateUploadUrls({contextString:'product_info'})` → PUT a 1×1 PNG → GET `<assetsDomain>/<key>` → same length, byte-equal, same sha256 |
| 105 | keeps two uploads distinct — each URL serves its own object | presign in two folders (product-images, tags) → different keys → each serves its own PNG, shas differ |
| 106 | gives every mime type in one call a usable URL | one call with `['image/png','image/jpeg']` → 2 distinct keys → both objects hold their own bytes |
| 107 | returns 404 for an object that was never uploaded | guards the read-back: a passing comparison must mean the object really exists |
## Harness reference
| Path | Purpose |

View file

@ -0,0 +1,133 @@
/**
* Image uploads — the round trip, not just the response shape.
*
* The presigned PUT carries its own signature, so this suite needs no R2 credentials:
* it PUTs real bytes to the URL `common.generateUploadUrls` returns, then GETs the object
* back from the public assets domain (the same source the app renders from) and compares.
*
* Objects are left in the dev bucket, consistent with the rest of these tests.
*/
import { createHash } from 'crypto'
import { apiClient, uniqueSuffix } from '../helpers/api'
import { essentialConsts } from '../helpers/cache'
import { userSession } from '../helpers/sessions'
/** Two 1x1 PNGs that differ only in pixel data, so a mix-up is visible. */
const PNG_RED = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg==',
'base64'
)
const PNG_BLUE = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAE/wH/9tH4WQAAAABJRU5ErkJggg==',
'base64'
)
const sha = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex')
/** The object key, as extractKeyFromPresignedUrl derives it (last two path segments). */
const keyFromUploadUrl = (url: string) => {
const parts = new URL(url).pathname.split('/').filter(Boolean)
return decodeURIComponent(parts.slice(-2).join('/'))
}
const publicUrlFor = (assetsDomain: string, key: string) =>
`${assetsDomain.replace(/\/+$/, '')}/${key}`
/** Presign one file and return its URL plus the key it points at. */
async function presign(
client: ReturnType<typeof apiClient>,
contextString: string,
mimeType: string
) {
const { uploadUrls } = await client.common.generateUploadUrls.mutate({
contextString: contextString as never,
mimeTypes: [mimeType],
})
const url = uploadUrls[0]
return { url, key: keyFromUploadUrl(url) }
}
async function put(url: string, bytes: Buffer) {
const res = await fetch(url, {
method: 'PUT',
body: new Uint8Array(bytes),
})
if (!res.ok) {
throw new Error(
`[uploads] PUT failed: ${res.status} ${res.statusText} ${await res.text().catch(() => '')}`
)
}
}
/** GET the object from the public domain; returns null when it is not there. */
async function fetchObject(url: string) {
const res = await fetch(url)
if (!res.ok) return null
return Buffer.from(await res.arrayBuffer())
}
describe('image upload round trip', () => {
let client: ReturnType<typeof apiClient>
let assetsDomain: string
beforeAll(async () => {
const session = await userSession()
client = apiClient(session.token)
assetsDomain = (await essentialConsts()).assetsDomain
})
it('stores exactly the bytes that were uploaded', async () => {
const { url, key } = await presign(client, 'product_info', 'image/png')
expect(url).toContain('X-Amz-Signature')
await put(url, PNG_RED)
const served = await fetchObject(publicUrlFor(assetsDomain, key))
expect(served).not.toBeNull()
expect(served!.length).toBe(PNG_RED.length)
expect(served!.equals(PNG_RED)).toBe(true)
expect(sha(served!)).toBe(sha(PNG_RED))
})
it('keeps two uploads distinct — each URL serves its own object', async () => {
const first = await presign(client, 'product_info', 'image/png')
const second = await presign(client, 'tags', 'image/png')
expect(second.key).not.toBe(first.key)
await put(first.url, PNG_RED)
await put(second.url, PNG_BLUE)
const servedFirst = await fetchObject(publicUrlFor(assetsDomain, first.key))
const servedSecond = await fetchObject(publicUrlFor(assetsDomain, second.key))
expect(servedFirst!.equals(PNG_RED)).toBe(true)
expect(servedSecond!.equals(PNG_BLUE)).toBe(true)
// The two documents really are different files.
expect(sha(servedFirst!)).not.toBe(sha(servedSecond!))
})
it('gives every mime type in one call a usable URL', async () => {
const { uploadUrls } = await client.common.generateUploadUrls.mutate({
contextString: 'review',
mimeTypes: ['image/png', 'image/jpeg'],
})
expect(uploadUrls).toHaveLength(2)
const keys = uploadUrls.map(keyFromUploadUrl)
expect(new Set(keys).size).toBe(2)
await put(uploadUrls[0], PNG_RED)
await put(uploadUrls[1], PNG_BLUE)
expect((await fetchObject(publicUrlFor(assetsDomain, keys[0])))!.equals(PNG_RED)).toBe(true)
expect((await fetchObject(publicUrlFor(assetsDomain, keys[1])))!.equals(PNG_BLUE)).toBe(true)
})
it('returns 404 for an object that was never uploaded', async () => {
// Guards the read-back itself: a passing comparison must mean the object is really there.
const missing = publicUrlFor(assetsDomain, `product-images/never-${uniqueSuffix()}.png`)
expect(await fetchObject(missing)).toBeNull()
})
})

View file

@ -2,7 +2,13 @@
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"isolatedModules": true
"isolatedModules": true,
/* Declared here as well as inherited: the app config's typeRoots are written
relative to apps/backend, so a checker that resolves inherited relative paths
against this file (apps/backend/tests) would miss the hoisted @types/jest and
lose the jest globals. These point at the same directories from here. */
"typeRoots": ["../../../node_modules/@types", "../node_modules/@types"],
"types": ["jest", "node"]
},
"include": ["./**/*.ts"]
}

View file

@ -94,6 +94,7 @@ export default function Addresses() {
const updateAddressMutation = trpc.user.address.updateAddress.useMutation();
const deleteAddressMutation = trpc.user.address.deleteAddress.useMutation();
const utils = trpc.useUtils();
const handleAddAddress = () => {
setEditingAddress(null);
@ -118,6 +119,8 @@ export default function Addresses() {
deleteAddressMutation.mutate({ id }, {
onSuccess: () => {
refetch();
// The quick-delivery selector observes getDefaultAddress.
utils.user.address.getDefaultAddress.invalidate();
Alert.alert('Success', 'Address deleted successfully');
},
onError: (error) => {
@ -147,6 +150,7 @@ export default function Addresses() {
}, {
onSuccess: () => {
refetch();
utils.user.address.getDefaultAddress.invalidate();
Alert.alert('Success', 'Default address updated');
},
onError: (error) => {

View file

@ -129,12 +129,15 @@ export default function Coupons() {
);
const { data, isLoading, error, refetch } = trpc.user.coupon.getMyCoupons.useQuery();
const utils = trpc.useUtils();
const [couponCode, setCouponCode] = useState('');
const redeemCouponMutation = trpc.user.coupon.redeemReservedCoupon.useMutation({
onSuccess: () => {
setCouponCode('');
refetch();
// The cart/checkout coupon dropdown observes getEligible.
utils.user.coupon.getEligible.invalidate();
Alert.alert('Success', 'Coupon added successfully!');
},
onError: (error: any) => {

View file

@ -13,6 +13,7 @@ import { orderStatusManipulator } from "@/src/lib/string-manipulators";
export default function OrderDetails() {
const { id } = useLocalSearchParams<{ id: string }>();
const router = useRouter();
const utils = trpc.useUtils();
const {
data: orderData,
@ -48,6 +49,8 @@ export default function OrderDetails() {
setCancelDialogOpen(false);
setCancelReason("");
refetch();
// The list behind this detail screen observes getOrders.
utils.user.order.getOrders.invalidate();
Alert.alert('Success', 'Order cancelled successfully');
},
onError: (error: any) => {

View file

@ -353,6 +353,8 @@ export default function MyOrders() {
pageSize: pageSize,
});
const utils = trpc.useUtils();
const createRazorpayOrderMutation = trpc.user.payment.createRazorpayOrder.useMutation({
@ -371,6 +373,8 @@ export default function MyOrders() {
const verifyPaymentMutation = trpc.user.payment.verifyPayment.useMutation({
onSuccess: () => {
refetch();
// Refresh the NextOrderGlimpse observer too.
utils.user.order.getOrders.invalidate();
Alert.alert('Success', 'Payment completed successfully');
},
onError: (error: any) => {

View file

@ -25,6 +25,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
const [locationLoading, setLocationLoading] = useState(false);
const [currentIndex, setCurrentIndex] = useState(0);
const queryClient = useQueryClient();
const utils = trpc.useUtils();
const scrollViewRef = useRef<ScrollView>(null);
const { isAuthenticated } = useAuth();
const { data: addresses } = trpc.user.address.getUserAddresses.useQuery(
@ -34,7 +35,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
const updateAddressMutation = trpc.user.address.updateAddress.useMutation({
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['user.address.getUserAddresses'] });
utils.user.address.getUserAddresses.invalidate();
setEditingLocationAddressId(null);
Alert.alert('Success', 'Location attached successfully');
},

View file

@ -13,6 +13,7 @@ interface OrderMenuProps {
const OrderMenu: React.FC<OrderMenuProps> = ({ orderId, postActionHandler }) => {
const router = useRouter();
const utils = trpc.useUtils();
const [open, setOpen] = useState(false);
const [editNotesDialogOpen, setEditNotesDialogOpen] = useState(false);
const [editNotes, setEditNotes] = useState('');
@ -54,6 +55,8 @@ const OrderMenu: React.FC<OrderMenuProps> = ({ orderId, postActionHandler }) =>
Alert.alert('Success', 'Order cancelled successfully');
setCancelDialogOpen(false);
setCancelReason('');
// Refresh every getOrders observer, including NextOrderGlimpse.
utils.user.order.getOrders.invalidate();
postActionHandler?.();
} catch (error: any) {
Alert.alert('Error', error.message || 'Failed to cancel order');

View file

@ -46,6 +46,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
const router = useRouter();
const queryClient = useQueryClient();
const utils = trpc.useUtils();
const [userNotes, setUserNotes] = useState('');
const [isLoadingDialogOpen, setIsLoadingDialogOpen] = useState(false);
const [paymentMethod, setPaymentMethod] = useState<'online' | 'cod'>('cod');
@ -75,6 +76,10 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
const orders = data.data; // Now an array of orders
const firstOrder = orders[0]; // Use first order for payment flow
// NextOrderGlimpse (home/me tabs) observes getOrders and would otherwise
// keep showing the pre-order list.
utils.user.order.getOrders.invalidate();
if (!firstOrder.isCod) {
// createRazorpayOrderMutation.mutate({ orderId: firstOrder.id.toString() });
} else {
@ -98,6 +103,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
onSuccess: () => {
const orders = placeOrderMutation.data?.data || [];
const firstOrder = orders[0];
utils.user.order.getOrders.invalidate();
// Clear cart and navigate to success page
clearCartAndInvalidateQueries(isFlashDelivery ? 'flash' : 'regular');
const successPath = isFlashDelivery

View file

@ -43,7 +43,13 @@ export const useRegister = () => {
};
export const useUpdateProfile = () => {
const mutation = trpc.user.auth.updateProfile.useMutation()
const utils = trpc.useUtils()
const mutation = trpc.user.auth.updateProfile.useMutation({
onSuccess: () => {
// The cached profile must match the edited one.
utils.user.user.getSelfData.invalidate()
},
})
return {
...mutation,

View file

@ -5,6 +5,7 @@ import { useRegister } from '@/src/api-hooks/auth.api';
import { AuthState, AuthContextType, LoginCredentials, RegisterData, User, UserDetails } from '@/src/types/auth';
import { trpc } from '@/src/trpc-client';
import { StorageServiceCasual } from 'common-ui';
import { useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'expo-router';
import constants from '@/src/constants';
import type { AuthRedirectOptions, ReactParentComponent } from '@packages/shared';
@ -19,6 +20,7 @@ const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
const router = useRouter();
const queryClient = useQueryClient();
const [authState, setAuthState] = useState<AuthState>({
user: null,
userDetails: null,
@ -261,6 +263,7 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
const logout = async (): Promise<void> => {
try {
await deleteAuthToken();
queryClient.clear();
setAuthState({
user: null,
userDetails: null,
@ -270,6 +273,7 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
});
} catch (error) {
// Still clear local state even if deleteJWT fails
queryClient.clear();
setAuthState({
user: null,
userDetails: null,

View file

@ -5,7 +5,7 @@ each one locks in. Companion to `tests/home-page/README.md` (long-form home-page
detail).
- **Runner**: `jest-expo` + `@testing-library/react-native`
- **Total**: **62 suites / 327 tests** — all green (`NODE_ENV=test bun run test`, ~45 s)
- **Total**: **63 suites / 329 tests** — all green (`NODE_ENV=test bun run test`, ~45 s)
- Per-group counts below are counted from the files (`it`/`test` lines); jest expands
`it.each` cases, so a run reports a few more than the sum of these tables.
- Network is mocked at the layer (`tests/mocks/api.ts`); components, stores, hooks and the router stay real.
@ -384,14 +384,15 @@ Cart: 2 x product 2 @ 215 = 430. Consts: freeDeliveryThreshold 249, deliveryChar
| 3 | creates an address via user.address.createAddress | payload |
| 4 | updates an address in edit mode via user.address.updateAddress | `{id, name}` |
### `address-selectors.test.tsx` — 5
### `address-selectors.test.tsx` — 6
| # | Test | Asserts |
| --- | --- | --- |
| 1 | lists the addresses and auto-selects the default | both cards + `onAddressSelect(2)` |
| 2 | selects an address on press | `onAddressSelect(1)` |
| 3 | shows the empty state | empty copy + Add Address |
| 4 | shows the earliest slot and changes it from the dialog | slot options → `onSlotChange` |
| 5 | shows the flash header variant | "Delivery in within 1 hour" |
| 3 | refreshes the addresses after attaching the current location | `updateAddress` gets the mocked coords, then `getUserAddresses` is fetched a **second** time (fails with the old dotted-string invalidation) |
| 4 | shows the empty state | empty copy + Add Address |
| 5 | shows the earliest slot and changes it from the dialog | slot options → `onSlotChange` |
| 6 | shows the flash header variant | "Delivery in within 1 hour" |
### `location-attacher.test.tsx` — 3
| # | Test | Asserts |
@ -440,7 +441,7 @@ Cart: 2 x product 2 @ 215 = 430. Consts: freeDeliveryThreshold 249, deliveryChar
---
# hooks / stores / lib / contexts — 81 (hooks 40, stores 19, contexts 14, lib 8)
# hooks / stores / lib / contexts — 82 (hooks 40, stores 19, contexts 14, lib 9)
### `hooks/cart-query-hooks.test.tsx` — 6
| # | Test | Asserts |
@ -531,6 +532,11 @@ Cart: 2 x product 2 @ 215 = 430. Consts: freeDeliveryThreshold 249, deliveryChar
| 1 | emits the force-logout event on a 401 UNAUTHORIZED response | `FORCE_LOGOUT_EVENT` |
| 2 | does not emit the force-logout event on a 500 response | no emit |
### `lib/query-invalidation-keys.test.tsx` — 1
| # | Test | Asserts |
| --- | --- | --- |
| 1 | matches the array path form and ignores the dotted string form | the stored key is `[['user','address','getUserAddresses'], {type}]`; `findAll({queryKey:['user.address.getUserAddresses']})` matches 0, the array form matches 1 (pins the stale-data bug in `CheckoutAddressSelector`) |
### `contexts/auth-context.test.tsx` — 4
| # | Test | Asserts |
| --- | --- | --- |

View file

@ -11,6 +11,7 @@ import CheckoutAddressSelector from '@/components/CheckoutAddressSelector'
import QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector'
import { mockSlots, resetStorage, setupApiMocks } from '../mocks/api'
import { authMock, resetAuthMock } from '../mocks/auth'
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
import { useAddressStore } from '@/src/store/addressStore'
import { renderWithProviders } from '../helpers/render'
@ -83,6 +84,38 @@ describe('CheckoutAddressSelector', () => {
expect(onAddressSelect).toHaveBeenCalledWith(1)
})
it('refreshes the addresses after attaching the current location', async () => {
const api = setupApiMocks({
procedures: {
'user.address.getUserAddresses': ADDRESSES,
'user.address.updateAddress': { data: { id: 2 } },
},
})
renderWithProviders(
<CheckoutAddressSelector selectedAddress={2} onAddressSelect={jest.fn()} />,
{ centralStores: false }
)
await waitFor(() => expect(screen.getByText('Work')).toBeVisible())
expect(expectProcedureCalled(api.fetchMock, 'user.address.getUserAddresses')).toHaveLength(1)
fireEvent.press(screen.getByText('+ Attach Current Location'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.address.updateAddress'))
expect(lastProcedureInput(api.fetchMock, 'user.address.updateAddress')).toMatchObject({
id: 2,
latitude: 17.385,
longitude: 78.4867,
})
// The invalidation has to actually match: a second read of the addresses.
await waitFor(() =>
expect(
expectProcedureCalled(api.fetchMock, 'user.address.getUserAddresses').length
).toBe(2)
)
})
it('shows the empty state', async () => {
setupApiMocks({
procedures: { 'user.address.getUserAddresses': { data: [] } },

View file

@ -0,0 +1,56 @@
/**
* AuthProvider.logout must clear the query cache.
*
* Without it, a signed-out (or deleted) account's orders, addresses, coupons
* and profile stay cached and are served to the next session on the same
* device. Uses the REAL provider (tests/setup.ts stubs AuthContext globally).
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
jest.unmock('@/src/contexts/AuthContext')
import React from 'react'
import { Text, TouchableOpacity } from 'react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import { AuthProvider, useAuth } from '@/src/contexts/AuthContext'
import { setupApiMocks } from '../mocks/api'
import { createQueryClient, renderWithProviders } from '../helpers/render'
const Probe = () => {
const { logout } = useAuth()
return (
<TouchableOpacity
testID="logout"
onPress={() => {
void logout()
}}
>
<Text>logout</Text>
</TouchableOpacity>
)
}
describe('AuthProvider logout', () => {
it('removes cached queries so the next session starts clean', async () => {
setupApiMocks()
const queryClient = createQueryClient()
// Stand in for the user-scoped data cached during a session.
queryClient.setQueryData(['user-scoped-data'], { orders: [1, 2, 3] })
expect(queryClient.getQueryData(['user-scoped-data'])).toEqual({ orders: [1, 2, 3] })
renderWithProviders(
<AuthProvider>
<Probe />
</AuthProvider>,
{ queryClient, centralStores: false }
)
fireEvent.press(screen.getByTestId('logout'))
await waitFor(() =>
expect(queryClient.getQueryData(['user-scoped-data'])).toBeUndefined()
)
})
})

View file

@ -0,0 +1,55 @@
/**
* Query-key shape — why `invalidateQueries({ queryKey: ['a.b.c'] })` silently does nothing.
*
* tRPC v11 stores keys as `[pathArray, { input?, type? }]` (see getQueryKeyInternal in
* @trpc/react-query). TanStack matches a filter against the stored key with partialMatchKey,
* which rejects a string where the key has an array — so the dotted form matches zero queries
* and the mutation's data stays stale.
*
* This is the regression guard for that class: CheckoutAddressSelector was invalidating
* `['user.address.getUserAddresses']` and never refreshing the addresses it renders.
*
* The assertions use getQueryCache().findAll(), which runs the same matcher invalidateQueries
* uses, so no network round trip is involved.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Text } from 'react-native'
import { screen, waitFor } from '@testing-library/react-native'
import { trpc } from '@/src/trpc-client'
import { setupApiMocks } from '../mocks/api'
import { createQueryClient, renderWithProviders } from '../helpers/render'
const PROCEDURE = 'user.address.getUserAddresses'
const Probe = () => {
const q = trpc.user.address.getUserAddresses.useQuery()
return <Text testID="state">{q.isSuccess ? 'ok' : 'pending'}</Text>
}
describe('query key shape', () => {
it('matches the array path form and ignores the dotted string form', async () => {
setupApiMocks({ procedures: { [PROCEDURE]: { data: [] } } })
const client = createQueryClient()
renderWithProviders(<Probe />, { centralStores: false, queryClient: client })
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('ok'))
// The key tRPC really produced for this hook.
const stored = client.getQueryCache().getAll()[0]
expect(stored.queryKey[0]).toEqual(['user', 'address', 'getUserAddresses'])
// The old, dotted form: matches nothing, so the invalidation was a no-op.
expect(
client.getQueryCache().findAll({ queryKey: ['user.address.getUserAddresses'] })
).toHaveLength(0)
// The form tRPC's own utils.X.invalidate() builds: matches.
expect(
client.getQueryCache().findAll({ queryKey: [['user', 'address', 'getUserAddresses']] })
).toHaveLength(1)
})
})

View file

@ -0,0 +1,282 @@
/**
* Mutation → refetch wiring.
*
* Each test mounts a real observer of the query the mutation is supposed to
* refresh, fires the mutation through the UI/hook, and asserts the query is
* fetched again. This deliberately checks that the invalidation key actually
* matches an observer — a spy on `invalidateQueries` would still pass for a
* no-op key like the string `['user.address.getUserAddresses']` (tRPC v11 keys
* are `[['user','address','getUserAddresses'], {...}]`).
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, renderHook, screen, waitFor } from '@testing-library/react-native'
import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent'
import OrderDetails from '@/app/(drawer)/(tabs)/me/my-orders/[id]'
import Addresses from '@/app/(drawer)/(tabs)/me/addresses/index'
import Coupons from '@/app/(drawer)/(tabs)/me/coupons/index'
import { useUpdateProfile } from '@/src/api-hooks/auth.api'
import { trpc } from '@/src/trpc-client'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { authMock, resetAuthMock } from '../mocks/auth'
import { procedureCalls } from '../mocks/procedures'
import { searchParamsMock } from '../mocks/router'
import { createQueryClient, Providers, renderWithProviders } from '../helpers/render'
const USER = {
id: 5,
name: 'Test User',
email: 'test@example.com',
mobile: '9876543210',
profileImage: '',
createdAt: '',
}
const ADDRESS = {
id: 1,
name: 'Home',
phone: '9876543210',
addressLine1: '12 Main Road',
addressLine2: 'Apt 4',
city: 'Hyderabad',
state: 'Telangana',
pincode: '500001',
isDefault: false,
}
const ORDER = {
id: 42,
orderId: 'ORD-42',
orderDate: '2026-09-20T10:00:00.000Z',
createdAt: '2026-09-20T10:00:00.000Z',
orderStatus: 'confirmed',
deliveryStatus: 'pending',
deliveryDate: '2026-09-26T10:00:00.000Z',
cancelReason: null,
paymentMode: 'COD',
paymentStatus: 'pending',
orderAmount: 500,
discountAmount: 0,
deliveryCharge: 15,
couponCode: null,
isFlashDelivery: false,
userNotes: null,
items: [
{
productName: 'Chicken Breast 500 g',
quantity: 1,
unitNotation: '500g',
price: 215,
amount: 215,
image: null,
},
],
}
const baseProps = {
selectedAddress: 1,
selectedSlots: { 1: 1849 },
selectedCouponId: null,
cartItems: [{ id: 1, skuId: 2, quantity: 1, slotId: 1849 }],
totalPrice: 215,
totalSavings: 0,
discountAmount: 0,
finalTotal: 215,
finalTotalWithDelivery: 230,
deliveryCharge: 15,
constsData: { freeDeliveryThreshold: 249, deliveryCharge: 15 },
selectedCoupons: [],
}
/** Mounted observers so an invalidation has something to refetch. */
const OrdersProbe = () => {
trpc.user.order.getOrders.useQuery({ page: 1, pageSize: 50 })
return null
}
const EligibleProbe = () => {
trpc.user.coupon.getEligible.useQuery(undefined, { enabled: true })
return null
}
const DefaultAddressProbe = () => {
trpc.user.address.getDefaultAddress.useQuery()
return null
}
const count = (api: ReturnType<typeof setupApiMocks>, name: string) =>
procedureCalls(api.fetchMock, name).length
describe('mutation invalidation', () => {
beforeEach(async () => {
// Flush a batched tRPC request left over from the previous test.
await act(async () => {
jest.advanceTimersByTime(1)
})
resetAuthMock()
await resetStorage()
searchParamsMock.current = {}
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('refetches getOrders after placeOrder, so NextOrderGlimpse updates', async () => {
const queryClient = createQueryClient()
const api = setupApiMocks({
orders: [],
procedures: { 'user.order.placeOrder': { data: [{ id: 99, isCod: true }] } },
})
renderWithProviders(
<>
<PaymentAndOrderComponent {...baseProps} />
<OrdersProbe />
</>,
{ centralStores: false, queryClient }
)
await waitFor(() => expect(count(api, 'user.order.getOrders')).toBeGreaterThan(0))
const before = count(api, 'user.order.getOrders')
fireEvent.press(screen.getByTestId('place-order-button'))
await waitFor(() => expect(count(api, 'user.order.getOrders')).toBeGreaterThan(before))
})
it('refetches getOrders after cancelling from the order detail screen', async () => {
const queryClient = createQueryClient()
const api = setupApiMocks({
orders: [],
procedures: {
'user.order.getOrderById': ORDER,
'user.order.cancelOrder': { success: true },
},
})
searchParamsMock.current = { id: String(ORDER.id) }
renderWithProviders(
<>
<OrderDetails />
<OrdersProbe />
</>,
{ centralStores: false, queryClient }
)
await waitFor(() => expect(screen.getByText('Cancel Order')).toBeVisible())
await waitFor(() => expect(count(api, 'user.order.getOrders')).toBeGreaterThan(0))
const before = count(api, 'user.order.getOrders')
fireEvent.press(screen.getByText('Cancel Order'))
await waitFor(() => expect(screen.getByTestId('cancel-reason')).toBeVisible())
fireEvent.changeText(screen.getByTestId('cancel-reason'), 'Changed my mind')
fireEvent.press(screen.getByText('Confirm Cancellation'))
await waitFor(() => expect(count(api, 'user.order.cancelOrder')).toBeGreaterThan(0))
await waitFor(() => expect(count(api, 'user.order.getOrders')).toBeGreaterThan(before))
})
it('refetches eligible coupons after redeeming a reserved coupon', async () => {
const queryClient = createQueryClient()
const api = setupApiMocks({
procedures: {
'user.coupon.getMyCoupons': { data: { personal: [], general: [] } },
'user.coupon.redeemReservedCoupon': { success: true },
'user.coupon.getEligible': { data: [] },
},
})
renderWithProviders(
<>
<Coupons />
<EligibleProbe />
</>,
{ queryClient }
)
await waitFor(() => expect(screen.getByText('Add a Coupon')).toBeVisible())
await waitFor(() => expect(count(api, 'user.coupon.getEligible')).toBeGreaterThan(0))
const before = count(api, 'user.coupon.getEligible')
fireEvent.changeText(screen.getByPlaceholderText('Enter coupon code'), 'secret1')
fireEvent.press(screen.getByText('Add Coupon'))
await waitFor(() =>
expect(count(api, 'user.coupon.redeemReservedCoupon')).toBeGreaterThan(0)
)
await waitFor(() => expect(count(api, 'user.coupon.getEligible')).toBeGreaterThan(before))
})
it('refetches the default address after setting a new default', async () => {
const queryClient = createQueryClient()
const api = setupApiMocks({
procedures: {
'user.address.getUserAddresses': { data: [ADDRESS] },
'user.address.updateAddress': { success: true },
'user.address.getDefaultAddress': { success: true, data: ADDRESS },
},
})
renderWithProviders(
<>
<Addresses />
<DefaultAddressProbe />
</>,
{ queryClient }
)
await waitFor(() => expect(screen.getByText('Set Default')).toBeVisible())
await waitFor(() =>
expect(count(api, 'user.address.getDefaultAddress')).toBeGreaterThan(0)
)
const before = count(api, 'user.address.getDefaultAddress')
fireEvent.press(screen.getByText('Set Default'))
await waitFor(() =>
expect(count(api, 'user.address.updateAddress')).toBeGreaterThan(0)
)
await waitFor(() =>
expect(count(api, 'user.address.getDefaultAddress')).toBeGreaterThan(before)
)
})
it('refetches getSelfData after updateProfile', async () => {
const queryClient = createQueryClient()
const api = setupApiMocks({
procedures: {
'user.user.getSelfData': { data: { user: USER } },
'user.auth.updateProfile': { data: { token: 't', user: USER } },
},
})
authMock.user = { id: USER.id }
const { result } = renderHook(
() => {
const mutation = useUpdateProfile()
const query = trpc.user.user.getSelfData.useQuery()
return { mutation, query }
},
{
wrapper: ({ children }: { children?: React.ReactNode }) => (
<Providers queryClient={queryClient} centralStores={false}>
{children}
</Providers>
),
}
)
await waitFor(() => expect(count(api, 'user.user.getSelfData')).toBeGreaterThan(0))
const before = count(api, 'user.user.getSelfData')
// Fire-and-forget: awaiting mutateAsync would deadlock under fake timers,
// because httpBatchLink flushes on a timer that only `waitFor` advances.
act(() => {
result.current.mutation.mutate({ name: 'New Name' })
})
await waitFor(() =>
expect(count(api, 'user.user.getSelfData')).toBeGreaterThan(before)
)
})
})

View file

@ -426,3 +426,203 @@ apps/fallback-ui (1 error, vite.config.ts TS2769), also pre-existing.
Still green for everything this work touches: apps/backend, apps/user-ui, apps/admin-ui,
apps/web-ui, packages/db_helper_sqlite, packages/migrator, packages/web-components — plus
62 suites / 327 tests in user-ui.
[2026-09-26 00:35:00] backend: jest globals not resolving in tests/api/*.test.ts.
Symptom: "Cannot find name 'describe'. Do you need to install type definitions for a test
runner? ... add 'jest' to the types field in your tsconfig" reported for
@apps/backend/tests/api/cache-products.test.ts.
Diagnosis: apps/backend/tests/tsconfig.json only extends ../tsconfig.json, so its typeRoots come
from the app config:
"typeRoots": ["../../node_modules/@types", "./node_modules/@types", "../shared-types"]
Those paths are written relative to apps/backend. @types/jest is installed at the repo root
(hoisted), so a run that resolves them relative to apps/backend finds it and passes
(`bun run test:api:typecheck` is clean), which is why the CLI never complained and the repo
`typecheck` script stays green — that script runs `tsc --noEmit` from each app root, and
apps/backend's own include does not cover tests/ at all. A checker that resolves the inherited
relative paths against the inheriting config (apps/backend/tests/) looks at apps/node_modules and
apps/backend/tests/node_modules instead, finds no @types/jest, and drops the jest globals.
Fix: declare the type roots in tests/tsconfig.json itself, with paths correct for its own
directory, and name the globals explicitly:
+ "typeRoots": ["../../../node_modules/@types", "../node_modules/@types"],
+ "types": ["jest", "node"]
Both are idempotent with the inherited values under correct resolution and independent of it
under the other.
Verified after the change: test:api:typecheck clean and one API suite still green (ts-jest reads
this tsconfig, so a restricted `types` array had to be proven not to break the runner).
[2026-09-26 00:40:00] backend: tsconfig fix verified.
- from apps/backend/tests, ../../../node_modules/@types/jest and ../node_modules/@types/node
both resolve (the earlier ls that said otherwise was run from apps/backend, one level up);
- `bun run test:api:typecheck` (tsc --noEmit -p tests/tsconfig.json) clean — all 21 test files
including tests/api/cache-products.test.ts;
- ts-jest still works with the restricted types array: health + auth suites run green (6 tests);
- the app project (`npx tsc --noEmit` in apps/backend) stays clean, so the repo `typecheck`
script's verdict for apps/backend is unchanged.
The same nested-tests-tsconfig hazard does not apply to apps/user-ui — it has a single root
tsconfig that the tests are checked through, so there are no inherited relative paths to
misresolve.
[2026-09-26 01:00:00] backend: image upload integrity suite.
New: apps/backend/tests/api/uploads.test.ts. Purpose: prove that what the app asks for and what
it later reads back are the same bytes — the presign -> PUT -> GET round trip, not just the shape
of the response the existing user-surface case asserts.
Mechanics: the presigned PUT carries its own signature, so the test process needs no R2
credentials: it PUTs a real PNG to the URL common.generateUploadUrls returns, then GETs
<assetsDomain>/<key> (assetsDomain comes from common.essentialConsts via helpers/cache.ts, the
same source the app uses) and compares bytes and sha256. The key is derived from the presigned
URL the way extractKeyFromPresignedUrl does (last two path segments after the bucket).
Cases: (1) a single PNG round-trips byte-identically with a matching content-length; (2) two
uploads in different folders stay distinct and each serves its own bytes; (3) one call with two
mime types returns two usable URLs whose objects hold their own bytes.
Per instruction the same-millisecond key collision in generateUploadUrls is NOT covered here.
Writes real objects into the dev bucket and leaves them, consistent with the existing data
policy.
[2026-09-26 01:10:00] backend: uploads suite verified + documented.
Verified: apps/backend/tests/api/uploads.test.ts 4/4 green on the first run — the presigned PUT
to R2 worked from the test process and every object read back byte-identically from the public
assets domain, with the 404 case proving the read-back is real. Full run 22 suites / 107 tests
green (was 21/103); test:api:typecheck clean.
Documented in apps/backend/test-case-info.md: header total 22/107, a new `api/uploads.test.ts`
section (cases 104-107), and four findings — a presigned URL is usable with no credentials and
unsigned Content-Type; the `${folder}/${Date.now()}${ext}` key (same-ms collision left uncovered
by request); every presign writing a pending status row that claimUploadUrl flips; and the
untested remainder (claim/re-claim, deleteImageUtil on replacement).
[2026-09-26 02:00:00] stale-data fixes across user-ui + admin-ui (from the mutation-refetch audit).
Planned changes (all app code):
A. Dead invalidations — the raw queryClient.invalidateQueries keys are dotted strings, which can
never match a tRPC v11 key ([pathArray, {type}]):
apps/user-ui/components/CheckoutAddressSelector.tsx:37 ['user.address.getUserAddresses']
apps/admin-ui/.../customize-app/popular-items.tsx:214 ['const.getConstants']
apps/admin-ui/.../customize-app/all-items-order.tsx:180 ['const.getConstants']
apps/admin-ui/.../product-tags/order.tsx:169 ['const.getConstants']
-> switch to trpc.useUtils().<router path>.invalidate(). Note the admin const procedures are
admin.const.*, so the old string was wrong twice (missing 'admin' and a string not an array).
B. packages/ui/hooks/useMarkDataFetchers.ts — refresh-on-focus fired only from the 3rd focus
(`focusCountRef.current > 1` from a ref starting at 0) and the callback was frozen by
useCallback(..., []). Fix keeps a callback ref (so the focus effect does not re-run on every
render, which would loop) and fires from the 2nd focus.
C. admin-ui mutations that leave the same screen stale (no refetch at all):
products/detail/[id].tsx respondToReview -> refetch getProductReviews
manage-orders/order-details/[id].tsx generateCancellationCoupon -> refetch getOrderDetails
manage-orders/order-details/[id].tsx initiateRefund -> refetch getOrderDetails
manage-orders/delivery-sequences/… handleSaveSequence -> refetchSequence/Orders
dashboard-banners/index.tsx handleEmptySlot -> refetch getBanners
manage-orders/delivery-sequences/… onAttachLocation={() => {}} -> refetch both
D. admin-ui edit screens that never refresh their own detail query — invalidate the router:
product-tags/edit/index.tsx, dashboard-banners/edit/[id].tsx, components/SlotForm.tsx
(update path), components/ProductGroupForm.tsx
Not touched: the identical dotted-key bug in apps/admin-web (3 sites) and apps/web-ui (3 sites),
outside the two apps in scope; apps/user-ui/utils/queryClient.ts staleTime: 1200000 is a policy
call and is left as-is.
[2026-09-26 02:30:00] stale-data fixes applied — A, B, C, D.
A. Dead invalidations replaced (dotted string -> tRPC utils, key built by the library):
apps/user-ui/components/CheckoutAddressSelector.tsx utils.user.address.getUserAddresses.invalidate()
admin-ui customize-app/popular-items.tsx utils.admin.const.getConstants.invalidate()
admin-ui customize-app/all-items-order.tsx utils.admin.const.getConstants.invalidate()
admin-ui product-tags/order.tsx utils.admin.const.getConstants.invalidate()
Each of the three admin files then had an unused queryClient + useQueryClient import; both
removed.
B. packages/ui/hooks/useMarkDataFetchers.ts rewritten: the callback is held in a ref (so the
focus effect does not re-subscribe on every render, which would refetch in a loop) and the
guard is now `focusCountRef.current > 0`, so the second focus refreshes. Previously `> 1`
skipped the first return-to-screen entirely and the callback was frozen at first render.
C. Same-screen refetches added (admin-ui):
products/detail/[id].tsx respondToReview -> utils.admin.product.getProductReviews.invalidate()
order-details/[id].tsx generateCancellationCoupon -> refetch()
order-details/[id].tsx initiateRefund -> refetch()
delivery-sequences/index.tsx handleSaveSequence -> refetchSequence() + refetchOrders()
dashboard-banners/index.tsx handleEmptySlot -> refetch()
delivery-sequences/index.tsx onAttachLocation={() => {}} -> refetchOrders() + refetchSequence()
D. Edit screens now invalidate what they were seeded from (admin-ui):
product-tags/edit/index.tsx utils.admin.product.getProductTagById.invalidate()
dashboard-banners/edit/[id].tsx utils.admin.banner.getBanner.invalidate()
components/SlotForm.tsx (update) utils.admin.slots.invalidate()
components/ProductGroupForm.tsx utils.admin.product.getGroups.invalidate()
Tests: apps/user-ui/tests/lib/query-invalidation-keys.test.tsx (new, 1 test) pins the root cause
without touching the network — it reads the key tRPC actually produced
([['user','address','getUserAddresses'], {type}]) and asserts getQueryCache().findAll() matches
the array form and returns nothing for the dotted form. findAll runs the same matcher
invalidateQueries uses, so it is the invalidation semantics minus the round trip.
Verified: apps/user-ui 63 suites / 328 tests green; test:typecheck clean; apps/admin-ui
`tsc --noEmit` clean (it has no test harness, so C/D are compile-verified only).
Still open, unchanged and out of the requested scope: the same dotted-key bug in apps/admin-web
(3 sites) and apps/web-ui (3 sites), and the user-ui client's staleTime: 1200000 policy —
fixing the invalidations removes the steady-state staleness but a 20-minute staleTime still
means any future missed invalidation is durable.
[2026-09-26 03:00:00] tests for the stale-data fixes.
New: apps/user-ui/tests/hooks/useMarkDataFetchers.test.tsx — pins fix B by driving the focus
lifecycle explicitly (the global setup mocks useFocusEffect to run once on mount, so this file
overrides it with a version that records the callback and lets the test fire further focuses).
Cases: the first focus does not refresh, the second does (the old `> 1` guard skipped it), and
after a re-render the newer callback runs rather than the one captured on mount (the frozen
useCallback).
Extended: apps/user-ui/tests/components/address-selectors.test.tsx — pins fix A end to end.
Asserts that '+ Attach Current Location' sends the mocked coords via user.address.updateAddress
AND that user.address.getUserAddresses is fetched a second time afterwards; with the old dotted
key that refetch never happened, so this fails against the previous code.
Not testable today: the admin-ui half (C + D). apps/admin-ui has no jest config, no mocks and no
provider harness — nothing in that app has ever been rendered under test. Recorded rather than
faked; scaffolding a harness for it is a separate, larger job.
[2026-09-26 03:30:00] tests outcome — one landed, one abandoned with the reason.
Landed:
apps/user-ui/tests/components/address-selectors.test.tsx +1 test (3 -> 6 total, was 5 with
two QuickDelivery cases): "refreshes the addresses after attaching the current location".
It presses the Attach button (the expo-location stub grants permission and returns
17.385/78.4867), asserts updateAddress receives those coords, then asserts
user.address.getUserAddresses is fetched a SECOND time. Against the old dotted-string key that
second read never happened, so the test pins fix A.
apps/user-ui/tests/lib/query-invalidation-keys.test.tsx (already in place) pins the same class
at the key level via getQueryCache().findAll(), which uses the matcher invalidateQueries uses.
Abandoned: a useMarkDataFetchers test (fix B). Three attempts failed for the same reason: the
hook's `useFocusEffect` never reaches the mock. Instrumentation settled it — a console.log inside
the useFocusEffect override in tests/setup.ts never fires while the hook renders successfully, so
packages/ui's import of '@react-navigation/native' resolves to a DIFFERENT module instance than
the app's (bun's symlinked install; jest keys the mock by resolved path). A per-file
jest.mock(...) does not intercept it either. I tried a shared seam (tests/mocks/focus.ts recording
callbacks + re-exporting fireFocus from the setup mock) and that failed the same way, so both the
seam and the test were reverted rather than left dead. tests/setup.ts is byte-identical to before.
Consequence worth knowing: the setup comment claims its useFocusEffect override "runs the callback
once on mount ... so focus-driven side effects are testable", but for the shared hook in
packages/ui that override is not in play at all. Making fix B testable needs either a
NavigationContainer in the test (so the real hook works) or a mock registered for the instance
packages/ui actually resolves. Not attempted here.
Result: apps/user-ui 63 suites / 329 tests green; test:typecheck clean. The admin-ui half (fixes C
and D) still has no harness — that app has no jest config at all, so nothing in it is testable
today.

1098
bun.lock

File diff suppressed because it is too large Load diff

View file

@ -3220,3 +3220,59 @@ early returns.
Suite: 61 files / 316 tests passed (was 51 files / 243). tsc clean.
Lint unchanged: 23 pre-existing errors in app/, components/ and src/; eslint
does not cover tests/.
[2026-09-26 21:58:09] user-ui + admin-ui: invalidate the queries the order/coupon/profile mutations forgot.
Follow-up to the mutation stale-data audit. The query client sets staleTime
1200000 (20 min) and refetchOnWindowFocus:false in both apps, so a missing
invalidate is not repaired by remount/focus — the screen keeps the old data.
user-ui:
- components/PaymentAndOrderComponent.tsx: placeOrder and verifyPayment
onSuccess now invalidate user.order.getOrders. NextOrderGlimpse is mounted
on the home/me tabs (pageSize 50) and never saw a newly placed order.
- app/(drawer)/(tabs)/me/my-orders/[id].tsx: cancelOrder onSuccess now
invalidates user.order.getOrders, so the list behind the detail refreshes
(previously only getOrderById was refetched).
- app/(drawer)/(tabs)/me/coupons/index.tsx: redeemReservedCoupon onSuccess now
invalidates user.coupon.getEligible, so a coupon redeemed from the cart's
"Add Coupons to account" link appears in the cart/checkout dropdown.
- app/(drawer)/(tabs)/me/addresses/index.tsx: set-default and delete now
invalidate user.address.getDefaultAddress (list refetch alone left it stale).
- src/api-hooks/auth.api.ts: useUpdateProfile now invalidates
user.user.getSelfData, so the cached profile matches the edited one.
- src/contexts/AuthContext.tsx: logout() now clears the query cache
(useQueryClient().clear()), so a deleted/signed-out account's orders,
addresses, coupons and profile are not served to the next session.
- components/OrderMenu.tsx: cancelOrder now invalidates user.order.getOrders
so the NextOrderGlimpse observer updates, not just the caller's list.
- app/(drawer)/(tabs)/me/my-orders/index.tsx: retry-payment verifyPayment
onSuccess invalidates user.order.getOrders for the same reason.
admin-ui (fixes only — admin-ui has no test harness, see below):
- app/(drawer)/dashboard/stores/edit.tsx: updateStore now invalidates
admin.store.getStores; only getStoreById was refetched before the push back
to the list.
- app/(drawer)/dashboard/coupons/create.tsx and edit/[id].tsx: replaced the
hardcoded { limit: 20, search: '' } refetch with
utils.admin.coupon.getAll/getReservedCoupons.invalidate(), which matches the
list's key whatever search term is active.
Tests added (user-ui only):
- tests/screens/mutation-invalidation.test.tsx: mounts a real observer of the
affected query alongside the screen and asserts the query is refetched after
the mutation (so a wrong/subtly-mismatched key fails, unlike a spy on
invalidateQueries).
- tests/contexts/auth-logout-cache.test.tsx: real AuthProvider — logout()
removes cached queries from the query client.
[2026-09-26 22:26:33] user-ui + admin-ui: mutation-invalidation fixes verified; user-ui tests green.
- Mutation-checked the new tests: with the invalidation removed, the
updateProfile test and the placeOrder test both fail; with it restored they
pass. So the tests assert a real refetch, not a no-op.
- Gotcha while writing them: awaiting `mutateAsync` directly under the suite's
fake timers deadlocks (httpBatchLink flushes on a setTimeout and jest's own
testTimeout is faked, so neither fires). Trigger with `mutate()` and assert
via `waitFor`, which advances the timers.
- Suite: 65 files / 335 tests passed. user-ui and admin-ui tsc both clean.

View file

@ -2,15 +2,22 @@ import { useCallback, useRef } from 'react';
import { useFocusEffect } from '@react-navigation/native';
export const useMarkDataFetchers = (callback: () => void) => {
// The callback is held in a ref: call sites pass inline arrows, so putting it in the
// dependency array below would re-run the focus effect on every render and refetch in a
// loop. The ref keeps the latest closure without re-subscribing.
const callbackRef = useRef(callback);
callbackRef.current = callback;
const focusCountRef = useRef(0);
useFocusEffect(
useCallback(() => {
if (focusCountRef.current > 1) {
callback();
// Skip the initial focus only (the screen fetched on mount); refresh from the
// second focus onward. This used to be `> 1`, which skipped the first return too.
if (focusCountRef.current > 0) {
callbackRef.current();
}
focusCountRef.current += 1;
},[])
}, [])
)
}
}