+
+
+
+
+ Freshyo Superadmin
+
+
+
+
+ {staff?.name && (
+ {staff.name}
+ )}
+
+
+
+
+
+
+
+ {open && (
+
setOpen(false)}
+ />
+ )}
+
+ {children}
+
+
+ )
+}
+
+export default AppShell
diff --git a/apps/superadmin-ui/src/routeTree.gen.ts b/apps/superadmin-ui/src/routeTree.gen.ts
index 949b887..70804ec 100644
--- a/apps/superadmin-ui/src/routeTree.gen.ts
+++ b/apps/superadmin-ui/src/routeTree.gen.ts
@@ -11,7 +11,9 @@
import { Route as rootRouteImport } from './routes/__root'
import { Route as IndexRouteImport } from './routes/index'
import { Route as ConstantsRouteImport } from './routes/constants'
+import { Route as DashboardRouteImport } from './routes/dashboard'
import { Route as LoginRouteImport } from './routes/login'
+import { Route as SendNotificationsRouteImport } from './routes/send-notifications'
const IndexRoute = IndexRouteImport.update({
id: '/',
@@ -23,40 +25,65 @@ const ConstantsRoute = ConstantsRouteImport.update({
path: '/constants',
getParentRoute: () => rootRouteImport,
} as any)
+const DashboardRoute = DashboardRouteImport.update({
+ id: '/dashboard',
+ path: '/dashboard',
+ getParentRoute: () => rootRouteImport,
+} as any)
const LoginRoute = LoginRouteImport.update({
id: '/login',
path: '/login',
getParentRoute: () => rootRouteImport,
} as any)
+const SendNotificationsRoute = SendNotificationsRouteImport.update({
+ id: '/send-notifications',
+ path: '/send-notifications',
+ getParentRoute: () => rootRouteImport,
+} as any)
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
'/constants': typeof ConstantsRoute
+ '/dashboard': typeof DashboardRoute
'/login': typeof LoginRoute
+ '/send-notifications': typeof SendNotificationsRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
'/constants': typeof ConstantsRoute
+ '/dashboard': typeof DashboardRoute
'/login': typeof LoginRoute
+ '/send-notifications': typeof SendNotificationsRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
'/constants': typeof ConstantsRoute
+ '/dashboard': typeof DashboardRoute
'/login': typeof LoginRoute
+ '/send-notifications': typeof SendNotificationsRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
- fullPaths: '/' | '/constants' | '/login'
+ fullPaths:
+ '/' | '/constants' | '/dashboard' | '/login' | '/send-notifications'
fileRoutesByTo: FileRoutesByTo
- to: '/' | '/constants' | '/login'
- id: '__root__' | '/' | '/constants' | '/login'
+ to: '/' | '/constants' | '/dashboard' | '/login' | '/send-notifications'
+ id:
+ | '__root__'
+ | '/'
+ | '/constants'
+ | '/dashboard'
+ | '/login'
+ | '/send-notifications'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
ConstantsRoute: typeof ConstantsRoute
+ DashboardRoute: typeof DashboardRoute
LoginRoute: typeof LoginRoute
+ SendNotificationsRoute: typeof SendNotificationsRoute
}
declare module '@tanstack/react-router' {
@@ -75,6 +102,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ConstantsRouteImport
parentRoute: typeof rootRouteImport
}
+ '/dashboard': {
+ id: '/dashboard'
+ path: '/dashboard'
+ fullPath: '/dashboard'
+ preLoaderRoute: typeof DashboardRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/login': {
id: '/login'
path: '/login'
@@ -82,13 +116,22 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof LoginRouteImport
parentRoute: typeof rootRouteImport
}
+ '/send-notifications': {
+ id: '/send-notifications'
+ path: '/send-notifications'
+ fullPath: '/send-notifications'
+ preLoaderRoute: typeof SendNotificationsRouteImport
+ parentRoute: typeof rootRouteImport
+ }
}
}
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
ConstantsRoute: ConstantsRoute,
+ DashboardRoute: DashboardRoute,
LoginRoute: LoginRoute,
+ SendNotificationsRoute: SendNotificationsRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
diff --git a/apps/superadmin-ui/src/routes/constants.tsx b/apps/superadmin-ui/src/routes/constants.tsx
index dd9062f..e8bdfe5 100644
--- a/apps/superadmin-ui/src/routes/constants.tsx
+++ b/apps/superadmin-ui/src/routes/constants.tsx
@@ -5,6 +5,7 @@ import { AppContainer, Checkbox, MyButton, p as MyText, pInput as PInput } from
import { ChevronRight, ListOrdered, Pencil } from 'lucide-react'
import { trpc } from '../lib/trpc-client'
import { ProtectedRoute } from '../components/ProtectedRoute'
+import { AppShell } from '../components/AppShell'
type ConstantFormData = Record
@@ -270,7 +271,9 @@ function CustomizeApp() {
export const Route = createFileRoute('/constants')({
component: () => (
-
+
+
+
),
})
diff --git a/apps/superadmin-ui/src/routes/dashboard.tsx b/apps/superadmin-ui/src/routes/dashboard.tsx
new file mode 100644
index 0000000..bf7b0c3
--- /dev/null
+++ b/apps/superadmin-ui/src/routes/dashboard.tsx
@@ -0,0 +1,64 @@
+import { createFileRoute, Link } from '@tanstack/react-router'
+import { AppContainer, p as MyText } from 'web-components'
+import { Send, Settings2, ChevronRight } from 'lucide-react'
+import { ProtectedRoute } from '../components/ProtectedRoute'
+import { AppShell } from '../components/AppShell'
+
+export const Route = createFileRoute('/dashboard')({
+ component: () => (
+
+
+
+
+
+ ),
+})
+
+const CARDS = [
+ {
+ to: '/send-notifications',
+ title: 'Send Admin Notifications',
+ description: 'Push a message to every admin device.',
+ icon: Send,
+ },
+ {
+ to: '/constants',
+ title: 'App Constants',
+ description: 'Tune delivery thresholds, charges and app config.',
+ icon: Settings2,
+ },
+] as const
+
+function Dashboard() {
+ return (
+
+
+
Dashboard
+
+ Manage the Freshyo platform.
+
+
+
+ {CARDS.map(({ to, title, description, icon: Icon }) => (
+
+
+
+
+
+
+ {title}
+ {description}
+
+
+
+
+ ))}
+
+
+
+ )
+}
diff --git a/apps/superadmin-ui/src/routes/index.tsx b/apps/superadmin-ui/src/routes/index.tsx
index 1c910f0..df88295 100644
--- a/apps/superadmin-ui/src/routes/index.tsx
+++ b/apps/superadmin-ui/src/routes/index.tsx
@@ -2,6 +2,6 @@ import { createFileRoute, redirect } from '@tanstack/react-router'
export const Route = createFileRoute('/')({
loader: () => {
- throw redirect({ to: '/constants' })
+ throw redirect({ to: '/dashboard' })
},
})
diff --git a/apps/superadmin-ui/src/routes/login.tsx b/apps/superadmin-ui/src/routes/login.tsx
index 6873c10..d42127b 100644
--- a/apps/superadmin-ui/src/routes/login.tsx
+++ b/apps/superadmin-ui/src/routes/login.tsx
@@ -13,7 +13,7 @@ function LoginPage() {
useEffect(() => {
if (!isLoading && isAuthenticated) {
- navigate({ to: '/constants' })
+ navigate({ to: '/dashboard' })
}
}, [isAuthenticated, isLoading, navigate])
@@ -22,7 +22,7 @@ function LoginPage() {
if (!name.trim() || !password.trim()) return
try {
await login(name.trim(), password)
- navigate({ to: '/constants' })
+ navigate({ to: '/dashboard' })
} catch {
// error surfaced via loginError
}
diff --git a/apps/superadmin-ui/src/routes/send-notifications.tsx b/apps/superadmin-ui/src/routes/send-notifications.tsx
new file mode 100644
index 0000000..402d00f
--- /dev/null
+++ b/apps/superadmin-ui/src/routes/send-notifications.tsx
@@ -0,0 +1,102 @@
+import { createFileRoute } from '@tanstack/react-router'
+import React, { useState } from 'react'
+import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
+import { Send } from 'lucide-react'
+import { trpc } from '../lib/trpc-client'
+import { ProtectedRoute } from '../components/ProtectedRoute'
+import { AppShell } from '../components/AppShell'
+
+export const Route = createFileRoute('/send-notifications')({
+ component: () => (
+
+
+
+
+
+ ),
+})
+
+function SendAdminNotifications() {
+ const [title, setTitle] = useState('')
+ const [text, setText] = useState('')
+ const [imageUrl, setImageUrl] = useState('')
+
+ const { mutate, isPending } = trpc.admin.staffUser.sendAdminNotification.useMutation({
+ onSuccess: (response) => {
+ window.alert(`Success\n\n${response.message}`)
+ setTitle('')
+ setText('')
+ setImageUrl('')
+ },
+ onError: (error) => {
+ window.alert(`Error\n\n${error.message || 'Failed to send notification'}`)
+ },
+ })
+
+ const handleSubmit = (e: React.FormEvent) => {
+ e.preventDefault()
+ if (!title.trim() || !text.trim()) {
+ window.alert('Title and message are required')
+ return
+ }
+ mutate({
+ title: title.trim(),
+ text: text.trim(),
+ ...(imageUrl.trim() ? { imageUrl: imageUrl.trim() } : {}),
+ })
+ }
+
+ return (
+
+
+
+ Send Admin Notifications
+
+
+ This push notification is delivered to every admin device.
+
+
+
+
+
+ )
+}
diff --git a/apps/user-ui/app/(drawer)/(tabs)/stores/store-detail/[id].tsx b/apps/user-ui/app/(drawer)/(tabs)/stores/store-detail/[id].tsx
index fa4a3d6..29a179c 100644
--- a/apps/user-ui/app/(drawer)/(tabs)/stores/store-detail/[id].tsx
+++ b/apps/user-ui/app/(drawer)/(tabs)/stores/store-detail/[id].tsx
@@ -1,4 +1,4 @@
-import React, { useMemo, useState } from "react";
+import React, { useMemo, useState, useEffect } from "react";
import { View, Dimensions, ScrollView, TouchableOpacity } from "react-native";
import { useRouter, useLocalSearchParams } from "expo-router";
import { Image } from 'expo-image';
@@ -81,9 +81,11 @@ export default function StoreDetail() {
// Set the store header title
const setStoreHeaderTitle = useStoreHeaderStore((state) => state.setTitle);
- if (storeData?.store?.name) {
- setStoreHeaderTitle(storeData.store.name);
- }
+ useEffect(() => {
+ if (storeData?.store?.name) {
+ setStoreHeaderTitle(storeData.store.name);
+ }
+ }, [storeData?.store?.name, setStoreHeaderTitle]);
useManualRefresh(() => {
refetch();
diff --git a/apps/user-ui/components/ProductDetail.tsx b/apps/user-ui/components/ProductDetail.tsx
index 2709a08..3236538 100644
--- a/apps/user-ui/components/ProductDetail.tsx
+++ b/apps/user-ui/components/ProductDetail.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useMemo } from 'react';
+import React, { useState, useMemo, useEffect } from 'react';
import { View, ScrollView, Alert, Dimensions, FlatList, RefreshControl } from 'react-native';
import { useRouter } from 'expo-router';
import { ImageCarousel, tw, BottomDialog, useManualRefresh, useMarkDataFetchers, LoadingDialog, ImageUploader, MyText, MyTextInput, MyTouchableOpacity, Quantifier } from 'common-ui';
@@ -204,9 +204,11 @@ const ProductDetail: React.FC = ({ productId, isFlashDeliver
// Set the store header title with product name
const setStoreHeaderTitle = useStoreHeaderStore((state) => state.setTitle);
- if (productDetail?.name) {
- setStoreHeaderTitle(productDetail.name);
- }
+ useEffect(() => {
+ if (productDetail?.name) {
+ setStoreHeaderTitle(productDetail.name);
+ }
+ }, [productDetail?.name, setStoreHeaderTitle]);
if (isLoading) {
return (
diff --git a/apps/user-ui/components/cart-page.tsx b/apps/user-ui/components/cart-page.tsx
index 72fdafe..375056e 100644
--- a/apps/user-ui/components/cart-page.tsx
+++ b/apps/user-ui/components/cart-page.tsx
@@ -60,7 +60,6 @@ interface DeliverySlotGroup {
interface DeliverySlotMergeSuggestion {
slotId: number;
label: string;
- feasible: boolean;
}
function DeliverySlotSummary({
@@ -115,38 +114,22 @@ function DeliverySlotSummary({
{!!mergeSuggestion && (
-
-
+
+
Deliver All items at {mergeSuggestion.label}
- {mergeSuggestion.feasible && (
-
-
-
- )}
+
+
+
)}
@@ -495,7 +478,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
}, [isFlashDelivery, cartItems, selectedSlots, slotsData, productsById, quantities]);
const mergeSuggestion = useMemo(() => {
- if (isFlashDelivery || slotGroups.length === 0) return null;
+ if (isFlashDelivery || slotGroups.length <= 1) return null;
// slotGroups is sorted by slot id, so ties keep the lowest id.
const majority = slotGroups.reduce((best, group) =>
@@ -508,7 +491,6 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
const now = dayjs();
const feasible =
- slotGroups.length > 1 &&
inStockItems.length > 0 &&
inStockItems.every((item) =>
(slotsData?.[item.skuId] || []).some(
@@ -518,7 +500,9 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
)
);
- return { slotId: majority.slotId, label: majority.label, feasible };
+ if (!feasible) return null;
+
+ return { slotId: majority.slotId, label: majority.label };
}, [isFlashDelivery, slotGroups, cartItems, productSlotsMap, slotsData]);
const handleMergeSlots = () => {
diff --git a/apps/user-ui/hooks/cart-query-hooks.tsx b/apps/user-ui/hooks/cart-query-hooks.tsx
index ebbfa4d..bdf555d 100644
--- a/apps/user-ui/hooks/cart-query-hooks.tsx
+++ b/apps/user-ui/hooks/cart-query-hooks.tsx
@@ -1,7 +1,7 @@
import { useCentralProductStore } from '@/src/store/centralProductStore';
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
import { Alert } from 'react-native';
-import { useEffect, useRef } from 'react';
+import { useEffect, useMemo } from 'react';
import dayjs from 'dayjs';
import { useQuery, useMutation, useQueryClient, UseQueryResult, UseMutationResult } from '@tanstack/react-query';
import type { CartData as SharedCartData, ProductSummaryCore } from '@packages/shared';
@@ -51,7 +51,7 @@ interface UseGetCartReturn {
data: CartData | undefined;
isLoading: boolean;
error: Error | null;
- refetch: () => Promise>;
+ refetch: UseQueryResult['refetch'];
cartItems: CartItem[];
totalItems: number;
totalPrice: number;
@@ -180,69 +180,75 @@ const clearLocalCart = async (cartType: CartType = "regular"): Promise =>
export function useGetCart(options: UseGetCartOptions = {}, cartType: CartType = "regular"): UseGetCartReturn {
const productsById = useCentralProductStore((state) => state.productsById);
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
-
- const query: UseQueryResult = useQuery({
+
+ // The query only reads the raw stored lines. The enriched view is derived below
+ // so it recomputes whenever the central product/slot stores populate — otherwise
+ // a cold start renders an empty cart until something else refetches (the bug
+ // where items "appear after a refresh").
+ const query: UseQueryResult = useQuery({
queryKey: [`local-cart-${cartType}`],
- queryFn: async (): Promise => {
- const cartItems = await getLocalCart(cartType);
-
- const productMap: Record> = Object.fromEntries(
- Object.values(productsById).map((p) => [
- p.id,
- {
- id: p.id,
- price: String(p.price),
- incrementStep: p.incrementStep,
- marketPrice: p.marketPrice === null || p.marketPrice === undefined ? null : String(p.marketPrice),
- name: p.name,
- flashPrice: p.flashPrice,
- images: p.images,
- productQuantity: p.productQuantity,
- unitNotation: p.unitNotation,
- },
- ])
- );
-
- const items: CartItem[] = cartItems
- .map((cartItem): CartItem | null => {
- const productBasic = productMap[cartItem.skuId];
- const productAvailability = productSlotsMap[cartItem.skuId];
-
- if (!productBasic || !productAvailability) return null;
-
- return {
- id: cartItem.id,
- skuId: cartItem.skuId,
- quantity: cartItem.quantity,
- addedAt: cartItem.addedAt,
- subtotal: Number(productBasic.price) * cartItem.quantity,
- slotId: cartItem.slotId,
- };
- })
- .filter((item): item is CartItem => item !== null);
-
- const totalAmount = items.reduce((sum, item) => sum + item.subtotal, 0);
-
- return {
- items,
- totalItems: items.length,
- totalAmount,
- };
- },
+ queryFn: async (): Promise => getLocalCart(cartType),
refetchOnWindowFocus: options?.refetchOnWindowFocus ?? true,
enabled: (options?.enabled ?? true) && Object.keys(productsById).length > 0,
});
-
+
+ const data = useMemo(() => {
+ const cartItems = query.data ?? [];
+
+ const productMap: Record> = Object.fromEntries(
+ Object.values(productsById).map((p) => [
+ p.id,
+ {
+ id: p.id,
+ price: String(p.price),
+ incrementStep: p.incrementStep,
+ marketPrice: p.marketPrice === null || p.marketPrice === undefined ? null : String(p.marketPrice),
+ name: p.name,
+ flashPrice: p.flashPrice,
+ images: p.images,
+ productQuantity: p.productQuantity,
+ unitNotation: p.unitNotation,
+ },
+ ])
+ );
+
+ const items: CartItem[] = cartItems
+ .map((cartItem): CartItem | null => {
+ const productBasic = productMap[cartItem.skuId];
+ const productAvailability = productSlotsMap[cartItem.skuId];
+
+ if (!productBasic || !productAvailability) return null;
+
+ return {
+ id: cartItem.id,
+ skuId: cartItem.skuId,
+ quantity: cartItem.quantity,
+ addedAt: cartItem.addedAt,
+ subtotal: Number(productBasic.price) * cartItem.quantity,
+ slotId: cartItem.slotId,
+ };
+ })
+ .filter((item): item is CartItem => item !== null);
+
+ const totalAmount = items.reduce((sum, item) => sum + item.subtotal, 0);
+
+ return {
+ items,
+ totalItems: items.length,
+ totalAmount,
+ };
+ }, [query.data, productsById, productSlotsMap]);
+
return {
- data: query.data,
+ data: query.data === undefined ? undefined : data,
isLoading: query.isLoading,
error: query.error,
refetch: query.refetch,
- cartItems: query.data?.items ?? [],
- totalItems: query.data?.totalItems ?? 0,
- totalPrice: query.data?.totalAmount ?? 0,
- isEmpty: !(query.data?.items?.length ?? 0),
- hasItems: Boolean(query.data?.items?.length),
+ cartItems: data.items,
+ totalItems: data.totalItems,
+ totalPrice: data.totalAmount,
+ isEmpty: data.items.length === 0,
+ hasItems: data.items.length > 0,
};
}
@@ -250,25 +256,22 @@ export function useReconcileCartSlots() {
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
const isSlotsLoaded = useCentralSlotStore((state) => state.isSlotsLoaded);
const queryClient = useQueryClient();
- const hasRun = useRef(false);
useEffect(() => {
- if (!isSlotsLoaded || hasRun.current) return;
- hasRun.current = true;
+ // Never run against an empty map: treating every line as un-slotted would
+ // otherwise persist a shortened cart.
+ if (!isSlotsLoaded || Object.keys(productSlotsMap).length === 0) return;
(async () => {
const items = await getLocalCart("regular");
if (items.length === 0) return;
let changed = false;
- const nextItems: LocalCartItem[] = [];
-
- for (const item of items) {
+ const nextItems: LocalCartItem[] = items.map((item) => {
const validSlots = productSlotsMap[item.skuId]?.slots ?? [];
if (validSlots.some((slot) => slot.id === item.slotId)) {
- nextItems.push(item);
- continue;
+ return item;
}
const nearestSlot = [...validSlots].sort(
@@ -276,10 +279,13 @@ export function useReconcileCartSlots() {
)[0];
if (nearestSlot) {
- nextItems.push({ ...item, slotId: nearestSlot.id });
+ changed = true;
+ return { ...item, slotId: nearestSlot.id };
}
- changed = true;
- }
+
+ // No slots for this product: keep the line instead of deleting it.
+ return item;
+ });
if (changed) {
await saveLocalCart(nextItems, "regular");
diff --git a/apps/user-ui/tests/KNOWN-GAPS.md b/apps/user-ui/tests/KNOWN-GAPS.md
index 75e9e44..0d7c4ce 100644
--- a/apps/user-ui/tests/KNOWN-GAPS.md
+++ b/apps/user-ui/tests/KNOWN-GAPS.md
@@ -93,13 +93,15 @@ the caller put in the query string".
## 5. Cart lines vanish when the product cache is incomplete
-`hooks/cart-query-hooks.tsx:207` — `useGetCart` maps a stored line to `null`
-when its `skuId` is missing from `productsById` or `productSlotsMap`, then
-filters it out. The line disappears from the view while still on disk, so the
-cart shows fewer rows than it holds and the user cannot see or remove the
-hidden items.
+`hooks/cart-query-hooks.tsx` — `useGetCart` maps a stored line to `null` when its
+`skuId` is missing from `productsById` or `productSlotsMap`, then filters it out.
+The line disappears from the view while still on disk, so the cart shows fewer
+rows than it holds and the user cannot see or remove the hidden items.
-**Fix:** surface unknown lines (or drop them from storage explicitly).
+**FIXED (visibility):** the enriched cart is now derived in a `useMemo` over
+`query.data + productsById + productSlotsMap`, so lines reappear as soon as the
+central stores populate (no manual refresh). Lines whose product is genuinely
+absent from the catalog are still hidden — that remainder is intentional.
**Pinned by:** `tests/hooks/cart-storage.test.tsx` — "drops lines whose product
is missing from the central stores" (asserts the line is still on disk).
@@ -108,21 +110,15 @@ is missing from the central stores" (asserts the line is still on disk).
## 6. `useReconcileCartSlots` deletes cart lines and never repairs them again
-Two bugs in `hooks/cart-query-hooks.tsx:255-283`:
+**FIXED.** The reconciler no longer drops a line whose product has no slots — it
+keeps the line untouched. It also runs whenever `productSlotsMap` changes (the
+once-per-mount `hasRun` ref is gone), so expired slots are repaired on the next
+slot refresh, and it bails when the slots map is empty so it can never wipe the
+cart.
-* When a product has **no slots at all**, the line is neither kept nor
- re-slotted. It is dropped and the shortened cart is persisted — the item
- vanishes with no notice.
-* `hasRun` is a ref set on the first pass, so a later slot reload never
- re-reconciles. A line left pointing at a slot that has since expired is never
- repaired.
-
-**Fix:** keep un-repairable lines (and flag them), and re-run the reconciler
-whenever `productSlotsMap` changes rather than once per mount.
-
-**Pinned by:** `tests/hooks/cart-storage.test.tsx` — "drops a line whose product
-has no slots and persists the shortened cart" and "reconciles once per mount and
-ignores later slot changes".
+**Pinned by:** `tests/hooks/cart-storage.test.tsx` — "keeps a line whose product
+has no slots instead of deleting it" and "re-reconciles when the slots map
+changes".
---
diff --git a/apps/user-ui/tests/hooks/cart-storage.test.tsx b/apps/user-ui/tests/hooks/cart-storage.test.tsx
index f78d04c..79e92d4 100644
--- a/apps/user-ui/tests/hooks/cart-storage.test.tsx
+++ b/apps/user-ui/tests/hooks/cart-storage.test.tsx
@@ -277,11 +277,11 @@ describe('useReconcileCartSlots', () => {
})
/**
- * KNOWN GAP: when a product has no slots at all, the line is neither kept nor
- * re-slotted — it is dropped and the shortened cart is persisted. The item
- * vanishes from the user's cart with no notice.
+ * A line whose product has no slots can't be re-pointed, but it must not be
+ * deleted: it stays on disk (and is hidden from the derived view) so the user
+ * can still act on it once slots return.
*/
- it('drops a line whose product has no slots and persists the shortened cart', async () => {
+ it('keeps a line whose product has no slots instead of deleting it', async () => {
setCentral(
{
[SKU_IN_STOCK]: product(SKU_IN_STOCK, 215),
@@ -296,20 +296,23 @@ describe('useReconcileCartSlots', () => {
renderHook(() => useReconcileCartSlots(), { wrapper })
- await waitFor(async () => expect(await readCart()).toHaveLength(1))
+ await waitFor(async () => {
+ const stored = await readCart()
+ expect(stored.find((i: { id: number }) => i.id === 1).slotId).toBe(SLOT_B)
+ })
+
const stored = await readCart()
- expect(stored[0].id).toBe(1)
- expect(stored[0].slotId).toBe(SLOT_B)
- // SKU_OTHER is gone from storage, not just from the derived view.
- expect(stored.some((i: { skuId: number }) => i.skuId === SKU_OTHER)).toBe(false)
+ expect(stored).toHaveLength(2)
+ // SKU_OTHER is kept untouched rather than dropped from storage.
+ expect(stored.find((i: { id: number }) => i.id === 2).skuId).toBe(SKU_OTHER)
+ expect(stored.find((i: { id: number }) => i.id === 2).slotId).toBe(9999)
})
/**
- * KNOWN GAP: `hasRun` is a ref set on the first pass, so a later slot reload
- * never re-reconciles. A line left pointing at a slot that has since expired
- * is never repaired.
+ * The reconciler re-runs whenever productSlotsMap changes, so a line left
+ * pointing at an expired slot is repaired on the next slot refresh.
*/
- it('reconciles once per mount and ignores later slot changes', async () => {
+ it('re-reconciles when the slots map changes', async () => {
setCentral(
{ [SKU_IN_STOCK]: product(SKU_IN_STOCK, 215) },
{ [SKU_IN_STOCK]: slotInfo([SLOT_B]) }
@@ -327,7 +330,6 @@ describe('useReconcileCartSlots', () => {
)
rerender(undefined)
- await waitFor(async () => expect(await readCart()).toHaveLength(1))
- expect((await readCart())[0].slotId).toBe(7777)
+ await waitFor(async () => expect((await readCart())[0].slotId).toBe(SLOT_A))
})
})
diff --git a/apps/user-ui/tests/screens/cart-screen.test.tsx b/apps/user-ui/tests/screens/cart-screen.test.tsx
index 0ee5b08..ab562a6 100644
--- a/apps/user-ui/tests/screens/cart-screen.test.tsx
+++ b/apps/user-ui/tests/screens/cart-screen.test.tsx
@@ -125,7 +125,7 @@ describe('Cart screen', () => {
)
})
- it('shows a pressable merge banner when every item can use the majority slot', async () => {
+ it('shows an enabled merge row when every item can use the majority slot', async () => {
setupApiMocks({
procedures: {
'user.cart.getCartSlots': {
@@ -149,12 +149,11 @@ describe('Cart screen', () => {
fireEvent.press(screen.getByTestId('delivery-slot-merge-apply'))
- // Merging onto one slot keeps the banner but removes the apply button.
- await waitFor(() => expect(screen.queryByTestId('delivery-slot-merge-apply')).toBeNull())
- expect(screen.getByTestId('delivery-slot-merge')).toBeVisible()
+ // Merging collapses to one slot, so the whole merge row is hidden.
+ await waitFor(() => expect(screen.queryByTestId('delivery-slot-merge')).toBeNull())
})
- it('shows the merge banner without the apply button when one item cannot use the majority slot', async () => {
+ it('hides the merge row when one item cannot use the majority slot', async () => {
setupApiMocks({
procedures: {
'user.cart.getCartSlots': {
@@ -170,12 +169,12 @@ describe('Cart screen', () => {
])
renderWithProviders()
- await waitFor(() => expect(screen.getByTestId('delivery-slot-merge')).toBeVisible())
- expect(screen.getByText(/Deliver All items at/)).toBeVisible()
+ await waitFor(() => expect(screen.getByTestId('delivery-slot-summary')).toBeVisible())
+ expect(screen.queryByTestId('delivery-slot-merge')).toBeNull()
expect(screen.queryByTestId('delivery-slot-merge-apply')).toBeNull()
})
- it('shows the merge banner without the apply button when only one slot is selected', async () => {
+ it('hides the merge row when only one slot is selected', async () => {
setupApiMocks({
procedures: { 'user.cart.getCartSlots': { [PRODUCT_ID]: [futureSlot()] } },
})
@@ -184,9 +183,8 @@ describe('Cart screen', () => {
renderWithProviders()
await waitFor(() => expect(screen.getByText('Chicken Breast 500 g')).toBeVisible())
- await waitFor(() => expect(screen.getByTestId('delivery-slot-merge')).toBeVisible())
- expect(screen.getByText(/Deliver All items at/)).toBeVisible()
- expect(screen.queryByTestId('delivery-slot-merge-apply')).toBeNull()
+ await waitFor(() => expect(screen.getByTestId('delivery-slot-summary')).toBeVisible())
+ expect(screen.queryByTestId('delivery-slot-merge')).toBeNull()
})
it('renders the flash cart variant without slot selection', async () => {
diff --git a/change-log.txt b/change-log.txt
index 587717b..ae54a61 100644
--- a/change-log.txt
+++ b/change-log.txt
@@ -3721,3 +3721,120 @@ Tests: added merge-banner cases in tests/screens/cart-screen.test.tsx (not run).
mergeSuggestion now returns whenever >=1 slot is selected (not only >1); `feasible`
(the apply button) additionally requires >1 distinct slots and a slot every item
can use. Single-slot -> muted banner, no button.
+
+[2026-10-02 02:00:48] user-ui: fix 'setStoreHeaderTitle during render' warning (DynamicHeaderTitle update).
+
+Writes to useStoreHeaderStore must not happen in the render body; move them into
+useEffect so the DynamicHeaderTitle subscriber isn't updated while rendering.
+ - components/ProductDetail.tsx: wrap setStoreHeaderTitle(productDetail.name)
+ in an effect; add useEffect import.
+ - app/(drawer)/(tabs)/stores/store-detail/[id].tsx: same for store name; add
+ useEffect import.
+
+[2026-10-02 02:10:02] user-ui: cart-page - merge row is enabled-or-hidden (no muted/disabled state).
+
+DeliverySlotSummary now renders the 'Deliver All items at ' row only when the
+merge is feasible; otherwise the row is not rendered at all. mergeSuggestion returns
+null unless >1 distinct slots AND every in-stock item can use the majority slot, so
+the component always shows an enabled button. Dropped the `feasible` field.
+Tests updated: non-mergeable cases assert the row is absent.
+
+[2026-10-02 02:21:36] user-ui: fix cart items not showing until refresh + reconcile deleting lines.
+
+apps/user-ui/hooks/cart-query-hooks.tsx:
+ - useGetCart: query now fetches ONLY the raw stored lines; the enriched CartData
+ is derived in a useMemo from productsById/productSlotsMap. Previously the query
+ (keyed only on local-cart-) computed the mapping inside queryFn and never
+ re-ran when the central stores populated, so a restart showed an empty cart until
+ a manual refetch. Derived data now updates as soon as the stores load.
+ - useReconcileCartSlots: no longer drops a line whose product has no slots (keeps
+ it untouched); removed the once-per-mount hasRun ref so it re-runs when
+ productSlotsMap changes, repairing lines whose slot expired; bails when the slots
+ map is empty so it can never wipe the cart.
+ - add useMemo import; refetch type updated.
+Tests: cart-storage.test.tsx updated (keep un-repairable lines; re-reconcile on slot
+change). KNOWN-GAPS 5/6 updated.
+
+[2026-10-02 11:29:42] admin-ui + backend: push notification setup (parity with user-ui).
+
+apps/admin-ui/app.json: android.googleServicesFile + 'expo-notifications' plugin.
+apps/admin-ui/services/notif-service/: notif-register.ts, notif-context.tsx,
+ notif-checker.tsx (tap routes to /(drawer)/dashboard; saves via
+ admin.staffUser.savePushToken).
+apps/admin-ui/app/_layout.tsx: mount NotificationProvider + NotifChecker + .
+backend:
+ - packages/db_helper_sqlite/src/db/schema.ts: new staffNotifCreds table.
+ - packages/db_helper_sqlite/src/admin-apis/staff-user.ts: getStaffNotifCred /
+ upsertStaffNotifCred.
+ - packages/db_helper_sqlite/index.ts: export the two helpers.
+ - apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts: savePushToken
+ (protectedProcedure, stores ctx.staffUser.id -> token).
+NOTE: staff_notif_creds needs a drizzle migration (user runs it).
+
+[2026-10-02 11:35:16] superadmin-ui + backend: burger menu, dashboard, and 'Send Admin Notifications'.
+
+backend:
+ - packages/db_helper_sqlite/src/admin-apis/staff-user.ts: getAllStaffNotifTokens().
+ - packages/db_helper_sqlite/index.ts: export it.
+ - apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts: sendAdminNotification
+ (protectedProcedure) queues 'send-admin-notification' jobs for every staff token.
+superadmin-ui:
+ - src/components/AppShell.tsx: header with burger toggle + slide-in nav
+ (Dashboard, Send Admin Notifications, Constants) + logout.
+ - src/routes/dashboard.tsx: new overview page.
+ - src/routes/send-notifications.tsx: form -> trpc.admin.staffUser.sendAdminNotification.
+ - src/routes/constants.tsx: wrapped in AppShell.
+ - src/routes/index.tsx: redirect '/' -> '/dashboard'.
+ - routeTree.gen.ts regenerated by the TanStack router plugin.
+
+[2026-10-02 11:41:08] db_helper_sqlite: add migration 0004_staff_notif_creds (staff_notif_creds table).
+
+- drizzle/0004_staff_notif_creds.sql: CREATE TABLE + unique index on token.
+ Columns use text timestamps (timestampText -> text) to match the current schema;
+ default added_at = (CURRENT_TIMESTAMP).
+- drizzle/meta/_journal.json: append entry idx 4.
+Note: hand-written because drizzle-kit generate prompts on unrelated stale-snapshot
+drift (product_combos etc.); runtime migrator only needs the journal + .sql.
+
+[2026-10-02 11:46:58] db_helper_sqlite: make 0004_staff_notif_creds idempotent.
+
+CREATE TABLE -> CREATE TABLE IF NOT EXISTS; CREATE UNIQUE INDEX -> CREATE UNIQUE
+INDEX IF NOT EXISTS, so re-applying the migration is a no-op and never throws.
+
+[2026-10-02 12:50:09] db_helper_sqlite: add delivered_at / packaged_at timestamps (schema + migration 0004).
+
+- schema.ts: orders.deliveredAt (timestampText 'delivered_at'); orderItems.packagedAt
+ (timestampText 'packaged_at'). Both nullable text timestamps.
+- drizzle/0004_staff_notif_creds.sql: ALTER TABLE orders ADD COLUMN delivered_at;
+ ALTER TABLE order_items ADD COLUMN packaged_at.
+Caveat: SQLite has no ADD COLUMN IF NOT EXISTS, so these ALTERs error if the raw
+file is re-run (the CREATE ... IF NOT EXISTS part is re-runnable).
+
+[2026-10-02 12:57:24] db_helper_sqlite: split order timestamps into 0005 so 0004 stays idempotent.
+
+- 0004_staff_notif_creds.sql: back to CREATE TABLE/INDEX IF NOT EXISTS only.
+- 0005_order_timestamps.sql: ALTER TABLE orders ADD COLUMN delivered_at;
+ ALTER TABLE order_items ADD COLUMN packaged_at.
+- meta/_journal.json: append idx 5 tag 0005_order_timestamps.
+
+[2026-10-02 13:23:17] order-tracker: track user's first order in KV; welcome-msg option in admin kebabs.
+
+backend:
+ - wrangler.dev.toml / wrangler.prod.toml: new kv_namespaces binding
+ freshyo_order_tracker_dev / freshyo_order_tracker.
+ - src/lib/env-exporter.ts: getOrderTrackerKvNamespace().
+ - src/lib/order-tracker.ts (new): trackIfFirstOrder, clearFirstOrderIfMatches,
+ getFirstOrderId (first_order: -> orderId).
+ - user order placeOrderUtil: trackIfFirstOrder(userId, createdOrders[0].id)
+ (no rollback on later payment failure).
+ - user cancelOrder + admin cancelOrder: clearFirstOrderIfMatches.
+ - admin.order.getAll + admin.order.getSlotOrders: add isFirstOrder to each row.
+packages:
+ - shared/types/admin.ts: AdminOrderListItem.isFirstOrder; AdminSlotOrder.isFirstOrder
+ + userId.
+ - db_helper_sqlite admin-apis/order.ts getSlotOrders: include userId.
+admin-ui:
+ - components/OrderOptionsMenu.tsx: 'Send Welcome Msg' (green, WhatsApp) when
+ isFirstOrder; no prefilled text.
+ - manage-orders/orders/index.tsx + delivery-sequences/index.tsx: pass isFirstOrder.
+tests: order-options-menu welcome row; order-tracker unit test.
diff --git a/packages/db_helper_sqlite/drizzle/0004_staff_notif_creds.sql b/packages/db_helper_sqlite/drizzle/0004_staff_notif_creds.sql
new file mode 100644
index 0000000..40acb5d
--- /dev/null
+++ b/packages/db_helper_sqlite/drizzle/0004_staff_notif_creds.sql
@@ -0,0 +1,14 @@
+-- Migration: staff push-notification tokens.
+-- One row per admin/staff device Expo push token, so notifications can be
+-- broadcast to all admins (see admin.staffUser.savePushToken / sendAdminNotification).
+
+CREATE TABLE IF NOT EXISTS `staff_notif_creds` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `token` text NOT NULL,
+ `added_at` text DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
+ `staff_user_id` integer NOT NULL,
+ `last_verified` text,
+ FOREIGN KEY (`staff_user_id`) REFERENCES `staff_users`(`id`) ON UPDATE no action ON DELETE no action
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS `staff_notif_creds_token_unique` ON `staff_notif_creds` (`token`);
diff --git a/packages/db_helper_sqlite/drizzle/0005_order_timestamps.sql b/packages/db_helper_sqlite/drizzle/0005_order_timestamps.sql
new file mode 100644
index 0000000..55ffcc8
--- /dev/null
+++ b/packages/db_helper_sqlite/drizzle/0005_order_timestamps.sql
@@ -0,0 +1,10 @@
+-- Migration: actual event timestamps for orders and order lines.
+-- (The scheduled slot time remains delivery_slot_info.delivery_time via orders.slot_id;
+-- order_items.is_packaged / order_status.is_delivered stay as the boolean flags.)
+--
+-- NOTE: SQLite has no `ADD COLUMN IF NOT EXISTS`, so this file is not re-runnable;
+-- rely on the migration journal to apply it once.
+
+ALTER TABLE `orders` ADD COLUMN `delivered_at` text;
+--> statement-breakpoint
+ALTER TABLE `order_items` ADD COLUMN `packaged_at` text;
diff --git a/packages/db_helper_sqlite/drizzle/meta/_journal.json b/packages/db_helper_sqlite/drizzle/meta/_journal.json
index 8fd57da..700e040 100644
--- a/packages/db_helper_sqlite/drizzle/meta/_journal.json
+++ b/packages/db_helper_sqlite/drizzle/meta/_journal.json
@@ -29,6 +29,20 @@
"when": 1789236103378,
"tag": "0003_first_order_only",
"breakpoints": true
+ },
+ {
+ "idx": 4,
+ "version": "6",
+ "when": 1790921481292,
+ "tag": "0004_staff_notif_creds",
+ "breakpoints": true
+ },
+ {
+ "idx": 5,
+ "version": "6",
+ "when": 1790926061639,
+ "tag": "0005_order_timestamps",
+ "breakpoints": true
}
]
-}
\ No newline at end of file
+}
diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts
index 66753cf..e46f12e 100644
--- a/packages/db_helper_sqlite/index.ts
+++ b/packages/db_helper_sqlite/index.ts
@@ -118,6 +118,9 @@ export {
checkStaffRoleExists,
createStaffUser,
getAllRoles,
+ getStaffNotifCred,
+ upsertStaffNotifCred,
+ getAllStaffNotifTokens,
} from './src/admin-apis/staff-user'
export {
diff --git a/packages/db_helper_sqlite/src/admin-apis/order.ts b/packages/db_helper_sqlite/src/admin-apis/order.ts
index 63d6e6a..91322df 100644
--- a/packages/db_helper_sqlite/src/admin-apis/order.ts
+++ b/packages/db_helper_sqlite/src/admin-apis/order.ts
@@ -396,6 +396,7 @@ export async function getSlotOrders(slotId: string): Promise {
return roles
}
+
+export async function getStaffNotifCred(staffUserId: number, token: string) {
+ return db.query.staffNotifCreds.findFirst({
+ where: and(eq(staffNotifCreds.staffUserId, staffUserId), eq(staffNotifCreds.token, token)),
+ })
+}
+
+export async function upsertStaffNotifCred(staffUserId: number, token: string): Promise {
+ const existing = await getStaffNotifCred(staffUserId, token)
+ if (existing) {
+ await db.update(staffNotifCreds)
+ .set({ lastVerified: new Date() })
+ .where(eq(staffNotifCreds.id, existing.id))
+ return
+ }
+
+ await db.insert(staffNotifCreds).values({
+ staffUserId,
+ token,
+ lastVerified: new Date(),
+ })
+}
+
+export async function getAllStaffNotifTokens(): Promise<{ staffUserId: number; token: string }[]> {
+ return db
+ .select({ staffUserId: staffNotifCreds.staffUserId, token: staffNotifCreds.token })
+ .from(staffNotifCreds)
+}
diff --git a/packages/db_helper_sqlite/src/db/schema.ts b/packages/db_helper_sqlite/src/db/schema.ts
index 4555e40..cde0050 100644
--- a/packages/db_helper_sqlite/src/db/schema.ts
+++ b/packages/db_helper_sqlite/src/db/schema.ts
@@ -349,6 +349,7 @@ export const orders = sqliteTable('orders', {
orderGroupProportion: numericText('order_group_proportion'),
isFlashDelivery: integer('is_flash_delivery', { mode: 'boolean' }).notNull().default(false),
createdAt: timestampText('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),
+ deliveredAt: timestampText('delivered_at'),
})
export const orderItems = sqliteTable('order_items', {
@@ -360,6 +361,7 @@ export const orderItems = sqliteTable('order_items', {
discountedPrice: numericText('discounted_price'),
is_packaged: integer('is_packaged', { mode: 'boolean' }).notNull().default(false),
is_package_verified: integer('is_package_verified', { mode: 'boolean' }).notNull().default(false),
+ packagedAt: timestampText('packaged_at'),
})
export const orderStatus = sqliteTable('order_status', {
@@ -525,6 +527,14 @@ export const unloggedUserTokens = sqliteTable('unlogged_user_tokens', {
lastVerified: timestampText('last_verified'),
})
+export const staffNotifCreds = sqliteTable('staff_notif_creds', {
+ id: integer().primaryKey({ autoIncrement: true }),
+ token: text().notNull().unique(),
+ addedAt: timestampText('added_at').notNull().default(sql`CURRENT_TIMESTAMP`),
+ staffUserId: integer('staff_user_id').notNull().references(() => staffUsers.id),
+ lastVerified: timestampText('last_verified'),
+})
+
// Relations
export const usersRelations = relations(users, ({ many, one }) => ({
addresses: many(addresses),
diff --git a/packages/shared/types/admin.ts b/packages/shared/types/admin.ts
index a698b8f..89af69b 100644
--- a/packages/shared/types/admin.ts
+++ b/packages/shared/types/admin.ts
@@ -197,6 +197,8 @@ export interface AdminSlotOrder {
slotId: number | null;
adminNotes: string | null;
userNotes: string | null;
+ userId: number;
+ isFirstOrder?: boolean;
}
export interface AdminGetSlotOrdersResult {
@@ -231,6 +233,7 @@ export interface AdminOrderListItem {
userNotes: string | null;
adminNotes: string | null;
userNegativityScore: number;
+ isFirstOrder?: boolean;
}
export interface AdminOrderListItemWithUserId extends AdminOrderListItem {