enh
This commit is contained in:
parent
286943c081
commit
ee95b2a7f6
42 changed files with 1158 additions and 230 deletions
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"expo": {
|
||||
"name": "Symbuyote Admin",
|
||||
"name": "Freshyo Admin",
|
||||
"slug": "freshyoadmin",
|
||||
"version": "1.0.0",
|
||||
"orientation": "portrait",
|
||||
|
|
@ -62,9 +62,10 @@
|
|||
"foregroundImage": "./assets/images/symbuyoteadmin.png",
|
||||
"backgroundColor": "#fff0f6"
|
||||
},
|
||||
"edgeToEdgeEnabled": true,
|
||||
"package": "in.freshyo.adminui",
|
||||
"intentFilters": [
|
||||
"edgeToEdgeEnabled": true,
|
||||
"package": "in.freshyo.adminui",
|
||||
"googleServicesFile": "./google-services.json",
|
||||
"intentFilters": [
|
||||
{
|
||||
"action": "VIEW",
|
||||
"autoVerify": true,
|
||||
|
|
@ -95,8 +96,9 @@
|
|||
"backgroundColor": "#ffffff"
|
||||
}
|
||||
],
|
||||
"expo-secure-store"
|
||||
],
|
||||
"expo-secure-store",
|
||||
"expo-notifications"
|
||||
],
|
||||
"experiments": {
|
||||
"typedRoutes": true
|
||||
},
|
||||
|
|
|
|||
|
|
@ -46,6 +46,7 @@ interface OrderWithSequence {
|
|||
adminNotes?: string | null;
|
||||
customerName?: string | null;
|
||||
assignedUserName?: string | null;
|
||||
isFirstOrder?: boolean;
|
||||
}
|
||||
|
||||
interface SlotProgressProps {
|
||||
|
|
@ -722,6 +723,7 @@ export default function DeliverySequences() {
|
|||
adminNotes: selectedOrder?.adminNotes || null,
|
||||
latitude: selectedOrder?.latitude || null,
|
||||
longitude: selectedOrder?.longitude || null,
|
||||
isFirstOrder: selectedOrder?.isFirstOrder ?? false,
|
||||
}}
|
||||
onViewDetails={() => {
|
||||
if (selectedOrder) {
|
||||
|
|
|
|||
|
|
@ -366,6 +366,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
|
|||
latitude: order.latitude,
|
||||
longitude: order.longitude,
|
||||
status: order.status,
|
||||
isFirstOrder: order.isFirstOrder,
|
||||
}}
|
||||
onViewDetails={handleMenuOption}
|
||||
onTogglePackaged={() => handleMarkPackaged(!order.isPackaged)}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,9 @@ import { StaffAuthProvider } from "@/components/context/staff-auth-context";
|
|||
import { trpc, trpcClient } from "@/src/trpc-client";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
import { RefreshProvider } from '../../../packages/ui/src/lib/refresh-context';
|
||||
import Toast from "react-native-toast-message";
|
||||
import { NotificationProvider } from "@/services/notif-service/notif-context";
|
||||
import NotifChecker from "@/services/notif-service/notif-checker";
|
||||
|
||||
// Silence dev warnings/errors in LogBox. The "Open debugger to view warnings"
|
||||
// toast overlays the bottom of the UI and intercepts taps (e.g. the Add Slot
|
||||
|
|
@ -19,15 +22,19 @@ export default function Layout() {
|
|||
<QueryClientProvider client={queryClient}>
|
||||
<trpc.Provider client={trpcClient} queryClient={queryClient}>
|
||||
<StaffAuthProvider>
|
||||
<SafeAreaView
|
||||
edges={['left', 'right', 'bottom']}
|
||||
style={{ flex: 1, backgroundColor: '#fff' }}
|
||||
testID="app-root"
|
||||
>
|
||||
<RefreshProvider queryClient={queryClient}>
|
||||
<Stack screenOptions={{ headerShown: false }} />
|
||||
</RefreshProvider>
|
||||
</SafeAreaView>
|
||||
<NotificationProvider>
|
||||
<SafeAreaView
|
||||
edges={['left', 'right', 'bottom']}
|
||||
style={{ flex: 1, backgroundColor: '#fff' }}
|
||||
testID="app-root"
|
||||
>
|
||||
<RefreshProvider queryClient={queryClient}>
|
||||
<Stack screenOptions={{ headerShown: false }} />
|
||||
</RefreshProvider>
|
||||
</SafeAreaView>
|
||||
<NotifChecker />
|
||||
<Toast />
|
||||
</NotificationProvider>
|
||||
</StaffAuthProvider>
|
||||
</trpc.Provider>
|
||||
</QueryClientProvider>
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ interface OrderOptionsMenuProps {
|
|||
latitude?: number | null;
|
||||
longitude?: number | null;
|
||||
status?: string;
|
||||
isFirstOrder?: boolean;
|
||||
};
|
||||
onViewDetails: () => void;
|
||||
onTogglePackaged: () => void;
|
||||
|
|
@ -292,6 +293,30 @@ export function OrderOptionsMenu({
|
|||
</TouchableOpacity>
|
||||
)}
|
||||
|
||||
{order.isFirstOrder && (
|
||||
<TouchableOpacity
|
||||
testID="send-welcome-msg"
|
||||
style={tw`flex-row items-center p-4 bg-emerald-50 border border-emerald-200 rounded-xl mb-3 shadow-sm`}
|
||||
onPress={() => {
|
||||
handleWhatsApp();
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
<View style={tw`w-10 h-10 rounded-full bg-emerald-100 items-center justify-center mr-4`}>
|
||||
<MaterialIcons name="celebration" size={20} color="#059669" />
|
||||
</View>
|
||||
<View>
|
||||
<MyText style={tw`font-semibold text-emerald-800 text-base`}>
|
||||
Send Welcome Msg
|
||||
</MyText>
|
||||
<MyText style={tw`text-emerald-600 text-xs`}>
|
||||
First order — welcome the customer on WhatsApp
|
||||
</MyText>
|
||||
</View>
|
||||
<MaterialIcons name="chevron-right" size={24} color="#9ca3af" style={tw`ml-auto`} />
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
|
||||
<TouchableOpacity
|
||||
style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl mb-3 shadow-sm`}
|
||||
onPress={() => {
|
||||
|
|
|
|||
48
apps/admin-ui/google-services.json
Normal file
48
apps/admin-ui/google-services.json
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
{
|
||||
"project_info": {
|
||||
"project_number": "535753078248",
|
||||
"project_id": "freshyo-cefb2",
|
||||
"storage_bucket": "freshyo-cefb2.firebasestorage.app"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:535753078248:android:a28dec271c1f916b38605d",
|
||||
"android_client_info": {
|
||||
"package_name": "in.freshyo.adminui"
|
||||
}
|
||||
},
|
||||
"oauth_client": [],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyDW4w6vGDrZnkf8vgwdQObBLnT_iucs2H8"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:535753078248:android:d00803550e29eb3238605d",
|
||||
"android_client_info": {
|
||||
"package_name": "in.freshyo.app"
|
||||
}
|
||||
},
|
||||
"oauth_client": [],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyDW4w6vGDrZnkf8vgwdQObBLnT_iucs2H8"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
}
|
||||
73
apps/admin-ui/services/notif-service/notif-checker.tsx
Normal file
73
apps/admin-ui/services/notif-service/notif-checker.tsx
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import React from "react";
|
||||
import { useNotification } from "./notif-context";
|
||||
import { BottomDialog } from "common-ui";
|
||||
import { MyText } from "common-ui";
|
||||
import { View, Linking } from "react-native";
|
||||
import { tw } from "common-ui";
|
||||
import { MyButton } from "common-ui";
|
||||
import { useStaffAuth } from "@/components/context/staff-auth-context";
|
||||
import { trpc } from "@/src/trpc-client";
|
||||
|
||||
function NotifChecker() {
|
||||
const [showPermissionDialog, setShowPermissionDialog] = React.useState(false);
|
||||
|
||||
const { isLoggedIn } = useStaffAuth();
|
||||
const savePushTokenMutation = trpc.admin.staffUser.savePushToken.useMutation();
|
||||
const { notifPermission, expoPushToken } = useNotification();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (expoPushToken && notifPermission === 'granted' && isLoggedIn) {
|
||||
savePushTokenMutation.mutate(
|
||||
{ token: expoPushToken },
|
||||
{
|
||||
onError: (error) => {
|
||||
console.error('Failed to save push token:', error);
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
}, [expoPushToken, notifPermission, isLoggedIn]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (notifPermission === "denied") {
|
||||
setShowPermissionDialog(true);
|
||||
}
|
||||
}, [notifPermission]);
|
||||
|
||||
return (
|
||||
<BottomDialog
|
||||
open={showPermissionDialog}
|
||||
onClose={() => setShowPermissionDialog(false)}
|
||||
>
|
||||
<View style={tw`flex flex-col h-64 p-4`}>
|
||||
<MyText weight="semibold" color="red1" style={tw`mb-2 text-lg`}>
|
||||
Notification Permission Denied
|
||||
</MyText>
|
||||
<MyText>
|
||||
It seems you have denied notification permissions. Please enable
|
||||
them in your device settings.
|
||||
</MyText>
|
||||
<View style={tw`flex flex-row gap-3 mt-auto justify-center`}>
|
||||
<MyButton
|
||||
fillColor="red1"
|
||||
onPress={() => setShowPermissionDialog(false)}
|
||||
style={tw`flex-1`}
|
||||
>
|
||||
Cancel
|
||||
</MyButton>
|
||||
<MyButton
|
||||
fillColor="brand500"
|
||||
onPress={() => {
|
||||
Linking.openSettings();
|
||||
}}
|
||||
style={tw`flex-1`}
|
||||
>
|
||||
Settings
|
||||
</MyButton>
|
||||
</View>
|
||||
</View>
|
||||
</BottomDialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default NotifChecker;
|
||||
104
apps/admin-ui/services/notif-service/notif-context.tsx
Normal file
104
apps/admin-ui/services/notif-service/notif-context.tsx
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import React, {
|
||||
createContext,
|
||||
useContext,
|
||||
useState,
|
||||
useEffect,
|
||||
useRef,
|
||||
} from "react";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import { registerForPushNotificationsAsync } from "./notif-register";
|
||||
import { useRouter } from "expo-router";
|
||||
import { NotificationToast } from "../toaster";
|
||||
import { NOTIF_PERMISSION_DENIED } from "common-ui/src/lib/const-strs";
|
||||
import type { ReactParentComponent } from '@packages/shared';
|
||||
|
||||
interface NotificationContextType {
|
||||
expoPushToken: string | null;
|
||||
notification: Notifications.Notification | null;
|
||||
error: Error | null;
|
||||
notifPermission: 'pending' | 'granted' | 'denied'
|
||||
}
|
||||
|
||||
export const NotificationContext = createContext<
|
||||
NotificationContextType | undefined
|
||||
>(undefined);
|
||||
|
||||
export const useNotification = () => {
|
||||
const context = useContext(NotificationContext);
|
||||
if (context === undefined) {
|
||||
throw new Error(
|
||||
"useNotification must be used within a NotificationProvider"
|
||||
);
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export const NotificationProvider: React.FC<ReactParentComponent> = ({
|
||||
children,
|
||||
}) => {
|
||||
const [expoPushToken, setExpoPushToken] = useState<string | null>(null);
|
||||
const [notification, setNotification] =
|
||||
useState<Notifications.Notification | null>(null);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const [notifPermission, setNotifPermission] = React.useState<NotificationContextType["notifPermission"]>("pending");
|
||||
|
||||
const notificationListener = useRef<any>(null);
|
||||
const responseListener = useRef<any>(null);
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
registerForPushNotificationsAsync()
|
||||
.then((token) => {
|
||||
setExpoPushToken(token);
|
||||
setNotifPermission("granted");
|
||||
})
|
||||
.catch((errorRaw) => {
|
||||
const err = String(errorRaw).slice(7); // strip leading "Error: "
|
||||
if (err === NOTIF_PERMISSION_DENIED) {
|
||||
setNotifPermission("denied");
|
||||
}
|
||||
});
|
||||
|
||||
notificationListener.current =
|
||||
Notifications.addNotificationReceivedListener((notification) => {
|
||||
setNotification(notification);
|
||||
const content = notification.request?.content;
|
||||
if (content) {
|
||||
NotificationToast(
|
||||
content.title || "Notification",
|
||||
content.body || "",
|
||||
content.data || {}
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
responseListener.current =
|
||||
Notifications.addNotificationResponseReceivedListener((response) => {
|
||||
const data = response.notification.request.content.data;
|
||||
if (data && data.orderId) {
|
||||
router.push("/(drawer)/dashboard/manage-orders/orders" as any);
|
||||
} else {
|
||||
router.push("/(drawer)/dashboard" as any);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (notificationListener.current) {
|
||||
Notifications.removeNotificationSubscription(
|
||||
notificationListener.current
|
||||
);
|
||||
}
|
||||
if (responseListener.current) {
|
||||
Notifications.removeNotificationSubscription(responseListener.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<NotificationContext.Provider
|
||||
value={{ expoPushToken, notification, error, notifPermission }}
|
||||
>
|
||||
{children}
|
||||
</NotificationContext.Provider>
|
||||
);
|
||||
};
|
||||
47
apps/admin-ui/services/notif-service/notif-register.ts
Normal file
47
apps/admin-ui/services/notif-service/notif-register.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import * as Notifications from "expo-notifications";
|
||||
import * as Device from "expo-device";
|
||||
import Constants from "expo-constants";
|
||||
import { Platform } from "react-native";
|
||||
import { NOTIF_PERMISSION_DENIED } from "common-ui/src/lib/const-strs";
|
||||
|
||||
export async function registerForPushNotificationsAsync() {
|
||||
if (Platform.OS === "android") {
|
||||
await Notifications.setNotificationChannelAsync("default", {
|
||||
name: "default",
|
||||
importance: Notifications.AndroidImportance.MAX,
|
||||
vibrationPattern: [0, 250, 250, 250],
|
||||
lightColor: "#FF231F7C",
|
||||
});
|
||||
}
|
||||
|
||||
if (Device.isDevice) {
|
||||
const { status: existingStatus } =
|
||||
await Notifications.getPermissionsAsync();
|
||||
let finalStatus = existingStatus;
|
||||
if (existingStatus !== "granted") {
|
||||
const { status } = await Notifications.requestPermissionsAsync();
|
||||
finalStatus = status;
|
||||
}
|
||||
|
||||
if (finalStatus !== "granted") {
|
||||
throw new Error(NOTIF_PERMISSION_DENIED);
|
||||
}
|
||||
|
||||
const projectId =
|
||||
Constants?.expoConfig?.extra?.eas?.projectId ??
|
||||
Constants?.easConfig?.projectId;
|
||||
if (!projectId) {
|
||||
throw new Error("Project ID not found");
|
||||
}
|
||||
try {
|
||||
const pushTokenString = (
|
||||
await Notifications.getExpoPushTokenAsync({ projectId })
|
||||
).data;
|
||||
return pushTokenString;
|
||||
} catch (e: unknown) {
|
||||
throw new Error(`${e}`);
|
||||
}
|
||||
} else {
|
||||
throw new Error("Must use physical device for push notifications");
|
||||
}
|
||||
}
|
||||
|
|
@ -207,6 +207,22 @@ describe('OrderOptionsMenu', () => {
|
|||
expect(Linking.openURL).toHaveBeenCalledWith('whatsapp://send?phone=+919876543210')
|
||||
})
|
||||
|
||||
it('shows the welcome message row only for a first order and opens WhatsApp', () => {
|
||||
renderMenu({ isFirstOrder: true })
|
||||
|
||||
expect(screen.getByText('Send Welcome Msg')).toBeVisible()
|
||||
|
||||
fireEvent.press(screen.getByText('Send Welcome Msg'))
|
||||
|
||||
expect(Linking.openURL).toHaveBeenCalledWith('whatsapp://send?phone=+919876543210')
|
||||
})
|
||||
|
||||
it('hides the welcome message row for repeat orders', () => {
|
||||
renderMenu({ isFirstOrder: false })
|
||||
|
||||
expect(screen.queryByText('Send Welcome Msg')).toBeNull()
|
||||
})
|
||||
|
||||
it('dials the phone parsed from the address', () => {
|
||||
renderMenu()
|
||||
|
||||
|
|
|
|||
|
|
@ -1,48 +1,4 @@
|
|||
toggleOutOfStock: protectedProcedure
|
||||
.input(z.object({
|
||||
id: z.number(),
|
||||
}))
|
||||
.mutation(async ({ input }): Promise<AdminToggleOutOfStockResult> => {
|
||||
const { id } = input;
|
||||
|
||||
const updatedProduct = await toggleProductOutOfStockInDb(id)
|
||||
bunx wrangler d1 execute --remote freshyo-backend-dev --file=../../packages/db_helper_sqlite/drizzle/0004_staff_notif_creds.sql --config wrangler.dev.toml
|
||||
|
||||
|
||||
if (!updatedProduct) {
|
||||
throw new ApiError('Product not found', 404)
|
||||
}
|
||||
|
||||
await scheduleStoreInitialization()
|
||||
|
||||
return {
|
||||
product: updatedProduct,
|
||||
message: `Product marked as ${updatedProduct.isOutOfStock ? 'out of stock' : 'in stock'}`,
|
||||
}
|
||||
}),
|
||||
|
||||
|
||||
|
||||
|
||||
export async function toggleProductOutOfStock(id: number): Promise<AdminProduct | null> {
|
||||
const product = await db.query.productInfo.findFirst({
|
||||
where: eq(productInfo.id, id),
|
||||
})
|
||||
|
||||
if (!product) {
|
||||
return null
|
||||
}
|
||||
|
||||
const [updatedProduct] = await db
|
||||
.update(productInfo)
|
||||
.set({
|
||||
isOutOfStock: !product.isOutOfStock,
|
||||
})
|
||||
.where(eq(productInfo.id, id))
|
||||
.returning()
|
||||
|
||||
if (!updatedProduct) {
|
||||
return null
|
||||
}
|
||||
|
||||
return mapProduct(updatedProduct)
|
||||
}
|
||||
I've created the both namespaces. show the option in all places where an order has a kebab menu in admin app.
|
||||
|
|
@ -15,7 +15,7 @@ export const createApp = () => {
|
|||
|
||||
// CORS middleware
|
||||
app.use(cors({
|
||||
origin: ['http://localhost:5174', 'http://localhost:4174', 'http://localhost:4175', 'https://ui.freshyo.in', 'https://www.freshyo.in', 'https://webui.freshyo.in', 'https://app.freshyo.in', 'https://admin.freshyo.in',],
|
||||
origin: ['http://localhost:5174', 'http://localhost:4174', 'http://localhost:4175', 'https://ui.freshyo.in', 'https://www.freshyo.in', 'https://webui.freshyo.in', 'https://app.freshyo.in', 'https://admin.freshyo.in', 'https://superadmin.freshyo.in'],
|
||||
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
||||
allowHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'Caller-Interface'],
|
||||
credentials: true,
|
||||
|
|
|
|||
|
|
@ -101,6 +101,11 @@ export const getOtpKvNamespace = () => {
|
|||
return (env.freshyo_otp || env.freshyo_otp_dev) as KVNamespace | undefined
|
||||
}
|
||||
|
||||
export const getOrderTrackerKvNamespace = () => {
|
||||
const env = getRuntimeEnv()
|
||||
return (env.freshyo_order_tracker || env.freshyo_order_tracker_dev) as KVNamespace | undefined
|
||||
}
|
||||
|
||||
export const getMinOrderValue = () => Number(getRuntimeEnv().MIN_ORDER_VALUE as string)
|
||||
|
||||
export const getDeliveryCharge = () => Number(getRuntimeEnv().DELIVERY_CHARGE as string)
|
||||
|
|
|
|||
51
apps/backend/src/lib/order-tracker.ts
Normal file
51
apps/backend/src/lib/order-tracker.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { getOrderTrackerKvNamespace } from '@/src/lib/env-exporter'
|
||||
|
||||
const firstOrderKey = (userId: number) => `first_order:${userId}`
|
||||
|
||||
/**
|
||||
* Records the user's first order id if the user has no entry yet.
|
||||
* No-op when the KV binding is not configured (local/tests).
|
||||
*/
|
||||
export async function trackIfFirstOrder(userId: number, orderId: number): Promise<void> {
|
||||
try {
|
||||
const kv = getOrderTrackerKvNamespace()
|
||||
if (!kv) return
|
||||
|
||||
const existing = await kv.get(firstOrderKey(userId))
|
||||
if (existing) return
|
||||
|
||||
await kv.put(firstOrderKey(userId), String(orderId))
|
||||
} catch (error) {
|
||||
console.error('trackIfFirstOrder failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the tracked first order only when the cancelled order is the tracked one.
|
||||
*/
|
||||
export async function clearFirstOrderIfMatches(userId: number, orderId: number): Promise<void> {
|
||||
try {
|
||||
const kv = getOrderTrackerKvNamespace()
|
||||
if (!kv) return
|
||||
|
||||
const existing = await kv.get(firstOrderKey(userId))
|
||||
if (existing && Number(existing) === orderId) {
|
||||
await kv.delete(firstOrderKey(userId))
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('clearFirstOrderIfMatches failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
export async function getFirstOrderId(userId: number): Promise<number | null> {
|
||||
try {
|
||||
const kv = getOrderTrackerKvNamespace()
|
||||
if (!kv) return null
|
||||
|
||||
const existing = await kv.get(firstOrderKey(userId))
|
||||
return existing ? Number(existing) : null
|
||||
} catch (error) {
|
||||
console.error('getFirstOrderId failed:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
|
@ -6,6 +6,7 @@ import {
|
|||
sendOrderDeliveredNotification,
|
||||
} from "@/src/lib/notif-job";
|
||||
import { publishCancellation } from "@/src/lib/post-order-handler"
|
||||
import { clearFirstOrderIfMatches, getFirstOrderId } from "@/src/lib/order-tracker"
|
||||
import { getMultipleUserNegativityScores } from "@/src/stores/user-negativity-store"
|
||||
import {
|
||||
updateOrderNotes as updateOrderNotesInDb,
|
||||
|
|
@ -173,7 +174,20 @@ export const orderRouter = router({
|
|||
|
||||
const result = await getSlotOrdersInDb(slotId)
|
||||
|
||||
return result
|
||||
const userIds = [...new Set(result.data.map((order) => order.userId))]
|
||||
const firstOrderIdByUser = new Map<number, number | null>()
|
||||
await Promise.all(
|
||||
userIds.map(async (userId) => {
|
||||
firstOrderIdByUser.set(userId, await getFirstOrderId(userId))
|
||||
})
|
||||
)
|
||||
|
||||
const data = result.data.map((order) => ({
|
||||
...order,
|
||||
isFirstOrder: firstOrderIdByUser.get(order.userId) === order.id,
|
||||
}))
|
||||
|
||||
return { ...result, data }
|
||||
}),
|
||||
|
||||
updateAddressCoords: protectedProcedure
|
||||
|
|
@ -204,11 +218,19 @@ export const orderRouter = router({
|
|||
const userIds = [...new Set(result.orders.map((order) => order.userId))]
|
||||
const negativityScores = await getMultipleUserNegativityScores(userIds)
|
||||
|
||||
const firstOrderIdByUser = new Map<number, number | null>()
|
||||
await Promise.all(
|
||||
userIds.map(async (userId) => {
|
||||
firstOrderIdByUser.set(userId, await getFirstOrderId(userId))
|
||||
})
|
||||
)
|
||||
|
||||
const orders = result.orders.map((order) => {
|
||||
const { userId, userNegativityScore, ...rest } = order
|
||||
return {
|
||||
...rest,
|
||||
userNegativityScore: negativityScores[userId] || 0,
|
||||
isFirstOrder: firstOrderIdByUser.get(userId) === order.id,
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -258,6 +280,10 @@ export const orderRouter = router({
|
|||
throw new ApiError(result.message, 400)
|
||||
}
|
||||
|
||||
if (result.orderId && result.userId) {
|
||||
await clearFirstOrderIfMatches(result.userId, result.orderId)
|
||||
}
|
||||
|
||||
if (result.orderId) {
|
||||
await publishCancellation(result.orderId, 'admin', reason)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,13 @@ import {
|
|||
checkStaffRoleExists,
|
||||
createStaffUser,
|
||||
getAllRoles,
|
||||
upsertStaffNotifCred,
|
||||
getAllStaffNotifTokens,
|
||||
} from '@/src/dbService'
|
||||
import { queueDataPusher } from '@/src/lib/queue-data-pusher'
|
||||
|
||||
// Number of push tokens batched into a single queue message.
|
||||
const TOKENS_PER_QUEUE_MESSAGE = 5
|
||||
|
||||
export const staffUserRouter = router({
|
||||
login: publicProcedure
|
||||
|
|
@ -115,4 +121,61 @@ export const staffUserRouter = router({
|
|||
})),
|
||||
};
|
||||
}),
|
||||
|
||||
savePushToken: protectedProcedure
|
||||
.input(z.object({ token: z.string().min(1) }))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const staffId = ctx.staffUser?.id;
|
||||
|
||||
if (!staffId) {
|
||||
throw new ApiError('Staff not authenticated', 401);
|
||||
}
|
||||
|
||||
await upsertStaffNotifCred(staffId, input.token);
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
sendAdminNotification: protectedProcedure
|
||||
.input(z.object({
|
||||
title: z.string().min(1, 'Title is required'),
|
||||
text: z.string().min(1, 'Message is required'),
|
||||
imageUrl: z.string().optional(),
|
||||
}))
|
||||
.mutation(async ({ input }) => {
|
||||
const { title, text, imageUrl } = input;
|
||||
|
||||
const tokens = (await getAllStaffNotifTokens()).map((t) => t.token);
|
||||
|
||||
let queuedCount = 0;
|
||||
for (let i = 0; i < tokens.length; i += TOKENS_PER_QUEUE_MESSAGE) {
|
||||
const tokenChunk = tokens.slice(i, i + TOKENS_PER_QUEUE_MESSAGE);
|
||||
try {
|
||||
await queueDataPusher.pushNotifQueue({
|
||||
name: 'send-admin-notification',
|
||||
jobData: {
|
||||
tokens: tokenChunk,
|
||||
title,
|
||||
body: text,
|
||||
imageUrl: imageUrl || null,
|
||||
},
|
||||
options: {
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 2000,
|
||||
},
|
||||
},
|
||||
});
|
||||
queuedCount += tokenChunk.length;
|
||||
} catch (error) {
|
||||
console.error(`Failed to queue admin notification for tokens:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Notification queued for ${queuedCount} admins`,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import { ApiError } from "@/src/lib/api-error";
|
|||
import type { DeliveryStatus, OrderStatus } from "@packages/shared";
|
||||
import { CONST_KEYS, getConstant, getConstants } from "@/src/lib/const-store";
|
||||
import { publishFormattedOrder, publishCancellation } from "@/src/lib/post-order-handler";
|
||||
import { trackIfFirstOrder, clearFirstOrderIfMatches } from "@/src/lib/order-tracker";
|
||||
import type {
|
||||
UserOrdersResponse,
|
||||
UserOrderDetail,
|
||||
|
|
@ -215,6 +216,10 @@ const placeOrderUtil = async (params: {
|
|||
totalWithDelivery,
|
||||
});
|
||||
|
||||
if (createdOrders.length > 0) {
|
||||
await trackIfFirstOrder(userId, createdOrders[0].id);
|
||||
}
|
||||
|
||||
await deleteUserCartItemsForOrder(
|
||||
userId,
|
||||
selectedItems.map((item) => item.skuId)
|
||||
|
|
@ -590,6 +595,8 @@ export const orderRouter = router({
|
|||
|
||||
await cancelUserOrderTransaction(id, status.id, reason, order.isCod);
|
||||
|
||||
await clearFirstOrderIfMatches(userId, id);
|
||||
|
||||
await publishCancellation(id, 'user', reason);
|
||||
|
||||
return { success: true, message: "Order cancelled successfully" };
|
||||
|
|
|
|||
|
|
@ -8,10 +8,10 @@ routes = [
|
|||
|
||||
[[d1_databases]]
|
||||
binding = "DB"
|
||||
#database_name = "freshyo-backend-dev"
|
||||
#database_id = "b2528bdb-0ec0-478e-8765-b118918153c0"
|
||||
database_name = "freshyo-dev"
|
||||
database_id = "3cad440f-dc14-4baa-ab05-04eb08e206de"
|
||||
database_name = "freshyo-backend-dev"
|
||||
database_id = "b2528bdb-0ec0-478e-8765-b118918153c0"
|
||||
#database_name = "freshyo-dev"
|
||||
#database_id = "3cad440f-dc14-4baa-ab05-04eb08e206de"
|
||||
migrations_dir="../../packages/db_helper_sqlite/drizzle"
|
||||
migrations_pattern="migration.sql"
|
||||
[durable_objects]
|
||||
|
|
@ -109,3 +109,7 @@ upload_source_maps = true
|
|||
[[kv_namespaces]]
|
||||
binding="freshyo_otp_dev"
|
||||
id="6f6dbada52584d7fb744c9c85bd0c1e5"
|
||||
|
||||
[[kv_namespaces]]
|
||||
binding="freshyo_order_tracker_dev"
|
||||
id="e9d770b725d748e489288a20cf786846"
|
||||
|
|
|
|||
|
|
@ -101,4 +101,8 @@ upload_source_maps = true
|
|||
|
||||
[[kv_namespaces]]
|
||||
binding="freshyo_otp"
|
||||
id="aba74be264df45c0b17757fe01c136e5"
|
||||
id="aba74be264df45c0b17757fe01c136e5"
|
||||
|
||||
[[kv_namespaces]]
|
||||
binding="freshyo_order_tracker"
|
||||
id="ec20eab6e50648b8b45e8e269f9aa0c1"
|
||||
85
apps/superadmin-ui/src/components/AppShell.tsx
Normal file
85
apps/superadmin-ui/src/components/AppShell.tsx
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
import React, { useState } from 'react'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { LayoutDashboard, Send, Settings2, Menu, X, LogOut } from 'lucide-react'
|
||||
import { useAuth } from '../lib/auth-context'
|
||||
|
||||
const NAV = [
|
||||
{ to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
||||
{ to: '/send-notifications', label: 'Send Admin Notifications', icon: Send },
|
||||
{ to: '/constants', label: 'App Constants', icon: Settings2 },
|
||||
] as const
|
||||
|
||||
export function AppShell({ children }: { children: React.ReactNode }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const { staff, logout } = useAuth()
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<header className="sticky top-0 z-40 flex h-14 items-center justify-between border-b border-gray-200 bg-white px-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Toggle menu"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="rounded-lg p-2 text-gray-700 hover:bg-gray-100 md:hidden"
|
||||
>
|
||||
{open ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
|
||||
</button>
|
||||
<Link to="/dashboard" className="text-lg font-bold text-gray-900">
|
||||
Freshyo Superadmin
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
{staff?.name && (
|
||||
<span className="hidden text-sm text-gray-500 sm:inline">{staff.name}</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={logout}
|
||||
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-100"
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
Logout
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex">
|
||||
<aside
|
||||
className={`fixed inset-y-0 left-0 z-30 w-64 transform border-r border-gray-200 bg-white pt-14 transition-transform duration-200 ease-in-out md:static md:translate-x-0 md:pt-0 ${
|
||||
open ? 'translate-x-0' : '-translate-x-full'
|
||||
}`}
|
||||
>
|
||||
<nav className="space-y-1 p-3">
|
||||
{NAV.map(({ to, label, icon: Icon }) => (
|
||||
<Link
|
||||
key={to}
|
||||
to={to}
|
||||
onClick={() => setOpen(false)}
|
||||
activeProps={{ className: 'bg-blue-50 text-blue-700' }}
|
||||
inactiveProps={{ className: 'text-gray-700' }}
|
||||
className="flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium hover:bg-gray-100"
|
||||
>
|
||||
<Icon className="h-5 w-5" />
|
||||
{label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
{open && (
|
||||
<div
|
||||
className="fixed inset-0 z-20 bg-black/30 md:hidden"
|
||||
onClick={() => setOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<main className="min-h-[calc(100vh-3.5rem)] flex-1">{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default AppShell
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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<string, any>
|
||||
|
||||
|
|
@ -270,7 +271,9 @@ function CustomizeApp() {
|
|||
export const Route = createFileRoute('/constants')({
|
||||
component: () => (
|
||||
<ProtectedRoute>
|
||||
<CustomizeApp />
|
||||
<AppShell>
|
||||
<CustomizeApp />
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
),
|
||||
})
|
||||
|
|
|
|||
64
apps/superadmin-ui/src/routes/dashboard.tsx
Normal file
64
apps/superadmin-ui/src/routes/dashboard.tsx
Normal file
|
|
@ -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: () => (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
<Dashboard />
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
),
|
||||
})
|
||||
|
||||
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 (
|
||||
<AppContainer>
|
||||
<div className="bg-gray-50 p-4">
|
||||
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Dashboard</MyText>
|
||||
<MyText className="mb-6 block text-gray-600">
|
||||
Manage the Freshyo platform.
|
||||
</MyText>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{CARDS.map(({ to, title, description, icon: Icon }) => (
|
||||
<Link
|
||||
key={to}
|
||||
to={to}
|
||||
className="flex items-center justify-between rounded-xl border border-gray-200 bg-white p-5 shadow-sm transition-colors hover:border-blue-300 hover:bg-blue-50/40"
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex h-11 w-11 items-center justify-center rounded-lg bg-blue-50">
|
||||
<Icon className="h-6 w-6 text-blue-600" />
|
||||
</div>
|
||||
<div>
|
||||
<MyText className="block font-semibold text-gray-900">{title}</MyText>
|
||||
<MyText className="block text-sm text-gray-500">{description}</MyText>
|
||||
</div>
|
||||
</div>
|
||||
<ChevronRight className="h-5 w-5 text-gray-400" />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</AppContainer>
|
||||
)
|
||||
}
|
||||
|
|
@ -2,6 +2,6 @@ import { createFileRoute, redirect } from '@tanstack/react-router'
|
|||
|
||||
export const Route = createFileRoute('/')({
|
||||
loader: () => {
|
||||
throw redirect({ to: '/constants' })
|
||||
throw redirect({ to: '/dashboard' })
|
||||
},
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
102
apps/superadmin-ui/src/routes/send-notifications.tsx
Normal file
102
apps/superadmin-ui/src/routes/send-notifications.tsx
Normal file
|
|
@ -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: () => (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
<SendAdminNotifications />
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
),
|
||||
})
|
||||
|
||||
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 (
|
||||
<AppContainer>
|
||||
<div className="bg-gray-50 p-4">
|
||||
<MyText className="mb-1 block text-2xl font-bold text-gray-900">
|
||||
Send Admin Notifications
|
||||
</MyText>
|
||||
<MyText className="mb-6 block text-gray-600">
|
||||
This push notification is delivered to every admin device.
|
||||
</MyText>
|
||||
|
||||
<div className="max-w-2xl rounded-xl border border-gray-200 bg-white p-6 shadow-sm">
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
<PInput
|
||||
topLabel="Title"
|
||||
placeholder="e.g. New order received"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
|
||||
<div>
|
||||
<MyText className="mb-2 block text-sm font-medium text-gray-700">Message</MyText>
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder="Write the notification body..."
|
||||
rows={4}
|
||||
className="w-full rounded-lg border border-gray-300 bg-white p-3 text-gray-900 outline-none focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<PInput
|
||||
topLabel="Image URL (optional)"
|
||||
placeholder="https://..."
|
||||
value={imageUrl}
|
||||
onChange={(e) => setImageUrl(e.target.value)}
|
||||
/>
|
||||
|
||||
<MyButton
|
||||
type="submit"
|
||||
fullWidth
|
||||
disabled={isPending || !title.trim() || !text.trim()}
|
||||
className={`flex h-12 items-center justify-center gap-2 rounded-lg bg-blue-600 text-white shadow-md transition-colors hover:bg-blue-700 ${
|
||||
isPending ? 'opacity-50' : ''
|
||||
}`}
|
||||
>
|
||||
<Send className="h-4 w-4" />
|
||||
{isPending ? 'Sending...' : 'Send to all admins'}
|
||||
</MyButton>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</AppContainer>
|
||||
)
|
||||
}
|
||||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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<ProductDetailProps> = ({ 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 (
|
||||
|
|
|
|||
|
|
@ -60,7 +60,6 @@ interface DeliverySlotGroup {
|
|||
interface DeliverySlotMergeSuggestion {
|
||||
slotId: number;
|
||||
label: string;
|
||||
feasible: boolean;
|
||||
}
|
||||
|
||||
function DeliverySlotSummary({
|
||||
|
|
@ -115,38 +114,22 @@ function DeliverySlotSummary({
|
|||
{!!mergeSuggestion && (
|
||||
<View
|
||||
testID="delivery-slot-merge"
|
||||
style={[
|
||||
tw`mt-3 flex-row items-center justify-between rounded-xl px-3 py-2.5 border`,
|
||||
mergeSuggestion.feasible
|
||||
? tw`bg-brand50 border-brand200`
|
||||
: tw`bg-gray-50 border-gray-200`,
|
||||
]}
|
||||
style={tw`mt-3 flex-row items-center justify-between rounded-xl px-3 py-2.5 border bg-brand50 border-brand200`}
|
||||
>
|
||||
<View style={tw`flex-row items-center flex-1 mr-2`}>
|
||||
<MaterialIcons
|
||||
name="merge-type"
|
||||
size={16}
|
||||
color={mergeSuggestion.feasible ? '#1570EF' : '#9CA3AF'}
|
||||
/>
|
||||
<MyText
|
||||
style={[
|
||||
tw`text-sm ml-2 flex-1`,
|
||||
mergeSuggestion.feasible ? tw`font-medium text-brand700` : tw`text-gray-500`,
|
||||
]}
|
||||
>
|
||||
<MaterialIcons name="merge-type" size={16} color="#1570EF" />
|
||||
<MyText style={tw`text-sm font-medium text-brand700 ml-2 flex-1`}>
|
||||
Deliver All items at {mergeSuggestion.label}
|
||||
</MyText>
|
||||
</View>
|
||||
{mergeSuggestion.feasible && (
|
||||
<MyTouchableOpacity
|
||||
testID="delivery-slot-merge-apply"
|
||||
onPress={onMerge}
|
||||
activeOpacity={0.7}
|
||||
style={tw`p-1`}
|
||||
>
|
||||
<MaterialIcons name="chevron-right" size={20} color="#1570EF" />
|
||||
</MyTouchableOpacity>
|
||||
)}
|
||||
<MyTouchableOpacity
|
||||
testID="delivery-slot-merge-apply"
|
||||
onPress={onMerge}
|
||||
activeOpacity={0.7}
|
||||
style={tw`p-1`}
|
||||
>
|
||||
<MaterialIcons name="chevron-right" size={20} color="#1570EF" />
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
|
@ -495,7 +478,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
}, [isFlashDelivery, cartItems, selectedSlots, slotsData, productsById, quantities]);
|
||||
|
||||
const mergeSuggestion = useMemo<DeliverySlotMergeSuggestion | null>(() => {
|
||||
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 = () => {
|
||||
|
|
|
|||
|
|
@ -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<UseQueryResult<CartData, Error>>;
|
||||
refetch: UseQueryResult<LocalCartItem[], Error>['refetch'];
|
||||
cartItems: CartItem[];
|
||||
totalItems: number;
|
||||
totalPrice: number;
|
||||
|
|
@ -180,69 +180,75 @@ const clearLocalCart = async (cartType: CartType = "regular"): Promise<void> =>
|
|||
export function useGetCart(options: UseGetCartOptions = {}, cartType: CartType = "regular"): UseGetCartReturn {
|
||||
const productsById = useCentralProductStore((state) => state.productsById);
|
||||
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
||||
|
||||
const query: UseQueryResult<CartData, Error> = 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<LocalCartItem[], Error> = useQuery({
|
||||
queryKey: [`local-cart-${cartType}`],
|
||||
queryFn: async (): Promise<CartData> => {
|
||||
const cartItems = await getLocalCart(cartType);
|
||||
|
||||
const productMap: Record<number, Omit<ProductSummary, 'isOutOfStock' | 'isFlashAvailable'>> = 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<LocalCartItem[]> => getLocalCart(cartType),
|
||||
refetchOnWindowFocus: options?.refetchOnWindowFocus ?? true,
|
||||
enabled: (options?.enabled ?? true) && Object.keys(productsById).length > 0,
|
||||
});
|
||||
|
||||
|
||||
const data = useMemo<CartData>(() => {
|
||||
const cartItems = query.data ?? [];
|
||||
|
||||
const productMap: Record<number, Omit<ProductSummary, 'isOutOfStock' | 'isFlashAvailable'>> = 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");
|
||||
|
|
|
|||
|
|
@ -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".
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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(<CartPage />)
|
||||
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(<CartPage />)
|
||||
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 () => {
|
||||
|
|
|
|||
117
change-log.txt
117
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 <slot>' 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-<type>) 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 + <Toast />.
|
||||
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:<userId> -> 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.
|
||||
|
|
|
|||
14
packages/db_helper_sqlite/drizzle/0004_staff_notif_creds.sql
Normal file
14
packages/db_helper_sqlite/drizzle/0004_staff_notif_creds.sql
Normal file
|
|
@ -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`);
|
||||
10
packages/db_helper_sqlite/drizzle/0005_order_timestamps.sql
Normal file
10
packages/db_helper_sqlite/drizzle/0005_order_timestamps.sql
Normal file
|
|
@ -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;
|
||||
|
|
@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -118,6 +118,9 @@ export {
|
|||
checkStaffRoleExists,
|
||||
createStaffUser,
|
||||
getAllRoles,
|
||||
getStaffNotifCred,
|
||||
upsertStaffNotifCred,
|
||||
getAllStaffNotifTokens,
|
||||
} from './src/admin-apis/staff-user'
|
||||
|
||||
export {
|
||||
|
|
|
|||
|
|
@ -396,6 +396,7 @@ export async function getSlotOrders(slotId: string): Promise<AdminGetSlotOrdersR
|
|||
return {
|
||||
id: order.id,
|
||||
readableId: order.id,
|
||||
userId: order.user.id,
|
||||
customerName: order.user.name || order.user.mobile+'',
|
||||
address: `${order.address.addressLine1}${
|
||||
order.address.addressLine2 ? `, ${order.address.addressLine2}` : ''
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { db } from '../db/db_index'
|
||||
import { staffUsers, staffRoles, users, userDetails, orders } from '../db/schema'
|
||||
import { staffUsers, staffRoles, users, userDetails, orders, staffNotifCreds } from '../db/schema'
|
||||
import { eq, or, like, and, lt, desc } from 'drizzle-orm'
|
||||
import type { StaffUser } from '@packages/shared'
|
||||
|
||||
|
|
@ -85,3 +85,31 @@ export async function getAllRoles(): Promise<any[]> {
|
|||
|
||||
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<void> {
|
||||
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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue