diff --git a/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx b/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx index 4ac5efe..6a14429 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx @@ -29,6 +29,7 @@ const CONST_LABELS: Record = { supportMobile: 'Support Mobile', supportEmail: 'Support Email', internalAppVersion: 'Internal App Version', + welcomeMessage: 'Welcome Message', }; const CONST_VISIBILITY: Record = { @@ -52,6 +53,7 @@ const CONST_VISIBILITY: Record = { supportMobile: true, supportEmail: true, internalAppVersion: false, + welcomeMessage: true, tester: false, }; @@ -159,6 +161,23 @@ const ConstantInput: React.FC = ({ constantKey, value, setFi ); } + // Welcome message — multiline text area + if (constantKey === 'welcomeMessage') { + return ( + { + setFieldValue(fieldName, value) + }} + placeholder="Enter welcome message" + multiline + numberOfLines={4} + style={tw`min-h-24`} + /> + ); + } + // Default to string return ( c.key === 'welcomeMessage')?.value; const handleAttachLocation = async () => { try { @@ -95,6 +97,17 @@ export function OrderOptionsMenu({ } }; + const handleWelcomeWhatsApp = () => { + const phone = extractPhone(order.address); + if (!phone) { + Alert.alert('No phone number found'); + return; + } + const message = welcomeMessage ? String(welcomeMessage) : ''; + const text = message ? `&text=${encodeURIComponent(message)}` : ''; + Linking.openURL(`whatsapp://send?phone=+91${phone}${text}`); + }; + const handleDial = () => { const phone = extractPhone(order.address); if (phone) { @@ -298,7 +311,7 @@ export function OrderOptionsMenu({ 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(); + handleWelcomeWhatsApp(); onClose(); }} > diff --git a/apps/admin-ui/services/notif-service/notif-context.tsx b/apps/admin-ui/services/notif-service/notif-context.tsx index 393611f..2643c6f 100644 --- a/apps/admin-ui/services/notif-service/notif-context.tsx +++ b/apps/admin-ui/services/notif-service/notif-context.tsx @@ -76,7 +76,7 @@ export const NotificationProvider: React.FC = ({ Notifications.addNotificationResponseReceivedListener((response) => { const data = response.notification.request.content.data; if (data && data.orderId) { - router.push("/(drawer)/dashboard/manage-orders/orders" as any); + router.push(`/(drawer)/dashboard/manage-orders/order-details/${data.orderId}` as any); } else { router.push("/(drawer)/dashboard" as any); } 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 f6686ae..35cd990 100644 --- a/apps/admin-ui/tests/components/order-options-menu.test.tsx +++ b/apps/admin-ui/tests/components/order-options-menu.test.tsx @@ -12,7 +12,7 @@ import * as Location from 'expo-location' import { OrderOptionsMenu } from '@/components/OrderOptionsMenu' import { setupApiMocks, resetStorage } from '../mocks/api' import { resetStaffAuthMock } from '../mocks/staff-auth' -import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures' +import { expectProcedureCalled, lastProcedureInput, procCount } from '../mocks/procedures' import { renderWithProviders } from '../helpers/render' type OrderProp = React.ComponentProps['order'] @@ -179,9 +179,8 @@ describe('OrderOptionsMenu', () => { 'Location permission is required to attach coordinates.' ) ) - expect(fetchMock).not.toHaveBeenCalled() + expect(procCount(fetchMock, 'admin.order.updateAddressCoords')).toBe(0) }) - it('opens the coordinates in Google Maps only when present', () => { const props = renderMenu({ latitude: 16.75, longitude: 78.0 }) @@ -223,6 +222,24 @@ describe('OrderOptionsMenu', () => { expect(screen.queryByText('Send Welcome Msg')).toBeNull() }) + it('prefills the welcome message when opening the first-order WhatsApp', async () => { + setupApiMocks({ + procedures: { + 'admin.order.updateAddressCoords': { success: true }, + 'admin.const.getConstants': [{ key: 'welcomeMessage', value: 'Hello & welcome!' }], + }, + }) + renderMenu({ isFirstOrder: true }) + + // The constant loads async; retry until the handler sees it. + await waitFor(() => { + fireEvent.press(screen.getByText('Send Welcome Msg')) + expect(Linking.openURL).toHaveBeenCalledWith( + 'whatsapp://send?phone=+919876543210&text=Hello%20%26%20welcome!' + ) + }) + }) + it('dials the phone parsed from the address', () => { renderMenu() diff --git a/apps/admin-web/src/routes/dashboard.customize-app.tsx b/apps/admin-web/src/routes/dashboard.customize-app.tsx index ef9a36b..61a9164 100644 --- a/apps/admin-web/src/routes/dashboard.customize-app.tsx +++ b/apps/admin-web/src/routes/dashboard.customize-app.tsx @@ -31,6 +31,7 @@ const CONST_LABELS: Record = { isFlashDeliveryEnabled: 'Enable Flash Delivery', supportMobile: 'Support Mobile', supportEmail: 'Support Email', + welcomeMessage: 'Welcome Message', } const CONST_VISIBILITY: Record = { @@ -53,6 +54,7 @@ const CONST_VISIBILITY: Record = { isFlashDeliveryEnabled: true, supportMobile: true, supportEmail: true, + welcomeMessage: true, tester: false, } @@ -155,6 +157,22 @@ const ConstantInput: React.FC = ({ constantKey, value, setFi ) } + // Welcome message — multiline text area + if (constantKey === 'welcomeMessage') { + return ( + { + setFieldValue(fieldName, e.target.value) + }} + placeholder="Enter welcome message" + multiline + numberOfLines={4} + /> + ) + } + return ( = [ + { label: 'Mahabubnagar town centre', lat: 16.747227, lng: 78.009737 }, + { label: 'Gol masjid (habeeb nagar)', lat: 16.7329, lng: 77.9906 }, + { label: 'Bk reddy colony', lat: 16.7404, lng: 78.0061 }, + { label: 'New Collectorate', lat: 16.720810, lng: 78.020549 }, + { label: 'Far away (Hyderabad)', lat: 17.385, lng: 78.4867 }, + { label: 'Yenugonda beyond track', lat:16.757162, lng:78.027120 }, + { label: 'Appanapally', lat:16.760978, lng:78.055362}, + { label: 'SVS Hospital', lat: 16.757856, lng: 78.043416} +] + +console.log('Mbnr-2 polygon check\n') + +for (const { label, lat, lng } of samples) { + const inside = await isInMbnrPolygon({ lat, lng }) + console.log( + `${inside ? '✓ inside ' : '✗ outside'} (${lat}, ${lng}) ${label}` + ) +} diff --git a/apps/backend/scripts/check-polygon.ts b/apps/backend/scripts/check-polygon.ts new file mode 100644 index 0000000..901011b --- /dev/null +++ b/apps/backend/scripts/check-polygon.ts @@ -0,0 +1,28 @@ +/** + * Demo runner for isInMbnrPolygon. + * + * bun run scripts/check-polygon.ts + * + * Prints whether each sample coordinate is inside the Mbnr-1 delivery polygon. + */ +import { isInMbnrPolygon } from '../src/map-assets/mbnr-1' + +const samples: Array<{ label: string; lat: number; lng: number }> = [ + { label: 'Mahabubnagar town centre', lat: 16.747227, lng: 78.009737 }, + { label: 'Gol masjid (habeeb nagar)', lat: 16.7329, lng: 77.9906 }, + { label: 'Bk reddy colony', lat: 16.7404, lng: 78.0061 }, + { label: 'New Collectorate', lat: 16.720810, lng: 78.020549 }, + { label: 'Far away (Hyderabad)', lat: 17.385, lng: 78.4867 }, + { label: 'Yenugonda beyond track', lat:16.757162, lng:78.027120 }, + { label: 'Appanapally', lat:16.760978, lng:78.055362}, + { label: 'SVS Hospital', lat: 16.757856, lng: 78.043416} +] + +console.log('Mbnr-1 polygon check\n') + +for (const { label, lat, lng } of samples) { + const inside = await isInMbnrPolygon({ lat, lng }) + console.log( + `${inside ? '✓ inside ' : '✗ outside'} (${lat}, ${lng}) ${label}` + ) +} diff --git a/apps/backend/src/lib/admin-notif.ts b/apps/backend/src/lib/admin-notif.ts new file mode 100644 index 0000000..e24a22e --- /dev/null +++ b/apps/backend/src/lib/admin-notif.ts @@ -0,0 +1,48 @@ +import { 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 + +/** + * Queues a push notification to every admin/staff device. `orderId`, when set, + * is delivered in the push `data` so the app can deep-link to that order. + * Returns the number of tokens the notification was queued for. + */ +export async function notifyAllAdmins(payload: { + title: string + body: string + imageUrl?: string | null + orderId?: number | null +}): Promise { + 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: payload.title, + body: payload.body, + imageUrl: payload.imageUrl ?? null, + orderId: payload.orderId ?? 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 queuedCount +} diff --git a/apps/backend/src/lib/cloud_cache.ts b/apps/backend/src/lib/cloud_cache.ts index 0228156..c6400ba 100644 --- a/apps/backend/src/lib/cloud_cache.ts +++ b/apps/backend/src/lib/cloud_cache.ts @@ -10,6 +10,7 @@ import { imageUploadS3 } from '@/src/lib/s3-client' import { getApiCacheKey, getCloudflareApiToken, getCloudflareZoneId, getAssetsDomain } from '@/src/lib/env-exporter' import { CACHE_FILENAMES } from '@packages/shared' import { retryWithExponentialBackoff } from '@/src/lib/retry' +import { refreshGenKv } from '@/src/lib/gen-store' const buildCachePath = (path: string, version: number) => `v-${version}/${path}` @@ -58,8 +59,8 @@ export async function createAllCacheFiles(): Promise createProductsFileInternal(cacheVersion), createEssentialConstsFileInternal(cacheVersion), createStoresFileInternal(cacheVersion), - createSlotsCacheFile(), - createAvailabilityCacheFile(), + createSlotsCacheFile(false), + createAvailabilityCacheFile(false), createBannersFileInternal(cacheVersion), createAllStoresFilesInternal(cacheVersion), ]) @@ -87,6 +88,9 @@ export async function createAllCacheFiles(): Promise console.log('All cache files created successfully') + // Single awaited mirror refresh for the whole cycle (all counters bumped above). + await refreshGenKv() + return { cacheVersion, products: productsKey, @@ -115,7 +119,7 @@ async function createProductsFileInternal(version: number): Promise { } -export async function createAvailabilityCacheFile(): Promise { +export async function createAvailabilityCacheFile(refresh = true): Promise { const version = await incrementAvailabilityVersionNum() const availabilityData = await scaffoldAvailability() const jsonContent = JSON.stringify(availabilityData, null, 2) @@ -129,6 +133,8 @@ export async function createAvailabilityCacheFile(): Promise { filePath ) + if (refresh) await refreshGenKv() + return version } @@ -154,7 +160,7 @@ async function createStoresFileInternal(version: number): Promise { ) } -export async function createSlotsCacheFile(): Promise { +export async function createSlotsCacheFile(refresh = true): Promise { const version = await incrementSlotsVersionNum() const slotsData = await scaffoldSlotsWithProducts() const jsonContent = JSON.stringify(slotsData, null, 2) @@ -168,6 +174,8 @@ export async function createSlotsCacheFile(): Promise { filePath ) + if (refresh) await refreshGenKv() + return version } diff --git a/apps/backend/src/lib/const-keys.ts b/apps/backend/src/lib/const-keys.ts index c9280e8..22ae47d 100644 --- a/apps/backend/src/lib/const-keys.ts +++ b/apps/backend/src/lib/const-keys.ts @@ -24,6 +24,7 @@ export const CONST_KEYS = { supportMobile: 'supportMobile', supportEmail: 'supportEmail', internalAppVersion: 'internalAppVersion', + welcomeMessage: 'welcomeMessage', } as const; export const CONST_LABELS: Record = { @@ -50,6 +51,7 @@ export const CONST_LABELS: Record = { supportMobile: 'Support Mobile', supportEmail: 'Support Email', internalAppVersion: 'Internal App Version', + welcomeMessage: 'Welcome Message', }; export type ConstKey = (typeof CONST_KEYS)[keyof typeof CONST_KEYS]; @@ -80,6 +82,7 @@ export const CONST_TYPES: Record = { supportMobile: 'string', supportEmail: 'string', internalAppVersion: 'number', + welcomeMessage: 'string', }; export const CONST_VISIBILITY: Record = { @@ -106,4 +109,5 @@ export const CONST_VISIBILITY: Record = { supportMobile: true, supportEmail: true, internalAppVersion: true, + welcomeMessage: true, }; diff --git a/apps/backend/src/lib/env-exporter.ts b/apps/backend/src/lib/env-exporter.ts index 9c75ec9..bc8e852 100755 --- a/apps/backend/src/lib/env-exporter.ts +++ b/apps/backend/src/lib/env-exporter.ts @@ -106,6 +106,11 @@ export const getOrderTrackerKvNamespace = () => { return (env.freshyo_order_tracker || env.freshyo_order_tracker_dev) as KVNamespace | undefined } +export const getGenKvNamespace = () => { + const env = getRuntimeEnv() + return (env.freshyo_gen || env.freshyo_gen_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/flash-delivery-cron.ts b/apps/backend/src/lib/flash-delivery-cron.ts index 9d130d4..4079286 100644 --- a/apps/backend/src/lib/flash-delivery-cron.ts +++ b/apps/backend/src/lib/flash-delivery-cron.ts @@ -1,6 +1,7 @@ import { toggleKeyVal } from '@/src/dbService' import { CONST_KEYS } from '@/src/lib/const-keys' import { computeConstants } from '@/src/lib/const-store' +import { refreshGenKv } from '@/src/lib/gen-store' import { ensureWorkerInit } from '@/src/lib/worker-init' @@ -27,4 +28,5 @@ export async function runFlashDeliveryToggleCron(params: { await toggleKeyVal(CONST_KEYS.isFlashDeliveryEnabled, enabled) await computeConstants() + await refreshGenKv() } diff --git a/apps/backend/src/lib/gen-store.ts b/apps/backend/src/lib/gen-store.ts new file mode 100644 index 0000000..339847a --- /dev/null +++ b/apps/backend/src/lib/gen-store.ts @@ -0,0 +1,59 @@ +import { getGenKvNamespace } from '@/src/lib/env-exporter' +import type { scaffoldEssentialConsts } from '@/src/trpc/apis/common-apis/common-trpc-index' + +export const GEN_KV_KEY = 'essential_consts' + +export type EssentialConstsPayload = Awaited> + +// Dynamic import: gen-store must not statically import common-trpc-index, because +// that module imports readEssentialConstsFromKv from here (cycle). +async function buildEssentialConsts(): Promise { + const { scaffoldEssentialConsts } = await import( + '../trpc/apis/common-apis/common-trpc-index' + ) + return scaffoldEssentialConsts() +} + +/** + * Rebuilds the full essentialConsts response (constants + counters + env-derived + * fields) from D1/env and mirrors it to KV. Call after a successful D1 write. + * No-op when the KV binding is absent (local/tests). + */ +export async function refreshGenKv(): Promise { + try { + const kv = getGenKvNamespace() + if (!kv) return + + const payload = await buildEssentialConsts() + await kv.put(GEN_KV_KEY, JSON.stringify(payload)) + } catch (error) { + console.error('refreshGenKv failed:', error) + } +} + +/** + * Client read path: serve the precomputed response from KV. On a miss, build it + * from D1/env, backfill KV, and return. + */ +export async function readEssentialConstsFromKv(): Promise { + try { + const kv = getGenKvNamespace() + if (kv) { + const cached = (await kv.get(GEN_KV_KEY, 'json')) as EssentialConstsPayload | null + if (cached) return cached + } + } catch (error) { + console.error('readEssentialConstsFromKv failed:', error) + } + + const payload = await buildEssentialConsts() + + try { + const kv = getGenKvNamespace() + if (kv) await kv.put(GEN_KV_KEY, JSON.stringify(payload)) + } catch (error) { + console.error('backfill essential_consts failed:', error) + } + + return payload +} diff --git a/apps/backend/src/lib/notif-job.ts b/apps/backend/src/lib/notif-job.ts index b6bd106..4bbadfa 100644 --- a/apps/backend/src/lib/notif-job.ts +++ b/apps/backend/src/lib/notif-job.ts @@ -42,8 +42,9 @@ export async function sendAdminNotification(data: { title: string; body: string; imageUrl: string | null; + orderId?: number | null; }) { - const { tokens, title, body, imageUrl } = data; + const { tokens, title, body, imageUrl, orderId } = data; const { Expo } = await import('expo-server-sdk') // Validate Expo push tokens (drop invalid ones) @@ -69,7 +70,10 @@ export async function sendAdminNotification(data: { sound: 'default' as const, title, body, - data: { imageUrl }, + data: { + imageUrl, + ...(orderId != null ? { orderId } : {}), + }, ...(signedImageUrl ? { attachments: [ { diff --git a/apps/backend/src/lib/post-order-handler.ts b/apps/backend/src/lib/post-order-handler.ts index b06e504..439818a 100644 --- a/apps/backend/src/lib/post-order-handler.ts +++ b/apps/backend/src/lib/post-order-handler.ts @@ -6,6 +6,7 @@ import { } from '@/src/dbService' import { sendTelegramMessage } from '@/src/lib/telegram-service' import { queueDataPusher } from '@/src/lib/queue-data-pusher' +import { notifyAllAdmins } from '@/src/lib/admin-notif' import { ensureWorkerInit } from './worker-init'; import { getAppUrl } from '@/src/lib/env-exporter' @@ -110,6 +111,17 @@ ${buildTelegramLinks(orderData.id, orderData.userId)} export const handleOrderPlaced = async (orderIds: number[], rawMessage?: string): Promise => { try { const ordersData = await getOrdersByIdsWithFullData(orderIds) + + // Push a notification to every admin device; tapping it opens that order's + // details page (data.orderId is the numeric order id). + for (const order of ordersData) { + await notifyAllAdmins({ + title: '🛒 New Order Placed', + body: `${order.address?.name || 'A customer'} • ₹${order.totalAmount}`, + orderId: order.id, + }) + } + const telegramMessage = formatOrderMessageWithFullData(ordersData) await sendTelegramMessage(telegramMessage) } catch (error) { diff --git a/apps/backend/src/lib/queue-consumer.ts b/apps/backend/src/lib/queue-consumer.ts index d1607ba..747a30e 100644 --- a/apps/backend/src/lib/queue-consumer.ts +++ b/apps/backend/src/lib/queue-consumer.ts @@ -20,6 +20,7 @@ export const handleNotifQueue =async (batch: any) => { title: body.jobData.title, body: body.jobData.body, imageUrl: body.jobData.imageUrl ?? null, + orderId: body.jobData.orderId ?? null, }) continue } diff --git a/apps/backend/src/lib/seed.ts b/apps/backend/src/lib/seed.ts index aabba5d..71426cc 100644 --- a/apps/backend/src/lib/seed.ts +++ b/apps/backend/src/lib/seed.ts @@ -12,6 +12,7 @@ import { } from '@/src/dbService' import { getMinOrderValue, getDeliveryCharge } from '@/src/lib/env-exporter' import { CONST_KEYS } from '@/src/lib/const-keys' +import { refreshGenKv } from '@/src/lib/gen-store' export async function seed() { console.log("Seeding database..."); @@ -63,8 +64,12 @@ export async function seed() { { key: CONST_KEYS.isFlashDeliveryEnabled, value: false }, { key: CONST_KEYS.supportMobile, value: '8688182552' }, { key: CONST_KEYS.supportEmail, value: 'qushammohd@gmail.com' }, + { key: CONST_KEYS.welcomeMessage, value: "Hi! Thank you for your first order at Freshyo. We're glad to have you." }, ]; await seedKeyValStore(constantsToSeed); + // Mirror the seeded constants into KV for client reads. + await refreshGenKv(); + console.log("Seeding completed."); } diff --git a/apps/backend/src/map-assets/Mbnr-1.geojson b/apps/backend/src/map-assets/Mbnr-1.geojson new file mode 100644 index 0000000..98d2100 --- /dev/null +++ b/apps/backend/src/map-assets/Mbnr-1.geojson @@ -0,0 +1,114 @@ +{ + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": { + "name": "Polygon 4" + }, + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [ + 77.9802307, + 16.7224827 + ], + [ + 77.9832452, + 16.7186281 + ], + [ + 77.9885003, + 16.7191643 + ], + [ + 78.0027771, + 16.7184524 + ], + [ + 78.0167635, + 16.717821 + ], + [ + 78.0176657, + 16.7225884 + ], + [ + 78.0245685, + 16.7301059 + ], + [ + 78.0346065, + 16.7366045 + ], + [ + 78.0483126, + 16.7469324 + ], + [ + 78.0558892, + 16.7506815 + ], + [ + 78.0533183, + 16.7547082 + ], + [ + 78.0497798, + 16.7596596 + ], + [ + 78.0456892, + 16.7640471 + ], + [ + 78.0383339, + 16.7641426 + ], + [ + 78.0343234, + 16.758687 + ], + [ + 78.021375, + 16.7570244 + ], + [ + 78.0163704, + 16.758279 + ], + [ + 78.0128516, + 16.7590231 + ], + [ + 78.0120219, + 16.7648881 + ], + [ + 78.0095524, + 16.7664414 + ], + [ + 77.99363, + 16.7660548 + ], + [ + 77.9720422, + 16.7596124 + ], + [ + 77.9679337, + 16.7449906 + ], + [ + 77.9802307, + 16.7224827 + ] + ] + ] + } + } + ] +} \ No newline at end of file diff --git a/apps/backend/src/map-assets/Mbnr-2.geojson b/apps/backend/src/map-assets/Mbnr-2.geojson new file mode 100644 index 0000000..b04e064 --- /dev/null +++ b/apps/backend/src/map-assets/Mbnr-2.geojson @@ -0,0 +1,74 @@ +{ + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": { + "name": "Mbnr-2" + }, + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [ + 77.9773739, + 16.7127921 + ], + [ + 77.9950359, + 16.7080928 + ], + [ + 78.0187929, + 16.70999 + ], + [ + 78.0289444, + 16.7211582 + ], + [ + 78.0570875, + 16.7502883 + ], + [ + 78.0662922, + 16.7519867 + ], + [ + 78.0652719, + 16.7684088 + ], + [ + 78.0204341, + 16.7689639 + ], + [ + 78.0023161, + 16.770186 + ], + [ + 77.9984809, + 16.7850848 + ], + [ + 77.983305, + 16.782843 + ], + [ + 77.971574, + 16.7646028 + ], + [ + 77.9686551, + 16.7454905 + ], + [ + 77.9773739, + 16.7127921 + ] + ] + ] + } + } + ] +} \ No newline at end of file diff --git a/apps/backend/src/map-assets/mbnr-1.ts b/apps/backend/src/map-assets/mbnr-1.ts new file mode 100644 index 0000000..ebd9a0a --- /dev/null +++ b/apps/backend/src/map-assets/mbnr-1.ts @@ -0,0 +1,82 @@ +// Inlined from ./Mbnr-1.geojson (hand-converted: .geojson cannot be imported +// directly — there is no bundler loader and resolveJsonModule only covers .json). +export const mbnr1GeoJson = { + type: 'FeatureCollection', + features: [ + { + type: 'Feature', + properties: { + name: 'Polygon 4', + }, + geometry: { + type: 'Polygon', + coordinates: [ + [ + [77.9802307, 16.7224827], + [77.9832452, 16.7186281], + [77.9885003, 16.7191643], + [78.0027771, 16.7184524], + [78.0167635, 16.717821], + [78.0176657, 16.7225884], + [78.0245685, 16.7301059], + [78.0346065, 16.7366045], + [78.0483126, 16.7469324], + [78.0558892, 16.7506815], + [78.0533183, 16.7547082], + [78.0497798, 16.7596596], + [78.0456892, 16.7640471], + [78.0383339, 16.7641426], + [78.0343234, 16.758687], + [78.021375, 16.7570244], + [78.0163704, 16.758279], + [78.0128516, 16.7590231], + [78.0120219, 16.7648881], + [78.0095524, 16.7664414], + [77.99363, 16.7660548], + [77.9720422, 16.7596124], + [77.9679337, 16.7449906], + [77.9802307, 16.7224827], + ], + ], + }, + }, + ], +} as const + +const mbnr1Coordinates = mbnr1GeoJson.features[0].geometry + .coordinates as unknown as number[][][] + +// Turf is imported lazily so it never runs during a Worker cold start — only the +// first time isInMbnrPolygon is actually called. Cached after first use. +let turfPolygonPromise: Promise< + (coords: { lat: number; lng: number }) => boolean +> | null = null + +async function getPointInPolygonChecker(): Promise< + (coords: { lat: number; lng: number }) => boolean +> { + if (!turfPolygonPromise) { + turfPolygonPromise = (async () => { + const [{ booleanPointInPolygon }, turfHelpers] = await Promise.all([ + import('@turf/boolean-point-in-polygon'), + import('@turf/helpers'), + ]) + const polygon = turfHelpers.polygon(mbnr1Coordinates) + return (coords) => + booleanPointInPolygon(turfHelpers.point([coords.lng, coords.lat]), polygon) + })() + } + return turfPolygonPromise +} + +/** + * Returns true when the given coordinates fall inside the Mbnr-1 delivery + * polygon. GeoJSON coordinates are [longitude, latitude]. + */ +export async function isInMbnrPolygon(coords: { + lat: number + lng: number +}): Promise { + const check = await getPointInPolygonChecker() + return check(coords) +} diff --git a/apps/backend/src/map-assets/mbnr-2.ts b/apps/backend/src/map-assets/mbnr-2.ts new file mode 100644 index 0000000..c29161a --- /dev/null +++ b/apps/backend/src/map-assets/mbnr-2.ts @@ -0,0 +1,72 @@ +// Inlined from ./Mbnr-2.geojson (hand-converted: .geojson cannot be imported +// directly — there is no bundler loader and resolveJsonModule only covers .json). +export const mbnr2GeoJson = { + type: 'FeatureCollection', + features: [ + { + type: 'Feature', + properties: { + name: 'Mbnr-2', + }, + geometry: { + type: 'Polygon', + coordinates: [ + [ + [77.9773739, 16.7127921], + [77.9950359, 16.7080928], + [78.0187929, 16.70999], + [78.0289444, 16.7211582], + [78.0570875, 16.7502883], + [78.0662922, 16.7519867], + [78.0652719, 16.7684088], + [78.0204341, 16.7689639], + [78.0023161, 16.770186], + [77.9984809, 16.7850848], + [77.983305, 16.782843], + [77.971574, 16.7646028], + [77.9686551, 16.7454905], + [77.9773739, 16.7127921], + ], + ], + }, + }, + ], +} as const + +const mbnr2Coordinates = mbnr2GeoJson.features[0].geometry + .coordinates as unknown as number[][][] + +// Turf is imported lazily so it never runs during a Worker cold start — only the +// first time isInMbnrPolygon is actually called. Cached after first use. +let turfPolygonPromise: Promise< + (coords: { lat: number; lng: number }) => boolean +> | null = null + +async function getPointInPolygonChecker(): Promise< + (coords: { lat: number; lng: number }) => boolean +> { + if (!turfPolygonPromise) { + turfPolygonPromise = (async () => { + const [{ booleanPointInPolygon }, turfHelpers] = await Promise.all([ + import('@turf/boolean-point-in-polygon'), + import('@turf/helpers'), + ]) + const polygon = turfHelpers.polygon(mbnr2Coordinates) + return (coords) => + booleanPointInPolygon(turfHelpers.point([coords.lng, coords.lat]), polygon) + })() + } + return turfPolygonPromise +} + +/** + * Returns true when the given coordinates fall inside the Mbnr-2 delivery + * polygon. GeoJSON coordinates are [longitude, latitude]. + */ +export async function isInMbnrPolygon(coords: { + lat: number + lng: number +}): Promise { + const check = await getPointInPolygonChecker() + return check(coords) +} diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/const.ts b/apps/backend/src/trpc/apis/admin-apis/apis/const.ts index 6435c46..530de02 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/const.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/const.ts @@ -1,6 +1,7 @@ import { router, protectedProcedure } from '@/src/trpc/trpc-index' import { z } from 'zod'; import { computeConstants } from '@/src/lib/const-store' +import { refreshGenKv } from '@/src/lib/gen-store' import { CONST_KEYS } from '@/src/lib/const-keys' import { scheduleStoreInitialization } from '@/src/stores/store-initializer' import { getAllConstants as getAllConstantsFromDb, upsertConstants as upsertConstantsInDb } from '@/src/dbService' @@ -47,6 +48,9 @@ export const constRouter = router({ // Refresh all constants in Redis after database update await computeConstants(); + // Mirror the full essentialConsts response into KV for client reads. + await refreshGenKv(); + // Constants like tagsOrder are baked into the versioned cache files. // Regenerate the cache (bumps cacheVersion) so the user app fetches the // new data (e.g., the new tab order on the home page). 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 3b80ac4..9f1ea9b 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 @@ -12,12 +12,8 @@ import { 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 +import { notifyAllAdmins } from '@/src/lib/admin-notif' export const staffUserRouter = router({ login: publicProcedure @@ -145,33 +141,11 @@ export const staffUserRouter = router({ .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); - } - } + const queuedCount = await notifyAllAdmins({ + title, + body: text, + imageUrl: imageUrl || null, + }); return { success: true, diff --git a/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts b/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts index 4ceb6c5..cbdefa5 100644 --- a/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts +++ b/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts @@ -15,6 +15,7 @@ import { mbnrGeoJson } from '@/src/lib/mbnr-geojson' import { generateUploadUrl } from '@/src/lib/s3-client' import { ApiError } from '@/src/lib/api-error' import { getAllConstValues } from '@/src/lib/const-store' +import { readEssentialConstsFromKv } from '@/src/lib/gen-store' import { CONST_KEYS } from '@/src/lib/const-keys' import { getAssetsDomain, getApiCacheKey } from '@/src/lib/env-exporter' @@ -146,7 +147,7 @@ export const commonApiRouter = router({

With love, from Freshyo

` - const response = await scaffoldEssentialConsts(); + const response = await readEssentialConstsFromKv(); const shouldShowNotice = host.includes('raw') || host.includes('mf') return { diff --git a/apps/backend/wrangler.dev.toml b/apps/backend/wrangler.dev.toml index b19f484..e9276ce 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] @@ -113,3 +113,7 @@ id="6f6dbada52584d7fb744c9c85bd0c1e5" [[kv_namespaces]] binding="freshyo_order_tracker_dev" id="e9d770b725d748e489288a20cf786846" + +[[kv_namespaces]] +binding="freshyo_gen_dev" +id="8213fdabe70d4374a209d886fe74da67" diff --git a/apps/backend/wrangler.prod.toml b/apps/backend/wrangler.prod.toml index 27fac34..66576ca 100644 --- a/apps/backend/wrangler.prod.toml +++ b/apps/backend/wrangler.prod.toml @@ -105,4 +105,8 @@ id="aba74be264df45c0b17757fe01c136e5" [[kv_namespaces]] binding="freshyo_order_tracker" -id="ec20eab6e50648b8b45e8e269f9aa0c1" \ No newline at end of file +id="ec20eab6e50648b8b45e8e269f9aa0c1" + +[[kv_namespaces]] +binding="freshyo_gen" +id="037cdf0159d8457ea22eeb9a0b4e53fd" \ No newline at end of file diff --git a/change-log.txt b/change-log.txt index ae54a61..7a8aad7 100644 --- a/change-log.txt +++ b/change-log.txt @@ -3838,3 +3838,88 @@ admin-ui: 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. + +[2026-10-02 14:50:08] backend: mirror essentialConsts response into freshyo_gen KV; client reads from KV. + +D1 stays source of truth (writes + all internal reads). After a successful D1 +write, the full essentialConsts response (constants + counters + env vars) is +mirrored to KV { + - wrangler.dev.toml / wrangler.prod.toml: add kv_namespaces freshyo_gen_dev / + freshyo_gen. + - src/lib/env-exporter.ts: getGenKvNamespace(). + - src/lib/gen-store.ts (new): GEN_KV_KEY='essential_consts'; refreshGenKv() + builds scaffoldEssentialConsts() and awaits kv.put; readEssentialConstsFromKv() + reads KV with D1 backfill; no-op/fallback when unbound. Dynamic import of the + builder avoids an import cycle. + - trpc/apis/common-apis/common-trpc-index.ts: common.essentialConsts procedure + now serves readEssentialConstsFromKv(); webview host override unchanged. + - awaited refreshGenKv() after D1 writes: admin const updateConstants; + cloud_cache createAllCacheFiles + standalone createAvailability/ SlotsCacheFile; + flash-delivery-cron toggle; backend seed. +Internal reads and the cached essential-consts file builder stay D1-backed. + +[2026-10-02 15:54:26] admin order-placed push: notify all admins, tap opens the order details. + +backend: + - lib/notif-job.ts sendAdminNotification: accept orderId, include it in the Expo + push `data` so the client can route. + - lib/admin-notif.ts (new): notifyAllAdmins({title, body, imageUrl?, orderId?}) -> + batches all staff tokens onto the 'send-admin-notification' queue. + - trpc admin staff-user sendAdminNotification: reuse notifyAllAdmins. + - lib/queue-consumer.ts: forward jobData.orderId. + - lib/post-order-handler.ts handleOrderPlaced: notifyAllAdmins per placed order + (data.orderId = numeric order id). +admin-ui: + - services/notif-service/notif-context.tsx: tap with data.orderId navigates to + /(drawer)/dashboard/manage-orders/order-details/. + +[2026-10-02 18:40:39] backend/scripts: add backfill-first-orders.ts (seed order-tracker KV from orders dump). + +One-off backfill of the freshyo_order_tracker KV: for every user, the earliest +NON-cancelled order id is written as key 'first_order:' -> '' +(matches trackIfFirstOrder). Reads the SQLite built from dumps/latest.sql via +bun:sqlite; emits a wrangler kv bulk put JSON and, with --run, executes it. +Dry-run by default. Not executed by the agent. + +[2026-10-02 18:42:23] backend/scripts: replace backfill-first-orders.ts with a wrangler-only shell script. + +Per request: the DB is built and the first-order values are computed by the agent; +the committed artifact is a shell script containing only `wrangler kv key put` +commands (dev namespace). Removed the previous Bun script. + +[2026-10-02 22:16:19] welcomeMessage constant: admin-only config, prefilled into first-order WhatsApp. + +- const-keys (apps/backend + packages/db_helper_sqlite): add welcomeMessage + ('Welcome Message', string, admin-visible) + CONST_DEFAULTS default text. +- Excluded from scaffoldEssentialConsts -> never sent to the user app / KV mirror. +- admin-ui + admin-web customize forms: field shown with a multiline textarea. +- admin-ui OrderOptionsMenu: 'Send Welcome Msg' opens WhatsApp with + &text=; regular 'Message On WhatsApp' unchanged. +- seeds: welcomeMessage default added. + +[2026-10-03 00:23:54] backend: add src/map-assets/mbnr-1.ts (isInMbnrPolygon helper). + +- New TS module inlining the Mbnr-1.geojson polygon (hand-converted; .geojson is + not importable). Exports mbnr1GeoJson + isInMbnrPolygon({ lat, lng }): boolean + using @turf/boolean-point-in-polygon. +- Additive only: checkLocationInPolygon still uses the old mbnr-geojson.ts and is + unchanged; old file kept; helper not wired anywhere. + +[2026-10-03 00:25:55] backend: add scripts/check-polygon.ts demo runner for isInMbnrPolygon. + +Runnable with `bun run scripts/check-polygon.ts`; calls the helper with a few +demo coordinates (inside + outside the Mbnr-1 polygon) and prints each result. + +[2026-10-03 00:27:24] backend: lazy-load turf in mbnr-1.ts (no turf import at cold start). + +Removed the top-level static imports of @turf/boolean-point-in-polygon and +@turf/helpers. isInMbnrPolygon is now async and dynamic-import()s turf on first +call, caching the module + the built turf polygon. The inlined GeoJSON stays a +plain constant, so nothing turf-related loads until the function is used. +Demo script updated to await the async helper. + +[2026-10-03 00:46:07] backend: add src/map-assets/mbnr-2.ts + scripts/check-polygon-2.ts. + +- mbnr-2.ts: Mbnr-2.geojson polygon inlined; exports mbnr2GeoJson and + isInMbnrPolygon({lat,lng}) with the same lazy dynamic-import of turf. +- scripts/check-polygon-2.ts: runs isInMbnrPolygon for the same demo coords. diff --git a/packages/db_helper_sqlite/src/db/seed.sql b/packages/db_helper_sqlite/src/db/seed.sql index 20b5057..6628a27 100644 --- a/packages/db_helper_sqlite/src/db/seed.sql +++ b/packages/db_helper_sqlite/src/db/seed.sql @@ -49,5 +49,6 @@ INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('appStoreUrl', 'https:/ INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('isFlashDeliveryEnabled', 'false'); INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('supportMobile', '8688182552'); INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('supportEmail', 'qushammohd@gmail.com'); +INSERT OR IGNORE INTO key_val_store (key, value) VALUES ('welcomeMessage', 'Hi! Thank you for your first order at Freshyo. We''re glad to have you.'); INSERT OR IGNORE INTO staff_users (name, password, staff_role_id) VALUES ('shafi', '$2b$12$ytHGIuhFJLog2pDbqipxYuBaxdppjedgBNDg73iAU/M7cGjyvCWRq', 1); \ No newline at end of file diff --git a/packages/db_helper_sqlite/src/db/seed.ts b/packages/db_helper_sqlite/src/db/seed.ts index af9e172..05ddacb 100644 --- a/packages/db_helper_sqlite/src/db/seed.ts +++ b/packages/db_helper_sqlite/src/db/seed.ts @@ -128,6 +128,7 @@ export async function seed() { { key: CONST_KEYS.isFlashDeliveryEnabled, value: false }, { key: CONST_KEYS.supportMobile, value: '8688182552' }, { key: CONST_KEYS.supportEmail, value: 'qushammohd@gmail.com' }, + { key: CONST_KEYS.welcomeMessage, value: "Hi! Thank you for your first order at Freshyo. We're glad to have you." }, ] for (const constant of constantsToSeed) { diff --git a/packages/db_helper_sqlite/src/lib/const-keys.ts b/packages/db_helper_sqlite/src/lib/const-keys.ts index e8b0e60..efd6dec 100644 --- a/packages/db_helper_sqlite/src/lib/const-keys.ts +++ b/packages/db_helper_sqlite/src/lib/const-keys.ts @@ -25,6 +25,7 @@ export const CONST_KEYS = { supportMobile: 'supportMobile', supportEmail: 'supportEmail', internalAppVersion: 'internalAppVersion', + welcomeMessage: 'welcomeMessage', } as const export const CONST_LABELS: Record = { @@ -52,6 +53,7 @@ export const CONST_LABELS: Record = { supportMobile: 'Support Mobile', supportEmail: 'Support Email', internalAppVersion: 'Internal App Version', + welcomeMessage: 'Welcome Message', } export type ConstKey = (typeof CONST_KEYS)[keyof typeof CONST_KEYS] @@ -83,6 +85,7 @@ export const CONST_TYPES: Record = { supportMobile: 'string', supportEmail: 'string', internalAppVersion: 'number', + welcomeMessage: 'string', } export const CONST_VISIBILITY: Record = { @@ -110,6 +113,7 @@ export const CONST_VISIBILITY: Record = { supportMobile: true, supportEmail: true, internalAppVersion: true, + welcomeMessage: true, } /** @@ -142,6 +146,7 @@ export const CONST_DEFAULTS: Record = { supportMobile: '', supportEmail: '', internalAppVersion: 1, + welcomeMessage: "Hi! Thank you for your first order at Freshyo. We're glad to have you.", } export const castConstValue = (key: string, value: unknown) => {