This commit is contained in:
shafi54 2026-10-03 10:45:42 +05:30
parent ee95b2a7f6
commit c19f827312
31 changed files with 741 additions and 49 deletions

View file

@ -29,6 +29,7 @@ const CONST_LABELS: Record<string, string> = {
supportMobile: 'Support Mobile',
supportEmail: 'Support Email',
internalAppVersion: 'Internal App Version',
welcomeMessage: 'Welcome Message',
};
const CONST_VISIBILITY: Record<string, boolean> = {
@ -52,6 +53,7 @@ const CONST_VISIBILITY: Record<string, boolean> = {
supportMobile: true,
supportEmail: true,
internalAppVersion: false,
welcomeMessage: true,
tester: false,
};
@ -159,6 +161,23 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
);
}
// Welcome message — multiline text area
if (constantKey === 'welcomeMessage') {
return (
<MyTextInput
topLabel={CONST_LABELS[constantKey] || constantKey}
value={value === null || value === undefined ? '' : String(value)}
onChangeText={(value) => {
setFieldValue(fieldName, value)
}}
placeholder="Enter welcome message"
multiline
numberOfLines={4}
style={tw`min-h-24`}
/>
);
}
// Default to string
return (
<MyTextInput

View file

@ -54,6 +54,8 @@ export function OrderOptionsMenu({
onDial,
}: OrderOptionsMenuProps) {
const updateAddressCoordsMutation = trpc.admin.order.updateAddressCoords.useMutation();
const { data: constants } = trpc.admin.const.getConstants.useQuery();
const welcomeMessage = constants?.find((c) => 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();
}}
>

View file

@ -76,7 +76,7 @@ export const NotificationProvider: React.FC<ReactParentComponent> = ({
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);
}

View file

@ -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<typeof OrderOptionsMenu>['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()

View file

@ -31,6 +31,7 @@ const CONST_LABELS: Record<string, string> = {
isFlashDeliveryEnabled: 'Enable Flash Delivery',
supportMobile: 'Support Mobile',
supportEmail: 'Support Email',
welcomeMessage: 'Welcome Message',
}
const CONST_VISIBILITY: Record<string, boolean> = {
@ -53,6 +54,7 @@ const CONST_VISIBILITY: Record<string, boolean> = {
isFlashDeliveryEnabled: true,
supportMobile: true,
supportEmail: true,
welcomeMessage: true,
tester: false,
}
@ -155,6 +157,22 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
)
}
// Welcome message — multiline text area
if (constantKey === 'welcomeMessage') {
return (
<MyTextInput
topLabel={CONST_LABELS[constantKey] || constantKey}
value={value === null || value === undefined ? '' : String(value)}
onChange={(e) => {
setFieldValue(fieldName, e.target.value)
}}
placeholder="Enter welcome message"
multiline
numberOfLines={4}
/>
)
}
return (
<MyTextInput
topLabel={CONST_LABELS[constantKey] || constantKey}

Binary file not shown.

View file

@ -0,0 +1,28 @@
/**
* Demo runner for isInMbnrPolygon (Mbnr-2 polygon).
*
* bun run scripts/check-polygon-2.ts
*
* Prints whether each sample coordinate is inside the Mbnr-2 delivery polygon.
*/
import { isInMbnrPolygon } from '../src/map-assets/mbnr-2'
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-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}`
)
}

View file

@ -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}`
)
}

View file

@ -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<number> {
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
}

View file

