diff --git a/apps/admin-ui/app.json b/apps/admin-ui/app.json index 7ec259a..ba0b510 100644 --- a/apps/admin-ui/app.json +++ b/apps/admin-ui/app.json @@ -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 }, diff --git a/apps/admin-ui/app/(drawer)/dashboard/manage-orders/delivery-sequences/index.tsx b/apps/admin-ui/app/(drawer)/dashboard/manage-orders/delivery-sequences/index.tsx index 4cb60af..cec7bf1 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/manage-orders/delivery-sequences/index.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/manage-orders/delivery-sequences/index.tsx @@ -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) { diff --git a/apps/admin-ui/app/(drawer)/dashboard/manage-orders/orders/index.tsx b/apps/admin-ui/app/(drawer)/dashboard/manage-orders/orders/index.tsx index b733918..a286478 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/manage-orders/orders/index.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/manage-orders/orders/index.tsx @@ -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)} diff --git a/apps/admin-ui/app/_layout.tsx b/apps/admin-ui/app/_layout.tsx index 8d23919..f2d651e 100644 --- a/apps/admin-ui/app/_layout.tsx +++ b/apps/admin-ui/app/_layout.tsx @@ -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() { - - - - - + + + + + + + + + diff --git a/apps/admin-ui/components/OrderOptionsMenu.tsx b/apps/admin-ui/components/OrderOptionsMenu.tsx index d771738..ac9b2d6 100644 --- a/apps/admin-ui/components/OrderOptionsMenu.tsx +++ b/apps/admin-ui/components/OrderOptionsMenu.tsx @@ -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({ )} + {order.isFirstOrder && ( + { + handleWhatsApp(); + onClose(); + }} + > + + + + + + Send Welcome Msg + + + First order — welcome the customer on WhatsApp + + + + + )} + { diff --git a/apps/admin-ui/google-services.json b/apps/admin-ui/google-services.json new file mode 100644 index 0000000..7e645d8 --- /dev/null +++ b/apps/admin-ui/google-services.json @@ -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" +} \ No newline at end of file diff --git a/apps/admin-ui/services/notif-service/notif-checker.tsx b/apps/admin-ui/services/notif-service/notif-checker.tsx new file mode 100644 index 0000000..7ee18c7 --- /dev/null +++ b/apps/admin-ui/services/notif-service/notif-checker.tsx @@ -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 ( + setShowPermissionDialog(false)} + > + + + Notification Permission Denied + + + It seems you have denied notification permissions. Please enable + them in your device settings. + + + setShowPermissionDialog(false)} + style={tw`flex-1`} + > + Cancel + + { + Linking.openSettings(); + }} + style={tw`flex-1`} + > + Settings + + + + + ); +} + +export default NotifChecker; diff --git a/apps/admin-ui/services/notif-service/notif-context.tsx b/apps/admin-ui/services/notif-service/notif-context.tsx new file mode 100644 index 0000000..393611f --- /dev/null +++ b/apps/admin-ui/services/notif-service/notif-context.tsx @@ -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 = ({ + children, +}) => { + const [expoPushToken, setExpoPushToken] = useState(null); + const [notification, setNotification] = + useState(null); + const [error, setError] = useState(null); + const [notifPermission, setNotifPermission] = React.useState("pending"); + + const notificationListener = useRef(null); + const responseListener = useRef(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 ( + + {children} + + ); +}; diff --git a/apps/admin-ui/services/notif-service/notif-register.ts b/apps/admin-ui/services/notif-service/notif-register.ts new file mode 100644 index 0000000..f1af410 --- /dev/null +++ b/apps/admin-ui/services/notif-service/notif-register.ts @@ -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"); + } +} diff --git a/apps/admin-ui/tests/components/order-options-menu.test.tsx b/apps/admin-ui/tests/components/order-options-menu.test.tsx index 207b3a6..f6686ae 100644 --- a/apps/admin-ui/tests/components/order-options-menu.test.tsx +++ b/apps/admin-ui/tests/components/order-options-menu.test.tsx @@ -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() diff --git a/apps/backend/creds/demo.txt b/apps/backend/creds/demo.txt index b35fc31..7ed32f4 100644 --- a/apps/backend/creds/demo.txt +++ b/apps/backend/creds/demo.txt @@ -1,48 +1,4 @@ - toggleOutOfStock: protectedProcedure - .input(z.object({ - id: z.number(), - })) - .mutation(async ({ input }): Promise => { - 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 { - 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) -} \ No newline at end of file +I've created the both namespaces. show the option in all places where an order has a kebab menu in admin app. \ No newline at end of file diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index dc24594..8bba1b9 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -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, diff --git a/apps/backend/src/lib/env-exporter.ts b/apps/backend/src/lib/env-exporter.ts index 7aaf201..9c75ec9 100755 --- a/apps/backend/src/lib/env-exporter.ts +++ b/apps/backend/src/lib/env-exporter.ts @@ -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) diff --git a/apps/backend/src/lib/order-tracker.ts b/apps/backend/src/lib/order-tracker.ts new file mode 100644 index 0000000..44109a0 --- /dev/null +++ b/apps/backend/src/lib/order-tracker.ts @@ -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 { + 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 { + 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 { + 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 + } +} diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/order.ts b/apps/backend/src/trpc/apis/admin-apis/apis/order.ts index 343037a..59cca21 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/order.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/order.ts @@ -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() + 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() + 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) } diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts b/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts index 0afe35e..3b80ac4 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts @@ -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`, + }; + }), }); diff --git a/apps/backend/src/trpc/apis/user-apis/apis/order.ts b/apps/backend/src/trpc/apis/user-apis/apis/order.ts index 554bfad..da1c520 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts @@ -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" }; diff --git a/apps/backend/wrangler.dev.toml b/apps/backend/wrangler.dev.toml index 1102f16..b19f484 100644 --- a/apps/backend/wrangler.dev.toml +++ b/apps/backend/wrangler.dev.toml @@ -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" diff --git a/apps/backend/wrangler.prod.toml b/apps/backend/wrangler.prod.toml index 6eec64a..27fac34 100644 --- a/apps/backend/wrangler.prod.toml +++ b/apps/backend/wrangler.prod.toml @@ -101,4 +101,8 @@ upload_source_maps = true [[kv_namespaces]] binding="freshyo_otp" -id="aba74be264df45c0b17757fe01c136e5" \ No newline at end of file +id="aba74be264df45c0b17757fe01c136e5" + +[[kv_namespaces]] +binding="freshyo_order_tracker" +id="ec20eab6e50648b8b45e8e269f9aa0c1" \ No newline at end of file diff --git a/apps/superadmin-ui/src/components/AppShell.tsx b/apps/superadmin-ui/src/components/AppShell.tsx new file mode 100644 index 0000000..aa221fe --- /dev/null +++ b/apps/superadmin-ui/src/components/AppShell.tsx @@ -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 ( +
+
+
+ + + 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. + + +
+
+ setTitle(e.target.value)} + /> + +
+ Message +