freshyo/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
2026-10-15 20:31:20 +05:30

268 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { router, publicProcedure, protectedProcedure, authenticatedProcedure } from '@/src/trpc/trpc-index'
import { commonRouter } from '@/src/trpc/apis/common-apis/common'
import {
getStoresSummary,
healthCheck,
getBoundById,
getAllRegions,
getEffectiveRegionSettings,
getBoundsForRegion,
getEffectiveBoundId,
getUserAddresses,
} from '@/src/dbService'
import type { StoresSummaryResponse, ResolvedRegion } from '@packages/shared'
import { polygon as turfPolygon, point as turfPoint } from '@turf/helpers';
import { booleanPointInPolygon } from '@turf/boolean-point-in-polygon';
import { resolveBoundInRegion, resolveRegionAndBound } from '@/src/lib/region-geo'
import { z } from 'zod';
import { mbnrGeoJson } from '@/src/lib/mbnr-geojson'
import { generateUploadUrl } from '@/src/lib/s3-client'
import { ApiError } from '@/src/lib/api-error'
import {
getGlobalConstValues,
getRegionConstValues,
getBoundConstValues,
} from '@/src/lib/const-store'
import { readEssentialConstsFromKv } from '@/src/lib/gen-store'
import { getAssetsDomain, getApiCacheKey } from '@/src/lib/env-exporter'
const polygon = turfPolygon(mbnrGeoJson.features[0].geometry.coordinates);
export async function scaffoldEssentialConsts(boundId: number) {
const bound = await getBoundById(boundId)
if (!bound) throw new ApiError('Bound not found', 404)
const regionId = bound.regionId
const [global, region, boundConsts] = await Promise.all([
getGlobalConstValues(),
getRegionConstValues(regionId),
getBoundConstValues(boundId),
])
const pickNumber = (raw: any, fallback: number): number => {
if (raw == null || raw === '') return fallback
const parsed = Number(raw)
return Number.isFinite(parsed) ? parsed : fallback
}
const pickRaw = (raw: any, fallback: any): any => (raw == null || raw === '' ? fallback : raw)
const pickBool = (raw: any, fallback: boolean): boolean => {
if (raw == null || raw === '') return fallback
if (typeof raw === 'boolean') return raw
const str = String(raw).toLowerCase()
return str === 'true' || str === '1'
}
// Flat union of global + region + bound consts (+ env + identity). Key names
// match the three tables exactly so clients read one flat object.
return {
// global_consts
versionNum: pickRaw(global['versionNum'], null),
playStoreUrl: pickRaw(global['playStoreUrl'], null),
appStoreUrl: pickRaw(global['appStoreUrl'], null),
internalAppVersion: pickNumber(global['internalAppVersion'], 1),
// region_consts
products_version_num: pickNumber(region['products_version_num'], 0),
availability_version_num: pickNumber(region['availability_version_num'], 0),
slots_version_num: pickNumber(region['slots_version_num'], 0),
popularItems: pickRaw(region['popularItems'], null),
allItemsOrder: pickRaw(region['allItemsOrder'], null),
supportMobile: pickRaw(region['supportMobile'], ''),
supportEmail: pickRaw(region['supportEmail'], ''),
welcomeMessage: pickRaw(region['welcomeMessage'], ''),
// region_bound_consts
freeDeliveryThreshold: pickNumber(boundConsts['freeDeliveryThreshold'], 200),
deliveryCharge: pickNumber(boundConsts['deliveryCharge'], 0),
flashFreeDeliveryThreshold: pickNumber(boundConsts['flashFreeDeliveryThreshold'], 500),
flashDeliveryCharge: pickNumber(boundConsts['flashDeliveryCharge'], 69),
// Per bound: each bound switches flash delivery on/off independently.
isFlashDeliveryEnabled: pickBool(boundConsts['isFlashDeliveryEnabled'], false),
// env + identity
assetsDomain: getAssetsDomain(),
apiCacheKey: getApiCacheKey(),
regionId,
boundId,
// stale-client notice (overridden per-request in the procedure)
webViewHtml: null,
webviewHtml: null,
isWebviewClosable: true,
}
}
export const commonApiRouter = router({
product: commonRouter,
getStoresSummary: protectedProcedure
.query(async ({ ctx }): Promise<StoresSummaryResponse> => {
// Admin-only picker: the caller's OWN region only, not an aggregate.
const stores = await getStoresSummary(ctx.staffUser!.regionId);
return {
stores,
};
}),
checkLocationInPolygon: publicProcedure
.input(z.object({
lat: z.number().min(-90).max(90),
lng: z.number().min(-180).max(180),
}))
.query(({ input }) => {
try {
const { lat, lng } = input;
const point = turfPoint([lng, lat]); // GeoJSON: [longitude, latitude]
const isInside = booleanPointInPolygon(point, polygon);
return { isInside };
} catch (error) {
throw new Error('Invalid coordinates or polygon data');
}
}),
generateUploadUrls: authenticatedProcedure
.input(z.object({
contextString: z.enum(['review', 'review_response', 'product_info', 'notification', 'store', 'complaint', 'profile', 'tags']),
mimeTypes: z.array(z.string()),
}))
.mutation(async ({ input }): Promise<{ uploadUrls: string[] }> => {
const { contextString, mimeTypes } = input;
const uploadUrls: string[] = [];
const keys: string[] = [];
for (const mimeType of mimeTypes) {
// Generate key based on context and mime type
let folder: string;
if (contextString === 'review') {
folder = 'review-images';
} else if (contextString === 'product_info') {
folder = 'product-images';
} else if (contextString === 'store') {
folder = 'store-images';
} else if (contextString === 'review_response') {
folder = 'review-response-images';
} else if (contextString === 'complaint') {
folder = 'complaint-images';
} else if (contextString === 'profile') {
folder = 'profile-images';
} else if (contextString === 'tags') {
folder = 'tags';
} else {
folder = '';
}
const extension = mimeType === 'image/jpeg' ? '.jpg' :
mimeType === 'image/png' ? '.png' :
mimeType === 'image/gif' ? '.gif' : '.jpg';
const key = `${folder}/${Date.now()}${extension}`;
try {
const uploadUrl = await generateUploadUrl(key, mimeType);
uploadUrls.push(uploadUrl);
keys.push(key);
} catch (error) {
console.error('Error generating upload URL:', error);
throw new ApiError('Failed to generate upload URL', 500);
}
}
return { uploadUrls };
}),
healthCheck: publicProcedure
.query(async () => {
const result = await healthCheck();
return result;
}),
// Public region discovery for the user app before a browsing region is chosen.
listRegions: publicProcedure
.query(async () => {
return getAllRegions();
}),
// Resolve device coordinates to a region + the bound that contains them.
// Every region is checked; within each region bounds are checked least
// priority first (lowest number wins). The first containing bound is returned.
resolveRegionByLocation: publicProcedure
.input(z.object({
lat: z.number().min(-90).max(90),
lng: z.number().min(-180).max(180),
}))
.query(async ({ input }): Promise<ResolvedRegion | null> => {
return resolveRegionAndBound(input.lat, input.lng)
}),
// Resolve a point to the bound of a chosen region (used by the add-address
// flow: pick a region, then pick a point on the map). Throws when the point
// is outside every bound of that region.
resolveBound: publicProcedure
.input(z.object({
regionId: z.number().int().positive(),
lat: z.number().min(-90).max(90),
lng: z.number().min(-180).max(180),
}))
.query(async ({ input }): Promise<{ regionId: number; boundId: number }> => {
const boundId = await resolveBoundInRegion(input.regionId, input.lat, input.lng)
if (boundId == null) {
throw new ApiError('Selected location is outside this region’s delivery area', 422)
}
return { regionId: input.regionId, boundId }
}),
// Effective business settings (from the region's lowest-priority bound).
regionSettings: publicProcedure
.input(z.object({ regionId: z.number().int().positive() }))
.query(async ({ input }) => {
const effective = await getEffectiveRegionSettings(input.regionId)
if (!effective) {
throw new ApiError('Region has no configured bound', 422)
}
return effective
}),
// The active bound for a region: for a signed-in user it is the least-priority
// bound among their addresses in that region; signed-out users get the
// region's effective (least-priority) bound.
activeBound: publicProcedure
.input(z.object({ regionId: z.number().int().positive() }))
.query(async ({ ctx, input }): Promise<{ regionId: number; boundId: number | null }> => {
const userId = ctx?.user?.userId
const addresses = userId ? await getUserAddresses(userId) : []
const boundIds = new Set(
addresses
.filter((address) => address.regionId === input.regionId && address.boundId != null)
.map((address) => address.boundId as number)
)
if (boundIds.size > 0) {
const bounds = await getBoundsForRegion(input.regionId) // priority ascending
const least = bounds.find((bound) => boundIds.has(bound.id))
if (least) return { regionId: input.regionId, boundId: least.id }
}
return { regionId: input.regionId, boundId: await getEffectiveBoundId(input.regionId) }
}),
essentialConsts: publicProcedure
.input(z.object({ boundId: z.number().int().positive() }))
.query(async ({ ctx, input }) => {
console.log({ boundId: input.boundId })
const requestUrl = ctx.req.url
const host = new URL(requestUrl).host
const updateNotice = `<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%;">
<h1 style="font-size: 72px">You're using an old version of app. please restart to update. Just close and open</h1>
<h1 style="font-size: 36px; margin-top: 48px">With love, from Freshyo</h5>
</div>`
const response = await readEssentialConstsFromKv(input.boundId);
const shouldShowNotice = host.includes('raw') || host.includes('mf')
console.log('essentialConsts request', { host, url: requestUrl, ...response })
return {
...response,
webviewHtml: shouldShowNotice ? updateNotice : null,
isWebviewClosable: shouldShowNotice ? false : true
};
}),
});
export type CommonApiRouter = typeof commonApiRouter;