@ -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<CreateAllCacheFilesResult>
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<CreateAllCacheFilesResult>
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<string> {
}
export async function createAvailabilityCacheFile(): Promise<number> {
export async function createAvailabilityCacheFile(refresh = true): Promise<number> {
const version = await incrementAvailabilityVersionNum()
const availabilityData = await scaffoldAvailability()
const jsonContent = JSON.stringify(availabilityData, null, 2)
@ -129,6 +133,8 @@ export async function createAvailabilityCacheFile(): Promise<number> {
filePath
)
if (refresh) await refreshGenKv()
return version
}
@ -154,7 +160,7 @@ async function createStoresFileInternal(version: number): Promise<string> {
)
}
export async function createSlotsCacheFile(): Promise<number> {
export async function createSlotsCacheFile(refresh = true): Promise<number> {
const version = await incrementSlotsVersionNum()
const slotsData = await scaffoldSlotsWithProducts()
const jsonContent = JSON.stringify(slotsData, null, 2)
@ -168,6 +174,8 @@ export async function createSlotsCacheFile(): Promise<number> {
filePath
)
if (refresh) await refreshGenKv()
return version
}

View file

@ -24,6 +24,7 @@ export const CONST_KEYS = {
supportMobile: 'supportMobile',
supportEmail: 'supportEmail',
internalAppVersion: 'internalAppVersion',
welcomeMessage: 'welcomeMessage',
} as const;
export const CONST_LABELS: Record<ConstKey, string> = {
@ -50,6 +51,7 @@ export const CONST_LABELS: Record<ConstKey, string> = {
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<ConstKey, ConstValueType> = {
supportMobile: 'string',
supportEmail: 'string',
internalAppVersion: 'number',
welcomeMessage: 'string',
};
export const CONST_VISIBILITY: Record<ConstKey, boolean> = {
@ -106,4 +109,5 @@ export const CONST_VISIBILITY: Record<ConstKey, boolean> = {
supportMobile: true,
supportEmail: true,
internalAppVersion: true,
welcomeMessage: true,
};

View file

@ -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)

View file

@ -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()
}

View file

@ -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<ReturnType<typeof scaffoldEssentialConsts>>
// Dynamic import: gen-store must not statically import common-trpc-index, because
// that module imports readEssentialConstsFromKv from here (cycle).
async function buildEssentialConsts(): Promise<EssentialConstsPayload> {
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<void> {
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<EssentialConstsPayload> {
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
}

View file

@ -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: [
{

View file

@ -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<void> => {
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) {

View file

@ -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
}

View file

@ -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.");
}

View file

@ -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
]
]
]
}
}
]
}

View file

@ -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
]
]
]
}
}
]
}

View file

@ -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<boolean> {
const check = await getPointInPolygonChecker()
return check(coords)
}

View file

@ -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<boolean> {
const check = await getPointInPolygonChecker()
return check(coords)
}

View file

@ -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).

View file

@ -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,

View file

@ -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({
<h1 style="font-size: 36px; margin-top: 48px">With love, from Freshyo</h5>
</div>`
const response = await scaffoldEssentialConsts();
const response = await readEssentialConstsFromKv();
const shouldShowNotice = host.includes('raw') || host.includes('mf')
return {

View file

@ -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"

View file

@ -105,4 +105,8 @@ id="aba74be264df45c0b17757fe01c136e5"
[[kv_namespaces]]
binding="freshyo_order_tracker"
id="ec20eab6e50648b8b45e8e269f9aa0c1"
id="ec20eab6e50648b8b45e8e269f9aa0c1"
[[kv_namespaces]]
binding="freshyo_gen"
id="037cdf0159d8457ea22eeb9a0b4e53fd"

View file

@ -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/<orderId>.
[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:<userId>' -> '<orderId>'
(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=<welcomeMessage>; 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.

View file

@ -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);

View file

@ -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) {

View file

@ -25,6 +25,7 @@ export const CONST_KEYS = {
supportMobile: 'supportMobile',
supportEmail: 'supportEmail',
internalAppVersion: 'internalAppVersion',
welcomeMessage: 'welcomeMessage',
} as const
export const CONST_LABELS: Record<ConstKey, string> = {
@ -52,6 +53,7 @@ export const CONST_LABELS: Record<ConstKey, string> = {
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<ConstKey, ConstValueType> = {
supportMobile: 'string',
supportEmail: 'string',
internalAppVersion: 'number',
welcomeMessage: 'string',
}
export const CONST_VISIBILITY: Record<ConstKey, boolean> = {
@ -110,6 +113,7 @@ export const CONST_VISIBILITY: Record<ConstKey, boolean> = {
supportMobile: true,
supportEmail: true,
internalAppVersion: true,
welcomeMessage: true,
}
/**
@ -142,6 +146,7 @@ export const CONST_DEFAULTS: Record<ConstKey, string | number | boolean> = {
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) => {