Compare commits

...
Sign in to create a new pull request.

4 commits

Author SHA1 Message Date
shafi54
8f1e40f8b2 enh 2026-10-07 00:27:11 +05:30
shafi54
5af1afd8ba enh 2026-10-06 11:53:12 +05:30
shafi54
e88f82c4c9 enh 2026-10-05 20:43:25 +05:30
shafi54
ac31dc2010 enh 2026-10-05 11:46:47 +05:30
288 changed files with 53697 additions and 12114 deletions

11
.gitignore vendored
View file

@ -141,3 +141,14 @@ apps/admin-ui/android/
.maestro-output/*
apps/admin-ui/.expo/cache/*
# Playwright web-test outputs (tests/web)
/test-results/
/playwright-report/
/playwright/.auth/
tests/web/.env
# Full-suite E2E generated files (tests/e2e/full-suite)
tests/e2e/full-suite/.env.e2e
tests/e2e/full-suite/gen/
tests/e2e/full-suite/.env

9
.mcp.json Normal file
View file

@ -0,0 +1,9 @@
{
"mcpServers": {
"maestro": {
"transport": "stdio",
"enabled": true,
"command": ["maestro", "mcp"]
}
}
}

105
MULTI_REGION_PROBLEMS.md Normal file
View file

@ -0,0 +1,105 @@
# Problems found — multi-region testing (2026-10-06, local dev)
Source: Maestro MCP runs (iOS sim `5A64695E`, Chromium) + tRPC API checks against
local backend `127.0.0.1:8787`. Test data: region 8 (`MCPTest-222329`),
products 157/158, tags 1–3, slot 1, user address 872. Full per-test report in
session notes; this file lists defects only.
## Open app defects
### P1 — Add Address silently drops the save (data-loss UX)
- Repro: Me → Addresses → + → fill Name/Phone/Line-1, Attach Current Location
(spoofed Jadcherla 16.76,78.14 → "Location Attached"), pick Jadcherla in the
region dropdown → Add Address. Sheet closes, no error — but `getUserAddresses`
still returns 1 address.
- Same payload via `user.address.createAddress` API succeeds (id 872, region 7),
so the app form never POSTs or swallows the error.
- Fix: surface backend errors; verify the payload mapping (city field still read
"Mahabubnagar"/pin "509001" while region=Jadcherla — check whether a
city/pin-vs-region validation rejects it server- or client-side without a toast).
### P2 — Changing default address to another region does not switch region
- Repro: set the Jadcherla address as default ("Success — Default address
updated") → Home still shows Mahabubnagar + MBNR data. No region switch, no
reconciliation notice.
- Product decision needed: should default-address drive the active region, or is
region strictly location/device-driven? Either way the silent no-op is wrong —
at minimum notify ("address saved; region unchanged").
### P3 — Availability cache goes stale; OOS persists after DB says in-stock
- DB `product_market_stats`: sku 160 in-stock @175 in region 6; slot 1 created
(region 6, skus 160+161). App still shows Out of Stock @₹100 after relaunch +
pull-to-refresh.
- Root cause: the app re-reads availability only when its version bumps, and
nothing in the tested writes bumped `availability_version_num`. Slot/product
writes go through fire-and-forget `scheduleStoreInitialization` (DO), which
never visibly ran locally.
- Impact: blocks all cart/checkout E2E (tests 16/17/19) — every item unreadable
as purchasable.
### P4 — Stale price display (same root cause as P3)
- Card shows ₹100/₹120 after backend price update to 175/200 (`admin.product.
updateProduct` verified via API). Products file is version-sticky the same way.
### P5 — Region name spelling: "Jadcherla" (app/region picker) vs "Jadcherla" (DB)
- `getRegions` returns `Jadcherla`; the app header, out-of-service cards, and the
address region picker render "Jadcherla". Maestro `tapOn: "Jadcherla"` fails —
only coordinate taps work. Confirm the intended spelling and fix one side.
### P6 — In-app location change alone does not re-resolve region
- Spoof MBNR→Jadcherla while the app is foregrounded: header stays Mahabubnagar.
Region re-resolves only on relaunch. If live re-resolution is intended, the
location listener is not firing/refreshing; if relaunch-only is intended,
document it (tests 14/15 depend on it).
### P7 — Region selector is sticky; spec expects scroll-out (test 20)
- After 2× swipe-up on Home, the region header + search remain visible.
Either the spec ("selector is scrolled out") is outdated or the sticky header
is a regression. Product call.
### P8 — No notif-creds endpoint fires on region change/detect (tests 23/24)
- No dedicated endpoint found in the user router; `notif_creds` table has a
`regionId` FK but nothing observed writing it on region switch or auto-detect.
Verify whether the mobile client is supposed to call something here or the
requirement is obsolete.
### P9 — Legacy default address points at dead region
- User 388's default address (id 285) has `regionId: 1`, but regions are now
6/7/8. Anything joining address→region for this user silently misses.
Data hygiene: re-point or null it.
## Test-harness notes (Maestro, not app bugs)
- Password `secureTextEntry` field: `inputText` never focuses it (no keyboard,
text goes nowhere). Working sequence: tap `user-login-password` by id →
`eraseText: 50` → `setClipboard` + `pasteText`. Note: `inputText` with `@`
keystroke-types an extra `y` (multilingual SIM keyboard `EN HI`); paste avoids it.
- Never tap a button with the keyboard up: the tap lands on the keyboard
(observed phantom `y` appended to the password when tapping Login).
- `inspect_screen` on the user app throws `RangeError: max depth 32` — used
screenshots + targeted `tapOn` instead.
- Out-of-service screen doubles as the region picker (lists all regions incl.
newly created ones) — useful fallback for region selection tests.
## Fixed during this session (for reference, not open)
- Store submit tap eaten by open keyboard → keyboard dismissal via static-text
tap + `assertVisible` before every button tap.
- BottomDialog sat under the iOS keyboard → manual `Keyboard`-driven inset;
the `maxHeight: 85%` cap choked the inset and was removed (verified live:
sheet bottom lands exactly at keyboard top).
- BottomDropdown option taps swallowed with keyboard open → added
`keyboardShouldPersistTaps="handled"` to the inner option-list ScrollView
(was only on the outer dialog scroll).
- Native iOS date picker: same-day picks never fire `onChange` (modal never
closes); freeze-picked-second crossed minute boundaries (`freeze > delivery`).
Now freeze-first + same-day force-change branch in `set-slot-time-ios.yaml`.
- Flow scoping: `output.*` from `evalScript` does not reach nested
`runFlow.when.commands` in subflows — all matchers compute slugs inline.
- `scrollUntilVisible` + `centerElement: true` re-nudges endlessly on visible
elements; screen-level scrolls move the page behind bottom sheets (superseded
by search-then-select in product pickers).
- BottomDropdown option ids now embed a label slug
(`<testID>-option-<value>-<slug>`); flow matchers anchor with `.*`.
- Exact slot times need the `slots/add.tsx` `dts`/`fts` deep-link prefill hook
(native picker is calendar-only).

183
PRODUCT-REPORT.txt Normal file
View file

@ -0,0 +1,183 @@
PRODUCT REPORT — Regions & Location Release
Date: 2026-10-04
Scope: everything currently uncommitted in the worktree (customer app, admin apps, superadmin console, backend).
Note: database migrations are written but not yet applied; nothing below is live until they run.
=====================================================================
1. CUSTOMER APP (user-ui)
=====================================================================
1.1 Automatic region detection on startup
- When the app opens, it asks for location permission and figures out which
service region the customer is in, using the delivery-area maps drawn for
each region. No manual setup needed for most users.
- If permission is denied, or the phone's location switch is off, the app
shows a clear "Unable to obtain location" screen explaining exactly which
of the two is the problem, with a button that opens the right Settings
page (app settings for permission, system location settings on Android).
The user can also just pick a region manually and continue.
- If the customer is outside every service area, the app says so plainly
and still lets them pick a region and browse.
1.2 Region display and switching
- The home screen shows the current region above the search bar. It slides
away as you scroll so the search bar stays visible.
- Tapping the region opens a dropdown to switch regions. The same dropdown
now appears on all main tabs (Home, Offers, Flash delivery, Stores, Me).
- Switching region reloads that region's products, prices, stores, slots
and offers automatically.
1.3 Cart is remembered per region
- The cart is saved separately for each region. Going back to a previous
region restores exactly what was left there, including quantities.
- When the cart is carried into a new region, every item is re-matched to
the closest available delivery slot. Items that can't be delivered there
are removed. A summary dialog shows what moved (old time vs new time,
with a warning when the shift is over an hour) and what was removed.
- Applies to both the regular cart and the 1-hour delivery cart.
1.4 Delivery addresses belong to regions
- The address form now ends with a mandatory region dropdown, pre-filled
with the customer's detected region.
- On the cart page there is an address selector. Adding a new address in
the current region selects it immediately. If the new address is in a
different region, the app shows all addresses in that region and asks the
user to pick one.
- Changing the selected address to one in another region triggers the same
cart check as switching regions: a confirmation dialog appears first when
slots would move or items would be removed; empty or unaffected carts
switch over silently.
- The checkout page no longer has its own address picker; it shows the
chosen address read-only. Address selection happens on the cart page.
1.5 Push notifications carry the region
- The device's push token is saved together with its region, both for
logged-in and logged-out users. If the same device is used by another
account or region later, the record moves with it instead of erroring.
- Older app installs that never reported a region are treated as region 1.
=====================================================================
2. ADMIN APPS (admin-ui + admin-web)
=====================================================================
2.1 Admins only see and touch their own region
- Product, store, slot, banner, tag, group, snippet and order screens are
all filtered to the logged-in admin's region. Cross-region editing is
blocked with a clear error, including:
- editing or deleting another region's product, store, prices or stock,
- narrowing an "available in all regions" product down to one region,
- widening a product to all regions.
- Only super-admins can perform cross-region actions.
- The "available in all regions" checkbox is locked (visible but disabled)
for non-super-admins on all-region products; the server enforces the
same rule regardless.
2.2 All-region products
- A product can be marked available in all regions. It carries one store
per region (chosen from per-region dropdowns in the product form, with
every region's stores visible), while price and stock stay per-region.
- Every region selection in the form is mandatory — a product cannot be
saved with a region missing its store.
- Editing a product's per-region stores later actually updates them
(previously those edits were silently lost).
2.3 Region-aware pickers
- Product/SKU/tag/store pickers in banners, groups, tags and campaign
screens now show the admin's own region data (super-admins see everything
combined), instead of always showing region 1.
2.4 App settings per area (customize-app)
- Settings such as delivery charges, free-delivery limits, flash delivery
charges and support contacts can now differ per delivery area (bound),
edited through tabs at the top of the customize screen — one tab per
area, the first marked Default.
- If an area has no value saved, it inherits from the default area, then
region-level values, then built-in defaults.
2.5 Broadcast notifications go region-wide only
- "Notify all users" from an admin reaches only devices registered in that
admin's region.
=====================================================================
3. SUPERADMIN CONSOLE
=====================================================================
3.1 Regions management
- Full list / create / edit screens for regions, each with any number of
delivery-area maps (GeoJSON polygons), a name, description and priority
per area. Areas are evaluated in priority order; priority 1 is the
region default. Duplicate priorities and missing names are rejected in
the form and on the server.
- Regions cannot be deleted (too much depends on them).
- The first region (Mahabubnagar) ships with its two delivery-area maps
already loaded.
3.2 Mandatory notification channels per region
- Every new region must be created with at least one Telegram channel
(bot + destination); the form won't submit without it.
- Staff admin accounts are created with an explicit region and role.
=====================================================================
4. ORDERS, NOTIFICATIONS & CHARGES (platform behavior)
=====================================================================
4.1 Order pricing follows the delivery address
- Item prices, flash availability, delivery charges and minimum-order
thresholds are all taken from the order address's area — not always
region 1 as before. An order placed in region 2 is validated and priced
with region 2's data.
4.2 Staff alerts are regional
- When an order is placed, only admins of that order's region get the push
alert (with a tap-through to the order). Orders with no determinable
region still alert everyone so nothing is missed.
- Order alerts also go to Telegram, one message per region, delivered to
every Telegram channel configured for that region. Regions with no
channel configured are logged and skipped.
- Raising a complaint also alerts the relevant region's admins (based on
the complaint's order, else the customer's default address).
4.3 Tags can repeat across regions
- The same tag name (e.g. "Fruits") can now exist in multiple regions;
names only need to be unique within one region. (Requires the pending
migration; until it runs, the old global uniqueness still applies.)
=====================================================================
5. EDGE CASES & SAFETY BEHAVIOR
=====================================================================
- No region match: user is told they are outside the service area and can
continue by picking a region manually.
- No permission / location off: distinct messages and correct Settings
destination for each case; manual region pick always available.
- App reinstall / corrupted saved data: stored region is validated on
launch; unknown values are discarded and the user is asked again.
- Empty cart on region/address change: switches over silently, no popups.
- Cart lines that survive a move keep working; only real changes are shown.
- Slot moves under an hour apply quietly on confirmation; moves over an
hour are flagged prominently in the confirmation.
- Canceling a region/address confirmation leaves everything exactly as it
was (cart, region, selected address).
- Rapid repeated switches: overlapping operations are guarded so carts
can't corrupt each other.
- Addresses without coordinates: area is resolved from the region default;
charges fall back down the chain (area → default area → region → built-in).
- Areas whose maps overlap: the highest-priority area wins, consistently
for detection, pricing and settings.
- Deleting a delivery area also cleans up its area-specific settings so
no orphaned values linger; editing an area keeps its identity (and its
settings) instead of recreating it.
- Old devices/tokens with no region recorded are treated as region 1, so
nobody silently stops receiving notifications after the upgrade.
=====================================================================
6. INTENTIONALLY UNCHANGED / KNOWN NOTES
=====================================================================
- Coupons, reviews, payments and complaint handling (other than the new
admin alert) are not region-dependent.
- Flash-delivery eligibility of a product is still decided per region.
- The legacy fallback vendor page and old REST summary endpoints were
removed; all screens use the current data paths.
- Super-admins retain full cross-region visibility and action rights in
every admin surface.

View file

@ -1,4 +1,4 @@
{
"dependencies": "4650ceb7c30aaa4d5fd17b9577e186af7a84b50d",
"devDependencies": "b3b38265f32b99a8299270a292f38ca26288d53d"
"dependencies": "0106f523449523fa8389ec59d4d1bcbce79e46ac",
"devDependencies": "ee6421f996bd5fd6168846996d47bafe1791fe2e"
}

View file

@ -47,7 +47,7 @@ const CONST_VISIBILITY: Record<string, boolean> = {
versionNum: false,
playStoreUrl: false,
appStoreUrl: false,
popularItems: true,
popularItems: false,
allItemsOrder: true,
isFlashDeliveryEnabled: true,
supportMobile: true,
@ -194,7 +194,24 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
export default function CustomizeApp() {
const router = useRouter();
const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery();
const [activeBoundId, setActiveBoundId] = React.useState<number | null>(null);
const [boundsReady, setBoundsReady] = React.useState(false);
const { data: boundsData } = trpc.admin.region.getMyRegionBounds.useQuery(undefined, {
staleTime: Infinity,
});
const bounds = boundsData?.bounds ?? [];
React.useEffect(() => {
if (!boundsReady && bounds.length > 0) {
setActiveBoundId(bounds[0].id);
setBoundsReady(true);
}
}, [bounds, boundsReady]);
const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery(
activeBoundId != null ? { boundId: activeBoundId } : undefined,
{ enabled: boundsReady || bounds.length === 0 }
);
const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation();
@ -214,7 +231,10 @@ export default function CustomizeApp() {
}
updateConstants(
{ constants: changedConstants },
{
constants: changedConstants,
...(activeBoundId != null ? { boundId: activeBoundId } : {}),
},
{
onSuccess: (response) => {
Alert.alert('Success', `Updated ${response.updatedCount} constants successfully.`);
@ -259,7 +279,33 @@ export default function CustomizeApp() {
Modify application constants. Changes will take effect immediately.
</MyText>
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
{bounds.length > 0 && (
<View style={tw`flex-row flex-wrap mb-6`} testID="const-bound-tabs">
{bounds.map((bound, index) => {
const active = bound.id === activeBoundId;
return (
<MyTouchableOpacity
key={bound.id}
testID={`const-bound-tab-${bound.id}`}
onPress={() => setActiveBoundId(bound.id)}
style={active
? tw`mr-2 mb-2 px-4 py-2 rounded-full border bg-blue-500 border-blue-500`
: tw`mr-2 mb-2 px-4 py-2 rounded-full border bg-white border-gray-200`}
>
<MyText style={active ? tw`text-sm font-semibold text-white` : tw`text-sm font-semibold text-gray-700`}>
{bound.name || `Bound ${index + 1}`}{index === 0 ? ' (Default)' : ''}
</MyText>
</MyTouchableOpacity>
);
})}
</View>
)}
<Formik
key={activeBoundId ?? 'region'}
initialValues={initialValues}
onSubmit={handleSubmit}
>
{({ handleSubmit, values, setFieldValue }) => (
<View>
{constants.map((constant) => {

View file

@ -205,7 +205,7 @@ export default function PricesOverview() {
for (const product of allProducts) {
if (product.skus && product.skus.length > 0) {
for (const sku of product.skus) {
skus.push({ ...sku, _productName: product.name, _storeId: product.storeId });
skus.push({ ...sku, _productName: product.name, _storeId: product.store?.id });
}
}
}

View file

@ -97,14 +97,26 @@ export default function AddProduct() {
}
})
const storeIdsByRegion = Object.entries(values.storeIdsByRegion || {}).reduce(
(acc, [regionId, storeId]) => {
const sid = Number(storeId)
if (Number.isFinite(sid) && sid > 0) acc[Number(regionId)] = sid
return acc
},
{} as Record<number, number>
)
await createProduct.mutateAsync({
name: values.name,
shortDescription: values.shortDescription || undefined,
longDescription: values.longDescription || undefined,
storeId: values.storeId,
productType: values.productType,
incrementStep: 1,
skus,
availableInAllRegions: !!values.availableInAllRegions,
...(values.availableInAllRegions
? { storeIdsByRegion }
: { storeId: values.storeId }),
})
await refetchProducts()
@ -118,6 +130,9 @@ export default function AddProduct() {
name: '',
shortDescription: '',
longDescription: '',
regionId: undefined as number | undefined,
availableInAllRegions: false,
storeIdsByRegion: {} as Record<number, number>,
storeId: 1,
productType: 'item' as const,
variants: [

View file

@ -41,6 +41,9 @@ export default function EditProduct() {
name: '',
shortDescription: '',
longDescription: '',
regionId: undefined as number | undefined,
availableInAllRegions: false,
storeIdsByRegion: {} as Record<number, number>,
storeId: 0,
productType: 'item' as const,
variants: [],
@ -50,7 +53,10 @@ export default function EditProduct() {
name: productData.name,
shortDescription: productData.shortDescription || '',
longDescription: productData.longDescription || '',
storeId: productData.storeId || 1,
regionId: productData.regionId,
availableInAllRegions: productData.availableInAllRegions ?? false,
storeIdsByRegion: {} as Record<number, number>,
storeId: productData.store?.id ?? 1,
productType: (productData.productType as 'item' | 'combo') || 'item',
variants: (productData.skus || []).map((sku) => ({
id: sku.id,
@ -176,17 +182,32 @@ export default function EditProduct() {
}
})
const storeIdsByRegion = Object.entries(values.storeIdsByRegion || {}).reduce(
(acc, [regionId, storeId]) => {
const sid = Number(storeId)
if (Number.isFinite(sid) && sid > 0) acc[Number(regionId)] = sid
return acc
},
{} as Record<number, number>
)
await updateProduct.mutateAsync({
id: productId,
name: values.name,
shortDescription: values.shortDescription || undefined,
longDescription: values.longDescription || undefined,
storeId: values.storeId,
// Null (global product) becomes undefined: the backend falls back to
// the staffer's region, which is the desired regional scoping.
regionId: values.regionId ?? undefined,
productType: values.productType,
incrementStep: 1,
skus,
deletedImageKeys,
newImageUrls: allUploadUrls,
availableInAllRegions: !!values.availableInAllRegions,
...(values.availableInAllRegions
? { storeIdsByRegion }
: { storeId: values.storeId }),
} as any)
await refetch()

View file

@ -7,9 +7,23 @@ import { trpc } from '@/src/trpc-client';
export default function AddSlot() {
const router = useRouter();
const { baseslot } = useLocalSearchParams();
const { baseslot, dts, fts } = useLocalSearchParams();
const baseSlotId = baseslot ? parseInt(baseslot as string) : null;
// e2e hook: SlotForm accepts initial times but nothing passed them, so the
// screen always opened with null times and e2e had to fight the native
// picker (which cannot set time-of-day). Deep links can carry the exact
// delivery/freeze instants as ISO strings: ...?dts=<ISO>&fts=<ISO>.
// URL-encoding collapses colons in ISO strings to %3A, so normalize.
const parseInstant = (raw?: string | string[]): Date | null => {
const value = Array.isArray(raw) ? raw[0] : raw
if (!value) return null
const date = new Date(value.replace(/%3A/gi, ':'))
return isNaN(date.getTime()) ? null : date
}
const initialDeliveryTime = parseInstant(dts)
const initialFreezeTime = parseInstant(fts)
const { refetch } = trpc.admin.slots.getAll.useQuery();
const { data: baseSlotData, isLoading } = trpc.admin.slots.getSlotById.useQuery(
{ id: baseSlotId! },
@ -35,6 +49,8 @@ export default function AddSlot() {
<AppContainer>
<SlotForm
onSlotAdded={handleSlotAdded}
initialDeliveryTime={initialDeliveryTime}
initialFreezeTime={initialFreezeTime}
initialProductIds={baseSlotData?.slot?.products?.map((p: any) => p.id) || []}
initialGroupIds={baseSlotData?.slot?.groupIds || []}
/>

View file

@ -43,7 +43,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
const initialSelectedProducts = useMemo(() => {
if (mode !== 'edit' || !productsData?.products) return [];
return productsData.products
.filter(p => p.storeId === storeId)
.filter(p => p.store?.id === storeId)
.flatMap(p => (p.skus || []).map(sku => sku.id));
}, [mode, productsData?.products, storeId]);
@ -128,6 +128,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
return (
<View>
<MyTextInput
testID="store-name-input"
topLabel="Store Name"
placeholder="Enter store name"
value={values.name}
@ -136,6 +137,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
style={{ marginBottom: 16 }}
/>
<MyTextInput
testID="store-description-input"
topLabel="Description"
placeholder="Enter store description"
multiline
@ -146,6 +148,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
style={{ marginBottom: 16 }}
/>
<BottomDropdown
testID="store-owner-dropdown"
label="Owner"
value={values.owner}
options={staffOptions}
@ -155,6 +158,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
style={{ marginBottom: 16 }}
/>
<ProductsSelector
testID="store-products-selector"
value={values.products || []}
onChange={(value) => setFieldValue('products', value)}
multiple={true}
@ -180,6 +184,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
/>
</View>
<TouchableOpacity
testID="store-submit-button"
onPress={submit}
disabled={isLoading || isUploading}
style={tw`px-4 py-2 rounded-lg shadow-lg items-center mt-2 ${isLoading || isUploading ? 'bg-gray-400' : 'bg-blue-500'}`}

View file

@ -0,0 +1,10 @@
import { trpc } from '../src/trpc-client'
/** True when the logged-in staff member is a super_admin (cached for the session). */
export function useIsSuperAdmin(): boolean {
const { data } = trpc.admin.staffUser.getSelf.useQuery(undefined, {
staleTime: Infinity,
retry: false,
})
return data?.staff?.roleName === 'super_admin'
}

View file

@ -1,6 +1,6 @@
import React, { useState, useImperativeHandle, forwardRef, useMemo } from 'react'
import React, { useState, useImperativeHandle, forwardRef, useMemo, useEffect } from 'react'
import { View, TouchableOpacity, ScrollView, Alert } from 'react-native'
import { Formik, FieldArray } from 'formik'
import { Formik, FieldArray, useFormikContext } from 'formik'
import * as Yup from 'yup'
import { MyTextInput, BottomDropdown, MyText, tw, ImageUploaderNeo, ImageUploaderNeoItem, ImageUploaderNeoPayload, Checkbox, InfoDialog } from 'common-ui'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
@ -34,6 +34,9 @@ interface ProductFormData {
name: string
shortDescription: string
longDescription: string
regionId?: number | null
availableInAllRegions?: boolean
storeIdsByRegion?: Record<number, number>
storeId: number
productType: 'item' | 'combo'
variants: Variant[]
@ -77,13 +80,17 @@ const defaultVariant = (): Variant => ({
const variantSignature = (attributes: Attribute[]): string =>
attributes
.map((a) => `${(a.featureName ?? '').trim().toLowerCase()}::${a.featureValue.trim().toLowerCase()}`)
.map((a) => `${(a?.featureName ?? '').trim().toLowerCase()}::${(a?.featureValue ?? '').trim().toLowerCase()}`)
.sort()
.join('|')
const productValidationSchema = Yup.object().shape({
name: Yup.string().required('Product name is required'),
storeId: Yup.number().required('Store is required').min(1, 'Store is required'),
storeId: Yup.number().when('availableInAllRegions', {
is: false,
then: (schema) => schema.required('Store is required').min(1, 'Store is required'),
otherwise: (schema) => schema.notRequired().nullable(),
}),
productType: Yup.string().oneOf(['item', 'combo'], 'Product type is required').required('Product type is required'),
variants: Yup.array()
.min(1, 'At least one variant is required')
@ -145,6 +152,34 @@ const productValidationSchema = Yup.object().shape({
}),
})
const makeProductValidationSchema = (regions: RegionOption[], onlyRegionId?: number | null) =>
productValidationSchema.concat(
Yup.object().shape({
storeIdsByRegion: Yup.mixed().test(
'store-every-region',
'Store is required for every region',
function (value: any) {
if (this.parent?.availableInAllRegions !== true) return true
// Regional staff editing a global product: only their own region
// must have a store. (Superadmin-role editors cover all regions.)
const applicable = onlyRegionId != null
? regions.filter((r) => r.id === onlyRegionId)
: regions
const map: Record<number, number> = value ?? {}
for (const region of applicable) {
const storeId = map[region.id]
if (storeId == null || Number(storeId) < 1) {
return this.createError({
message: `Create a store for "${region.name}" before saving`,
})
}
}
return true
}
),
})
)
// Collect every string message from a Formik errors tree (objects, arrays, strings).
// Variant-level errors (e.g. 'Each SKU can have only one quantity feature') can get
// hidden by Formik when index-level errors are also present, so we walk everything.
@ -158,6 +193,39 @@ const collectErrorMessages = (errors: unknown, depth = 0): string[] => {
return []
}
type RegionStoreOption = { id: number; name: string; regionId?: number | null; availableInAllRegions?: boolean }
type RegionOption = { id: number; name: string }
// On edit, an all-regions product has no per-region store payload from the API,
// so fill each region with the store whose name matches the current product store.
const RegionStorePrefill = ({
stores,
regions,
currentStoreName,
}: {
stores: RegionStoreOption[]
regions: RegionOption[]
currentStoreName?: string
}) => {
const { values, setFieldValue } = useFormikContext<ProductFormData>()
useEffect(() => {
if (!values.availableInAllRegions || !currentStoreName) return
if (stores.length === 0 || regions.length === 0) return
const next: Record<number, number> = { ...(values.storeIdsByRegion ?? {}) }
let changed = false
for (const region of regions) {
if (next[region.id] != null) continue
const match = stores.find((store) => store.regionId === region.id && store.name === currentStoreName)
if (match) {
next[region.id] = match.id
changed = true
}
}
if (changed) setFieldValue('storeIdsByRegion', next)
}, [stores, regions, currentStoreName, values.availableInAllRegions, values.storeIdsByRegion, setFieldValue])
return null
}
const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
mode,
initialValues,
@ -176,11 +244,62 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
clearImages: () => setVariantImages(initialValues.variants.map(() => [])),
}), [initialValues.variants])
const { data: storesData } = trpc.common.getStoresSummary.useQuery()
const storeOptions = storesData?.stores.map((store) => ({
label: store.name,
value: store.id,
})) || []
// All-region products are managed from superadmin-ui only: the flag is
// hidden here (so global products can never be created from this app).
// Regional staff may still edit a global product, but every write applies
// to their own region only (backend scopes via the staffer's region).
const isAllRegionsProduct = !!initialValues.availableInAllRegions
// Staffer identity for scoping global-product edits. Superadmin-role staff
// keep the full per-region UI; everyone else is collapsed to their region.
const { data: selfData } = trpc.admin.staffUser.getSelf.useQuery(undefined, {
staleTime: Infinity,
retry: false,
})
const staffIsSuperAdmin = selfData?.staff?.roleName === 'super_admin'
const staffRegionId: number | null = selfData?.staff?.regionId ?? null
const editingGlobalAsRegional = isAllRegionsProduct && !staffIsSuperAdmin
const { data: storesData } = trpc.admin.store.getStores.useQuery()
const allStores: RegionStoreOption[] = useMemo(
() => (storesData?.stores || []) as RegionStoreOption[],
[storesData]
)
const storeOptions = useMemo(
() => allStores.map((store) => ({ label: store.name, value: store.id })),
[allStores]
)
const { data: allRegionsStoresData } = trpc.admin.store.getStoresForAllRegions.useQuery()
const allRegionsStores: RegionStoreOption[] = useMemo(
() => (allRegionsStoresData?.stores || []) as RegionStoreOption[],
[allRegionsStoresData]
)
const storesForRegion = (regionId: number) =>
allRegionsStores
.filter((store) => store.regionId === regionId || store.availableInAllRegions)
.map((store) => ({ label: store.name, value: store.id }))
const { data: regionsData } = trpc.admin.region.getRegions.useQuery()
const regions: RegionOption[] = useMemo(
() => (regionsData?.regions || []).map((region) => ({ id: region.id, name: region.name })),
[regionsData]
)
// Regions whose stores are editable in this form: just the staffer's own
// when they are regionally editing a global product, else everything.
const editableRegions = useMemo(
() => (editingGlobalAsRegional && staffRegionId != null
? regions.filter((r) => r.id === staffRegionId)
: regions),
[editingGlobalAsRegional, staffRegionId, regions]
)
const staffRegionName = regions.find((r) => r.id === staffRegionId)?.name ?? 'your region'
const validationSchema = useMemo(
// -1 matches no region: while the staffer's region is still loading the
// check passes vacuously (the backend enforces region scope regardless).
() => makeProductValidationSchema(regions, editingGlobalAsRegional ? (staffRegionId ?? -1) : null),
[regions, editingGlobalAsRegional, staffRegionId]
)
const { data: skusData } = trpc.common.product.getAllSkusSummary.useQuery()
const skuOptions = (skusData?.skus || []).map((sku) => ({
@ -193,6 +312,8 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
const formInitialValues = useMemo(() => {
return {
...initialValues,
availableInAllRegions: initialValues.availableInAllRegions ?? false,
storeIdsByRegion: initialValues.storeIdsByRegion ?? {},
variants: (initialValues.variants || []).map((v) => {
const hasQuantity = (v.features || []).some(
(a) => (a.featureName ?? '').trim().toLowerCase() === 'quantity'
@ -206,7 +327,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
return (
<Formik
initialValues={formInitialValues}
validationSchema={productValidationSchema}
validationSchema={validationSchema}
onSubmit={(values) => {
// Normalize feature names before sending to backend: the mandatory
// 'quantity' feature must always go out lowercase (case-insensitive
@ -252,8 +373,19 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
enableReinitialize
>
{({ handleChange, handleSubmit, values, setFieldValue, validateForm }) => {
// Name-match prefill source for the own-region store dropdown when a
// regional staffer edits a global product (the API sends no per-region
// store payload, so match by the product's current store name).
const editStoreName = allStores.find((s) => s.id === initialValues.storeId)?.name
return (
<ScrollView style={tw`flex-1`} contentContainerStyle={tw`px-4 pt-4 pb-10`} keyboardShouldPersistTaps="handled">
{editingGlobalAsRegional && (
<View style={tw`mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3`}>
<MyText style={tw`text-sm font-medium text-amber-800`}>
Global product — changes you save here apply to {staffRegionName} only.
</MyText>
</View>
)}
<MyTextInput
testID="product-name-input"
topLabel="Product Name"
@ -282,16 +414,46 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
onChangeText={handleChange('longDescription')}
style={{ marginBottom: 16 }}
/>
<BottomDropdown
testID="product-store-dropdown"
topLabel="Store"
label="Store"
value={values.storeId}
options={storeOptions}
onValueChange={(value) => setFieldValue('storeId', value)}
placeholder="Select store"
style={{ marginBottom: 16 }}
/>
{!values.availableInAllRegions ? (
<BottomDropdown
testID="product-store-dropdown"
topLabel="Store"
label="Store"
value={values.storeId}
options={storeOptions}
onValueChange={(value) => setFieldValue('storeId', value)}
placeholder="Select store"
style={{ marginBottom: 16 }}
/>
) : (
editableRegions.map((region) => {
const regionStores = storesForRegion(region.id)
return (
<View key={region.id}>
{regionStores.length === 0 && (
<MyText style={tw`text-xs text-red-500 mb-1`}>
Create a store for "{region.name}" before saving.
</MyText>
)}
<BottomDropdown
testID={`product-region-${region.id}-store-dropdown`}
topLabel={`Store — ${region.name}`}
label={`Store — ${region.name}`}
value={values.storeIdsByRegion?.[region.id] ?? ''}
options={regionStores}
onValueChange={(value) =>
setFieldValue(`storeIdsByRegion.${region.id}`, Number(value))
}
placeholder="Select store"
style={{ marginBottom: 16 }}
/>
</View>
)
})
)}
<RegionStorePrefill stores={allRegionsStores} regions={editableRegions} currentStoreName={editStoreName} />
<BottomDropdown
testID="product-type-dropdown"
@ -410,7 +572,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<MyTextInput
testID={`variant-${vIndex}-attr-${aIndex}-value`}
placeholder={isQuantityFeature(attr) ? 'e.g. 0.5 kg' : 'Value'}
value={attr.featureValue}
value={attr.featureValue ?? ''}
onChangeText={handleChange(`variants.${vIndex}.features.${aIndex}.featureValue`)}
/>
</View>
@ -546,6 +708,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View style={tw`flex-row justify-between items-center mb-2`}>
<MyText style={tw`font-medium text-gray-600`}>Included Items</MyText>
<TouchableOpacity
testID={`variant-${vIndex}-combo-add`}
onPress={() => {
const items = variant.comboItems || []
items.push({ skuId: 0 })
@ -561,6 +724,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<View key={cIndex} style={tw`flex-row items-center gap-2 mb-2`}>
<View style={tw`flex-1`}>
<BottomDropdown
testID={`variant-${vIndex}-combo-sku-${cIndex}`}
label="SKU"
value={ci.skuId}
options={skuOptions.map((opt: { label: string; value: number }) => ({

View file

@ -61,17 +61,19 @@ const TagForm = forwardRef<any, TagFormProps>(({
imageUrl: sku.images?.[0] || null,
}));
// Build the ordered list from initialValues.productIds (product ids, in sortOrder).
// Build the ordered list from initialValues.productIds.
// NOTE: product_tags.product_id references product_skus.id, so these are
// SKU ids (despite the legacy field name) — key the map by skuId.
useEffect(() => {
const ordered: SelectedProduct[] = [];
const skuMap = new Map<number, SelectedProduct>();
for (const sku of allSkus) {
skuMap.set(sku.productId, sku);
skuMap.set(sku.skuId, sku);
}
for (const productId of initialValues.productIds || []) {
const sku = skuMap.get(productId);
if (sku) ordered.push(sku);
else ordered.push({ skuId: 0, productId, label: `Product #${productId}`, imageUrl: null });
else ordered.push({ skuId: productId, productId, label: `Product #${productId}`, imageUrl: null });
}
setSelectedProducts(ordered);
// eslint-disable-next-line react-hooks/exhaustive-deps
@ -151,7 +153,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={(values) => onSubmit({ ...values, productIds: selectedProducts.map((p) => p.productId) }, images, removedExisting)}
onSubmit={(values) => onSubmit({ ...values, productIds: selectedProducts.map((p) => p.skuId) }, images, removedExisting)}
enableReinitialize
>
{({ handleChange, handleSubmit, values, setFieldValue, errors, touched, resetForm }) => {
@ -171,6 +173,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
return (
<View style={tw`p-4`}>
<MyTextInput
testID="tag-name-input"
topLabel="Tag Name"
placeholder="Enter tag name"
value={values.tagName}
@ -179,6 +182,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
/>
<MyTextInput
testID="tag-description-input"
topLabel="Description (Optional)"
placeholder="Enter tag description"
multiline
@ -195,6 +199,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
</MyText>
<ImageUploaderNeo
testID="tag-image-add"
images={images}
onImageAdd={(payload: ImageUploaderNeoPayload[]) => {
setImages((prev) => [...prev, ...payload.map((img) => ({
@ -215,6 +220,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
{/* Dashboard Tag Checkbox */}
<View style={tw`flex-row items-center mb-6`}>
<Checkbox
testID="tag-dashboard-checkbox"
checked={isDashboardTagChecked}
onPress={() => {
const newValue = !isDashboardTagChecked;
@ -231,6 +237,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
Related Stores
</MyText>
<BottomDropdown
testID="tag-stores-dropdown"
label="Select Related Stores"
placeholder="Select stores..."
value={values.relatedStores.map(id => id.toString())}
@ -252,6 +259,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
Products
</MyText>
<ProductsSelector
testID="tag-products-selector"
value={[]}
onChange={handleProductSelect}
multiple
@ -288,6 +296,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
</View>
<TouchableOpacity
testID="tag-submit-button"
onPress={() => handleSubmit()}
disabled={isLoading}
style={tw`px-4 py-3 rounded-lg shadow-lg items-center ${isLoading ? 'bg-gray-400' : 'bg-blue-500'}`}

View file

@ -45,6 +45,7 @@ const existingGroup: ProductGroup = {
id: 5,
groupName: 'Beef Box',
description: 'Bundle',
regionId: 1,
createdAt: '2024-01-01T00:00:00.000Z',
products: [{ id: 10 }, { id: 11 }],
productCount: 2,

View file

@ -25,7 +25,7 @@ export interface VendorSnippet {
// Vendor-snippet form row — anchored to the shared input (wire validTill);
// form requires slotId and carries the serialized createdAt.
export type VendorSnippetForm = Omit<AdminVendorSnippetInput, 'slotId'> & {
export type VendorSnippetForm = Omit<AdminVendorSnippetInput, 'slotId' | 'regionId'> & {
id: number;
slotId: number;
createdAt: string;

View file

@ -187,6 +187,8 @@ export default function BannerForm({
onChange={handleChange('redirectUrl')}
onBlur={handleBlur('redirectUrl')}
type="url"
autoCorrect="off"
autoCapitalize="none"
style={{ marginBottom: errors.redirectUrl && touched.redirectUrl ? 8 : 16 }}
/>
{errors.redirectUrl && touched.redirectUrl && (

View file

@ -97,6 +97,7 @@ export function MultiSelect({
}}
onSearch={onSearch}
className="mb-3"
testID={testID ? `${testID}-search` : undefined}
/>
<div className="overflow-y-auto" style={{ maxHeight: 320 }}>
{filtered.map((option) => {
@ -104,7 +105,7 @@ export function MultiSelect({
return (
<div
key={String(option.value)}
data-testid="multiselect-option"
data-testid={testID ? `${testID}-option-${option.value}` : undefined}
onClick={() => {
if (!option.disabled) toggle(option.value)
}}
@ -138,6 +139,7 @@ export function MultiSelect({
<button
type="button"
onClick={() => setOpen(false)}
data-testid={testID ? `${testID}-done` : undefined}
className="flex-1 p-3 rounded-lg bg-blue-500 text-white text-center font-semibold text-sm"
>
Done

View file

@ -1,7 +1,7 @@
import React from 'react'
import { p as P, BottomDialog, Checkbox } from 'web-components'
import { trpc } from '@/lib/trpc-client'
import { ChevronRight, Eye, Pencil, XCircle, MapPin, Map, MessageCircle, Phone } from 'lucide-react'
import { ChevronRight, Eye, Pencil, XCircle, MapPin, Map, MessageCircle, Phone, PartyPopper } from 'lucide-react'
interface OrderOptionsMenuProps {
open: boolean
@ -19,6 +19,7 @@ interface OrderOptionsMenuProps {
latitude?: number | null
longitude?: number | null
status?: string
isFirstOrder?: boolean
}
onViewDetails: () => void
onTogglePackaged: () => void
@ -89,6 +90,20 @@ export function OrderOptionsMenu({
}
}
const { data: constants } = trpc.admin.const.getConstants.useQuery()
const welcomeMessage = constants?.find((c) => c.key === 'welcomeMessage')?.value
const handleWelcomeWhatsApp = () => {
const phone = extractPhone(order.address)
if (!phone) {
window.alert('No phone number found')
return
}
const message = welcomeMessage ? String(welcomeMessage) : ''
const text = message ? `&text=${encodeURIComponent(message)}` : ''
window.open(`https://wa.me/91${phone}${text}`, '_blank')
}
const handleDial = () => {
const phone = extractPhone(order.address)
if (phone) {
@ -319,6 +334,31 @@ export function OrderOptionsMenu({
</div>
<ChevronRight className="h-6 w-6 text-gray-400 ml-auto" />
</button>
{order.isFirstOrder && (
<button
type="button"
data-testid="send-welcome-msg"
onClick={() => {
handleWelcomeWhatsApp()
onClose()
}}
className="flex flex-row items-center p-4 bg-emerald-50 border border-emerald-200 rounded-xl mb-3 shadow-sm w-full text-left"
>
<div className="w-10 h-10 rounded-full bg-emerald-100 items-center justify-center mr-4 flex shrink-0">
<PartyPopper className="h-5 w-5 text-emerald-600" />
</div>
<div>
<P className="font-semibold text-emerald-800 text-base block">
Send Welcome Msg
</P>
<P className="text-emerald-600 text-xs block">
First order — welcome the customer on WhatsApp
</P>
</div>
<ChevronRight className="h-6 w-6 text-gray-400 ml-auto" />
</button>
)}
</div>
</div>
</div>

View file

@ -1,5 +1,5 @@
import { useState, useImperativeHandle, forwardRef, useMemo } from 'react'
import { Formik, FieldArray } from 'formik'
import { useState, useImperativeHandle, forwardRef, useMemo, useEffect } from 'react'
import { Formik, FieldArray, useFormikContext } from 'formik'
import * as Yup from 'yup'
import { pInput as PInput, Dropdown, p as P, Checkbox, BottomDialog, ImageUploaderNeo } from 'web-components'
import type { ImageUploaderNeoItem, ImageUploaderNeoPayload } from 'web-components'
@ -35,6 +35,9 @@ interface ProductFormData {
name: string
shortDescription: string
longDescription: string
regionId?: number | null
availableInAllRegions?: boolean
storeIdsByRegion?: Record<number, number>
storeId: number
productType: 'item' | 'combo'
variants: Variant[]
@ -99,9 +102,36 @@ const variantSignature = (attributes: Attribute[]): string =>
.sort()
.join('|')
const makeProductValidationSchema = (regions: RegionOption[]) =>
productValidationSchema.concat(
Yup.object().shape({
storeIdsByRegion: Yup.mixed().test(
'store-every-region',
'Store is required for every region',
function (value: any) {
if (this.parent?.availableInAllRegions !== true) return true
const map: Record<number, number> = value ?? {}
for (const region of regions) {
const storeId = map[region.id]
if (storeId == null || Number(storeId) < 1) {
return this.createError({
message: `Create a store for "${region.name}" before saving`,
})
}
}
return true
}
),
})
)
const productValidationSchema = Yup.object().shape({
name: Yup.string().required('Product name is required'),
storeId: Yup.number().required('Store is required').min(1, 'Store is required'),
storeId: Yup.number().when('availableInAllRegions', {
is: false,
then: (schema) => schema.required('Store is required').min(1, 'Store is required'),
otherwise: (schema) => schema.notRequired().nullable(),
}),
productType: Yup.string().oneOf(['item', 'combo'], 'Product type is required').required('Product type is required'),
variants: Yup.array()
.min(1, 'At least one variant is required')
@ -176,6 +206,39 @@ const collectErrorMessages = (errors: unknown, depth = 0): string[] => {
return []
}
type RegionStoreOption = { id: number; name: string; regionId?: number }
type RegionOption = { id: number; name: string }
// On edit, an all-regions product has no per-region store payload from the API,
// so fill each region with the store whose name matches the current product store.
const RegionStorePrefill = ({
stores,
regions,
currentStoreName,
}: {
stores: RegionStoreOption[]
regions: RegionOption[]
currentStoreName?: string
}) => {
const { values, setFieldValue } = useFormikContext<ProductFormData>()
useEffect(() => {
if (!values.availableInAllRegions || !currentStoreName) return
if (stores.length === 0 || regions.length === 0) return
const next: Record<number, number> = { ...(values.storeIdsByRegion ?? {}) }
let changed = false
for (const region of regions) {
if (next[region.id] != null) continue
const match = stores.find((store) => store.regionId === region.id && store.name === currentStoreName)
if (match) {
next[region.id] = match.id
changed = true
}
}
if (changed) setFieldValue('storeIdsByRegion', next)
}, [stores, regions, currentStoreName, values.availableInAllRegions, values.storeIdsByRegion, setFieldValue])
return null
}
const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
mode,
initialValues,
@ -194,11 +257,36 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
clearImages: () => setVariantImages(initialValues.variants.map(() => [])),
}), [initialValues.variants])
const { data: storesData } = trpc.common.getStoresSummary.useQuery()
const storeOptions = storesData?.stores.map((store) => ({
label: store.name,
value: store.id,
})) || []
// All-region products are managed from superadmin-ui only: the flag is
// hidden here, and edits to such products are read-only in this app.
const isAllRegionsProduct = !!initialValues.availableInAllRegions
const { data: storesData } = trpc.admin.store.getStores.useQuery()
const allStores: RegionStoreOption[] = useMemo(
() => (storesData?.stores || []) as RegionStoreOption[],
[storesData]
)
const storeOptions = useMemo(
() => allStores.map((store) => ({ label: store.name, value: store.id })),
[allStores]
)
const { data: allRegionsStoresData } = trpc.admin.store.getStoresForAllRegions.useQuery()
const allRegionsStores: RegionStoreOption[] = useMemo(
() => (allRegionsStoresData?.stores || []) as RegionStoreOption[],
[allRegionsStoresData]
)
const storesForRegion = (regionId: number) =>
allRegionsStores
.filter((store) => store.regionId === regionId)
.map((store) => ({ label: store.name, value: store.id }))
const { data: regionsData } = trpc.admin.region.getRegions.useQuery()
const regions: RegionOption[] = useMemo(
() => (regionsData?.regions || []).map((region) => ({ id: region.id, name: region.name })),
[regionsData]
)
const validationSchema = useMemo(() => makeProductValidationSchema(regions), [regions])
const { data: skusData } = trpc.common.product.getAllSkusSummary.useQuery()
const skuOptions = (skusData?.skus || []).map((sku) => ({
@ -211,6 +299,8 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
const formInitialValues = useMemo(() => {
return {
...initialValues,
availableInAllRegions: initialValues.availableInAllRegions ?? false,
storeIdsByRegion: initialValues.storeIdsByRegion ?? {},
variants: (initialValues.variants || []).map((v) => {
const hasQuantity = (v.features || []).some(
(a) => (a.featureName ?? '').trim().toLowerCase() === 'quantity'
@ -224,7 +314,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
return (
<Formik
initialValues={formInitialValues}
validationSchema={productValidationSchema}
validationSchema={validationSchema}
onSubmit={(values) => {
// Normalize feature names before sending to backend: the mandatory
// 'quantity' feature must always go out lowercase (case-insensitive
@ -272,12 +362,20 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
{({ handleChange, handleSubmit, values, setFieldValue, validateForm }) => {
return (
<div className="flex-1 overflow-auto pb-10">
{isAllRegionsProduct && (
<div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3">
<p className="text-sm font-medium text-amber-800">
This product serves all regions and is managed from superadmin. Changes here are disabled.
</p>
</div>
)}
<PInput
topLabel="Product Name"
placeholder="Enter product name"
value={values.name}
onChange={handleChange('name')}
style={{ marginBottom: 16 }}
data-testid="product-name-input"
/>
<PInput
topLabel="Short Description"
@ -287,6 +385,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
value={values.shortDescription}
onChange={handleChange('shortDescription')}
style={{ marginBottom: 16 }}
data-testid="product-short-description-input"
/>
<PInput
topLabel="Long Description"
@ -296,19 +395,50 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
value={values.longDescription}
onChange={handleChange('longDescription')}
style={{ marginBottom: 16 }}
data-testid="product-long-description-input"
/>
<div className="mb-4" data-testid="product-store-select">
<P className="mb-1 text-sm text-gray-500 font-medium">Store</P>
<Dropdown
label="Select store"
value={values.storeId}
options={storeOptions}
onValueChange={(value) => setFieldValue('storeId', Number(value))}
className="w-full"
/>
</div>
<div className="mb-4" data-testid="product-type-select">
{!values.availableInAllRegions ? (
<div className="mb-4">
<P className="mb-1 text-sm text-gray-500 font-medium">Store</P>
<Dropdown
label="Select store"
value={values.storeId}
options={storeOptions}
onValueChange={(value) => setFieldValue('storeId', Number(value))}
className="w-full"
testID="product-store-dropdown"
/>
</div>
) : (
regions.map((region) => {
const regionStores = storesForRegion(region.id)
return (
<div key={region.id} className="mb-4">
<P className="mb-1 text-sm text-gray-500 font-medium">Store — {region.name}</P>
{regionStores.length === 0 && (
<p className="mb-1 text-xs text-red-500">
Create a store for "{region.name}" before saving.
</p>
)}
<Dropdown
label="Select store"
value={values.storeIdsByRegion?.[region.id] ?? ''}
options={regionStores}
onValueChange={(value) =>
setFieldValue(`storeIdsByRegion.${region.id}`, Number(value))
}
className="w-full"
testID={`product-region-${region.id}-store-dropdown`}
/>
</div>
)
})
)}
<RegionStorePrefill stores={allRegionsStores} regions={regions} currentStoreName={undefined} />
<div className="mb-4">
<P className="mb-1 text-sm text-gray-500 font-medium">Product Type</P>
<Dropdown
label="Select product type"
@ -319,6 +449,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
]}
onValueChange={(value) => setFieldValue('productType', value as 'item' | 'combo')}
className="w-full"
testID="product-type-dropdown"
/>
</div>
@ -329,6 +460,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<P className="text-lg font-bold text-gray-800">Variants</P>
<button
type="button"
data-testid="add-variant-button"
onClick={() => {
push(defaultVariant())
setVariantImages((prev) => [...prev, []])
@ -357,6 +489,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
{(values.variants.length > 1 || isExistingSku) && (
<button
type="button"
data-testid={`variant-${vIndex}-remove`}
onClick={() => {
if (isExistingSku) {
// Mark existing SKU as deleted (sent to backend on save).
@ -383,6 +516,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
value={variant.name ?? ''}
onChange={handleChange(`variants.${vIndex}.name`)}
style={{ marginBottom: 12 }}
data-testid={`variant-${vIndex}-sku-name`}
/>
<FieldArray name={`variants.${vIndex}.features`}>
@ -411,6 +545,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<PInput
placeholder="Name"
value={attr.featureName ?? ''}
data-testid={`variant-${vIndex}-attr-${aIndex}-name`}
onChange={(e) =>
setFieldValue(
`variants.${vIndex}.features.${aIndex}.featureName`,
@ -425,6 +560,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<PInput
placeholder={isQuantityFeature(attr) ? 'e.g. 0.5 kg' : 'Value'}
value={attr.featureValue}
data-testid={`variant-${vIndex}-attr-${aIndex}-value`}
onChange={handleChange(`variants.${vIndex}.features.${aIndex}.featureValue`)}
/>
</div>
@ -461,6 +597,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
placeholder="MRP"
type="number"
inputMode="numeric"
data-testid={`variant-${vIndex}-market-price`}
value={variant.marketPrice?.toString() ?? ''}
onChange={handleChange(`variants.${vIndex}.marketPrice`)}
/>
@ -471,6 +608,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
placeholder="Selling price"
type="number"
inputMode="numeric"
data-testid={`variant-${vIndex}-price`}
value={variant.price?.toString() ?? ''}
onChange={handleChange(`variants.${vIndex}.price`)}
/>
@ -480,6 +618,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<div className="flex flex-row items-center mb-3">
<Checkbox
checked={variant.isFlashAvailable}
testID={`variant-${vIndex}-flash`}
onPress={() => {
setFieldValue(`variants.${vIndex}.isFlashAvailable`, !variant.isFlashAvailable)
if (variant.isFlashAvailable) setFieldValue(`variants.${vIndex}.flashPrice`, null)
@ -491,6 +630,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<div className="flex flex-row items-center mb-3">
<Checkbox
checked={variant.isOffer}
testID={`variant-${vIndex}-offer`}
onPress={() => setFieldValue(`variants.${vIndex}.isOffer`, !variant.isOffer)}
/>
<P className="text-gray-700 font-medium ml-3">Offer SKU</P>
@ -500,6 +640,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<div className="flex flex-row items-center mb-3">
<Checkbox
checked={variant.isComboOnly}
testID={`variant-${vIndex}-combo-only`}
onPress={() => setFieldValue(`variants.${vIndex}.isComboOnly`, !variant.isComboOnly)}
/>
<P className="text-gray-700 font-medium ml-3">Combo Only SKU</P>
@ -507,9 +648,10 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
)}
{mode === 'edit' && (
<div className="flex flex-row items-center mb-3" data-testid={`variant-suspend-row-${vIndex}`}>
<div className="flex flex-row items-center mb-3">
<Checkbox
checked={variant.isSuspended}
testID={`variant-${vIndex}-suspend`}
onPress={() => setFieldValue(`variants.${vIndex}.isSuspended`, !variant.isSuspended)}
/>
<P className="text-gray-700 font-medium ml-3">Suspend SKU</P>
@ -522,6 +664,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
placeholder="Enter flash price"
type="number"
inputMode="numeric"
data-testid={`variant-${vIndex}-flash-price`}
value={variant.flashPrice?.toString() ?? ''}
onChange={handleChange(`variants.${vIndex}.flashPrice`)}
style={{ marginBottom: 12 }}
@ -530,6 +673,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<ImageUploaderNeo
images={variantImages[vIndex] || []}
testID={`variant-${vIndex}-image-add`}
onImageAdd={(payloads) =>
setVariantImages((prev) => {
const next = [...prev]
@ -553,6 +697,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<P className="font-medium text-gray-600">Included Items</P>
<button
type="button"
data-testid={`variant-${vIndex}-combo-add`}
onClick={() => {
const items = variant.comboItems || []
items.push({ skuId: 0 })
@ -570,6 +715,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<SearchableSelect
label="SKU"
value={ci.skuId}
testID={`variant-${vIndex}-combo-sku-${cIndex}`}
options={skuOptions.map((opt: { label: string; value: number }) => ({
...opt,
// Disable SKUs already picked in another row of this combo.
@ -611,6 +757,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<button
type="button"
data-testid="add-variant-button-footer"
onClick={() => {
push(defaultVariant())
setVariantImages((prev) => [...prev, []])
@ -626,8 +773,12 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
<button
type="button"
data-testid="product-submit-button"
data-testid="create-product-button"
onClick={async () => {
if (isAllRegionsProduct) {
window.alert('This product serves all regions and can only be edited from superadmin.')
return
}
const validationErrors = await validateForm()
if (Object.keys(validationErrors).length > 0) {
const variantsMessages = collectErrorMessages(validationErrors.variants)
@ -638,7 +789,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
}
handleSubmit()
}}
disabled={isLoading}
disabled={isLoading || isAllRegionsProduct}
className={`px-4 py-3 rounded-lg shadow-lg items-center mt-4 text-white text-lg font-bold w-full disabled:opacity-70 ${isLoading ? 'bg-gray-400' : 'bg-blue-500'}`}
>
{(() => {

View file

@ -82,6 +82,7 @@ export function SearchableSelect({
}}
onSearch={onSearch}
className="mb-3"
testID={testID ? `${testID}-search` : undefined}
/>
<div className="overflow-y-auto" style={{ maxHeight: 320 }}>
{filtered.map((option) => {
@ -92,6 +93,7 @@ export function SearchableSelect({
type="button"
disabled={option.disabled}
onClick={() => handleSelect(option.value)}
data-testid={testID ? `${testID}-option-${option.value}` : undefined}
className={`flex flex-row items-center w-full p-3 border-b border-gray-100 text-left ${option.disabled ? 'opacity-50' : 'cursor-pointer hover:bg-gray-50'} ${selected ? 'bg-blue-50' : ''}`}
>
<span className={`text-sm flex-1 ${selected ? 'font-semibold text-blue-700' : 'text-gray-800'}`}>

View file

@ -180,6 +180,7 @@ export default function SlotForm({
<div className="mb-4">
<ProductsSelector
testID="snippet-products-selector"
value={snippet.skuIds || []}
onChange={(newSkuIds) => setFieldValue(`vendorSnippetList.${index}.skuIds`, newSkuIds)}
groups={mappedGroups.filter(group =>

View file

@ -42,7 +42,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
const initialSelectedProducts = useMemo(() => {
if (mode !== 'edit' || !productsData?.products) return []
return productsData.products
.filter(p => p.storeId === storeId)
.filter(p => p.store?.id === storeId)
.flatMap(p => (p.skus || []).map(sku => sku.id))
}, [mode, productsData?.products, storeId])
@ -133,6 +133,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
onChange={handleChange('name')}
error={!!(touched.name && errors.name)}
style={{ marginBottom: 16 }}
data-testid="store-name-input"
/>
<PInput
topLabel="Description"
@ -143,6 +144,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
onChange={handleChange('description')}
error={!!(touched.description && errors.description)}
style={{ marginBottom: 16 }}
data-testid="store-description-input"
/>
<div className="mb-4">
<P className="mb-1 text-sm text-gray-500 font-medium">Owner</P>
@ -152,6 +154,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
options={staffOptions}
onValueChange={(value) => setFieldValue('owner', Number(value))}
className="mb-4"
testID="store-owner-dropdown"
/>
</div>
<ProductsSelector
@ -162,6 +165,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
placeholder="Select products"
isDisabled={(sku) => sku.storeId !== null && sku.storeId !== storeId}
labelFormat={(sku) => `${sku.productName} - ₹${sku.price}`}
testID="store-products-selector"
/>
<div className="mb-6">
<P className="text-sm font-bold text-gray-700 mb-3 uppercase tracking-wider block">Store Image</P>
@ -183,6 +187,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
type="button"
onClick={submit}
disabled={isLoading || isUploading}
data-testid="store-submit-button"
className={`px-4 py-2 rounded-lg shadow-lg items-center mt-2 text-white text-lg font-bold w-full disabled:opacity-70 ${isLoading || isUploading ? 'bg-gray-400' : 'bg-blue-500'}`}
>
{isUploading ? 'Uploading...' : isLoading ? (mode === 'create' ? 'Creating...' : 'Updating...') : (mode === 'create' ? 'Create Store' : 'Update Store')}

View file

@ -118,17 +118,19 @@ const TagForm = forwardRef<any, TagFormProps>(({
imageUrl: sku.images?.[0] || null,
}))
// Build the ordered list from initialValues.productIds (product ids, in sortOrder).
// Build the ordered list from initialValues.productIds.
// NOTE: product_tags.product_id references product_skus.id, so these are
// SKU ids (despite the legacy field name) — key the map by skuId.
useEffect(() => {
const ordered: SelectedProduct[] = []
const skuMap = new Map<number, SelectedProduct>()
for (const sku of allSkus) {
skuMap.set(sku.productId, sku)
skuMap.set(sku.skuId, sku)
}
for (const productId of initialValues.productIds || []) {
const sku = skuMap.get(productId)
if (sku) ordered.push(sku)
else ordered.push({ skuId: 0, productId, label: `Product #${productId}`, imageUrl: null })
else ordered.push({ skuId: productId, productId, label: `Product #${productId}`, imageUrl: null })
}
setSelectedProducts(ordered)
// eslint-disable-next-line react-hooks/exhaustive-deps
@ -187,7 +189,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={(values) => onSubmit({ ...values, productIds: selectedProducts.map((prod) => prod.productId) }, images, removedExisting)}
onSubmit={(values) => onSubmit({ ...values, productIds: selectedProducts.map((prod) => prod.skuId) }, images, removedExisting)}
enableReinitialize
>
{({ handleChange, handleSubmit, values, setFieldValue, errors, touched, resetForm }) => {
@ -212,6 +214,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
value={values.tagName}
onChange={handleChange('tagName')}
style={{ marginBottom: 16 }}
data-testid="tag-name-input"
/>
{errors.tagName && touched.tagName ? (
<P className="text-red-500 text-sm -mt-2 mb-4 block">{errors.tagName}</P>
@ -225,6 +228,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
value={values.tagDescription}
onChange={handleChange('tagDescription')}
style={{ marginBottom: 16 }}
data-testid="tag-description-input"
/>
{errors.tagDescription && touched.tagDescription ? (
<P className="text-red-500 text-sm -mt-2 mb-4 block">{errors.tagDescription}</P>
@ -238,6 +242,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
<ImageUploaderNeo
images={images}
testID="tag-image-add"
onImageAdd={(payload: ImageUploaderNeoPayload[]) => {
setImages((prev) => [...prev, ...payload.map((img) => ({
imgUrl: img.url,
@ -258,6 +263,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
<div className="flex flex-row items-center mb-6">
<Checkbox
checked={isDashboardTagChecked}
testID="tag-dashboard-checkbox"
onPress={() => {
const newValue = !isDashboardTagChecked
setIsDashboardTagChecked(newValue)
@ -275,6 +281,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
<MultiSelect
label="Select Related Stores"
placeholder="Select stores..."
testID="tag-stores-dropdown"
value={values.relatedStores.map(id => id.toString())}
options={stores.map(store => ({
label: store.name,
@ -299,6 +306,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
label="Select Products"
placeholder="Search and select products..."
showGroups={false}
testID="tag-products-selector"
/>
<div className="mt-4">
{selectedProducts.length > 0 && (
@ -329,6 +337,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
type="button"
onClick={() => handleSubmit()}
disabled={isLoading}
data-testid="tag-submit-button"
className={`px-4 py-3 rounded-lg shadow-lg items-center text-white text-lg font-bold w-full disabled:opacity-70 ${isLoading ? 'bg-gray-400' : 'bg-blue-500'}`}
>
{isLoading ? (mode === 'create' ? 'Creating...' : 'Updating...') : (mode === 'create' ? 'Create Tag' : 'Update Tag')}

View file

@ -0,0 +1,10 @@
import { trpc } from '../lib/trpc-client'
/** True when the logged-in staff member is a super_admin (cached for the session). */
export function useIsSuperAdmin(): boolean {
const { data } = trpc.admin.staffUser.getSelf.useQuery(undefined, {
staleTime: Infinity,
retry: false,
})
return data?.staff?.roleName === 'super_admin'
}

View file

@ -31,6 +31,7 @@ const CONST_LABELS: Record<string, string> = {
isFlashDeliveryEnabled: 'Enable Flash Delivery',
supportMobile: 'Support Mobile',
supportEmail: 'Support Email',
internalAppVersion: 'Internal App Version',
welcomeMessage: 'Welcome Message',
}
@ -40,20 +41,21 @@ const CONST_VISIBILITY: Record<string, boolean> = {
deliveryCharge: true,
flashFreeDeliveryThreshold: true,
flashDeliveryCharge: true,
platformFeePercent: true,
platformFeePercent: false,
taxRate: false,
minOrderAmountForCoupon: true,
minOrderAmountForCoupon: false,
maxCouponDiscount: false,
flashDeliverySlotId: true,
flashDeliverySlotId: false,
readableOrderId: false,
versionNum: true,
playStoreUrl: true,
appStoreUrl: true,
popularItems: true,
versionNum: false,
playStoreUrl: false,
appStoreUrl: false,
popularItems: false,
allItemsOrder: true,
isFlashDeliveryEnabled: true,
supportMobile: true,
supportEmail: true,
internalAppVersion: false,
welcomeMessage: true,
tester: false,
}
@ -190,7 +192,24 @@ function CustomizeApp() {
const router = {
push: (to: string) => navigate({ to: to as any }),
}
const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery()
const [activeBoundId, setActiveBoundId] = React.useState<number | null>(null)
const [boundsReady, setBoundsReady] = React.useState(false)
const { data: boundsData } = trpc.admin.region.getMyRegionBounds.useQuery(undefined, {
staleTime: Infinity,
})
const bounds = boundsData?.bounds ?? []
React.useEffect(() => {
if (!boundsReady && bounds.length > 0) {
setActiveBoundId(bounds[0].id)
setBoundsReady(true)
}
}, [bounds, boundsReady])
const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery(
activeBoundId != null ? { boundId: activeBoundId } : undefined,
{ enabled: boundsReady || bounds.length === 0 }
)
const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation()
const handleSubmit = (values: ConstantFormData) => {
@ -208,7 +227,10 @@ function CustomizeApp() {
}
updateConstants(
{ constants: changedConstants },
{
constants: changedConstants,
...(activeBoundId != null ? { boundId: activeBoundId } : {}),
},
{
onSuccess: (response) => {
window.alert(`Updated ${response.updatedCount} constants successfully.`)
@ -251,7 +273,26 @@ function CustomizeApp() {
Modify application constants. Changes will take effect immediately.
</MyText>
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
{bounds.length > 0 && (
<div className="mb-6 flex flex-row flex-wrap" data-testid="const-bound-tabs">
{bounds.map((bound, index) => {
const active = bound.id === activeBoundId
return (
<button
key={bound.id}
type="button"
data-testid={`const-bound-tab-${bound.id}`}
onClick={() => setActiveBoundId(bound.id)}
className={`mr-2 mb-2 rounded-full border px-4 py-2 text-sm font-semibold ${active ? 'border-blue-500 bg-blue-500 text-white' : 'border-gray-200 bg-white text-gray-700'}`}
>
{bound.name || `Bound ${index + 1}`}{index === 0 ? ' (Default)' : ''}
</button>
)
})}
</div>
)}
<Formik key={activeBoundId ?? 'region'} initialValues={initialValues} onSubmit={handleSubmit}>
{({ handleSubmit, values, setFieldValue }) => (
<div>
{constants.map((constant) => {

View file

@ -392,6 +392,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)}

View file

@ -61,7 +61,8 @@ interface OrderWithSequence {
addressId: number,
adminNotes?: string | null,
customerName?: string | null,
assignedUserName?: string | null
assignedUserName?: string | null,
isFirstOrder?: boolean
}
interface SlotProgressProps {
@ -721,6 +722,7 @@ function DeliverySequences() {
adminNotes: selectedOrder?.adminNotes || null,
latitude: selectedOrder?.latitude || null,
longitude: selectedOrder?.longitude || null,
isFirstOrder: selectedOrder?.isFirstOrder,
}}
onViewDetails={() => {
if (selectedOrder) {

View file

@ -200,7 +200,7 @@ function PricesOverview() {
for (const product of allProducts) {
if (product.skus && product.skus.length > 0) {
for (const sku of product.skus) {
skus.push({ ...sku, _productName: product.name, _storeId: product.storeId })
skus.push({ ...sku, _productName: product.name, _storeId: product.store?.id })
}
}
}

View file

@ -37,6 +37,9 @@ function EditProduct() {
name: '',
shortDescription: '',
longDescription: '',
regionId: undefined as number | undefined,
availableInAllRegions: false,
storeIdsByRegion: {} as Record<number, number>,
storeId: 0,
productType: 'item' as const,
variants: [],
@ -46,7 +49,10 @@ function EditProduct() {
name: productData.name,
shortDescription: productData.shortDescription || '',
longDescription: productData.longDescription || '',
storeId: productData.storeId || 1,
regionId: productData.regionId,
availableInAllRegions: productData.availableInAllRegions ?? false,
storeIdsByRegion: {} as Record<number, number>,
storeId: productData.store?.id ?? 1,
productType: (productData.productType as 'item' | 'combo') || 'item',
variants: (productData.skus || []).map((sku) => ({
id: sku.id,
@ -169,17 +175,30 @@ function EditProduct() {
}
})
const storeIdsByRegion = Object.entries(values.storeIdsByRegion || {}).reduce(
(acc, [regionId, storeId]) => {
const sid = Number(storeId)
if (Number.isFinite(sid) && sid > 0) acc[Number(regionId)] = sid
return acc
},
{} as Record<number, number>
)
await updateProduct.mutateAsync({
id: productId,
name: values.name,
shortDescription: values.shortDescription || undefined,
longDescription: values.longDescription || undefined,
storeId: values.storeId,
regionId: values.regionId,
productType: values.productType,
incrementStep: 1,
skus,
deletedImageKeys,
newImageUrls: allUploadUrls,
availableInAllRegions: !!values.availableInAllRegions,
...(values.availableInAllRegions
? { storeIdsByRegion }
: { storeId: values.storeId }),
} as any)
await refetch()

View file

@ -91,14 +91,26 @@ function AddProduct() {
}
})
const storeIdsByRegion = Object.entries(values.storeIdsByRegion || {}).reduce(
(acc, [regionId, storeId]) => {
const sid = Number(storeId)
if (Number.isFinite(sid) && sid > 0) acc[Number(regionId)] = sid
return acc
},
{} as Record<number, number>
)
await createProduct.mutateAsync({
name: values.name,
shortDescription: values.shortDescription || undefined,
longDescription: values.longDescription || undefined,
storeId: values.storeId,
productType: values.productType,
incrementStep: 1,
skus,
availableInAllRegions: !!values.availableInAllRegions,
...(values.availableInAllRegions
? { storeIdsByRegion }
: { storeId: values.storeId }),
})
await refetchProducts()
@ -112,6 +124,9 @@ function AddProduct() {
name: '',
shortDescription: '',
longDescription: '',
regionId: undefined as number | undefined,
availableInAllRegions: false,
storeIdsByRegion: {} as Record<number, number>,
storeId: 1,
productType: 'item' as const,
variants: [

View file

@ -124,7 +124,7 @@ function Products() {
<>
<div className="mb-6 flex flex-row items-center justify-between">
<MyText className="text-2xl font-bold text-gray-800">Products</MyText>
<MyButton onClick={() => navigate({ to: '/dashboard/products/new' })}>
<MyButton onClick={() => navigate({ to: '/dashboard/products/new' })} data-testid="add-product-button">
Add Product
</MyButton>
</div>

View file

@ -201,6 +201,7 @@ function SlotDetails() {
<button
onClick={() => navigate({ to: '/dashboard/slots/$id/edit', params: { id: String(slot.id) } })}
aria-label="Edit slot"
data-testid="edit-slot-fab"
className="fixed flex h-16 w-16 items-center justify-center rounded-[24px] shadow-lg"
style={{ bottom: 32, right: 24, zIndex: 100, background: 'linear-gradient(135deg,#F83758,#E91E63)' }}
>

View file

@ -25,7 +25,7 @@ export interface VendorSnippet {
// Vendor-snippet form row — anchored to the shared input (wire validTill);
// form requires slotId and carries the serialized createdAt.
export type VendorSnippetForm = Omit<AdminVendorSnippetInput, 'slotId'> & {
export type VendorSnippetForm = Omit<AdminVendorSnippetInput, 'slotId' | 'regionId'> & {
id: number;
slotId: number;
createdAt: string;

View file

@ -1,4 +1,4 @@
bunx wrangler d1 execute --remote freshyo-backend-dev --file=../../packages/db_helper_sqlite/drizzle/0004_staff_notif_creds.sql --config wrangler.dev.toml
bunx wrangler d1 execute freshyo-backend-dev --file=../../packages/db_helper_sqlite/drizzle/0004_staff_notif_creds.sql --config wrangler.dev.toml
bunx wrangler d1 execute freshyo-dev --file=../../packages/db_helper_sqlite/drizzle/0006_regions.sql --config wrangler.dev.toml
I've created the both namespaces. show the option in all places where an order has a kebab menu in admin app.

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -2,10 +2,8 @@ import 'dotenv/config';
import { serve } from '@hono/node-server';
import initFunc from '@/src/lib/init';
import { createApp } from '@/src/app'
import { seed } from '@/src/lib/seed';
import '@/src/jobs/jobs-index';
seed()
initFunc()
const app = createApp()

View file

@ -0,0 +1,73 @@
-- ============================================================
-- delete-orders-before.sql
--
-- Deletes every order created BEFORE the cutoff below, together
-- with its dependent rows (coupon usage, complaints, incidents,
-- payments, refunds, status, items).
--
-- HOW TO USE
-- 1. Edit the cutoff date in the helper step below (single place).
-- 2. Run (remote):
-- bunx wrangler d1 execute <db-name> --remote --config <wrangler.toml> \
-- --file scripts/delete-orders-before.sql
-- (omit --remote for the local dev DB.)
--
-- DATE FORMAT — orders.created_at is stored as an ISO-8601 string,
-- e.g. '2025-12-24T02:50:33.284Z'. Accepted cutoff values:
-- * Date only : 'YYYY-MM-DD' e.g. '2026-01-01' <-- recommended
-- * Full timestamp : 'YYYY-MM-DDTHH:MM:SS.sssZ' e.g. '2026-01-01T00:00:00.000Z'
-- * Space format : 'YYYY-MM-DD HH:MM:SS' e.g. '2026-01-01 00:00:00'
-- Where the placeholders mean, in order left to right:
-- YYYY = year (2026-01-01 -> 2026)
-- MM = month (01-12) e.g. Jan = 01, Feb = 02, Mar = 03, Apr = 04,
-- DD = day of month (01-31)
-- HH = hour 00-23, MM = minutes, SS = seconds
-- Example: 25 March 2024 is written '2024-03-25'.
-- Rows strictly EARLIER than the value are removed.
--
-- WARNING: destructive and NOT reversible. Back up first:
-- bunx wrangler d1 export <db-name> --remote --output dumps/backup.sql
-- ============================================================
-- Helper: capture the targeted orders once, so the cutoff appears in ONE place.
-- (Dropped at the end; dropped first too, so a re-run never reuses stale ids.)
DROP TABLE IF EXISTS `_old_orders`;
CREATE TABLE `_old_orders` AS
SELECT `id`, `payment_info_id` FROM `orders`
WHERE `created_at` < '2026-08-28'; -- <<< EDIT THE CUTOFF DATE HERE
-- 1) coupon_usage references both orders and order_items -> delete first.
DELETE FROM `coupon_usage`
WHERE `order_id` IN (SELECT `id` FROM `_old_orders`)
OR `order_item_id` IN (
SELECT `id` FROM `order_items`
WHERE `order_id` IN (SELECT `id` FROM `_old_orders`)
);
--> statement-breakpoint
-- 2) remaining direct children of orders.
DELETE FROM `complaints` WHERE `order_id` IN (SELECT `id` FROM `_old_orders`);
--> statement-breakpoint
DELETE FROM `user_incidents` WHERE `order_id` IN (SELECT `id` FROM `_old_orders`);
--> statement-breakpoint
DELETE FROM `payments` WHERE `order_id` IN (SELECT `id` FROM `_old_orders`);
--> statement-breakpoint
DELETE FROM `refunds` WHERE `order_id` IN (SELECT `id` FROM `_old_orders`);
--> statement-breakpoint
DELETE FROM `order_status` WHERE `order_id` IN (SELECT `id` FROM `_old_orders`);
--> statement-breakpoint
-- 3) order_items (no longer referenced by coupon_usage).
DELETE FROM `order_items` WHERE `order_id` IN (SELECT `id` FROM `_old_orders`);
--> statement-breakpoint
-- 4) the orders.
DELETE FROM `orders` WHERE `id` IN (SELECT `id` FROM `_old_orders`);
--> statement-breakpoint
-- 5) OPTIONAL: remove now-orphaned payment_info rows. Comment out to keep them.
DELETE FROM `payment_info`
WHERE `id` IN (SELECT `payment_info_id` FROM `_old_orders` WHERE `payment_info_id` IS NOT NULL);
--> statement-breakpoint
DROP TABLE IF EXISTS `_old_orders`;

View file

@ -1,58 +0,0 @@
import { Context } from 'hono';
import { scaffoldAssetUrl } from "@/src/lib/s3-client"
import { getNextDeliveryDate } from "@/src/trpc/apis/common-apis/common"
import {
getAllProductsWithUnits,
type ProductSummaryData,
} from "@/src/dbService"
/**
* Get all products summary for dropdown
*/
export const getAllProductsSummary = async (c: Context) => {
try {
const tagId = c.req.query('tagId');
const tagIdNum = tagId ? parseInt(tagId) : undefined;
// If tagId is provided but no products found, return empty array
if (tagIdNum) {
const products = await getAllProductsWithUnits(tagIdNum);
if (products.length === 0) {
return c.json({
products: [],
count: 0,
}, 200);
}
}
const productsWithUnits = await getAllProductsWithUnits(tagIdNum);
// Generate signed URLs for product images
const formattedProducts = await Promise.all(
productsWithUnits.map(async (product: ProductSummaryData) => {
const nextDeliveryDate = await getNextDeliveryDate(product.id);
return {
id: product.id,
name: product.name,
shortDescription: product.shortDescription,
price: product.price,
marketPrice: product.marketPrice,
unit: product.unitShortNotation,
productQuantity: product.productQuantity,
isOutOfStock: product.isOutOfStock,
nextDeliveryDate: nextDeliveryDate ? nextDeliveryDate.toISOString() : null,
images: scaffoldAssetUrl((product.images as string[]) || []),
};
})
);
return c.json({
products: formattedProducts,
count: formattedProducts.length,
}, 200);
} catch (error) {
console.error("Get products summary error:", error);
return c.json({ error: "Failed to fetch products summary" }, 500);
}
};

View file

@ -1,10 +0,0 @@
import { Hono } from 'hono';
import { getAllProductsSummary } from "@/src/apis/common-apis/apis/common-product.controller"
const router = new Hono();
router.get("/summary", getAllProductsSummary);
const commonProductsRouter= router;
export default commonProductsRouter;

View file

@ -1,10 +0,0 @@
import { Hono } from 'hono';
import commonProductsRouter from "@/src/apis/common-apis/apis/common-product.router"
const router = new Hono();
router.route('/products', commonProductsRouter)
const commonRouter = router;
export default commonRouter;

View file

@ -3,7 +3,7 @@ import type { Context } from 'hono'
import { cors } from 'hono/cors'
import { logger } from 'hono/logger'
import { trpcServer } from '@hono/trpc-server'
import { getStaffUserById, isUserSuspended } from '@/src/dbService'
import { getStaffUserById, getStaffRoleById, getSuperadminById, isUserSuspended } from '@/src/dbService'
import mainRouter from '@/src/main-router'
import { appRouter } from '@/src/trpc/router'
import { TRPCError } from '@trpc/server'
@ -30,6 +30,7 @@ export const createApp = () => {
createContext: async ({ req }, c) => {
let user = null
let staffUser = null
let superadmin = null
const authHeader = req.headers.get('authorization')
const callerInterface = req.headers.get('caller-interface')
@ -57,15 +58,29 @@ export const createApp = () => {
const decoded = payload as any
// Check if this is a staff token (has staffId)
if (decoded.staffId) {
if (decoded.superadminId) {
// This is a superadmin token, verify the row exists
const row = await getSuperadminById(decoded.superadminId)
if (row) {
superadmin = {
id: row.id,
name: row.name,
}
}
} else if (decoded.staffId) {
// This is a staff token, verify staff exists
const staff = await getStaffUserById(decoded.staffId)
if (staff) {
const role = staff.staffRoleId != null ? await getStaffRoleById(staff.staffRoleId) : null
user = staffUser
staffUser = {
id: staff.id,
name: staff.name,
regionId: staff.regionId,
staffRoleId: staff.staffRoleId ?? null,
staffRoleName: role?.roleName ?? null,
}
}
} else {
@ -86,7 +101,7 @@ export const createApp = () => {
// Invalid token, both user and staffUser remain null
}
}
return { req, c, user, staffUser, callerInterface }
return { req, c, user, staffUser, superadmin, callerInterface }
},
onError({ error, path, type, ctx }) {
console.error('🚨 tRPC Error :', {

View file

@ -24,6 +24,7 @@ export type {
UserMiniInfo,
Store,
StaffUser,
Superadmin,
StaffRole,
AdminOrderRow,
AdminOrderDetails,

View file

@ -3,7 +3,12 @@ import { initializeAllStores } from '@/src/stores/store-initializer'
import { ensureWorkerInit } from '@/src/lib/worker-init'
const LAST_TRIGGER_KEY = 'lastTrigger'
const FIRST_TRIGGER_KEY = 'firstTrigger'
const ALARM_DELAY_MINUTES = 0.5
// Upper bound on debounce deferral: bursts of admin writes must not push
// regeneration out forever. The alarm forces a run when the oldest pending
// trigger is older than this.
const MAX_DEFER_MINUTES = 5
// const ALARM_DELAY_MINUTES = 0.1
export class CacheCreator {
@ -18,19 +23,14 @@ export class CacheCreator {
async schedule(): Promise<void> {
console.log( 'from the fetch method of durable object')
// if (request.method === 'POST' && url.pathname === '/schedule') {
const now = Date.now()
await this.state.storage.put(LAST_TRIGGER_KEY, now)
const first = await this.state.storage.get(FIRST_TRIGGER_KEY)
if (!first) {
await this.state.storage.put(FIRST_TRIGGER_KEY, now)
}
const alarmAt = dayjs(now).add(ALARM_DELAY_MINUTES, 'minute').valueOf()
await this.state.storage.setAlarm(alarmAt)
// return new Response('OK')
// }
// if (request.method === 'POST' && url.pathname === '/clear') {
await this.state.storage.deleteAll()
// return new Response('OK')
// }
// return new Response('CacheCreator ready', { status: 200 })
}
@ -39,6 +39,10 @@ export class CacheCreator {
if (request.method === 'POST' && url.pathname === '/schedule') {
const now = Date.now()
await this.state.storage.put(LAST_TRIGGER_KEY, now)
const first = await this.state.storage.get(FIRST_TRIGGER_KEY)
if (!first) {
await this.state.storage.put(FIRST_TRIGGER_KEY, now)
}
const alarmAt = dayjs(now).add(ALARM_DELAY_MINUTES, 'minute').valueOf()
await this.state.storage.setAlarm(alarmAt)
return new Response('OK')
@ -60,10 +64,20 @@ export class CacheCreator {
}
const threshold = dayjs().subtract(ALARM_DELAY_MINUTES, 'minute')
const isQualify = dayjs(lastTrigger).isBefore(threshold);
console.log({isQualify, threshold, curr: dayjs(lastTrigger)})
const firstTrigger = await this.state.storage.get(FIRST_TRIGGER_KEY)
const forcedByMaxDefer = firstTrigger != null &&
dayjs(firstTrigger).isBefore(dayjs().subtract(MAX_DEFER_MINUTES, 'minute'))
const isQualify = dayjs(lastTrigger).isBefore(threshold) || forcedByMaxDefer;
console.log({isQualify, forcedByMaxDefer, threshold, curr: dayjs(lastTrigger)})
if (isQualify) {
await initializeAllStores()
await this.state.storage.delete(FIRST_TRIGGER_KEY)
await this.state.storage.delete(LAST_TRIGGER_KEY)
try {
await initializeAllStores()
console.log('CacheCreator alarm: store initialization completed')
} catch (error) {
console.error('CacheCreator alarm: store initialization failed:', error)
}
}
}
}

View file

@ -14,8 +14,8 @@ export async function notifyAllAdmins(payload: {
body: string
imageUrl?: string | null
orderId?: number | null
}): Promise<number> {
const tokens = (await getAllStaffNotifTokens()).map((t) => t.token)
}, regionId?: number | null): Promise<number> {
const tokens = (await getAllStaffNotifTokens(regionId ?? undefined)).map((t) => t.token)
let queuedCount = 0
for (let i = 0; i < tokens.length; i += TOKENS_PER_QUEUE_MESSAGE) {

View file

@ -5,29 +5,35 @@ import { scaffoldStores } from '@/src/trpc/apis/user-apis/apis/stores'
import { scaffoldSlotsWithProducts } from '@/src/trpc/apis/user-apis/apis/slots'
import { scaffoldBanners } from '@/src/trpc/apis/user-apis/apis/banners'
import { scaffoldStoreWithProducts } from '@/src/trpc/apis/user-apis/apis/stores'
import { getStoresSummary, incrementCacheVersion, incrementAvailabilityVersionNum, incrementSlotsVersionNum } from '@/src/dbService'
import { getStoresSummary, getRegions, incrementCacheVersion, incrementAvailabilityVersionNum, incrementSlotsVersionNum } from '@/src/dbService'
import { imageUploadS3 } from '@/src/lib/s3-client'
import { getApiCacheKey, getCloudflareApiToken, getCloudflareZoneId, getAssetsDomain } from '@/src/lib/env-exporter'
import { CACHE_FILENAMES } from '@packages/shared'
import { CACHE_FILENAMES, DEFAULT_REGION_ID } 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}`
const regionPathPrefix = (regionId?: number) =>
regionId == null || regionId === DEFAULT_REGION_ID ? '' : `r-${regionId}/`
const buildAvailabilityPath = (version: number) => `av-${version}/${CACHE_FILENAMES.availability}`
const buildCachePath = (path: string, version: number, regionId?: number) =>
`${regionPathPrefix(regionId)}v-${version}/${path}`
const buildSlotsPath = (version: number) => `slots/v-${version}/${CACHE_FILENAMES.slots}`
const buildAvailabilityPath = (version: number, regionId?: number) =>
`${regionPathPrefix(regionId)}av-${version}/${CACHE_FILENAMES.availability}`
function constructCacheUrl(path: string, version: number): string {
return `${getAssetsDomain()}${getApiCacheKey()}/${buildCachePath(path, version)}`
const buildSlotsPath = (version: number, regionId?: number) =>
`${regionPathPrefix(regionId)}slots/v-${version}/${CACHE_FILENAMES.slots}`
function constructCacheUrl(path: string, version: number, regionId?: number): string {
return `${getAssetsDomain()}${getApiCacheKey()}/${buildCachePath(path, version, regionId)}`
}
function constructAvailabilityUrl(version: number): string {
return `${getAssetsDomain()}${buildAvailabilityPath(version)}`
function constructAvailabilityUrl(version: number, regionId?: number): string {
return `${getAssetsDomain()}${buildAvailabilityPath(version, regionId)}`
}
function constructSlotsUrl(version: number): string {
return `${getAssetsDomain()}${buildSlotsPath(version)}`
function constructSlotsUrl(version: number, regionId?: number): string {
return `${getAssetsDomain()}${buildSlotsPath(version, regionId)}`
}
export interface CreateAllCacheFilesResult {
@ -44,7 +50,23 @@ export interface CreateAllCacheFilesResult {
export async function createAllCacheFiles(): Promise<CreateAllCacheFilesResult> {
console.log('Starting creation of all cache files...')
const cacheVersion = await incrementCacheVersion()
const regions = await getRegions()
const regionIds = regions.length > 0 ? regions.map((region) => region.id) : [DEFAULT_REGION_ID]
const results: CreateAllCacheFilesResult[] = []
for (const regionId of regionIds) {
results.push(await createRegionCacheFiles(regionId))
}
console.log('All cache files created successfully')
const defaultResult = results.find((result, index) => regionIds[index] === DEFAULT_REGION_ID)
return defaultResult ?? results[0]
}
async function createRegionCacheFiles(regionId: number): Promise<CreateAllCacheFilesResult> {
const cacheVersion = await incrementCacheVersion(regionId)
// Create all global cache files in parallel
const [
@ -56,40 +78,38 @@ export async function createAllCacheFiles(): Promise<CreateAllCacheFilesResult>
bannersKey,
individualStoreKeys,
] = await Promise.all([
createProductsFileInternal(cacheVersion),
createEssentialConstsFileInternal(cacheVersion),
createStoresFileInternal(cacheVersion),
createSlotsCacheFile(false),
createAvailabilityCacheFile(false),
createBannersFileInternal(cacheVersion),
createAllStoresFilesInternal(cacheVersion),
createProductsFileInternal(cacheVersion, regionId),
createEssentialConstsFileInternal(cacheVersion, regionId),
createStoresFileInternal(cacheVersion, regionId),
createSlotsCacheFile(false, regionId),
createAvailabilityCacheFile(false, regionId),
createBannersFileInternal(cacheVersion, regionId),
createAllStoresFilesInternal(cacheVersion, regionId),
])
const stores = await getStoresSummary()
const stores = await getStoresSummary(regionId)
// Collect all URLs for batch cache purge
const urls = [
constructCacheUrl(CACHE_FILENAMES.products, cacheVersion),
constructCacheUrl(CACHE_FILENAMES.essentialConsts, cacheVersion),
constructCacheUrl(CACHE_FILENAMES.stores, cacheVersion),
constructSlotsUrl(slotsVersion),
constructAvailabilityUrl(availabilityVersion),
constructCacheUrl(CACHE_FILENAMES.banners, cacheVersion),
...stores.map((store) => constructCacheUrl(`stores/${store.id}.json`, cacheVersion)),
constructCacheUrl(CACHE_FILENAMES.products, cacheVersion, regionId),
constructCacheUrl(CACHE_FILENAMES.essentialConsts, cacheVersion, regionId),
constructCacheUrl(CACHE_FILENAMES.stores, cacheVersion, regionId),
constructSlotsUrl(slotsVersion, regionId),
constructAvailabilityUrl(availabilityVersion, regionId),
constructCacheUrl(CACHE_FILENAMES.banners, cacheVersion, regionId),
...stores.map((store) => constructCacheUrl(`stores/${store.id}.json`, cacheVersion, regionId)),
]
// Purge all caches in one batch with retry
try {
await retryWithExponentialBackoff(() => clearUrlCache(urls))
console.log(`Cache purged for all ${urls.length} files`)
console.log(`Cache purged for all ${urls.length} files (region ${regionId})`)
} catch (error) {
console.error(`Failed to purge cache for all files after 3 retries`, error)
console.error(`Failed to purge cache for all files after 3 retries (region ${regionId})`, error)
}
console.log('All cache files created successfully')
// Single awaited mirror refresh for the whole cycle (all counters bumped above).
await refreshGenKv()
// Single awaited mirror refresh for this region (all counters bumped above).
await refreshGenKv(regionId)
return {
cacheVersion,
@ -103,12 +123,18 @@ export async function createAllCacheFiles(): Promise<CreateAllCacheFilesResult>
}
}
/** Resolve the region ids to regenerate when no explicit region is given. */
async function resolveRegionIds(): Promise<number[]> {
const regions = await getRegions()
return regions.length > 0 ? regions.map((region) => region.id) : [DEFAULT_REGION_ID]
}
// Internal versions that skip cache purging (for batch operations)
async function createProductsFileInternal(version: number): Promise<string> {
const productsData = await scaffoldProducts()
async function createProductsFileInternal(version: number, regionId?: number): Promise<string> {
const productsData = await scaffoldProducts(regionId)
const jsonContent = JSON.stringify(productsData, null, 2)
const buffer = Buffer.from(jsonContent, 'utf-8')
const filePath = `${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.products, version)}`
const filePath = `${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.products, version, regionId)}`
console.log(filePath)
return await imageUploadS3(
@ -119,12 +145,21 @@ async function createProductsFileInternal(version: number): Promise<string> {
}
export async function createAvailabilityCacheFile(refresh = true): Promise<number> {
const version = await incrementAvailabilityVersionNum()
const availabilityData = await scaffoldAvailability()
export async function createAvailabilityCacheFile(refresh = true, regionId?: number): Promise<number> {
if (regionId == null) {
let defaultVersion = 0
for (const id of await resolveRegionIds()) {
const version = await createAvailabilityCacheFile(refresh, id)
if (id === DEFAULT_REGION_ID) defaultVersion = version
}
return defaultVersion
}
const version = await incrementAvailabilityVersionNum(regionId)
const availabilityData = await scaffoldAvailability(regionId)
const jsonContent = JSON.stringify(availabilityData, null, 2)
const buffer = Buffer.from(jsonContent, 'utf-8')
const filePath = buildAvailabilityPath(version)
const filePath = buildAvailabilityPath(version, regionId)
console.log(filePath)
await imageUploadS3(
@ -132,40 +167,50 @@ export async function createAvailabilityCacheFile(refresh = true): Promise<numbe
'application/json',
filePath
)
console.log(`Availability cache regenerated: region ${regionId}, av-${version}, ${availabilityData.count} rows`)
if (refresh) await refreshGenKv()
if (refresh) await refreshGenKv(regionId)
return version
}
async function createEssentialConstsFileInternal(version: number): Promise<string> {
const essentialConstsData = await scaffoldEssentialConsts()
async function createEssentialConstsFileInternal(version: number, regionId?: number): Promise<string> {
const essentialConstsData = await scaffoldEssentialConsts(regionId)
const jsonContent = JSON.stringify(essentialConstsData, null, 2)
const buffer = Buffer.from(jsonContent, 'utf-8')
return await imageUploadS3(
buffer,
'application/json',
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.essentialConsts, version)}`
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.essentialConsts, version, regionId)}`
)
}
async function createStoresFileInternal(version: number): Promise<string> {
const storesData = await scaffoldStores()
async function createStoresFileInternal(version: number, regionId?: number): Promise<string> {
const storesData = await scaffoldStores(regionId)
const jsonContent = JSON.stringify(storesData, null, 2)
const buffer = Buffer.from(jsonContent, 'utf-8')
return await imageUploadS3(
buffer,
'application/json',
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.stores, version)}`
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.stores, version, regionId)}`
)
}
export async function createSlotsCacheFile(refresh = true): Promise<number> {
const version = await incrementSlotsVersionNum()
const slotsData = await scaffoldSlotsWithProducts()
export async function createSlotsCacheFile(refresh = true, regionId?: number): Promise<number> {
if (regionId == null) {
let defaultVersion = 0
for (const id of await resolveRegionIds()) {
const version = await createSlotsCacheFile(refresh, id)
if (id === DEFAULT_REGION_ID) defaultVersion = version
}
return defaultVersion
}
const version = await incrementSlotsVersionNum(regionId)
const slotsData = await scaffoldSlotsWithProducts(regionId)
const jsonContent = JSON.stringify(slotsData, null, 2)
const buffer = Buffer.from(jsonContent, 'utf-8')
const filePath = buildSlotsPath(version)
const filePath = buildSlotsPath(version, regionId)
console.log(filePath)
await imageUploadS3(
@ -173,36 +218,37 @@ export async function createSlotsCacheFile(refresh = true): Promise<number> {
'application/json',
filePath
)
console.log(`Slots cache regenerated: region ${regionId}, v-${version}`)
if (refresh) await refreshGenKv()
if (refresh) await refreshGenKv(regionId)
return version
}
async function createBannersFileInternal(version: number): Promise<string> {
const bannersData = await scaffoldBanners()
async function createBannersFileInternal(version: number, regionId?: number): Promise<string> {
const bannersData = await scaffoldBanners(regionId)
const jsonContent = JSON.stringify(bannersData, null, 2)
const buffer = Buffer.from(jsonContent, 'utf-8')
return await imageUploadS3(
buffer,
'application/json',
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.banners, version)}`
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.banners, version, regionId)}`
)
}
async function createAllStoresFilesInternal(version: number): Promise<string[]> {
async function createAllStoresFilesInternal(version: number, regionId?: number): Promise<string[]> {
const stores = await getStoresSummary()
const stores = await getStoresSummary(regionId)
const results: string[] = []
for (const store of stores) {
const storeData = await scaffoldStoreWithProducts(store.id)
const storeData = await scaffoldStoreWithProducts(store.id, regionId)
const jsonContent = JSON.stringify(storeData, null, 2)
const buffer = Buffer.from(jsonContent, 'utf-8')
const s3Key = await imageUploadS3(
buffer,
'application/json',
`${getApiCacheKey()}/${buildCachePath(`stores/${store.id}.json`, version)}`
`${getApiCacheKey()}/${buildCachePath(`stores/${store.id}.json`, version, regionId)}`
)
results.push(s3Key)
}

View file

@ -58,6 +58,25 @@ export type ConstKey = (typeof CONST_KEYS)[keyof typeof CONST_KEYS];
export const CONST_KEYS_ARRAY = Object.values(CONST_KEYS) as ConstKey[];
/**
* Constants edited per region (the admin customize-app visible fields).
* These live in region_consts; everything else stays in key_val_store.
*/
export const REGION_CONST_KEYS = [
CONST_KEYS.minRegularOrderValue,
CONST_KEYS.freeDeliveryThreshold,
CONST_KEYS.deliveryCharge,
CONST_KEYS.flashFreeDeliveryThreshold,
CONST_KEYS.flashDeliveryCharge,
CONST_KEYS.allItemsOrder,
CONST_KEYS.isFlashDeliveryEnabled,
CONST_KEYS.supportMobile,
CONST_KEYS.supportEmail,
CONST_KEYS.welcomeMessage,
] as const;
export const REGION_CONST_KEYS_ARRAY = [...REGION_CONST_KEYS] as string[];
export const CONST_TYPES: Record<ConstKey, ConstValueType> = {
minRegularOrderValue: 'number',
freeDeliveryThreshold: 'number',

View file

@ -1,6 +1,7 @@
import { getAllKeyValStore } from '@/src/dbService'
import { getAllKeyValStore, getAllRegionConsts } from '@/src/dbService'
// import redisClient from '@/src/lib/redis-client'
import { CONST_KEYS, CONST_KEYS_ARRAY, type ConstKey } from '@/src/lib/const-keys'
import { castConstValue } from '../../../../packages/db_helper_sqlite/src/lib/const-keys'
// const CONST_REDIS_PREFIX = 'const:';
@ -23,7 +24,21 @@ export const computeConstants = async (): Promise<void> => {
}
};
export const getConstant = async <T = any>(key: string): Promise<T | null> => {
/** Global rows overlaid with the region's rows, then the bound's rows. */
const mergedConstMap = async (regionId?: number, boundId?: number | null): Promise<Map<string, any>> => {
const constants = await getAllKeyValStore();
// DB stores every value as text; cast so arithmetic/boolean checks behave.
const map = new Map(constants.map(c => [c.key, castConstValue(c.key, c.value)]));
if (regionId != null) {
const regional = await getAllRegionConsts(regionId, boundId);
for (const row of regional) {
map.set(row.key, castConstValue(row.key, row.value));
}
}
return map;
}
export const getConstant = async <T = any>(key: string, regionId?: number, boundId?: number | null): Promise<T | null> => {
// const redisKey = `${CONST_REDIS_PREFIX}${key}`;
// const value = await redisClient.get(redisKey);
//
@ -41,13 +56,16 @@ export const getConstant = async <T = any>(key: string): Promise<T | null> => {
const entry = constants.find(c => c.key === key);
if (!entry) {
return null;
if (regionId == null) return null;
const regional = await getAllRegionConsts(regionId, boundId);
const row = regional.find(r => r.key === key);
return (row ? castConstValue(row.key, row.value) : null) as T | null;
}
return entry.value as T;
return castConstValue(entry.key, entry.value) as T;
};
export const getConstants = async <T = any>(keys: string[]): Promise<Record<string, T | null>> => {
export const getConstants = async <T = any>(keys: string[], regionId?: number, boundId?: number | null): Promise<Record<string, T | null>> => {
// const redisKeys = keys.map(key => `${CONST_REDIS_PREFIX}${key}`);
// const values = await redisClient.MGET(redisKeys);
//
@ -67,8 +85,7 @@ export const getConstants = async <T = any>(keys: string[]): Promise<Record<stri
//
// return result;
const constants = await getAllKeyValStore();
const constantsMap = new Map(constants.map(c => [c.key, c.value]));
const constantsMap = await mergedConstMap(regionId, boundId);
const result: Record<string, T | null> = {};
for (const key of keys) {
@ -79,7 +96,7 @@ export const getConstants = async <T = any>(keys: string[]): Promise<Record<stri
return result;
};
export const getAllConstValues = async (): Promise<Record<ConstKey, any>> => {
export const getAllConstValues = async (regionId?: number, boundId?: number | null): Promise<Record<ConstKey, any>> => {
// const result: Record<string, any> = {};
//
// for (const key of CONST_KEYS_ARRAY) {
@ -88,8 +105,7 @@ export const getAllConstValues = async (): Promise<Record<ConstKey, any>> => {
//
// return result as Record<ConstKey, any>;
const constants = await getAllKeyValStore();
const constantsMap = new Map(constants.map(c => [c.key, c.value]));
const constantsMap = await mergedConstMap(regionId, boundId);
const result: Record<string, any> = {};
for (const key of CONST_KEYS_ARRAY) {

View file

@ -1,17 +1,23 @@
import { getGenKvNamespace } from '@/src/lib/env-exporter'
import { DEFAULT_REGION_ID } from '@packages/shared'
import type { scaffoldEssentialConsts } from '@/src/trpc/apis/common-apis/common-trpc-index'
export const GEN_KV_KEY = 'essential_consts'
export const regionKvKey = (regionId?: number, boundId?: number | null) => {
if (boundId != null) return `${GEN_KV_KEY}_${regionId}_${boundId}`
return regionId == null || regionId === DEFAULT_REGION_ID ? GEN_KV_KEY : `${GEN_KV_KEY}_${regionId}`
}
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> {
async function buildEssentialConsts(regionId?: number, boundId?: number | null): Promise<EssentialConstsPayload> {
const { scaffoldEssentialConsts } = await import(
'../trpc/apis/common-apis/common-trpc-index'
)
return scaffoldEssentialConsts()
return scaffoldEssentialConsts(regionId, boundId)
}
/**
@ -19,13 +25,16 @@ async function buildEssentialConsts(): Promise<EssentialConstsPayload> {
* 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> {
export async function refreshGenKv(regionId?: number, boundId?: number | null): Promise<void> {
try {
const kv = getGenKvNamespace()
if (!kv) return
const payload = await buildEssentialConsts()
await kv.put(GEN_KV_KEY, JSON.stringify(payload))
const payload = await buildEssentialConsts(regionId, boundId)
await kv.put(regionKvKey(regionId, boundId), JSON.stringify(payload))
if ((regionId == null || regionId === DEFAULT_REGION_ID) && boundId == null) {
await kv.put(GEN_KV_KEY, JSON.stringify(payload))
}
} catch (error) {
console.error('refreshGenKv failed:', error)
}
@ -35,22 +44,22 @@ export async function refreshGenKv(): Promise<void> {
* 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> {
export async function readEssentialConstsFromKv(regionId?: number, boundId?: number | null): Promise<EssentialConstsPayload> {
try {
const kv = getGenKvNamespace()
if (kv) {
const cached = (await kv.get(GEN_KV_KEY, 'json')) as EssentialConstsPayload | null
const cached = (await kv.get(regionKvKey(regionId, boundId), 'json')) as EssentialConstsPayload | null
if (cached) return cached
}
} catch (error) {
console.error('readEssentialConstsFromKv failed:', error)
}
const payload = await buildEssentialConsts()
const payload = await buildEssentialConsts(regionId, boundId)
try {
const kv = getGenKvNamespace()
if (kv) await kv.put(GEN_KV_KEY, JSON.stringify(payload))
if (kv) await kv.put(regionKvKey(regionId, boundId), JSON.stringify(payload))
} catch (error) {
console.error('backfill essential_consts failed:', error)
}

View file

@ -1,10 +1,11 @@
import {
getOrdersByIdsWithFullData,
getOrderByIdWithFullData,
getRegionTelegramCreds,
composeSkuName,
composeUnitNotation,
} from '@/src/dbService'
import { sendTelegramMessage } from '@/src/lib/telegram-service'
import { sendTelegramMessage, sendTelegramMessageToCreds } 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';
@ -112,18 +113,21 @@ export const handleOrderPlaced = async (orderIds: number[], rawMessage?: string)
try {
const ordersData = await getOrdersByIdsWithFullData(orderIds)
// Push a notification to every admin device; tapping it opens that order's
// Push to the order's region admins only; tapping opens that order's
// details page (data.orderId is the numeric order id).
for (const order of ordersData) {
const orderRegionId = order.address?.regionId ?? null
if (orderRegionId == null) {
console.error(`Order ${order.id} has no address region; notifying all staff`)
}
await notifyAllAdmins({
title: '🛒 New Order Placed',
body: `${order.address?.name || 'A customer'} • ₹${order.totalAmount}`,
orderId: order.id,
})
}, orderRegionId)
}
const telegramMessage = formatOrderMessageWithFullData(ordersData)
await sendTelegramMessage(telegramMessage)
await sendOrderMessagePerRegion(ordersData, (group) => formatOrderMessageWithFullData(group))
} catch (error) {
console.error('Failed to process order message:', error)
const fallback = rawMessage ? `⚠️ Error parsing order: ${rawMessage}` : '⚠️ Error parsing order'
@ -131,6 +135,42 @@ export const handleOrderPlaced = async (orderIds: number[], rawMessage?: string)
}
}
/**
* Group orders by their address region and send each group to every Telegram
* cred of that region. Regions with no creds (or orders with no region) are
* skipped with an error log — never broadcast cross-region.
*/
const sendOrderMessagePerRegion = async (
ordersData: any[],
format: (group: any[]) => string
): Promise<void> => {
const byRegion = new Map<number, any[]>()
let unregioned = 0
for (const order of ordersData) {
const regionId = order.address?.regionId
if (regionId == null) {
unregioned++
continue
}
const group = byRegion.get(regionId) ?? []
group.push(order)
byRegion.set(regionId, group)
}
if (unregioned > 0) {
console.error(`Skipping Telegram for ${unregioned} order(s) with no address region`)
}
for (const [regionId, group] of byRegion) {
const creds = await getRegionTelegramCreds(regionId)
if (creds.length === 0) {
console.error(`No Telegram creds for region ${regionId}, skipping ${group.length} order(s)`)
continue
}
await sendTelegramMessageToCreds(format(group), creds)
}
}
export const handleOrderCancelled = async (
cancellationData: CancellationMessage,
rawMessage?: string
@ -147,9 +187,9 @@ export const handleOrderCancelled = async (
const refundStatus = orderData.refunds?.[0]?.refundStatus || 'pending'
const telegramMessage = formatCancellationMessage({ ...orderData, refundStatus }, cancellationData)
await sendTelegramMessage(telegramMessage)
await sendOrderMessagePerRegion([orderData], (group) =>
formatCancellationMessage({ ...group[0], refundStatus }, cancellationData)
)
} catch (error) {
console.error('Failed to process cancellation message:', error)
const fallback = rawMessage ? `⚠️ Error processing cancellation: ${rawMessage}` : '⚠️ Error processing cancellation'

View file

@ -0,0 +1,67 @@
import { getRegions } from '@/src/dbService'
import { polygon as turfPolygon, point as turfPoint } from '@turf/helpers';
import { booleanPointInPolygon } from '@turf/boolean-point-in-polygon';
export interface ResolvedBound {
regionId: number | null
regionName: string | null
boundId: number | null
boundName: string | null
}
/** Collect Polygon coordinate rings from a stored bound GeoJSON string.
* Accepts Polygon, MultiPolygon, Feature, and FeatureCollection shapes;
* returns [] for anything unparseable so callers can skip safely. */
export function extractPolygonRings(geojson: string): number[][][][] {
let parsed: any;
try {
parsed = JSON.parse(geojson);
} catch {
return [];
}
if (!parsed || typeof parsed !== 'object') return [];
if (parsed.type === 'Polygon' && Array.isArray(parsed.coordinates)) {
return [parsed.coordinates];
}
if (parsed.type === 'MultiPolygon' && Array.isArray(parsed.coordinates)) {
return parsed.coordinates;
}
if (parsed.type === 'Feature') {
return extractPolygonRings(JSON.stringify(parsed.geometry ?? null));
}
if (parsed.type === 'FeatureCollection' && Array.isArray(parsed.features)) {
return parsed.features.flatMap((f: any) => {
try {
return extractPolygonRings(JSON.stringify(f?.geometry ?? f ?? null));
} catch {
return [];
}
});
}
return [];
}
/** Point-in-polygon over regions+bounds in priority order. First match wins. */
export async function resolveBoundForPoint(lat: number, lng: number): Promise<ResolvedBound> {
const point = turfPoint([lng, lat]); // GeoJSON: [longitude, latitude]
const regions = await getRegions();
for (const region of regions) {
for (const bound of region.bounds ?? []) {
for (const coords of extractPolygonRings(bound.geojson)) {
try {
if (booleanPointInPolygon(point, turfPolygon(coords))) {
return {
regionId: region.id as number,
regionName: region.name as string,
boundId: bound.id as number,
boundName: (bound.name as string | null) ?? null,
};
}
} catch {
// Skip malformed polygons; other bounds still count.
}
}
}
}
return { regionId: null, regionName: null, boundId: null, boundName: null };
}

View file

@ -1,5 +1,32 @@
import { getIsDevMode, getTelegramBotToken, getTelegramChatIds } from '@/src/lib/env-exporter'
export interface TelegramCred {
botToken: string
chatId: string
}
const postToChat = async (botToken: string, chatId: string, message: string): Promise<boolean> => {
try {
const response = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: chatId, text: message, parse_mode: 'HTML' }),
})
const data = await response.json() as { ok: boolean }
if (data.ok) {
console.log(`Telegram message sent successfully to ${chatId}`)
return true
} else {
console.error(`Telegram API error for ${chatId}:`, data)
return false
}
} catch (error) {
console.error(`Failed to send Telegram message to ${chatId}:`, error)
return false
}
}
export const sendTelegramMessage = async (message: string): Promise<boolean | null> => {
if (getIsDevMode()) {
return null;
@ -10,30 +37,35 @@ export const sendTelegramMessage = async (message: string): Promise<boolean | nu
console.warn('Telegram credentials not configured, skipping notification')
return null
}
const telegramApiUrl = `https://api.telegram.org/bot${botToken}`
try {
const results = await Promise.all(
chatIds.map(async (chatId) => {
try {
const response = await fetch(`${telegramApiUrl}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: chatId, text: message, parse_mode: 'HTML' }),
})
const data = await response.json() as { ok: boolean }
if (data.ok) {
console.log(`Telegram message sent successfully to ${chatId}`)
return true
} else {
console.error(`Telegram API error for ${chatId}:`, data)
return false
}
} catch (error) {
console.error(`Failed to send Telegram message to ${chatId}:`, error)
return false
}
})
chatIds.map(async (chatId) => postToChat(botToken, chatId, message))
)
console.log('sent telegram message successfully')
return results.some((result) => result)
} catch (error) {
console.error('Failed to send Telegram message:', error)
return false
}
}
/** Region-scoped fan-out: one message to every cred of the order's region. */
export const sendTelegramMessageToCreds = async (
message: string,
creds: TelegramCred[]
): Promise<boolean | null> => {
if (getIsDevMode()) {
return null;
}
if (creds.length === 0) {
console.warn('No Telegram creds provided, skipping notification')
return null
}
try {
const results = await Promise.all(
creds.map(async (cred) => postToChat(cred.botToken, cred.chatId, message))
)
console.log('sent telegram message successfully')

View file

@ -1,5 +1,4 @@
import { Hono } from 'hono';
import v1Router from "@/src/v1-router"
import testController from "@/src/test-controller"
import { authenticateUser } from "@/src/middleware/auth.middleware"
@ -26,7 +25,6 @@ router.get('/seed', (c) => {
// Apply authentication middleware to all subsequent routes
router.use('*', authenticateUser);
router.route('/v1', v1Router);
router.route('/test', testController);
const mainRouter = router;

View file

@ -0,0 +1,74 @@
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "Jadcherla"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
78.1403916,
16.744066
],
[
78.1548681,
16.7415277
],
[
78.1593669,
16.7523755
],
[
78.1621315,
16.7630654
],
[
78.1620705,
16.7692272
],
[
78.1564687,
16.7758419
],
[
78.1513873,
16.7783785
],
[
78.1455877,
16.7796921
],
[
78.1326433,
16.781202
],
[
78.123043,
16.7805196
],
[
78.118775,
16.7757046
],
[
78.1173809,
16.7685992
],
[
78.1205895,
16.7633171
],
[
78.1403916,
16.744066
]
]
]
}
}
]
}

View file

@ -31,6 +31,9 @@ export {
// Admin - Constants
getAllConstants,
upsertConstants,
getRegionConstants,
upsertRegionConstants,
getAllRegionConsts,
// Admin - Coupon
getAllCoupons,
getCouponById,
@ -59,6 +62,17 @@ export {
rebalanceSlots,
cancelOrder,
deleteOrderById,
// Admin - Region
getRegions,
getRegionById,
getRegionSummaries,
createRegion,
updateRegion,
deleteRegion,
addRegionBound,
deleteRegionBound,
getRegionTelegramCreds,
getDefaultBoundId,
// Admin - Product
getAllProducts,
getProductById,
@ -83,9 +97,10 @@ export {
deleteProductGroup,
updateProductPrices,
toggleProductOutOfStock,
getSkuProductRegions,
backfillMarketStatsForRegion,
// Admin - Slots
getActiveSlotsWithProducts,
getSlotsAfterDate,
getSlotByIdWithRelations,
createSlotWithRelations,
updateSlotWithRelations,
@ -101,6 +116,7 @@ export {
checkStaffRoleExists,
createStaffUser,
getAllRoles,
getStaffRoleById,
// Admin - Store
getAllStores,
getStoreById,
@ -160,8 +176,6 @@ export {
getUserProductReviews,
getUserProductByIdBasic,
createUserProductReview,
getAllProductsWithUnits,
type ProductSummaryData,
// User - Slots
getUserActiveSlotsList,
getUserProductAvailability,
@ -246,6 +260,7 @@ export {
// Post-order handler helpers
getOrdersByIdsWithFullData,
getOrderByIdWithFullData,
getOrderAddressRegion,
// Common API helpers
getSuspendedSkuIds,
getNextDeliveryDateWithCapacity,

View file

@ -127,9 +127,9 @@ export async function initializeProducts(): Promise<void> {
}
}
export async function getProductById(id: number): Promise<Product | null> {
export async function getProductById(id: number, regionId?: number): Promise<Product | null> {
try {
const allProducts = await getAllProducts()
const allProducts = await getAllProducts(regionId)
const product = allProducts.find(p => p.id === id)
return product || null
} catch (error) {
@ -138,7 +138,7 @@ export async function getProductById(id: number): Promise<Product | null> {
}
}
export async function getAllProducts(): Promise<Product[]> {
export async function getAllProducts(regionId?: number): Promise<Product[]> {
try {
// Get all keys matching the pattern "product:*"
// const keys = await redisClient.KEYS('product:*')
@ -159,12 +159,12 @@ export async function getAllProducts(): Promise<Product[]> {
//
// return products
const productsData = await getAllProductsForCache()
const productsData = await getAllProductsForCache(regionId)
const allStores = await getAllStoresForCache()
const allStores = await getAllStoresForCache(regionId)
const storeMap = new Map(allStores.map((s) => [s.id, s]))
const allDeliverySlots = await getAllDeliverySlotsForCache()
const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
for (const slot of allDeliverySlots) {
if (!deliverySlotsMap.has(slot.skuId))
@ -180,7 +180,7 @@ export async function getAllProducts(): Promise<Product[]> {
specialDealsMap.get(deal.skuId)!.push(deal)
}
const allProductTags = await getAllProductTagsForCache()
const allProductTags = await getAllProductTagsForCache(regionId)
const productTagsMap = new Map<number, string[]>()
for (const tag of allProductTags) {
if (!productTagsMap.has(tag.productId))
@ -189,7 +189,7 @@ export async function getAllProducts(): Promise<Product[]> {
}
const products: Product[] = []
const allProductCombos = await getAllProductCombosForCache()
const allProductCombos = await getAllProductCombosForCache(regionId)
const productCombosMap = new Map<number, ProductComboCacheData[]>()
for (const comboItem of allProductCombos) {
if (!productCombosMap.has(comboItem.comboSkuId))

View file

@ -6,6 +6,7 @@ import {
} from '@/src/dbService'
import { scaffoldAssetUrl } from '@/src/lib/s3-client'
import type { ProductTagCore } from '@packages/shared'
import { DEFAULT_REGION_ID } from '@packages/shared'
// Tag Type (matches getDashboardTags return) — anchored to the shared tag core
interface Tag extends ProductTagCore {
@ -85,7 +86,7 @@ export async function initializeProductTagStore(): Promise<void> {
}
}
export async function getTagsByStoreId(storeId: number): Promise<Tag[]> {
export async function getTagsByStoreId(storeId: number, regionId: number = DEFAULT_REGION_ID): Promise<Tag[]> {
try {
// Get all keys matching the pattern "tag:*"
// const keys = await redisClient.KEYS('tag:*')
@ -109,7 +110,7 @@ export async function getTagsByStoreId(storeId: number): Promise<Tag[]> {
//
// return storeTags
const tags = await getAllProductTags()
const tags = await getAllProductTags(regionId)
const result: Tag[] = []
for (const tag of tags) {

View file

@ -63,8 +63,8 @@ function extractSlotInfo(slot: SlotWithProductsData): SlotInfo {
}
}
async function fetchAllTransformedSlots(): Promise<SlotWithProducts[]> {
const slots = await getAllSlotsWithProductsForCache()
async function fetchAllTransformedSlots(regionId?: number): Promise<SlotWithProducts[]> {
const slots = await getAllSlotsWithProductsForCache(regionId)
return Promise.all(slots.map(transformSlotToStoreSlot))
}
@ -140,25 +140,7 @@ export async function initializeSlotStore(): Promise<void> {
}
}
export async function getSlotById(slotId: number): Promise<SlotWithProducts | null> {
try {
// const key = `slot:${slotId}`
// const data = await redisClient.get(key)
// if (!data) return null
// return JSON.parse(data) as SlotWithProducts
const slots = await getAllSlotsWithProductsForCache()
const slot = slots.find(s => s.id === slotId)
if (!slot) return null
return transformSlotToStoreSlot(slot)
} catch (error) {
console.error(`Error getting slot ${slotId}:`, error)
return null
}
}
export async function getAllSlots(): Promise<SlotWithProducts[]> {
export async function getAllSlots(regionId?: number): Promise<SlotWithProducts[]> {
try {
// Get all keys matching the pattern "slot:*"
// const keys = await redisClient.KEYS('slot:*')
@ -177,7 +159,7 @@ export async function getAllSlots(): Promise<SlotWithProducts[]> {
//
// return slots
return fetchAllTransformedSlots()
return fetchAllTransformedSlots(regionId)
} catch (error) {
console.error('Error getting all slots:', error)
return []
@ -185,7 +167,8 @@ export async function getAllSlots(): Promise<SlotWithProducts[]> {
}
export async function getMultipleProductsSlots(
productIds: number[]
productIds: number[],
regionId?: number
): Promise<Record<number, SlotInfo[]>> {
try {
if (productIds.length === 0) return {}
@ -208,7 +191,7 @@ export async function getMultipleProductsSlots(
//
// return result
const slots = await getAllSlotsWithProductsForCache()
const slots = await getAllSlotsWithProductsForCache(regionId)
const productIdSet = new Set(productIds)
const result: Record<number, SlotInfo[]> = {}

View file

@ -12,6 +12,7 @@ import { adminPaymentsRouter } from '@/src/trpc/apis/admin-apis/apis/payments'
import { bannerRouter } from '@/src/trpc/apis/admin-apis/apis/banner'
import { userRouter } from '@/src/trpc/apis/admin-apis/apis/user'
import { constRouter } from '@/src/trpc/apis/admin-apis/apis/const'
import { regionRouter } from '@/src/trpc/apis/admin-apis/apis/region'
export const adminRouter = router({
complaint: complaintRouter,
@ -26,6 +27,7 @@ export const adminRouter = router({
banner: bannerRouter,
user: userRouter,
const: constRouter,
region: regionRouter,
});
export type AdminRouter = typeof adminRouter;

View file

@ -1,5 +1,5 @@
import { z } from 'zod';
import { protectedProcedure, router } from '@/src/trpc/trpc-index'
import { protectedProcedure, adminProcedure, router } from '@/src/trpc/trpc-index'
import { extractKeyFromPresignedUrl, scaffoldAssetUrl } from '@/src/lib/s3-client'
import { ApiError } from '@/src/lib/api-error';
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
@ -14,12 +14,12 @@ import type { Banner } from '@packages/shared'
export const bannerRouter = router({
// Get all banners
getBanners: protectedProcedure
.query(async (): Promise<{ banners: Banner[] }> => {
getBanners: adminProcedure
.query(async ({ ctx }): Promise<{ banners: Banner[] }> => {
try {
// Using dbService helper (new implementation)
const banners = await getBannersFromDb();
const banners = await getBannersFromDb(ctx.staffUser!.regionId);
// Convert S3 keys to signed URLs for client
const bannersWithSignedUrls = await Promise.all(
@ -82,7 +82,7 @@ export const bannerRouter = router({
}),
// Create new banner
createBanner: protectedProcedure
createBanner: adminProcedure
.input(z.object({
name: z.string().min(1),
imageUrl: z.string().url(),
@ -91,7 +91,7 @@ export const bannerRouter = router({
redirectUrl: z.string().url().optional(),
// serialNum removed completely
}))
.mutation(async ({ input }): Promise<Banner> => {
.mutation(async ({ input, ctx }): Promise<Banner> => {
try {
// Using dbService helper (new implementation)
const imageUrl = extractKeyFromPresignedUrl(input.imageUrl)
@ -103,6 +103,7 @@ export const bannerRouter = router({
redirectUrl: input.redirectUrl ?? null,
serialNum: 999, // Default value, not used
isActive: false, // Default to inactive
regionId: ctx.staffUser!.regionId,
});
// Reinitialize stores to reflect changes

View file

@ -1,10 +1,16 @@
import { router, protectedProcedure } from '@/src/trpc/trpc-index'
import { router, adminProcedure } 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 { CONST_KEYS, REGION_CONST_KEYS_ARRAY } from '@/src/lib/const-keys'
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
import { getAllConstants as getAllConstantsFromDb, upsertConstants as upsertConstantsInDb } from '@/src/dbService'
import {
getAllConstants as getAllConstantsFromDb,
upsertConstants as upsertConstantsInDb,
getRegionConstants as getRegionConstantsFromDb,
upsertRegionConstants as upsertRegionConstantsInDb,
getRegionById as getRegionByIdFromDb,
} from '@/src/dbService'
import type { Constant, ConstantUpdateResult } from '@packages/shared'
// Constants that are baked into the versioned cache files (products.json etc.)
@ -14,23 +20,48 @@ const CACHE_AFFECTING_KEYS: string[] = [
]
export const constRouter = router({
getConstants: protectedProcedure
.query(async (): Promise<Constant[]> => {
// Using dbService helper (new implementation)
const constants = await getAllConstantsFromDb();
getConstants: adminProcedure
.input(z.object({ boundId: z.number().int().positive().optional() }).optional())
.query(async ({ ctx, input }): Promise<Constant[]> => {
// Global constants plus this admin's region/bound overrides (same shape
// as before, so the customize-app forms work unchanged).
const regionId = ctx.staffUser?.regionId;
const boundId = input?.boundId ?? null;
if (boundId != null && regionId != null) {
const region = await getRegionByIdFromDb(regionId);
if (!region?.bounds?.some((b) => b.id === boundId)) {
throw new Error('Bound does not belong to your region');
}
}
const [globals, regional] = await Promise.all([
getAllConstantsFromDb(),
regionId != null ? getRegionConstantsFromDb(regionId, boundId) : [],
]);
return constants;
return [...globals, ...regional];
}),
updateConstants: protectedProcedure
updateConstants: adminProcedure
.input(z.object({
constants: z.array(z.object({
key: z.string(),
value: z.any(),
})),
boundId: z.number().int().positive().optional(),
}))
.mutation(async ({ input }): Promise<ConstantUpdateResult> => {
.mutation(async ({ input, ctx }): Promise<ConstantUpdateResult> => {
const { constants } = input;
const regionId = ctx.staffUser?.regionId;
const boundId = input.boundId ?? null;
if (boundId != null) {
if (regionId == null) {
throw new Error('regionId is required to update bound constants');
}
const region = await getRegionByIdFromDb(regionId);
if (!region?.bounds?.some((b) => b.id === boundId)) {
throw new Error('Bound does not belong to your region');
}
}
const validKeys = Object.values(CONST_KEYS) as string[];
const invalidKeys = constants
@ -42,14 +73,25 @@ export const constRouter = router({
}
console.log(input)
// Using dbService helper (new implementation)
await upsertConstantsInDb(constants);
const regional = constants.filter((c) => REGION_CONST_KEYS_ARRAY.includes(c.key));
const global = constants.filter((c) => !REGION_CONST_KEYS_ARRAY.includes(c.key));
// Using dbService helpers (new implementation)
if (global.length > 0) {
await upsertConstantsInDb(global);
}
if (regional.length > 0) {
if (regionId == null) {
throw new Error('regionId is required to update regional constants');
}
await upsertRegionConstantsInDb(regionId, boundId, regional);
}
// Refresh all constants in Redis after database update
await computeConstants();
// Mirror the full essentialConsts response into KV for client reads.
await refreshGenKv();
await refreshGenKv(regionId ?? undefined, boundId);
// Constants like tagsOrder are baked into the versioned cache files.
// Regenerate the cache (bumps cacheVersion) so the user app fetches the

View file

@ -1,4 +1,4 @@
import { router, protectedProcedure } from "@/src/trpc/trpc-index"
import { router, protectedProcedure, adminProcedure } from "@/src/trpc/trpc-index"
import { z } from "zod";
import { ApiError } from "@/src/lib/api-error"
import {
@ -167,12 +167,17 @@ export const orderRouter = router({
return result
}),
getSlotOrders: protectedProcedure
getSlotOrders: adminProcedure
.input(getSlotOrdersSchema)
.query(async ({ input }): Promise<AdminGetSlotOrdersResult> => {
.query(async ({ input, ctx }): Promise<AdminGetSlotOrdersResult> => {
const { slotId } = input;
const result = await getSlotOrdersInDb(slotId)
// Superadmins see all regions; everyone else is scoped to their region.
const regionId = ctx.staffUser?.staffRoleName === 'super_admin'
? undefined
: ctx.staffUser?.regionId
const result = await getSlotOrdersInDb(slotId, regionId)
const userIds = [...new Set(result.data.map((order) => order.userId))]
const firstOrderIdByUser = new Map<number, number | null>()
@ -210,11 +215,15 @@ export const orderRouter = router({
return result
}),
getAll: protectedProcedure
getAll: adminProcedure
.input(getAllOrdersSchema)
.query(async ({ input }): Promise<AdminGetAllOrdersResult | undefined> => {
.query(async ({ input, ctx }): Promise<AdminGetAllOrdersResult | undefined> => {
try {
const result = await getAllOrdersInDb(input)
const regionId = ctx.staffUser?.staffRoleName === 'super_admin'
? undefined
: ctx.staffUser?.regionId
const result = await getAllOrdersInDb({ ...input, regionId })
const userIds = [...new Set(result.orders.map((order) => order.userId))]
const negativityScores = await getMultipleUserNegativityScores(userIds)
@ -243,12 +252,12 @@ export const orderRouter = router({
}
}),
rebalanceSlots: protectedProcedure
rebalanceSlots: adminProcedure
.input(z.object({ slotIds: z.array(z.number()).min(1).max(50) }))
.mutation(async ({ input }): Promise<AdminRebalanceSlotsResult> => {
.mutation(async ({ input, ctx }): Promise<AdminRebalanceSlotsResult> => {
const slotIds = input.slotIds;
const result = await rebalanceSlotsInDb(slotIds)
const result = await rebalanceSlotsInDb(slotIds, ctx.staffUser!.regionId)
return result
}),

View file

@ -1,4 +1,4 @@
import { router, protectedProcedure } from '@/src/trpc/trpc-index'
import { router, protectedProcedure, adminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import { ApiError } from '@/src/lib/api-error'
import { scaffoldAssetUrl, claimUploadUrl, extractKeyFromPresignedUrl, deleteImageUtil } from '@/src/lib/s3-client'
@ -16,6 +16,7 @@ import {
deleteProductGroup as deleteProductGroupInDb,
updateProductPrices as updateProductPricesInDb,
toggleProductOutOfStock as toggleProductOutOfStockInDb,
getSkuProductRegions as getSkuProductRegionsInDb,
checkProductExistsByName,
createProduct as createProductInDb,
replaceTagProducts,
@ -41,10 +42,39 @@ import type {
AdminToggleOutOfStockResult,
} from '@packages/shared'
const ctxRegion = (ctx: any) => ctx.staffUser?.regionId as number
const scopedRegion = (ctx: any) =>
ctx.staffUser?.staffRoleName === 'super_admin' ? undefined : ctx.staffUser?.regionId
// Write target region: only super_admins may target another region; every other
// staff member's writes are forced to their own region (client input ignored).
const writeRegion = (ctx: any, inputRegion?: number) =>
ctx.staffUser?.staffRoleName === 'super_admin'
? (inputRegion ?? ctx.staffUser?.regionId)
: ctx.staffUser?.regionId
const isSuperAdmin = (ctx: any) => ctx.staffUser?.staffRoleName === 'super_admin'
/** Ownership gate for product writes: non-superadmins may only touch
* own-region restricted products. All-region products pass here; flag flips
* are rejected separately by callers that accept the flag. */
const assertOwnRestrictedProduct = (
ctx: any,
product: { regionId: number | null; availableInAllRegions: boolean } | null
): void => {
if (!product) {
throw new ApiError('Product not found', 404)
}
if (isSuperAdmin(ctx)) return
if (!product.availableInAllRegions && product.regionId !== ctx.staffUser?.regionId) {
throw new ApiError('Product does not belong to your region', 403)
}
}
export const productRouter = router({
getProducts: protectedProcedure
.query(async (): Promise<AdminProductListResponse> => {
const products = await getAllProductsInDb()
getProducts: adminProcedure
.query(async ({ ctx }): Promise<AdminProductListResponse> => {
const products = await getAllProductsInDb(scopedRegion(ctx))
const productsWithImageUrls = products.map((product) => ({
...product,
@ -60,14 +90,14 @@ export const productRouter = router({
}
}),
getProductById: protectedProcedure
getProductById: adminProcedure
.input(z.object({
id: z.number(),
}))
.query(async ({ input }): Promise<AdminProductResponse> => {
.query(async ({ input, ctx }): Promise<AdminProductResponse> => {
const { id } = input;
const product = await getProductByIdInDb(id)
const product = await getProductByIdInDb(id, scopedRegion(ctx))
if (!product) {
throw new ApiError('Product not found', 404)
@ -90,9 +120,22 @@ export const productRouter = router({
.input(z.object({
id: z.number(),
}))
.mutation(async ({ input }): Promise<AdminDeleteProductResult> => {
.mutation(async ({ input, ctx }): Promise<AdminDeleteProductResult> => {
const { id } = input;
const currentProduct = await getProductByIdInDb(id, undefined)
if (!currentProduct) {
throw new ApiError('Product not found', 404)
}
if (currentProduct.availableInAllRegions) {
throw new ApiError('All-region products can only be deleted from superadmin', 403)
}
if (!isSuperAdmin(ctx)) {
if (currentProduct.regionId !== ctx.staffUser?.regionId) {
throw new ApiError('Product does not belong to your region', 403)
}
}
const deletedProduct = await deleteProductInDb(id)
if (!deletedProduct) {
@ -107,14 +150,16 @@ export const productRouter = router({
}
}),
toggleOutOfStock: protectedProcedure
toggleOutOfStock: adminProcedure
.input(z.object({
id: z.number(),
}))
.mutation(async ({ input }): Promise<AdminToggleOutOfStockResult> => {
.mutation(async ({ input, ctx }): Promise<AdminToggleOutOfStockResult> => {
const { id } = input;
const result = await toggleProductOutOfStockInDb(id)
assertOwnRestrictedProduct(ctx, await getProductByIdInDb(id, undefined))
const result = await toggleProductOutOfStockInDb(id, ctxRegion(ctx))
if (!result) {
throw new ApiError('Product not found', 404)
@ -132,12 +177,15 @@ export const productRouter = router({
}
}),
createProduct: protectedProcedure
createProduct: adminProcedure
.input(z.object({
name: z.string().min(1, 'Name is required'),
shortDescription: z.string().optional(),
longDescription: z.string().optional(),
storeId: z.number().min(1, 'Store is required'),
storeId: z.number().min(1, 'Store is required').optional(),
regionId: z.number().int().positive().optional(),
availableInAllRegions: z.boolean().optional(),
storeIdsByRegion: z.record(z.string(), z.number()).optional(),
incrementStep: z.number().optional().default(1),
productType: z.enum(['item', 'combo']).optional().default('item'),
skus: z.array(z.object({
@ -161,8 +209,17 @@ export const productRouter = router({
})).optional(),
})).min(1, 'At least one SKU is required'),
}))
.mutation(async ({ input }): Promise<{ product: AdminProductWithRelations; message: string }> => {
const { name, shortDescription, longDescription, storeId, incrementStep, productType, skus } = input
.mutation(async ({ input, ctx }): Promise<{ product: AdminProductWithRelations; message: string }> => {
const { name, shortDescription, longDescription, storeId, regionId, availableInAllRegions, storeIdsByRegion, incrementStep, productType, skus } = input
// All-region products are managed from superadmin-ui only.
if (availableInAllRegions) {
throw new ApiError('All-region products can only be created from superadmin', 403)
}
const normalizedStoreIdsByRegion = storeIdsByRegion
? Object.fromEntries(Object.entries(storeIdsByRegion).map(([k, v]) => [Number(k), v]))
: undefined
const existingProduct = await checkProductExistsByName(name.trim())
if (existingProduct) {
@ -195,6 +252,10 @@ export const productRouter = router({
shortDescription,
longDescription,
storeId,
// Only super_admins may target another region; others are forced to ctx region.
regionId: writeRegion(ctx, regionId),
availableInAllRegions,
storeIdsByRegion: normalizedStoreIdsByRegion,
incrementStep,
productType,
skus: skuInputs,
@ -220,13 +281,16 @@ export const productRouter = router({
}
}),
updateProduct: protectedProcedure
updateProduct: adminProcedure
.input(z.object({
id: z.number(),
name: z.string().min(1, 'Name is required'),
shortDescription: z.string().optional(),
longDescription: z.string().optional(),
storeId: z.number().min(1, 'Store is required'),
storeId: z.number().min(1, 'Store is required').optional(),
regionId: z.number().int().positive().optional(),
availableInAllRegions: z.boolean().optional(),
storeIdsByRegion: z.record(z.string(), z.number()).optional(),
incrementStep: z.number().optional().default(1),
productType: z.enum(['item', 'combo']).optional(),
skus: z.array(z.object({
@ -253,8 +317,20 @@ export const productRouter = router({
deletedImageKeys: z.array(z.string()).optional().default([]),
newImageUrls: z.array(z.string()).optional().default([]),
}))
.mutation(async ({ input }): Promise<{ product: AdminProductWithRelations; message: string }> => {
const { id, name, shortDescription, longDescription, storeId, incrementStep, productType, skus, deletedImageKeys, newImageUrls } = input
.mutation(async ({ input, ctx }): Promise<{ product: AdminProductWithRelations; message: string }> => {
const { id, name, shortDescription, longDescription, storeId, regionId, availableInAllRegions, storeIdsByRegion, incrementStep, productType, skus, deletedImageKeys, newImageUrls } = input
const currentProduct = await getProductByIdInDb(id, undefined)
assertOwnRestrictedProduct(ctx, currentProduct)
// All-region products are managed from superadmin-ui only.
const nextAllRegions = availableInAllRegions ?? currentProduct!.availableInAllRegions
if (nextAllRegions !== currentProduct!.availableInAllRegions) {
throw new ApiError('All-region availability can only be changed from superadmin', 403)
}
const normalizedStoreIdsByRegion = storeIdsByRegion
? Object.fromEntries(Object.entries(storeIdsByRegion).map(([k, v]) => [Number(k), v]))
: undefined
if (deletedImageKeys.length > 0) {
await deleteImageUtil({ keys: deletedImageKeys })
@ -285,6 +361,10 @@ export const productRouter = router({
shortDescription,
longDescription,
storeId,
// Only super_admins may target another region; others are forced to ctx region.
regionId: writeRegion(ctx, regionId),
availableInAllRegions,
storeIdsByRegion: normalizedStoreIdsByRegion,
incrementStep,
productType,
skus: skuInputs,
@ -359,27 +439,27 @@ export const productRouter = router({
return { success: true, review: updatedReview }
}),
getGroups: protectedProcedure
.query(async (): Promise<AdminProductGroupsResult> => {
getGroups: adminProcedure
.query(async ({ ctx }): Promise<AdminProductGroupsResult> => {
// getAllProductGroupsInDb already returns groups with products mapped
// as AdminSku[] (SKU ids per the ProductsSelector).
const groups = await getAllProductGroupsInDb()
const groups = await getAllProductGroupsInDb(scopedRegion(ctx))
return {
groups,
}
}),
createGroup: protectedProcedure
createGroup: adminProcedure
.input(z.object({
group_name: z.string().min(1),
description: z.string().optional(),
product_ids: z.array(z.number()).default([]),
}))
.mutation(async ({ input }): Promise<AdminProductGroupResponse> => {
.mutation(async ({ input, ctx }): Promise<AdminProductGroupResponse> => {
const { group_name, description, product_ids } = input;
const newGroup = await createProductGroupInDb(group_name, description, product_ids)
const newGroup = await createProductGroupInDb(group_name, description, product_ids, ctxRegion(ctx))
await scheduleStoreInitialization()
@ -433,7 +513,7 @@ export const productRouter = router({
}
}),
updateProductPrices: protectedProcedure
updateProductPrices: adminProcedure
.input(z.object({
updates: z.array(z.object({
productId: z.number(),
@ -443,17 +523,36 @@ export const productRouter = router({
isFlashAvailable: z.boolean().optional(),
})),
}))
.mutation(async ({ input }): Promise<AdminUpdateProductPricesResult> => {
.mutation(async ({ input, ctx }): Promise<AdminUpdateProductPricesResult> => {
const { updates } = input;
if (updates.length === 0) {
throw new ApiError('No updates provided', 400)
}
if (updates.length === 0) {
throw new ApiError('No updates provided', 400)
}
const result = await updateProductPricesInDb(updates)
// Non-superadmins may not touch SKUs of foreign-region restricted
// products; fold those ids into invalidIds (batch semantics preserved).
let scopedUpdates = updates
const foreignIds: number[] = []
if (!isSuperAdmin(ctx)) {
const regions = await getSkuProductRegionsInDb(updates.map((u) => u.productId))
const bySku = new Map(regions.map((r) => [r.skuId, r]))
const region = ctxRegion(ctx)
scopedUpdates = updates.filter((u) => {
const r = bySku.get(u.productId)
if (r && !r.availableInAllRegions && r.regionId !== region) {
foreignIds.push(u.productId)
return false
}
return true
})
}
if (result.invalidIds.length > 0) {
throw new ApiError(`Invalid product IDs: ${result.invalidIds.join(', ')}`, 400)
const result = await updateProductPricesInDb(scopedUpdates, ctxRegion(ctx))
const invalidIds = [...result.invalidIds, ...foreignIds]
if (invalidIds.length > 0) {
throw new ApiError(`Invalid product IDs: ${invalidIds.join(', ')}`, 400)
}
await createAvailabilityCacheFile().catch((err) => {
@ -466,9 +565,9 @@ export const productRouter = router({
}
}),
getProductTags: protectedProcedure
.query(async (): Promise<{ tags: Array<{ id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: number[] | null; createdAt: Date }>; message: string }> => {
const tags = await getAllProductTagInfosInDb()
getProductTags: adminProcedure
.query(async ({ ctx }): Promise<{ tags: Array<{ id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: number[] | null; createdAt: Date }>; message: string }> => {
const tags = await getAllProductTagInfosInDb(scopedRegion(ctx))
const tagsWithImageUrls = tags.map((tag) => ({
...tag,
@ -481,10 +580,10 @@ export const productRouter = router({
}
}),
getProductTagById: protectedProcedure
getProductTagById: adminProcedure
.input(z.object({ id: z.number() }))
.query(async ({ input }): Promise<{ tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[]; createdAt: Date; products: Array<{ productId: number; tagId: number; assignedAt: Date; product: any }>; productIds: number[] }; message: string }> => {
const tag = await getProductTagByIdInDb(input.id)
.query(async ({ input, ctx }): Promise<{ tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[]; createdAt: Date; products: Array<{ productId: number; tagId: number; assignedAt: Date; product: any }>; productIds: number[] }; message: string }> => {
const tag = await getProductTagByIdInDb(input.id, ctxRegion(ctx))
if (!tag) {
throw new ApiError('Tag not found', 404)
@ -501,7 +600,7 @@ export const productRouter = router({
}
}),
createProductTag: protectedProcedure
createProductTag: adminProcedure
.input(z.object({
tagName: z.string().min(1, 'Tag name is required'),
tagDescription: z.string().optional(),
@ -511,10 +610,10 @@ export const productRouter = router({
productIds: z.array(z.number()).optional().default([]),
uploadUrls: z.array(z.string()).optional().default([]),
}))
.mutation(async ({ input }): Promise<{ tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[]; createdAt: Date }; message: string }> => {
.mutation(async ({ input, ctx }): Promise<{ tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[]; createdAt: Date }; message: string }> => {
const { tagName, tagDescription, imageUrl, isDashboardTag, relatedStores, productIds, uploadUrls } = input
const existingTag = await checkProductTagExistsByName(tagName.trim())
const existingTag = await checkProductTagExistsByName(tagName.trim(), ctx.staffUser!.regionId)
if (existingTag) {
throw new ApiError('A tag with this name already exists', 400)
}
@ -526,6 +625,7 @@ export const productRouter = router({
isDashboardTag,
relatedStores,
sortOrder: productIds,
regionId: ctx.staffUser?.regionId,
})
await replaceTagProducts(createdTag.id, productIds)
@ -547,7 +647,7 @@ export const productRouter = router({
}
}),
updateProductTag: protectedProcedure
updateProductTag: adminProcedure
.input(z.object({
id: z.number(),
tagName: z.string().min(1).optional(),
@ -558,7 +658,7 @@ export const productRouter = router({
productIds: z.array(z.number()).optional(),
uploadUrls: z.array(z.string()).optional().default([]),
}))
.mutation(async ({ input }): Promise<{ tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[]; createdAt: Date }; message: string }> => {
.mutation(async ({ input, ctx }): Promise<{ tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[]; createdAt: Date }; message: string }> => {
const { id, tagName, tagDescription, imageUrl, isDashboardTag, relatedStores, productIds, uploadUrls } = input
const currentTag = await getProductTagInfoByIdInDb(id)
@ -580,7 +680,7 @@ export const productRouter = router({
isDashboardTag,
relatedStores,
sortOrder: productIds,
})
}, ctxRegion(ctx))
if (productIds !== undefined) {
await replaceTagProducts(id, productIds)

View file

@ -0,0 +1,155 @@
import { router, protectedProcedure, superAdminProcedure, adminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import { ApiError } from '@/src/lib/api-error'
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
import {
getRegions as getRegionsFromDb,
getRegionById as getRegionByIdFromDb,
createRegion as createRegionInDb,
updateRegion as updateRegionInDb,
addRegionBound as addRegionBoundInDb,
deleteRegionBound as deleteRegionBoundFromDb,
backfillMarketStatsForRegion as backfillMarketStatsForRegionInDb,
} from '@/src/dbService'
import type { Region } from '@packages/shared'
const boundInput = z.object({
id: z.number().int().positive().optional(),
geojson: z.string().min(1, 'GeoJSON is required'),
name: z.string().min(1, 'Bound name is required'),
description: z.string().min(1, 'Bound description is required'),
priority: z.number().int().min(0).optional(),
})
const telegramCredInput = z.object({
botToken: z.string().min(1, 'Bot token is required'),
chatId: z.string().min(1, 'Chat ID is required'),
})
/** Reject duplicate priorities within one bounds payload. */
function assertUniquePriorities(bounds: { priority?: number }[] | undefined): void {
if (!bounds) return
const seen = new Set<number>()
for (const bound of bounds) {
const priority = bound.priority ?? 0
if (seen.has(priority)) {
throw new ApiError(`Duplicate bound priority ${priority}: priorities must be unique within a region`, 400)
}
seen.add(priority)
}
}
export const regionRouter = router({
getRegions: protectedProcedure.query(
async (): Promise<{ regions: Region[]; count: number }> => {
const regions = await getRegionsFromDb()
return { regions, count: regions.length }
}
),
getRegionById: protectedProcedure
.input(z.object({ id: z.number() }))
.query(async ({ input }): Promise<{ region: Region }> => {
const region = await getRegionByIdFromDb(input.id)
if (!region) {
throw new ApiError('Region not found', 404)
}
return { region }
}),
getMyRegionBounds: adminProcedure
.query(async ({ ctx }) => {
const regionId = ctx.staffUser?.regionId
if (regionId == null) return { bounds: [] }
const region = await getRegionByIdFromDb(regionId)
return { bounds: region?.bounds ?? [] }
}),
createRegion: superAdminProcedure
.input(
z.object({
name: z.string().min(1, 'Name is required'),
description: z.string().nullish(),
bounds: z.array(boundInput).optional(),
creds: z.array(telegramCredInput).min(1, 'At least one Telegram cred is required'),
})
)
.mutation(async ({ input }): Promise<{ region: Region; message: string }> => {
assertUniquePriorities(input.bounds)
const region = await createRegionInDb({
name: input.name,
description: input.description ?? null,
bounds: input.bounds,
creds: input.creds,
})
// New region: give every existing SKU an (out-of-stock) market-stats row.
await backfillMarketStatsForRegionInDb(region.id)
// Regenerate cache files so the new region gets its own set.
await scheduleStoreInitialization()
return { region, message: 'Region created successfully' }
}),
updateRegion: superAdminProcedure
.input(
z.object({
id: z.number(),
name: z.string().min(1, 'Name is required').optional(),
description: z.string().nullish(),
bounds: z.array(boundInput).optional(),
})
)
.mutation(async ({ input }): Promise<{ region: Region; message: string }> => {
assertUniquePriorities(input.bounds)
const region = await updateRegionInDb(input.id, {
name: input.name,
description: input.description,
bounds: input.bounds,
})
if (!region) {
throw new ApiError('Region not found', 404)
}
return { region, message: 'Region updated successfully' }
}),
// Regions are non-deletable: many tables reference region_id.
deleteRegion: superAdminProcedure
.input(z.object({ id: z.number() }))
.mutation(async (): Promise<{ message: string }> => {
throw new ApiError('Regions cannot be deleted', 400)
}),
addRegionBound: superAdminProcedure
.input(z.object({
regionId: z.number(),
geojson: z.string().min(1),
name: z.string().min(1, 'Bound name is required'),
description: z.string().min(1, 'Bound description is required'),
priority: z.number().int().min(0).optional(),
}))
.mutation(async ({ input }) => {
const region = await getRegionByIdFromDb(input.regionId)
if (!region) {
throw new ApiError('Region not found', 404)
}
if (region.bounds?.some((b) => (b.priority ?? 0) === (input.priority ?? 0))) {
throw new ApiError(`Duplicate bound priority ${input.priority ?? 0}: priorities must be unique within a region`, 400)
}
const bound = await addRegionBoundInDb(input.regionId, {
geojson: input.geojson,
name: input.name,
description: input.description,
priority: input.priority,
})
return { bound, message: 'Bound added successfully' }
}),
deleteRegionBound: superAdminProcedure
.input(z.object({ id: z.number() }))
.mutation(async ({ input }): Promise<{ message: string }> => {
await deleteRegionBoundFromDb(input.id)
return { message: 'Bound deleted successfully' }
}),
})

View file

@ -80,7 +80,7 @@ export const slotsRouter = router({
throw new TRPCError({ code: "UNAUTHORIZED", message: "Access denied" });
}
const slots = await getActiveSlotsWithProductsInDb(20)
const slots = await getActiveSlotsWithProductsInDb(20, ctx.staffUser!.regionId)
return {
slots,
@ -109,6 +109,7 @@ export const slotsRouter = router({
freezeTime,
isActive,
skuIds,
regionId: ctx.staffUser!.regionId,
// Complete SlotSnippetInput payloads — groupIds unused by sqlite but
// always sent; absent validTill becomes null.
vendorSnippets: snippets?.map((snippet) => ({

View file

@ -1,4 +1,4 @@
import { router, publicProcedure, protectedProcedure } from '@/src/trpc/trpc-index'
import { router, publicProcedure, protectedProcedure, superAdminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod';
import bcrypt from 'bcryptjs';
import { SignJWT } from 'jose';
@ -6,11 +6,13 @@ import { getEncodedJwtSecret } from '@/src/lib/env-exporter';
import { ApiError } from '@/src/lib/api-error'
import {
getStaffUserByName,
getStaffUserById,
getAllStaff,
checkStaffUserExists,
checkStaffRoleExists,
createStaffUser,
getAllRoles,
getStaffRoleById,
upsertStaffNotifCred,
} from '@/src/dbService'
import { notifyAllAdmins } from '@/src/lib/admin-notif'
@ -44,10 +46,18 @@ export const staffUserRouter = router({
.setExpirationTime('30d')
.sign(getEncodedJwtSecret());
const role = staff.staffRoleId != null ? await getStaffRoleById(staff.staffRoleId) : null
return {
message: 'Login successful',
token,
staff: { id: staff.id, name: staff.name },
staff: {
id: staff.id,
name: staff.name,
regionId: staff.regionId,
staffRoleId: staff.staffRoleId ?? null,
roleName: role?.roleName ?? null,
},
};
}),
@ -59,6 +69,7 @@ export const staffUserRouter = router({
const transformedStaff = staff.map((user) => ({
id: user.id,
name: user.name,
regionId: user.regionId,
role: user.role ? {
id: user.role.id,
name: user.role.roleName,
@ -74,11 +85,34 @@ export const staffUserRouter = router({
};
}),
createStaffUser: protectedProcedure
getSelf: protectedProcedure
.query(async ({ ctx }) => {
const staffId = ctx.staffUser?.id
if (!staffId) {
throw new ApiError('Staff user not authenticated', 401)
}
const staff = await getStaffUserById(staffId)
if (!staff) {
throw new ApiError('Staff user not found', 404)
}
const role = staff.staffRoleId != null ? await getStaffRoleById(staff.staffRoleId) : null
return {
staff: {
id: staff.id,
name: staff.name,
regionId: staff.regionId,
staffRoleId: staff.staffRoleId ?? null,
roleName: role?.roleName ?? null,
},
}
}),
createStaffUser: superAdminProcedure
.input(z.object({
name: z.string().min(1, 'Name is required'),
password: z.string().min(6, 'Password must be at least 6 characters'),
roleId: z.number().int().positive('Role is required'),
regionId: z.number().int().positive().optional(),
}))
.mutation(async ({ input, ctx }) => {
const { name, password, roleId } = input;
@ -97,13 +131,20 @@ export const staffUserRouter = router({
throw new ApiError('Invalid role selected', 400);
}
// Default region: superadmin's own region.
const regionId = input.regionId ?? ctx.staffUser?.regionId;
if (!regionId) {
throw new ApiError('Region is required', 400);
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 12);
// Create staff user
const newUser = await createStaffUser(name, hashedPassword, roleId);
const newUser = await createStaffUser(name, hashedPassword, roleId, regionId);
return { success: true, user: { id: newUser.id, name: newUser.name } };
return { success: true, user: { id: newUser.id, name: newUser.name, regionId: newUser.regionId } };
}),
getRoles: protectedProcedure

View file

@ -1,4 +1,4 @@
import { router, protectedProcedure } from '@/src/trpc/trpc-index'
import { router, protectedProcedure, adminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod';
import { ApiError } from '@/src/lib/api-error'
import { extractKeyFromPresignedUrl, deleteImageUtil, scaffoldAssetUrl } from '@/src/lib/s3-client'
@ -12,10 +12,38 @@ import {
} from '@/src/dbService'
import type { Store } from '@packages/shared'
// Write target region: only super_admins may target another region; every other
// staff member's writes are forced to their own region (client input ignored).
const writeRegion = (ctx: any, inputRegion?: number) =>
ctx.staffUser?.staffRoleName === 'super_admin'
? (inputRegion ?? ctx.staffUser?.regionId)
: ctx.staffUser?.regionId
export const storeRouter = router({
getStores: protectedProcedure
getStores: adminProcedure
.query(async ({ ctx }): Promise<{ stores: any[]; count: number }> => {
const stores = await getAllStoresFromDb();
const regionId = ctx.staffUser?.staffRoleName === 'super_admin'
? undefined
: ctx.staffUser?.regionId
const stores = await getAllStoresFromDb(regionId);
await Promise.all(stores.map(async store => {
if(store.imageUrl)
store.imageUrl = scaffoldAssetUrl(store.imageUrl)
})).catch((e) => {
throw new ApiError("Unable to find store image urls")
})
return {
stores,
count: stores.length,
};
}),
getStoresForAllRegions: adminProcedure
.query(async (): Promise<{ stores: any[]; count: number }> => {
const stores = await getAllStoresFromDb(undefined);
await Promise.all(stores.map(async store => {
if(store.imageUrl)
@ -48,17 +76,24 @@ export const storeRouter = router({
};
}),
createStore: protectedProcedure
createStore: adminProcedure
.input(z.object({
name: z.string().min(1, "Name is required"),
description: z.string().optional(),
imageUrl: z.string().optional(),
owner: z.number().min(1, "Owner is required"),
products: z.array(z.number()).optional(),
regionId: z.number().int().positive().optional(),
availableInAllRegions: z.boolean().optional(),
}))
.mutation(async ({ input, ctx }): Promise<{ store: Store; message: string }> => {
const { name, description, imageUrl, owner, products } = input;
// All-region stores are managed from superadmin-ui only.
if (input.availableInAllRegions) {
throw new ApiError("All-region stores can only be created from superadmin", 403);
}
const imageKey = imageUrl ? extractKeyFromPresignedUrl(imageUrl) : undefined;
const newStore = await createStoreInDb(
@ -67,6 +102,7 @@ export const storeRouter = router({
description,
imageUrl: imageKey,
owner,
regionId: writeRegion(ctx, input.regionId),
},
products
);
@ -80,7 +116,7 @@ export const storeRouter = router({
};
}),
updateStore: protectedProcedure
updateStore: adminProcedure
.input(z.object({
id: z.number(),
name: z.string().min(1, "Name is required"),
@ -88,6 +124,8 @@ export const storeRouter = router({
imageUrl: z.string().optional(),
owner: z.number().min(1, "Owner is required"),
products: z.array(z.number()).optional(),
regionId: z.number().int().positive().optional(),
availableInAllRegions: z.boolean().optional(),
}))
.mutation(async ({ input, ctx }): Promise<{ store: Store; message: string }> => {
const { id, name, description, imageUrl, owner, products } = input;
@ -97,7 +135,16 @@ export const storeRouter = router({
if (!existingStore) {
throw new ApiError("Store not found", 404);
}
// All-region stores are managed from superadmin-ui only.
if (existingStore.regionId == null || input.availableInAllRegions) {
throw new ApiError("All-region stores can only be edited from superadmin", 403);
}
if (
ctx.staffUser?.staffRoleName !== 'super_admin' &&
existingStore.regionId !== ctx.staffUser?.regionId
) {
throw new ApiError("Store does not belong to your region", 403);
}
const oldImageKey = existingStore.imageUrl;
const newImageKey = imageUrl ? extractKeyFromPresignedUrl(imageUrl) : oldImageKey;
@ -123,6 +170,7 @@ export const storeRouter = router({
description,
imageUrl: newImageKey,
owner,
regionId: writeRegion(ctx, input.regionId),
},
products
);

View file

@ -186,15 +186,17 @@ export const userRouter = {
text: z.string().min(1, 'Message is required'),
imageUrl: z.string().optional(),
}))
.mutation(async ({ input }) => {
.mutation(async ({ input, ctx }) => {
const { userIds, title, text, imageUrl } = input;
const regionId = ctx.staffUser?.regionId;
let tokens: string[] = [];
if (userIds.length === 0) {
// Send to all users - get tokens from both logged-in and unlogged users
const loggedInTokens = await getAllNotifCreds();
const unloggedTokens = await getAllUnloggedTokens();
// Broadcast: only this admin's region. Region-less tokens (older app
// versions) are excluded.
const loggedInTokens = await getAllNotifCreds(regionId);
const unloggedTokens = await getAllUnloggedTokens(regionId);
tokens = [
...loggedInTokens.map(t => t.token),

View file

@ -1,6 +1,5 @@
import { router, publicProcedure, protectedProcedure } from '@/src/trpc/trpc-index'
import { router, publicProcedure, protectedProcedure, adminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import dayjs from 'dayjs'
import { getAppUrl } from '@/src/lib/env-exporter'
import {
checkVendorSnippetExists as checkVendorSnippetExistsInDb,
@ -14,7 +13,6 @@ import {
getVendorSlotById as getVendorSlotByIdInDb,
getVendorOrdersBySlotId as getVendorOrdersBySlotIdInDb,
updateVendorOrderItemPackaging as updateVendorOrderItemPackagingInDb,
getSlotsAfterDate as getSlotsAfterDateInDb,
composeSkuName,
composeUnitNotation,
} from '@/src/dbService'
@ -24,7 +22,6 @@ import type {
AdminVendorSnippetDeleteResult,
AdminVendorSnippetOrdersResult,
AdminVendorSnippetOrdersWithSlotResult,
AdminUpcomingSlotsResult,
AdminVendorUpdatePackagingResult,
} from '@packages/shared'
@ -46,7 +43,7 @@ const updateSnippetSchema = z.object({
});
export const vendorSnippetsRouter = router({
create: protectedProcedure
create: adminProcedure
.input(createSnippetSchema)
.mutation(async ({ input, ctx }): Promise<AdminVendorSnippet> => {
const { snippetCode, slotId, skuIds, validTill, isPermanent } = input;
@ -80,17 +77,22 @@ export const vendorSnippetsRouter = router({
skuIds,
isPermanent,
validTill: validTill ? new Date(validTill) : undefined,
regionId: ctx.staffUser?.regionId,
})
return result
}),
getAll: protectedProcedure
.query(async (): Promise<AdminVendorSnippetWithProducts[]> => {
getAll: adminProcedure
.query(async ({ ctx }): Promise<AdminVendorSnippetWithProducts[]> => {
console.log('from the vendor snipptes methods')
try {
const result = await getAllVendorSnippetsInDb()
const regionId = ctx.staffUser?.staffRoleName === 'super_admin'
? undefined
: ctx.staffUser?.regionId
const result = await getAllVendorSnippetsInDb(regionId)
const snippetsWithProducts = await Promise.all(
result.map(async (snippet) => {
@ -256,22 +258,6 @@ export const vendorSnippetsRouter = router({
}
}),
getUpcomingSlots: publicProcedure
.query(async (): Promise<AdminUpcomingSlotsResult> => {
const threeHoursAgo = dayjs().subtract(3, 'hour').toDate();
const slots = await getSlotsAfterDateInDb(threeHoursAgo)
return {
success: true,
data: slots.map(slot => ({
id: slot.id,
deliveryTime: slot.deliveryTime.toISOString(),
freezeTime: slot.freezeTime.toISOString(),
deliverySequence: slot.deliverySequence,
})),
}
}),
getOrdersBySnippetAndSlot: publicProcedure
.input(z.object({
snippetCode: z.string().min(1, "Snippet code is required"),

View file

@ -6,10 +6,14 @@ import {
getCacheVersion,
getAvailabilityVersionNum,
getSlotsVersionNum,
getRegionSummaries,
getRegions,
} from '@/src/dbService'
import { DEFAULT_REGION_ID } from '@packages/shared'
import type { StoresSummaryResponse } from '@packages/shared'
import { polygon as turfPolygon, point as turfPoint } from '@turf/helpers';
import { booleanPointInPolygon } from '@turf/boolean-point-in-polygon';
import { extractPolygonRings, resolveBoundForPoint, type ResolvedBound } from '@/src/lib/region-resolver';
import { z } from 'zod';
import { mbnrGeoJson } from '@/src/lib/mbnr-geojson'
import { generateUploadUrl } from '@/src/lib/s3-client'
@ -21,11 +25,14 @@ import { getAssetsDomain, getApiCacheKey } from '@/src/lib/env-exporter'
const polygon = turfPolygon(mbnrGeoJson.features[0].geometry.coordinates);
export async function scaffoldEssentialConsts() {
const consts = await getAllConstValues();
const cacheVersion = await getCacheVersion()
const availabilityVersionNum = await getAvailabilityVersionNum()
const slotsVersionNum = await getSlotsVersionNum()
export async function scaffoldEssentialConsts(regionId?: number, boundId?: number | null) {
const consts = await getAllConstValues(regionId, boundId);
const cacheVersion = await getCacheVersion(regionId)
const availabilityVersionNum = await getAvailabilityVersionNum(regionId)
const slotsVersionNum = await getSlotsVersionNum(regionId)
const cachePathPrefix =
regionId == null || regionId === DEFAULT_REGION_ID ? '' : `r-${regionId}/`
return {
freeDeliveryThreshold: consts[CONST_KEYS.freeDeliveryThreshold] ?? 200,
@ -48,22 +55,33 @@ export async function scaffoldEssentialConsts() {
cacheVersion,
availabilityVersionNum,
slotsVersionNum,
cachePathPrefix,
};
}
export type { ResolvedBound } from '@/src/lib/region-resolver';
export { resolveBoundForPoint } from '@/src/lib/region-resolver';
export const commonApiRouter = router({
product: commonRouter,
getStoresSummary: publicProcedure
.query(async (): Promise<StoresSummaryResponse> => {
.input(z.object({ regionId: z.number().int().positive().optional() }).optional())
.query(async ({ input }): Promise<StoresSummaryResponse> => {
const stores = await getStoresSummary();
const stores = await getStoresSummary(input?.regionId);
return {
stores,
};
}),
getRegions: publicProcedure
.query(async () => {
const regions = await getRegionSummaries();
return { regions };
}),
checkLocationInPolygon: publicProcedure
.input(z.object({
lat: z.number().min(-90).max(90),
@ -80,6 +98,15 @@ export const commonApiRouter = router({
}
}),
resolveRegionForLocation: publicProcedure
.input(z.object({
lat: z.number().min(-90).max(90),
lng: z.number().min(-180).max(180),
}))
.query(async ({ input }) => {
return resolveBoundForPoint(input.lat, input.lng);
}),
generateUploadUrls: protectedProcedure
.input(z.object({
contextString: z.enum(['review', 'review_response', 'product_info', 'notification', 'store', 'complaint', 'profile', 'tags']),
@ -138,16 +165,19 @@ export const commonApiRouter = router({
}),
essentialConsts: publicProcedure
.query(async ({ ctx }) => {
.input(z.object({ regionId: z.number().optional(), boundId: z.number().optional() }).optional())
.query(async ({ ctx, input }) => {
const regionId = input?.regionId
const boundId = input?.boundId
const requestUrl = ctx.req.url
const host = new URL(requestUrl).host
console.log('essentialConsts request', { host, url: requestUrl })
console.log('essentialConsts request', { host, url: requestUrl, regionId, boundId })
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();
const response = await readEssentialConstsFromKv(regionId, boundId);
const shouldShowNotice = host.includes('raw') || host.includes('mf')
return {

View file

@ -1,4 +1,4 @@
import { router, publicProcedure } from '@/src/trpc/trpc-index'
import { router, publicProcedure, adminProcedure } from '@/src/trpc/trpc-index'
import {
getSuspendedSkuIds,
getNextDeliveryDateWithCapacity,
@ -7,21 +7,19 @@ import {
getAllTagsForCache,
getAllTagProductMappings,
getAvailabilityForCache,
getRegionSummaries,
} from '@/src/dbService'
import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url, scaffoldAssetUrl } from '@/src/lib/s3-client'
import { getAllProducts as getAllProductsFromCache } from '@/src/stores/product-store'
import { getConstant } from '@/src/lib/const-store'
import { CONST_KEYS } from '@/src/lib/const-keys'
// Re-export with original name for backwards compatibility
export const getNextDeliveryDate = getNextDeliveryDateWithCapacity
export async function scaffoldProducts() {
export async function scaffoldProducts(regionId?: number) {
// Get all products from cache
let products = await getAllProductsFromCache();
let products = await getAllProductsFromCache(regionId);
products = products.filter(item => Boolean(item.id))
const suspendedSkuIds = new Set(await getSuspendedSkuIds());
const suspendedSkuIds = new Set(await getSuspendedSkuIds(regionId));
// Filter out suspended products
products = products.filter(product => !suspendedSkuIds.has(product.id));
@ -29,7 +27,7 @@ export async function scaffoldProducts() {
// Format products to match the expected response structure
const formattedProducts = await Promise.all(
products.map(async (product) => {
const nextDeliveryDate = await getNextDeliveryDateWithCapacity(product.id);
const nextDeliveryDate = await getNextDeliveryDateWithCapacity(product.id, regionId);
return {
id: product.id,
name: product.name,
@ -55,8 +53,8 @@ export async function scaffoldProducts() {
// Fetch all product tags with their mapped product ids
const [allTags, tagMappings] = await Promise.all([
getAllTagsForCache(),
getAllTagProductMappings(),
getAllTagsForCache(regionId),
getAllTagProductMappings(regionId),
])
// Order tags by the admin-defined tagsOrder (unknown tags go to the end).
@ -117,8 +115,8 @@ export async function scaffoldProducts() {
};
}
export async function scaffoldAvailability() {
const availability = await getAvailabilityForCache()
export async function scaffoldAvailability(regionId?: number) {
const availability = await getAvailabilityForCache(regionId)
return {
availability,
@ -127,15 +125,41 @@ export async function scaffoldAvailability() {
}
export const commonRouter = router({
getAllProductsSummary: publicProcedure
.query(async () => {
const response = await scaffoldProducts();
getAllProductsSummary: adminProcedure
.query(async ({ ctx }) => {
if (ctx.staffUser?.staffRoleName === 'super_admin') {
// Union across regions so every product is pickable (dedupe by id,
// union tag productIds).
const regions = await getRegionSummaries()
const productsById = new Map<number, any>()
const tagsById = new Map<number, any>()
for (const region of regions) {
const response = await scaffoldProducts(region.id)
for (const product of response.products) {
if (!productsById.has(product.id)) productsById.set(product.id, product)
}
for (const tag of response.tags) {
const existing = tagsById.get(tag.id)
if (!existing) {
tagsById.set(tag.id, { ...tag, productIds: [...(tag.productIds || [])] })
} else {
const merged = new Set([...(existing.productIds || []), ...(tag.productIds || [])])
existing.productIds = [...merged]
}
}
}
const products = [...productsById.values()]
return { products, count: products.length, tags: [...tagsById.values()] }
}
const response = await scaffoldProducts(ctx.staffUser?.regionId);
return response;
}),
getAllSkusSummary: publicProcedure
.query(async () => {
const skus = await getAllSkusSummaryInDb()
getAllSkusSummary: adminProcedure
.query(async ({ ctx }) => {
const skus = await getAllSkusSummaryInDb(
ctx.staffUser?.staffRoleName === 'super_admin' ? undefined : ctx.staffUser?.regionId
)
return { skus }
}),

View file

@ -0,0 +1,47 @@
import { router, publicProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod';
import bcrypt from 'bcryptjs';
import { SignJWT } from 'jose';
import { getEncodedJwtSecret } from '@/src/lib/env-exporter';
import { ApiError } from '@/src/lib/api-error'
import { getSuperadminByName } from '@/src/dbService'
export const superadminAuthRouter = router({
login: publicProcedure
.input(z.object({
name: z.string(),
password: z.string(),
}))
.mutation(async ({ input }) => {
const { name, password } = input;
if (!name || !password) {
throw new ApiError('Name and password are required', 400);
}
const row = await getSuperadminByName(name);
if (!row) {
throw new ApiError('Invalid credentials', 401);
}
const isPasswordValid = await bcrypt.compare(password, row.password);
if (!isPasswordValid) {
throw new ApiError('Invalid credentials', 401);
}
const token = await new SignJWT({ superadminId: row.id, name: row.name })
.setProtectedHeader({ alg: 'HS256' })
.setExpirationTime('30d')
.sign(getEncodedJwtSecret());
return {
message: 'Login successful',
token,
superadmin: {
id: row.id,
name: row.name,
},
};
}),
});

View file

@ -0,0 +1,123 @@
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod';
import { DEFAULT_REGION_ID } from '@packages/shared';
import { computeConstants } from '@/src/lib/const-store'
import { refreshGenKv } from '@/src/lib/gen-store'
import { CONST_KEYS, REGION_CONST_KEYS_ARRAY } from '@/src/lib/const-keys'
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
import { createAllCacheFiles } from '@/src/lib/cloud_cache'
import {
getAllConstants as getAllConstantsFromDb,
upsertConstants as upsertConstantsInDb,
getRegionConstants as getRegionConstantsFromDb,
upsertRegionConstants as upsertRegionConstantsInDb,
getRegionById as getRegionByIdFromDb,
} from '@/src/dbService'
import type { Constant, ConstantUpdateResult } from '@packages/shared'
// Constants that are baked into the versioned cache files (products.json etc.)
// — changing them requires regenerating the cache so the user app picks it up.
const CACHE_AFFECTING_KEYS: string[] = [
CONST_KEYS.tagsOrder,
]
// Superadmins have no region of their own. Regional constant keys still need
// one, so the wrappers accept an explicit regionId and default to the legacy
// region (DEFAULT_REGION_ID) — matching what the admin.* scope did for the
// superadmin-ui's region-bound staff row.
export const superadminConstRouter = router({
getConstants: superadminProcedure
.input(z.object({
regionId: z.number().int().positive().optional(),
boundId: z.number().int().positive().optional(),
}).optional())
.query(async ({ input }): Promise<Constant[]> => {
const regionId = input?.regionId ?? DEFAULT_REGION_ID;
const boundId = input?.boundId ?? null;
if (boundId != null) {
const region = await getRegionByIdFromDb(regionId);
if (!region?.bounds?.some((b) => b.id === boundId)) {
throw new Error('Bound does not belong to the region');
}
}
const [globals, regional] = await Promise.all([
getAllConstantsFromDb(),
getRegionConstantsFromDb(regionId, boundId),
]);
return [...globals, ...regional];
}),
updateConstants: superadminProcedure
.input(z.object({
constants: z.array(z.object({
key: z.string(),
value: z.any(),
})),
regionId: z.number().int().positive().optional(),
boundId: z.number().int().positive().optional(),
}))
.mutation(async ({ input }): Promise<ConstantUpdateResult> => {
const { constants } = input;
const regionId = input.regionId ?? DEFAULT_REGION_ID;
const boundId = input.boundId ?? null;
if (boundId != null) {
const region = await getRegionByIdFromDb(regionId);
if (!region?.bounds?.some((b) => b.id === boundId)) {
throw new Error('Bound does not belong to the region');
}
}
const validKeys = Object.values(CONST_KEYS) as string[];
const invalidKeys = constants
.filter(c => !validKeys.includes(c.key))
.map(c => c.key);
if (invalidKeys.length > 0) {
throw new Error(`Invalid constant keys: ${invalidKeys.join(', ')}`);
}
console.log(input)
const regional = constants.filter((c) => REGION_CONST_KEYS_ARRAY.includes(c.key));
const global = constants.filter((c) => !REGION_CONST_KEYS_ARRAY.includes(c.key));
if (global.length > 0) {
await upsertConstantsInDb(global);
}
if (regional.length > 0) {
await upsertRegionConstantsInDb(regionId, boundId, regional);
}
// Refresh all constants in Redis after database update
await computeConstants();
// Mirror the full essentialConsts response into KV for client reads.
await refreshGenKv(regionId, boundId);
// 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).
if (constants.some((c) => CACHE_AFFECTING_KEYS.includes(c.key))) {
await scheduleStoreInitialization()
}
return {
success: true,
updatedCount: constants.length,
keys: constants.map(c => c.key),
};
}),
regenerateCache: superadminProcedure
.mutation(async () => {
// Manual recovery/diagnostics: run the full cache regen inline
// (same work the CacheCreator DO alarm does) and report versions.
const result = await createAllCacheFiles()
return {
success: true,
cacheVersion: result.cacheVersion,
slotsVersion: result.slotsVersion,
availabilityVersion: result.availabilityVersion,
}
}),
});

View file

@ -0,0 +1,341 @@
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import { ApiError } from '@/src/lib/api-error'
import { scaffoldAssetUrl, claimUploadUrl, extractKeyFromPresignedUrl, deleteImageUtil } from '@/src/lib/s3-client'
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
import { createAvailabilityCacheFile } from '@/src/lib/cloud_cache'
import {
getAllProducts as getAllProductsInDb,
getProductById as getProductByIdInDb,
deleteProduct as deleteProductInDb,
toggleProductOutOfStock as toggleProductOutOfStockInDb,
getAllSkusSummary as getAllSkusSummaryInDb,
checkProductExistsByName,
createProduct as createProductInDb,
updateProduct as updateProductInDb,
} from '@/src/dbService'
import type {
AdminProductWithRelations,
AdminProductListResponse,
AdminProductResponse,
AdminDeleteProductResult,
AdminToggleOutOfStockResult,
} from '@packages/shared'
const regionStatsInput = z.record(
z.string(),
z.object({
price: z.number().positive().optional().nullable(),
marketPrice: z.number().optional().nullable(),
flashPrice: z.number().optional().nullable(),
isFlashAvailable: z.boolean().optional(),
isOffer: z.boolean().optional(),
isSuspended: z.boolean().optional(),
isOutOfStock: z.boolean().optional(),
storeId: z.number().int().positive().optional().nullable(),
}).optional()
).optional()
const skuInput = z.object({
id: z.number().optional(),
name: z.string().optional().nullable(),
price: z.number().positive('Price must be positive'),
marketPrice: z.number().optional().nullable(),
images: z.array(z.string()).optional().default([]),
isFlashAvailable: z.boolean().optional().default(false),
flashPrice: z.number().optional().nullable(),
isOutOfStock: z.boolean().optional().default(false),
isOffer: z.boolean().optional().default(false),
isComboOnly: z.boolean().optional().default(false),
isDeleted: z.boolean().optional().default(false),
isSuspended: z.boolean().optional().default(false),
features: z.array(z.object({
featureName: z.string().nullable().optional(),
featureValue: z.string().min(1, 'Value is required'),
})).min(1, 'At least one feature is required'),
comboItems: z.array(z.object({
skuId: z.number().int().positive(),
})).optional(),
regionStats: regionStatsInput,
})
export const superadminProductRouter = router({
getAllSkusSummary: superadminProcedure
.query(async () => {
const skus = await getAllSkusSummaryInDb(undefined)
return { skus }
}),
getProducts: superadminProcedure
.query(async (): Promise<AdminProductListResponse> => {
const products = await getAllProductsInDb(undefined)
const productsWithImageUrls = products.map((product) => ({
...product,
skus: product.skus.map((sku) => ({
...sku,
images: scaffoldAssetUrl((sku.images as string[]) || []),
})),
}))
return {
products: productsWithImageUrls,
count: productsWithImageUrls.length,
}
}),
getProductById: superadminProcedure
.input(z.object({
id: z.number(),
}))
.query(async ({ input }): Promise<AdminProductResponse> => {
const { id } = input;
const product = await getProductByIdInDb(id, undefined)
if (!product) {
throw new ApiError('Product not found', 404)
}
const productWithImageUrls = {
...product,
skus: product.skus.map((sku) => ({
...sku,
images: scaffoldAssetUrl((sku.images as string[]) || []),
})),
}
return {
product: productWithImageUrls,
}
}),
deleteProduct: superadminProcedure
.input(z.object({
id: z.number(),
}))
.mutation(async ({ input }): Promise<AdminDeleteProductResult> => {
const { id } = input;
const currentProduct = await getProductByIdInDb(id, undefined)
if (!currentProduct) {
throw new ApiError('Product not found', 404)
}
const deletedProduct = await deleteProductInDb(id)
if (!deletedProduct) {
throw new ApiError('Product not found', 404)
}
await scheduleStoreInitialization()
return {
message: 'Product deleted successfully',
}
}),
toggleOutOfStock: superadminProcedure
.input(z.object({
id: z.number(),
regionId: z.number().int().positive(),
}))
.mutation(async ({ input }): Promise<AdminToggleOutOfStockResult> => {
const { id, regionId } = input;
const currentProduct = await getProductByIdInDb(id, undefined)
if (!currentProduct) {
throw new ApiError('Product not found', 404)
}
const result = await toggleProductOutOfStockInDb(id, regionId)
if (!result) {
throw new ApiError('Product not found', 404)
}
// Only the availability cache needs regenerating for a stock flip.
await createAvailabilityCacheFile().catch((err) => {
console.error('Failed to regenerate availability cache after stock update:', err)
})
return {
productId: result.id,
isOutOfStock: result.isOutOfStock,
message: `Product marked as ${result.isOutOfStock ? 'out of stock' : 'in stock'}`,
}
}),
createProduct: superadminProcedure
.input(z.object({
name: z.string().min(1, 'Name is required'),
shortDescription: z.string().optional(),
longDescription: z.string().optional(),
storeId: z.number().min(1, 'Store is required').optional(),
// Creator/primary region. Required in both modes: for all-region
// products it decides initial stock/prices (other regions start OOS);
// product_info.region_id itself is still nulled by the flag.
regionId: z.number().int().positive('Region is required'),
availableInAllRegions: z.boolean().optional(),
storeIdsByRegion: z.record(z.string(), z.number()).optional(),
incrementStep: z.number().optional().default(1),
productType: z.enum(['item', 'combo']).optional().default('item'),
skus: z.array(skuInput.omit({ id: true })).min(1, 'At least one SKU is required'),
}))
.mutation(async ({ input }): Promise<{ product: AdminProductWithRelations; message: string }> => {
const { name, shortDescription, longDescription, storeId, regionId, availableInAllRegions, storeIdsByRegion, incrementStep, productType, skus } = input
const normalizedStoreIdsByRegion = storeIdsByRegion
? Object.fromEntries(Object.entries(storeIdsByRegion).map(([k, v]) => [Number(k), v]))
: undefined
const existingProduct = await checkProductExistsByName(name.trim())
if (existingProduct) {
throw new ApiError('A product with this name already exists', 400)
}
const allUploadUrls: string[] = skus.flatMap((sku) => sku.images)
const skuInputs = skus.map((sku) => ({
name: sku.name ?? null,
price: sku.price,
marketPrice: sku.marketPrice ?? null,
images: sku.images.map((url) => extractKeyFromPresignedUrl(url)),
isFlashAvailable: sku.isFlashAvailable,
flashPrice: sku.flashPrice ?? null,
isOutOfStock: sku.isOutOfStock,
isOffer: sku.isOffer,
isComboOnly: sku.isComboOnly,
isDeleted: sku.isDeleted ?? false,
isSuspended: sku.isSuspended,
features: sku.features.map((f) => ({
featureName: f.featureName?.trim() || null,
featureValue: f.featureValue,
})),
comboItems: (sku.comboItems || []).map((ci) => ({ skuId: ci.skuId })),
regionStats: sku.regionStats ?? undefined,
}))
const newProduct = await createProductInDb({
name,
shortDescription,
longDescription,
storeId,
regionId,
availableInAllRegions,
storeIdsByRegion: normalizedStoreIdsByRegion,
incrementStep,
productType,
skus: skuInputs,
} as any)
if (allUploadUrls.length > 0) {
await Promise.all(allUploadUrls.map((url) => claimUploadUrl(url)))
}
await scheduleStoreInitialization()
const productWithImageUrls = {
...newProduct,
skus: newProduct.skus.map((sku) => ({
...sku,
images: scaffoldAssetUrl((sku.images as string[]) || []),
})),
}
return {
product: productWithImageUrls,
message: 'Product created successfully',
}
}),
updateProduct: superadminProcedure
.input(z.object({
id: z.number(),
name: z.string().min(1, 'Name is required'),
shortDescription: z.string().optional(),
longDescription: z.string().optional(),
storeId: z.number().min(1, 'Store is required').optional(),
regionId: z.number().int().positive().optional(),
availableInAllRegions: z.boolean().optional(),
storeIdsByRegion: z.record(z.string(), z.number()).optional(),
incrementStep: z.number().optional().default(1),
productType: z.enum(['item', 'combo']).optional(),
skus: z.array(skuInput).min(1, 'At least one SKU is required'),
deletedImageKeys: z.array(z.string()).optional().default([]),
newImageUrls: z.array(z.string()).optional().default([]),
}))
.mutation(async ({ input }): Promise<{ product: AdminProductWithRelations; message: string }> => {
const { id, name, shortDescription, longDescription, storeId, regionId, availableInAllRegions, storeIdsByRegion, incrementStep, productType, skus, deletedImageKeys, newImageUrls } = input
const currentProduct = await getProductByIdInDb(id, undefined)
if (!currentProduct) {
throw new ApiError('Product not found', 404)
}
const normalizedStoreIdsByRegion = storeIdsByRegion
? Object.fromEntries(Object.entries(storeIdsByRegion).map(([k, v]) => [Number(k), v]))
: undefined
if (deletedImageKeys.length > 0) {
await deleteImageUtil({ keys: deletedImageKeys })
}
const skuInputs = skus.map((sku) => ({
id: sku.id,
name: sku.name ?? null,
price: sku.price,
marketPrice: sku.marketPrice ?? null,
images: sku.images.map((url) => extractKeyFromPresignedUrl(url)),
isFlashAvailable: sku.isFlashAvailable,
flashPrice: sku.flashPrice ?? null,
isOutOfStock: sku.isOutOfStock,
isOffer: sku.isOffer,
isComboOnly: sku.isComboOnly,
isDeleted: sku.isDeleted ?? false,
isSuspended: sku.isSuspended,
features: sku.features.map((f) => ({
featureName: f.featureName?.trim() || null,
featureValue: f.featureValue,
})),
comboItems: (sku.comboItems || []).map((ci) => ({ skuId: ci.skuId })),
regionStats: sku.regionStats ?? undefined,
}))
const updatedProduct = await updateProductInDb(id, {
name,
shortDescription,
longDescription,
storeId,
regionId,
availableInAllRegions,
storeIdsByRegion: normalizedStoreIdsByRegion,
incrementStep,
productType,
skus: skuInputs,
} as any)
if (!updatedProduct) {
throw new ApiError('Product not found', 404)
}
if (newImageUrls.length > 0) {
await Promise.all(newImageUrls.map((url) => claimUploadUrl(url)))
}
await scheduleStoreInitialization()
const productWithImageUrls = {
...updatedProduct,
skus: updatedProduct.skus.map((sku) => ({
...sku,
images: scaffoldAssetUrl((sku.images as string[]) || []),
})),
}
return {
product: productWithImageUrls,
message: 'Product updated successfully',
}
}),
});

View file

@ -0,0 +1,147 @@
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import { ApiError } from '@/src/lib/api-error'
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
import {
getRegions as getRegionsFromDb,
getRegionById as getRegionByIdFromDb,
createRegion as createRegionInDb,
updateRegion as updateRegionInDb,
addRegionBound as addRegionBoundInDb,
deleteRegionBound as deleteRegionBoundFromDb,
backfillMarketStatsForRegion as backfillMarketStatsForRegionInDb,
} from '@/src/dbService'
import type { Region } from '@packages/shared'
const boundInput = z.object({
id: z.number().int().positive().optional(),
geojson: z.string().min(1, 'GeoJSON is required'),
name: z.string().min(1, 'Bound name is required'),
description: z.string().min(1, 'Bound description is required'),
priority: z.number().int().min(0).optional(),
})
const telegramCredInput = z.object({
botToken: z.string().min(1, 'Bot token is required'),
chatId: z.string().min(1, 'Chat ID is required'),
})
/** Reject duplicate priorities within one bounds payload. */
function assertUniquePriorities(bounds: { priority?: number }[] | undefined): void {
if (!bounds) return
const seen = new Set<number>()
for (const bound of bounds) {
const priority = bound.priority ?? 0
if (seen.has(priority)) {
throw new ApiError(`Duplicate bound priority ${priority}: priorities must be unique within a region`, 400)
}
seen.add(priority)
}
}
export const superadminRegionRouter = router({
getRegions: superadminProcedure.query(
async (): Promise<{ regions: Region[]; count: number }> => {
const regions = await getRegionsFromDb()
return { regions, count: regions.length }
}
),
getRegionById: superadminProcedure
.input(z.object({ id: z.number() }))
.query(async ({ input }): Promise<{ region: Region }> => {
const region = await getRegionByIdFromDb(input.id)
if (!region) {
throw new ApiError('Region not found', 404)
}
return { region }
}),
createRegion: superadminProcedure
.input(
z.object({
name: z.string().min(1, 'Name is required'),
description: z.string().nullish(),
bounds: z.array(boundInput).optional(),
creds: z.array(telegramCredInput).min(1, 'At least one Telegram cred is required'),
})
)
.mutation(async ({ input }): Promise<{ region: Region; message: string }> => {
assertUniquePriorities(input.bounds)
const region = await createRegionInDb({
name: input.name,
description: input.description ?? null,
bounds: input.bounds,
creds: input.creds,
})
// New region: give every existing SKU an (out-of-stock) market-stats row.
await backfillMarketStatsForRegionInDb(region.id)
// Regenerate cache files so the new region gets its own set.
await scheduleStoreInitialization()
return { region, message: 'Region created successfully' }
}),
updateRegion: superadminProcedure
.input(
z.object({
id: z.number(),
name: z.string().min(1, 'Name is required').optional(),
description: z.string().nullish(),
bounds: z.array(boundInput).optional(),
})
)
.mutation(async ({ input }): Promise<{ region: Region; message: string }> => {
assertUniquePriorities(input.bounds)
const region = await updateRegionInDb(input.id, {
name: input.name,
description: input.description,
bounds: input.bounds,
})
if (!region) {
throw new ApiError('Region not found', 404)
}
return { region, message: 'Region updated successfully' }
}),
// Regions are non-deletable: many tables reference region_id.
deleteRegion: superadminProcedure
.input(z.object({ id: z.number() }))
.mutation(async (): Promise<{ message: string }> => {
throw new ApiError('Regions cannot be deleted', 400)
}),
addRegionBound: superadminProcedure
.input(z.object({
regionId: z.number(),
geojson: z.string().min(1),
name: z.string().min(1, 'Bound name is required'),
description: z.string().min(1, 'Bound description is required'),
priority: z.number().int().min(0).optional(),
}))
.mutation(async ({ input }) => {
const region = await getRegionByIdFromDb(input.regionId)
if (!region) {
throw new ApiError('Region not found', 404)
}
if (region.bounds?.some((b) => (b.priority ?? 0) === (input.priority ?? 0))) {
throw new ApiError(`Duplicate bound priority ${input.priority ?? 0}: priorities must be unique within a region`, 400)
}
const bound = await addRegionBoundInDb(input.regionId, {
geojson: input.geojson,
name: input.name,
description: input.description,
priority: input.priority,
})
return { bound, message: 'Bound added successfully' }
}),
deleteRegionBound: superadminProcedure
.input(z.object({ id: z.number() }))
.mutation(async ({ input }): Promise<{ message: string }> => {
await deleteRegionBoundFromDb(input.id)
return { message: 'Bound deleted successfully' }
}),
});

View file

@ -0,0 +1,173 @@
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod';
import bcrypt from 'bcryptjs';
import { ApiError } from '@/src/lib/api-error'
import {
checkStaffUserExists,
checkStaffRoleExists,
createStaffUser,
getAllRoles,
getAllStaff,
getRegions as getRegionsFromDb,
getStaffUserById as getStaffUserByIdFromDb,
updateStaffUserInfo as updateStaffUserInfoInDb,
deleteStaffUser as deleteStaffUserFromDb,
} from '@/src/dbService'
import { notifyAllAdmins } from '@/src/lib/admin-notif'
export const superadminStaffRouter = router({
getStaff: superadminProcedure
.query(async () => {
const [staff, regions] = await Promise.all([getAllStaff(), getRegionsFromDb()]);
const regionById = new Map(regions.map((r: any) => [r.id, r.name]));
return {
staff: staff.map((user: any) => ({
id: user.id,
name: user.name,
regionId: user.regionId,
regionName: regionById.get(user.regionId) ?? null,
roleId: user.role?.id ?? null,
roleName: user.role?.roleName ?? null,
})),
};
}),
createStaffUser: superadminProcedure
.input(z.object({
name: z.string().min(1, 'Name is required'),
password: z.string().min(6, 'Password must be at least 6 characters'),
roleId: z.number().int().positive('Role is required'),
regionId: z.number().int().positive('Region is required'),
}))
.mutation(async ({ input }) => {
const { name, password, roleId, regionId } = input;
// Check if staff user already exists
const existingUser = await checkStaffUserExists(name);
if (existingUser) {
throw new ApiError('Staff user with this name already exists', 409);
}
// Check if role exists
const roleExists = await checkStaffRoleExists(roleId);
if (!roleExists) {
throw new ApiError('Invalid role selected', 400);
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 12);
// Create staff user
const newUser = await createStaffUser(name, hashedPassword, roleId, regionId);
return { success: true, user: { id: newUser.id, name: newUser.name, regionId: newUser.regionId } };
}),
getRoles: superadminProcedure
.query(async () => {
const roles = await getAllRoles();
return {
roles: roles.map((role: any) => ({
id: role.id,
name: role.roleName,
})),
};
}),
updateStaffUser: superadminProcedure
.input(z.object({
id: z.number().int().positive(),
name: z.string().min(1, 'Name is required').optional(),
roleId: z.number().int().positive().optional(),
regionId: z.number().int().positive().optional(),
password: z.string().min(6, 'Password must be at least 6 characters').optional(),
}))
.mutation(async ({ input }) => {
const existing = await getStaffUserByIdFromDb(input.id);
if (!existing) {
throw new ApiError('Staff user not found', 404);
}
if (input.name !== undefined && input.name.trim() !== existing.name) {
const taken = await checkStaffUserExists(input.name.trim());
if (taken) {
throw new ApiError('Staff user with this name already exists', 409);
}
}
if (input.roleId !== undefined) {
const roleExists = await checkStaffRoleExists(input.roleId);
if (!roleExists) {
throw new ApiError('Invalid role selected', 400);
}
}
const updated = await updateStaffUserInfoInDb(input.id, {
name: input.name,
roleId: input.roleId,
regionId: input.regionId,
password: input.password !== undefined ? await bcrypt.hash(input.password, 12) : undefined,
});
if (!updated) {
throw new ApiError('Staff user not found', 404);
}
return { success: true, user: { id: updated.id, name: updated.name, regionId: updated.regionId } };
}),
deleteStaffUser: superadminProcedure
.input(z.object({ id: z.number().int().positive() }))
.mutation(async ({ input }) => {
const existing = await getStaffUserByIdFromDb(input.id);
if (!existing) {
throw new ApiError('Staff user not found', 404);
}
const result = await deleteStaffUserFromDb(input.id);
if (!result.deleted) {
const { blocker } = result;
if (blocker.type === 'stores') {
throw new ApiError(
`Cannot delete ${existing.name}: they own ${blocker.count} store${blocker.count === 1 ? '' : 's'}. Reassign or remove those stores first.`,
409
);
}
if (blocker.type === 'coupons') {
throw new ApiError(
`Cannot delete ${existing.name}: they created ${blocker.count} coupon${blocker.count === 1 ? '' : 's'}. Those coupons keep them as creator.`,
409
);
}
throw new ApiError(
`Cannot delete ${existing.name}: they filed ${blocker.count} user incident report${blocker.count === 1 ? '' : 's'}.`,
409
);
}
return { success: true, message: 'Staff user deleted successfully' };
}),
sendAdminNotification: superadminProcedure
.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 queuedCount = await notifyAllAdmins({
title,
body: text,
imageUrl: imageUrl || null,
});
return {
success: true,
message: `Notification queued for ${queuedCount} admins`,
};
}),
});

View file

@ -0,0 +1,172 @@
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod';
import { ApiError } from '@/src/lib/api-error'
import { extractKeyFromPresignedUrl, deleteImageUtil, scaffoldAssetUrl } from '@/src/lib/s3-client'
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
import {
getAllStores as getAllStoresFromDb,
getStoreById as getStoreByIdFromDb,
createStore as createStoreInDb,
updateStore as updateStoreInDb,
deleteStore as deleteStoreFromDb,
} from '@/src/dbService'
import type { Store } from '@packages/shared'
export const superadminStoreRouter = router({
getStores: superadminProcedure
.query(async (): Promise<{ stores: any[]; count: number }> => {
const stores = await getAllStoresFromDb(undefined);
await Promise.all(stores.map(async store => {
if(store.imageUrl)
store.imageUrl = scaffoldAssetUrl(store.imageUrl)
})).catch((e) => {
throw new ApiError("Unable to find store image urls")
})
return {
stores,
count: stores.length,
};
}),
getStoreById: superadminProcedure
.input(z.object({
id: z.number(),
}))
.query(async ({ input }): Promise<{ store: any }> => {
const { id } = input;
const store = await getStoreByIdFromDb(id);
if (!store) {
throw new ApiError("Store not found", 404);
}
store.imageUrl = scaffoldAssetUrl(store.imageUrl);
return {
store,
};
}),
createStore: superadminProcedure
.input(z.object({
name: z.string().min(1, "Name is required"),
description: z.string().optional(),
imageUrl: z.string().optional(),
owner: z.number().min(1, "Owner is required"),
products: z.array(z.number()).optional(),
// Home region. Omitted (with availableInAllRegions) = all-region store.
regionId: z.number().int().positive().nullable().optional(),
availableInAllRegions: z.boolean().optional(),
}))
.mutation(async ({ input }): Promise<{ store: Store; message: string }> => {
const { name, description, imageUrl, owner, products, availableInAllRegions } = input;
const regionId = availableInAllRegions ? null : (input.regionId ?? null);
if (!availableInAllRegions && regionId == null) {
throw new ApiError("Region is required for region-exclusive stores", 400);
}
const imageKey = imageUrl ? extractKeyFromPresignedUrl(imageUrl) : undefined;
const newStore = await createStoreInDb(
{
name,
description,
imageUrl: imageKey,
owner,
regionId,
availableInAllRegions: availableInAllRegions ?? false,
},
products
);
// Reinitialize stores to reflect changes
await scheduleStoreInitialization()
return {
store: newStore,
message: "Store created successfully",
};
}),
updateStore: superadminProcedure
.input(z.object({
id: z.number(),
name: z.string().min(1, "Name is required"),
description: z.string().optional(),
imageUrl: z.string().optional(),
owner: z.number().min(1, "Owner is required"),
products: z.array(z.number()).optional(),
regionId: z.number().int().positive().nullable().optional(),
availableInAllRegions: z.boolean().optional(),
}))
.mutation(async ({ input }): Promise<{ store: Store; message: string }> => {
const { id, name, description, imageUrl, owner, products, availableInAllRegions } = input;
const existingStore = await getStoreByIdFromDb(id);
if (!existingStore) {
throw new ApiError("Store not found", 404);
}
const regionId = availableInAllRegions ? null : (input.regionId ?? existingStore.regionId ?? null);
if (!availableInAllRegions && regionId == null) {
throw new ApiError("Region is required for region-exclusive stores", 400);
}
const oldImageKey = existingStore.imageUrl;
const newImageKey = imageUrl ? extractKeyFromPresignedUrl(imageUrl) : oldImageKey;
// Delete old image only if:
// 1. New image provided and keys are different, OR
// 2. No new image but old exists (clearing the image)
if (oldImageKey && (
(newImageKey && newImageKey !== oldImageKey) ||
(!newImageKey)
)) {
try {
await deleteImageUtil({keys: [oldImageKey]});
} catch (error) {
console.error('Failed to delete old image:', error);
// Continue with update even if deletion fails
}
}
const updatedStore = await updateStoreInDb(
id,
{
name,
description,
imageUrl: newImageKey,
owner,
regionId,
...(availableInAllRegions !== undefined ? { availableInAllRegions } : {}),
},
products
);
// Reinitialize stores to reflect changes
await scheduleStoreInitialization()
return {
store: updatedStore,
message: "Store updated successfully",
};
}),
deleteStore: superadminProcedure
.input(z.object({
storeId: z.number(),
}))
.mutation(async ({ input }): Promise<{ message: string }> => {
const { storeId } = input;
const result = await deleteStoreFromDb(storeId);
// Reinitialize stores to reflect changes (outside transaction)
await scheduleStoreInitialization()
return result;
}),
});

View file

@ -0,0 +1,20 @@
import { router } from '@/src/trpc/trpc-index'
import { superadminAuthRouter } from '@/src/trpc/apis/superadmin-apis/apis/auth'
import { superadminRegionRouter } from '@/src/trpc/apis/superadmin-apis/apis/region'
import { superadminStaffRouter } from '@/src/trpc/apis/superadmin-apis/apis/staff'
import { superadminConstRouter } from '@/src/trpc/apis/superadmin-apis/apis/const'
import { superadminStoreRouter } from '@/src/trpc/apis/superadmin-apis/apis/store'
import { superadminProductRouter } from '@/src/trpc/apis/superadmin-apis/apis/product'
import { superadminUploadRouter } from '@/src/trpc/apis/superadmin-apis/apis/upload'
export const superadminRouter = router({
auth: superadminAuthRouter,
region: superadminRegionRouter,
staffUser: superadminStaffRouter,
const: superadminConstRouter,
store: superadminStoreRouter,
product: superadminProductRouter,
upload: superadminUploadRouter,
});
export type SuperadminRouter = typeof superadminRouter;

View file

@ -0,0 +1,56 @@
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod';
import { ApiError } from '@/src/lib/api-error'
import { generateUploadUrl } from '@/src/lib/s3-client'
export const superadminUploadRouter = router({
generateUploadUrls: superadminProcedure
.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 };
}),
});

View file

@ -10,6 +10,7 @@ import {
updateUserAddress as updateUserAddressInDb,
deleteUserAddress as deleteUserAddressInDb,
hasOngoingOrdersForAddress as hasOngoingOrdersForAddressInDb,
getRegionById as getRegionByIdInDb,
} from '@/src/dbService'
import type {
UserAddressResponse,
@ -48,10 +49,11 @@ export const addressRouter = router({
latitude: z.number().optional(),
longitude: z.number().optional(),
googleMapsUrl: z.string().optional(),
regionId: z.number().int().positive().optional(),
}))
.mutation(async ({ input, ctx }): Promise<UserAddressResponse> => {
const userId = ctx.user.userId;
const { name, phone, addressLine1, addressLine2, city, state, pincode, isDefault, googleMapsUrl } = input;
const { name, phone, addressLine1, addressLine2, city, state, pincode, isDefault, googleMapsUrl, regionId } = input;
let { latitude, longitude } = input;
@ -68,6 +70,11 @@ export const addressRouter = router({
throw new Error('Missing required fields');
}
// Reject dead/unknown regions instead of storing them silently.
if (regionId != null && !(await getRegionByIdInDb(regionId))) {
throw new Error('Region not found');
}
// If setting as default, unset other defaults
if (isDefault) {
await clearDefaultAddressInDb(userId)
@ -86,6 +93,7 @@ export const addressRouter = router({
latitude,
longitude,
googleMapsUrl,
regionId,
})
return { success: true, data: newAddress }
@ -105,10 +113,11 @@ export const addressRouter = router({
latitude: z.number().optional(),
longitude: z.number().optional(),
googleMapsUrl: z.string().optional(),
regionId: z.number().int().positive().optional(),
}))
.mutation(async ({ input, ctx }): Promise<UserAddressResponse> => {
const userId = ctx.user.userId;
const { id, name, phone, addressLine1, addressLine2, city, state, pincode, isDefault, googleMapsUrl } = input;
const { id, name, phone, addressLine1, addressLine2, city, state, pincode, isDefault, googleMapsUrl, regionId } = input;
let { latitude, longitude } = input;
@ -126,6 +135,11 @@ export const addressRouter = router({
throw new Error('Address not found')
}
// Reject dead/unknown regions instead of storing them silently.
if (regionId != null && !(await getRegionByIdInDb(regionId))) {
throw new Error('Region not found')
}
// If setting as default, unset other defaults
if (isDefault) {
await clearDefaultAddressInDb(userId)
@ -145,6 +159,7 @@ export const addressRouter = router({
googleMapsUrl,
latitude,
longitude,
regionId,
})
return { success: true, data: updatedAddress }

View file

@ -2,8 +2,8 @@ import { scaffoldAssetUrl } from '@/src/lib/s3-client'
import { getUserActiveBanners as getUserActiveBannersInDb } from '@/src/dbService'
import type { UserBannersResponse } from '@packages/shared'
export async function scaffoldBanners(): Promise<UserBannersResponse> {
const banners = await getUserActiveBannersInDb()
export async function scaffoldBanners(regionId?: number): Promise<UserBannersResponse> {
const banners = await getUserActiveBannersInDb(regionId)
const bannersWithSignedUrls = banners.map((banner) => ({
...banner,

View file

@ -6,15 +6,16 @@ export const cartRouter = router({
// Cache-based getCartSlots
getCartSlots: publicProcedure
.input(z.object({
productIds: z.array(z.number().int().positive())
productIds: z.array(z.number().int().positive()),
regionId: z.number().int().positive().optional(),
}))
.query(async ({ input }) => {
const { productIds } = input;
const { productIds, regionId } = input;
if (productIds.length === 0) {
return {};
}
return await getMultipleProductsSlots(productIds);
return await getMultipleProductsSlots(productIds, regionId);
}),
});

View file

@ -3,7 +3,10 @@ import { z } from 'zod'
import {
getUserComplaints as getUserComplaintsInDb,
createUserComplaint as createUserComplaintInDb,
getOrderAddressRegion as getOrderAddressRegionInDb,
getUserDefaultAddress as getDefaultAddressInDb,
} from '@/src/dbService'
import { notifyAllAdmins } from '@/src/lib/admin-notif'
import type { UserComplaintsResponse, UserRaiseComplaintResponse } from '@packages/shared'
export const complaintRouter = router({
@ -44,6 +47,30 @@ export const complaintRouter = router({
imageUrls && imageUrls.length > 0 ? imageUrls : null
)
// Notify the relevant region's admins (order region, else the user's
// default address region). Fire-and-forget: a notif failure must not
// fail the complaint itself.
try {
let regionId: number | null = null
if (orderIdNum != null) {
regionId = await getOrderAddressRegionInDb(orderIdNum)
}
if (regionId == null) {
regionId = (await getDefaultAddressInDb(userId))?.regionId ?? null
}
if (regionId == null) {
console.error(`Complaint by user ${userId} has no region; notifying all staff`)
}
const snippet = complaintBody.trim().slice(0, 120)
await notifyAllAdmins({
title: '⚠️ New Complaint Raised',
body: orderIdNum != null ? `Order #${orderIdNum} • ${snippet}` : snippet,
orderId: orderIdNum,
}, regionId)
} catch (error) {
console.error('Failed to notify admins of complaint:', error)
}
return { success: true, message: 'Complaint raised successfully' }
}),
});

View file

@ -27,6 +27,7 @@ import { scaffoldAssetUrl } from "@/src/lib/s3-client";
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 { resolveBoundForPoint } from "@/src/lib/region-resolver";
import { publishFormattedOrder, publishCancellation } from "@/src/lib/post-order-handler";
import { trackIfFirstOrder, clearFirstOrderIfMatches } from "@/src/lib/order-tracker";
import type {
@ -58,12 +59,27 @@ const placeOrderUtil = async (params: {
userNotes,
} = params;
const address = await getUserAddressByIdAndUser(addressId, userId);
if (!address) {
throw new ApiError("Invalid address", 400);
}
// Bound-scoped consts: resolve the address point to a bound; falls back to
// the region default (then region/global rows) when coords are absent.
let addressBoundId: number | null = null;
if (address.latitude != null && address.longitude != null) {
const resolved = await resolveBoundForPoint(address.latitude, address.longitude);
if (resolved.boundId != null && resolved.regionId === address.regionId) {
addressBoundId = resolved.boundId;
}
}
const constants = await getConstants<number>([
CONST_KEYS.minRegularOrderValue,
CONST_KEYS.deliveryCharge,
CONST_KEYS.flashFreeDeliveryThreshold,
CONST_KEYS.flashDeliveryCharge,
]);
], address.regionId, addressBoundId);
const isFlashDelivery = params.isFlash;
const minOrderValue = (isFlashDelivery ? constants[CONST_KEYS.flashFreeDeliveryThreshold] : constants[CONST_KEYS.minRegularOrderValue]) || 0;
@ -71,11 +87,6 @@ const placeOrderUtil = async (params: {
const orderGroupId = `${Date.now()}-${userId}`;
const address = await getUserAddressByIdAndUser(addressId, userId);
if (!address) {
throw new ApiError("Invalid address", 400);
}
const ordersBySlot = new Map<
number | null,
Array<{
@ -87,7 +98,7 @@ const placeOrderUtil = async (params: {
>();
for (const item of selectedItems) {
const product = await getOrderProductById(item.skuId);
const product = await getOrderProductById(item.skuId, address.regionId);
if (!product) {
throw new ApiError(`Product ${item.skuId} not found`, 400);
}
@ -100,7 +111,7 @@ const placeOrderUtil = async (params: {
if (params.isFlash) {
for (const item of selectedItems) {
const product = await getOrderProductById(item.skuId);
const product = await getOrderProductById(item.skuId, address.regionId);
if (!product?.isFlashAvailable) {
throw new ApiError(`Product ${item.skuId} is not available for flash delivery`, 400);
}
@ -275,7 +286,19 @@ export const orderRouter = router({
} = input;
if (isFlashDelivery) {
const isFlashDeliveryEnabled = await getConstant<boolean>(CONST_KEYS.isFlashDeliveryEnabled);
const orderAddress = await getUserAddressByIdAndUser(addressId, userId);
let flashBoundId: number | null = null;
if (orderAddress?.latitude != null && orderAddress?.longitude != null) {
const resolved = await resolveBoundForPoint(orderAddress.latitude, orderAddress.longitude);
if (resolved.boundId != null && resolved.regionId === orderAddress.regionId) {
flashBoundId = resolved.boundId;
}
}
const isFlashDeliveryEnabled = await getConstant<boolean>(
CONST_KEYS.isFlashDeliveryEnabled,
orderAddress?.regionId ?? undefined,
flashBoundId
);
if (!isFlashDeliveryEnabled) {
throw new ApiError("Flash delivery is currently unavailable. Please opt for scheduled delivery.", 403);
}

View file

@ -27,9 +27,10 @@ export const productRouter = router({
getProductDetails: publicProcedure
.input(z.object({
id: z.string().regex(/^\d+$/, 'Invalid product ID'),
regionId: z.number().int().positive().optional(),
}))
.query(async ({ input }): Promise<UserProductDetail> => {
const { id } = input;
const { id, regionId } = input;
const productId = parseInt(id);
if (isNaN(productId)) {
@ -39,7 +40,7 @@ export const productRouter = router({
console.log('from the api to get product details')
// First, try to get the product from Redis cache
const cachedProduct = await getProductByIdFromCache(productId);
const cachedProduct = await getProductByIdFromCache(productId, regionId);
if (cachedProduct) {
// Filter delivery slots to only include those with future freeze times and not at full capacity
@ -56,7 +57,7 @@ export const productRouter = router({
}
// If not in cache, fetch from database (fallback)
const productData = await getUserProductDetailByIdInDb(productId)
const productData = await getUserProductDetailByIdInDb(productId, regionId)
if (!productData) {
throw new Error('Product not found')

View file

@ -1,11 +1,12 @@
import { router, publicProcedure } from "@/src/trpc/trpc-index"
import { z } from "zod"
import { getAllSlots as getAllSlotsFromCache } from "@/src/stores/slot-store"
import dayjs from 'dayjs'
import { getUserActiveSlotsList as getUserActiveSlotsListInDb, getUserProductAvailability as getUserProductAvailabilityInDb } from '@/src/dbService'
import type { UserSlotsListResponse, UserSlotsWithProductsResponse } from '@packages/shared'
export async function scaffoldSlotsWithProducts(): Promise<UserSlotsWithProductsResponse> {
const allSlots = await getAllSlotsFromCache();
export async function scaffoldSlotsWithProducts(regionId?: number): Promise<UserSlotsWithProductsResponse> {
const allSlots = await getAllSlotsFromCache(regionId);
const currentTime = new Date();
const validSlots = allSlots
.filter((slot) => {
@ -15,7 +16,7 @@ export async function scaffoldSlotsWithProducts(): Promise<UserSlotsWithProducts
})
.sort((a, b) => dayjs(a.deliveryTime).valueOf() - dayjs(b.deliveryTime).valueOf());
const productAvailability = await getUserProductAvailabilityInDb()
const productAvailability = await getUserProductAvailabilityInDb(regionId)
return {
slots: validSlots.map((slot) => ({
@ -33,8 +34,10 @@ export async function scaffoldSlotsWithProducts(): Promise<UserSlotsWithProducts
}
export const slotsRouter = router({
getSlots: publicProcedure.query(async (): Promise<UserSlotsListResponse> => {
const slots = await getUserActiveSlotsListInDb()
getSlots: publicProcedure
.input(z.object({ regionId: z.number().int().positive().optional() }).optional())
.query(async ({ input }): Promise<UserSlotsListResponse> => {
const slots = await getUserActiveSlotsListInDb(input?.regionId)
return {
slots,

View file

@ -11,8 +11,8 @@ import type {
UserStoreSummary,
} from '@packages/shared'
export async function scaffoldStores(): Promise<UserStoresResponse> {
const storesData = await getUserStoreSummariesInDb()
export async function scaffoldStores(regionId?: number): Promise<UserStoresResponse> {
const storesData = await getUserStoreSummariesInDb(regionId)
const storesWithDetails: UserStoreSummary[] = storesData.map((store) => {
const signedImageUrl = store.imageUrl ? scaffoldAssetUrl(store.imageUrl) : null
@ -39,8 +39,8 @@ export async function scaffoldStores(): Promise<UserStoresResponse> {
}
}
export async function scaffoldStoreWithProducts(storeId: number): Promise<UserStoreDetail> {
const storeDetail = await getUserStoreDetailInDb(storeId)
export async function scaffoldStoreWithProducts(storeId: number, regionId?: number): Promise<UserStoreDetail> {
const storeDetail = await getUserStoreDetailInDb(storeId, regionId)
if (!storeDetail) {
throw new ApiError('Store not found', 404)
@ -64,7 +64,7 @@ export async function scaffoldStoreWithProducts(storeId: number): Promise<UserSt
productQuantity: product.productQuantity,
}))
const tags = await getTagsByStoreId(storeId)
const tags = await getTagsByStoreId(storeId, regionId)
return {
store: {

View file

@ -68,15 +68,15 @@ export const userRouter = router({
}),
savePushToken: publicProcedure
.input(z.object({ token: z.string() }))
.input(z.object({ token: z.string(), regionId: z.number().int().positive().optional() }))
.mutation(async ({ input, ctx }): Promise<UserSavePushTokenResponse> => {
const { token } = input;
const { token, regionId } = input;
const userId = ctx.user?.userId;
if (userId) {
// AUTHENTICATED USER
// Check if token exists in notif_creds for this user
await upsertUserNotifCredInDb(userId, token)
await upsertUserNotifCredInDb(userId, token, regionId)
await deleteUserUnloggedTokenInDb(token)
} else {
@ -84,9 +84,9 @@ export const userRouter = router({
// Save/update in unlogged_user_tokens
const existing = await getUserUnloggedTokenInDb(token)
if (existing) {
await upsertUserUnloggedTokenInDb(token)
await upsertUserUnloggedTokenInDb(token, regionId)
} else {
await upsertUserUnloggedTokenInDb(token)
await upsertUserUnloggedTokenInDb(token, regionId)
}
}

View file

@ -2,6 +2,7 @@ import { router } from '@/src/trpc/trpc-index'
import { adminRouter } from '@/src/trpc/apis/admin-apis/apis/admin-trpc-index'
import { userRouter } from '@/src/trpc/apis/user-apis/apis/user-trpc-index'
import { commonApiRouter } from '@/src/trpc/apis/common-apis/common-trpc-index'
import { superadminRouter } from '@/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index'
import { scaffoldProducts, scaffoldAvailability } from './apis/common-apis/common';
import { scaffoldStores, scaffoldStoreWithProducts } from './apis/user-apis/apis/stores';
import { scaffoldSlotsWithProducts } from './apis/user-apis/apis/slots';
@ -13,6 +14,7 @@ export const appRouter = router({
admin: adminRouter,
user: userRouter,
common: commonApiRouter,
superadmin: superadminRouter,
});

View file

@ -8,6 +8,13 @@ export interface Context {
staffUser?: {
id: number;
name: string;
regionId: number;
staffRoleId: number | null;
staffRoleName: string | null;
} | null;
superadmin?: {
id: number;
name: string;
} | null;
callerInterface?: string | null;
}
@ -42,7 +49,7 @@ const errorLoggerMiddleware = middleware(async ({ path, type, next, ctx }) => {
path,
type,
duration: `${duration}ms`,
userId: ctx?.user?.userId || ctx?.staffUser?.id || 'anonymous',
userId: ctx?.user?.userId || ctx?.staffUser?.id || ctx?.superadmin?.id || 'anonymous',
error: {
name: err.name,
message: err.message,
@ -69,3 +76,56 @@ export const protectedProcedure = t.procedure.use(errorLoggerMiddleware).use(
return next();
})
);
// Staff-only. Requires an authenticated staff user with a region.
export const adminProcedure = t.procedure.use(errorLoggerMiddleware).use(
middleware(async ({ ctx, next }) => {
if (!ctx.staffUser) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Staff authentication required' });
}
if (ctx.staffUser.regionId == null) {
throw new TRPCError({ code: 'FORBIDDEN', message: 'Staff user has no region assigned' });
}
return next({
ctx: {
...ctx,
staffUser: ctx.staffUser,
},
});
})
);
// Superadmin-only. Requires an authenticated superadmin (superadmins table,
// superadmin.* scope) — distinct from superAdminProcedure below, which gates
// the super_admin *role* on staff_users rows for the admin.* scope.
export const superadminProcedure = t.procedure.use(errorLoggerMiddleware).use(
middleware(async ({ ctx, next }) => {
if (!ctx.superadmin) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Superadmin authentication required' });
}
return next({
ctx: {
...ctx,
superadmin: ctx.superadmin,
},
});
})
);
// Superadmin-only. Requires an authenticated staff user whose role is super_admin.
export const superAdminProcedure = t.procedure.use(errorLoggerMiddleware).use(
middleware(async ({ ctx, next }) => {
if (!ctx.staffUser) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Staff authentication required' });
}
if (ctx.staffUser.staffRoleName !== 'super_admin') {
throw new TRPCError({ code: 'FORBIDDEN', message: 'Superadmin access required' });
}
return next({
ctx: {
...ctx,
staffUser: ctx.staffUser,
},
});
})
);

View file

@ -1,10 +0,0 @@
import { Hono } from 'hono';
import commonRouter from "@/src/apis/common-apis/apis/common.router"
const router = new Hono();
router.route('/cm', commonRouter);
const v1Router = router;
export default v1Router;

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]

View file

@ -1,4 +1,4 @@
import { useMemo, useState, useEffect } from "react";
import { useMemo, useState } from "react";
import { useSearch } from "@tanstack/react-router";
import { trpc } from "../trpc/client";
import { cn } from "@/lib/utils";
@ -21,63 +21,22 @@ interface VendorOrder {
}>;
}
interface DeliverySlot {
id: number;
deliveryTime: string;
freezeTime: string;
deliverySequence: any;
}
export function VendorOrderListRoute() {
const { id } = useSearch({ from: "/vendor-order-list" });
// Fetch snippet info
const { data: snippetInfo, isLoading: isLoadingSnippet } = id
? trpc.admin.vendorSnippets.getOrdersBySnippet.useQuery({ snippetCode: id })
: { data: null, isLoading: false };
const snippet = snippetInfo?.snippet;
const isPermanent = snippet?.isPermanent;
const { data: upcomingSlots } =
trpc.admin.vendorSnippets.getUpcomingSlots.useQuery(undefined, {
enabled: !!id,
});
// State for selected slot
const [selectedSlotId, setSelectedSlotId] = useState<number | null>(null);
// Auto-select first slot when snippets are loaded and isPermanent is true
useEffect(() => {
if (
isPermanent &&
upcomingSlots?.data &&
upcomingSlots.data.length > 0 &&
!selectedSlotId
) {
setSelectedSlotId(upcomingSlots.data[0].id);
}
}, [isPermanent, upcomingSlots, selectedSlotId]);
// Fetch orders based on mode
const {
data: slotOrdersData,
data: snippetOrders,
error,
isLoading: isLoadingOrders,
isFetching,
refetch,
} = trpc.admin.vendorSnippets.getOrdersBySnippetAndSlot.useQuery(
{ snippetCode: id!, slotId: selectedSlotId! },
{ enabled: !!id && !!selectedSlotId && isPermanent },
} = trpc.admin.vendorSnippets.getOrdersBySnippet.useQuery(
{ snippetCode: id! },
{ enabled: !!id },
);
const { data: regularOrders } =
trpc.admin.vendorSnippets.getOrdersBySnippet.useQuery(
{ snippetCode: id! },
{ enabled: !!id && !isPermanent },
);
const orders = slotOrdersData?.data || regularOrders?.data || [];
const isLoadingCurrent = isPermanent ? isLoadingOrders : isLoadingSnippet;
const orders = snippetOrders?.data || [];
const isLoadingCurrent = isLoadingOrders;
const updatePackagingMutation =
trpc.admin.vendorSnippets.updateOrderItemPackaging.useMutation();
@ -152,41 +111,19 @@ export function VendorOrderListRoute() {
</h2>
<p className="text-sm text-slate-500">
Track incoming orders and fulfilment progress for vendor partners.
{id && <span className="block mt-1 text-xs">Snippet: {id}</span>}
</p>
</div>
{isPermanent && upcomingSlots?.data && (
<div className="flex items-center gap-2">
<label
htmlFor="slot-select"
className="text-sm font-medium text-slate-700"
>
Select Slot:
</label>
<select
id="slot-select"
value={selectedSlotId || ""}
onChange={(e) => setSelectedSlotId(Number(e.target.value))}
className="base-select px-3 py-2 text-sm border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
>
{upcomingSlots.data.map((slot) => (
<option key={slot.id} value={slot.id}>
{dayjs(slot.deliveryTime).format("ddd, MMM DD hh:mm A")}
</option>
))}
</select>
</div>
)}
<Button
variant="outline"
onClick={() => {
void refetch();
}}
disabled={isFetching}
>
{isFetching ? "Refreshing…" : "Refresh"}
</Button>
</div>
{id && <span className="block mt-1 text-xs">Snippet: {id}</span>}
</p>
</div>
<Button
variant="outline"
onClick={() => {
void refetch();
}}
disabled={isFetching}
>
{isFetching ? "Refreshing…" : "Refresh"}
</Button>
</div>
<div className="mt-6">
{isLoadingCurrent ? (

View file

@ -1,10 +1,14 @@
import React, { useState } from 'react'
import { Link } from '@tanstack/react-router'
import { LayoutDashboard, Send, Settings2, Menu, X, LogOut } from 'lucide-react'
import { LayoutDashboard, Send, Settings2, MapPin, UserPlus, Menu, X, LogOut, Store, Package } from 'lucide-react'
import { useAuth } from '../lib/auth-context'
const NAV = [
{ to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
{ to: '/admins', label: 'Admins', icon: UserPlus },
{ to: '/regions', label: 'Regions', icon: MapPin },
{ to: '/stores', label: 'Stores', icon: Store },
{ to: '/products', label: 'Products', icon: Package },
{ to: '/send-notifications', label: 'Send Admin Notifications', icon: Send },
{ to: '/constants', label: 'App Constants', icon: Settings2 },
] as const

View file

@ -0,0 +1,154 @@
import { useMemo, useState } from 'react'
import { BottomDialog, Checkbox, SearchBar, p as P } from 'web-components'
import { Check, ChevronDown } from 'lucide-react'
export interface MultiSelectOption {
label: string
value: string | number
disabled?: boolean
}
interface MultiSelectProps {
label?: string
topLabel?: string
options: MultiSelectOption[]
value: (string | number)[]
onValueChange: (v: (string | number)[]) => void
placeholder?: string
disabled?: boolean
onSearch?: (q: string) => void
error?: boolean
className?: string
testID?: string
// Tolerated for screen compatibility (RN BottomDropdown leftovers) — ignored on web
multiple?: boolean
triggerComponent?: any
}
export function MultiSelect({
label,
topLabel,
options,
value,
onValueChange,
placeholder,
disabled = false,
onSearch,
error = false,
className,
testID,
}: MultiSelectProps) {
const [open, setOpen] = useState(false)
const [query, setQuery] = useState('')
const selectedSet = useMemo(() => new Set(value.map((v) => String(v))), [value])
const displayText = useMemo(() => {
if (value.length === 0) return placeholder ?? label ?? 'Select...'
if (value.length === 1) {
const found = options.find((o) => String(o.value) === String(value[0]))
return found ? found.label : (placeholder ?? label ?? 'Select...')
}
return `${value.length} selected`
}, [value, options, placeholder, label])
const filtered = useMemo(() => {
const q = query.trim().toLowerCase()
if (!q) return options
return options.filter((o) => o.label.toLowerCase().includes(q))
}, [options, query])
const toggle = (optionValue: string | number) => {
const key = String(optionValue)
if (selectedSet.has(key)) {
onValueChange(value.filter((v) => String(v) !== key))
} else {
onValueChange([...value, optionValue])
}
}
const heading = topLabel ?? label
return (
<div className={className} data-testid={testID}>
{heading ? (
<P className="mb-1 text-sm text-gray-500 font-medium">{heading}</P>
) : null}
<button
type="button"
disabled={disabled}
onClick={() => setOpen(true)}
className={`flex w-full items-center justify-between rounded-md border bg-white px-3 py-2 text-sm text-left disabled:cursor-not-allowed disabled:opacity-50 ${error ? 'border-red-500' : 'border-gray-300'}`}
>
<span className={`truncate ${value.length === 0 ? 'text-gray-400' : 'text-gray-800'}`}>
{displayText}
</span>
<ChevronDown className="h-4 w-4 shrink-0 text-gray-400" />
</button>
<BottomDialog open={open} onClose={() => setOpen(false)}>
<div className="p-4">
<P className="text-lg font-semibold mb-4">{heading ?? placeholder ?? 'Select'}</P>
<SearchBar
placeholder="Search..."
value={query}
onChange={(q) => {
setQuery(q)
onSearch?.(q)
}}
onSearch={onSearch}
className="mb-3"
testID={testID ? `${testID}-search` : undefined}
/>
<div className="overflow-y-auto" style={{ maxHeight: 320 }}>
{filtered.map((option) => {
const checked = selectedSet.has(String(option.value))
return (
<div
key={String(option.value)}
data-testid={testID ? `${testID}-option-${option.value}` : undefined}
onClick={() => {
if (!option.disabled) toggle(option.value)
}}
className={`flex flex-row items-center p-3 border-b border-gray-100 ${option.disabled ? 'opacity-50' : 'cursor-pointer hover:bg-gray-50'}`}
>
<span onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={checked}
onPress={() => {
if (!option.disabled) toggle(option.value)
}}
/>
</span>
<span className="ml-3 text-sm text-gray-800 flex-1">{option.label}</span>
{checked ? <Check className="h-4 w-4 text-blue-600" /> : null}
</div>
)
})}
{filtered.length === 0 ? (
<P className="text-center text-gray-500 text-sm p-4">No options found</P>
) : null}
</div>
<div className="flex flex-row gap-2 mt-4">
<button
type="button"
onClick={() => onValueChange([])}
className="flex-1 p-3 rounded-lg bg-gray-100 text-gray-700 text-center font-semibold text-sm"
>
Clear
</button>
<button
type="button"
onClick={() => setOpen(false)}
data-testid={testID ? `${testID}-done` : undefined}
className="flex-1 p-3 rounded-lg bg-blue-500 text-white text-center font-semibold text-sm"
>
Done
</button>
</div>
</div>
</BottomDialog>
</div>
)
}
export default MultiSelect

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,181 @@
import React, { useState, useMemo } from 'react'
import { trpc } from '@/lib/trpc-client'
import type { SkuSummary as SharedSkuSummary } from '@packages/shared'
import MultiSelect from './MultiSelect'
import SearchableSelect from './SearchableSelect'
// Selector works with skus that may not have images resolved yet
type SkuSummary = Omit<SharedSkuSummary, 'images'>
interface Group {
id: number
groupName: string
products: { id: number }[]
}
interface ProductsSelectorProps {
value: number | number[]
onChange: (value: number | number[]) => void
multiple?: boolean
label?: string
placeholder?: string
disabled?: boolean
error?: boolean
isDisabled?: (product: SkuSummary) => boolean
labelFormat?: (product: SkuSummary) => string
groups?: Group[]
selectedGroupIds?: number[]
onGroupChange?: (groupIds: number[]) => void
showGroups?: boolean
testID?: string
}
export default function ProductsSelector({
value,
onChange,
multiple = true,
label = 'Select Products',
placeholder = 'Select products',
disabled = false,
error = false,
isDisabled,
labelFormat,
groups = [],
showGroups = true,
selectedGroupIds = [],
onGroupChange,
testID,
}: ProductsSelectorProps) {
const { data: skusData } = trpc.superadmin.product.getAllSkusSummary.useQuery()
const allSkus: SkuSummary[] = skusData?.skus || []
const [searchQuery, setSearchQuery] = useState('')
// Handle group selection changes
const handleGroupChange = (newGroupIds: number[]) => {
if (!onGroupChange) return
const previousGroupIds = selectedGroupIds
const addedGroups = newGroupIds.filter(id => !previousGroupIds.includes(id))
const removedGroups = previousGroupIds.filter(id => !newGroupIds.includes(id))
let currentSkus = Array.isArray(value) ? [...value] : value ? [value] : []
const addedSkus = addedGroups.flatMap(groupId => {
const group = groups.find(g => g.id === groupId)
if (!group) return []
const productIds = new Set(group.products.map(p => p.id))
return allSkus.filter(s => productIds.has(s.productId)).map(s => s.id)
})
const removedSkus = removedGroups.flatMap(groupId => {
const group = groups.find(g => g.id === groupId)
if (!group) return []
const productIds = new Set(group.products.map(p => p.id))
return allSkus.filter(s => productIds.has(s.productId)).map(s => s.id)
})
currentSkus = [...new Set([...currentSkus, ...addedSkus])]
currentSkus = currentSkus.filter(id => !removedSkus.includes(id))
onGroupChange(newGroupIds)
if (multiple) {
onChange(currentSkus.length > 0 ? currentSkus : [])
} else {
onChange(currentSkus.length > 0 ? currentSkus[0] : 0)
}
}
// Filter products based on search query
const filteredSkus = useMemo(() => {
if (!searchQuery.trim()) return allSkus
const query = searchQuery.toLowerCase()
return allSkus.filter(sku =>
sku.label.toLowerCase().includes(query) ||
sku.productName.toLowerCase().includes(query)
)
}, [allSkus, searchQuery])
// Build dropdown options
const productOptions = useMemo(() => {
return filteredSkus.map((sku) => {
const isFromGroup = selectedGroupIds.length > 0 && groups.some(group => {
if (!selectedGroupIds.includes(group.id)) return false
return group.products.some(p => p.id === sku.productId)
})
const isProductDisabled = isDisabled ? isDisabled(sku) : false
const displayLabel = labelFormat
? labelFormat(sku)
: sku.label
return {
label: `${displayLabel}${isFromGroup ? ' (from group)' : ''}`,
value: sku.id.toString(),
disabled: isProductDisabled,
}
})
}, [filteredSkus, selectedGroupIds, groups, isDisabled, labelFormat])
// Build group options if groups are provided
const groupOptions = useMemo(() => {
return groups.map(group => ({
label: group.groupName,
value: group.id.toString(),
}))
}, [groups])
return (
<div className="w-full">
{showGroups && groups.length > 0 && (
<div className="mb-4">
<MultiSelect
testID="product-groups-dropdown"
label="Select Product Groups"
options={groupOptions}
value={selectedGroupIds.map(id => id.toString())}
onValueChange={(selectedValue) => {
const selectedValues = Array.isArray(selectedValue) ? selectedValue : typeof selectedValue === 'string' ? [selectedValue] : []
const newGroupIds = selectedValues.map(v => parseInt(v as string))
handleGroupChange(newGroupIds)
}}
placeholder="Select product groups (optional)"
/>
</div>
)}
{multiple ? (
<MultiSelect
label={label}
testID={testID}
options={productOptions}
value={Array.isArray(value) ? value.map(id => id.toString()) : []}
onValueChange={(selectedValue) => {
const selectedValues = Array.isArray(selectedValue) ? selectedValue : typeof selectedValue === 'string' ? [selectedValue] : []
onChange(selectedValues.map(v => Number(v)))
}}
placeholder={placeholder}
disabled={disabled}
error={error}
onSearch={setSearchQuery}
/>
) : (
<SearchableSelect
label={label}
testID={testID}
options={productOptions}
value={value ? value.toString() : ''}
onValueChange={(selectedValue) => {
onChange(Number(selectedValue))
}}
placeholder={placeholder}
disabled={disabled}
error={error}
onSearch={setSearchQuery}
/>
)}
</div>
)
}

View file

@ -0,0 +1,116 @@
import { useMemo, useState } from 'react'
import { BottomDialog, SearchBar, p as P } from 'web-components'
import { Check, ChevronDown } from 'lucide-react'
export interface SearchableSelectOption {
label: string
value: string | number
disabled?: boolean
}
interface SearchableSelectProps {
label: string
options: SearchableSelectOption[]
value: string | number
onValueChange: (v: string | number) => void
onSearch?: (q: string) => void
placeholder?: string
disabled?: boolean
error?: boolean
className?: string
testID?: string
// Tolerated for screen compatibility (RN BottomDropdown leftover) — ignored on web
triggerComponent?: any
}
export function SearchableSelect({
label,
options,
value,
onValueChange,
onSearch,
placeholder,
disabled = false,
error = false,
className,
testID,
}: SearchableSelectProps) {
const [open, setOpen] = useState(false)
const [query, setQuery] = useState('')
const selectedLabel = useMemo(() => {
const found = options.find((o) => String(o.value) === String(value))
return found ? found.label : null
}, [options, value])
const displayText = selectedLabel ?? placeholder ?? label
const filtered = useMemo(() => {
const q = query.trim().toLowerCase()
if (!q) return options
return options.filter((o) => o.label.toLowerCase().includes(q))
}, [options, query])
const handleSelect = (optionValue: string | number) => {
onValueChange(optionValue)
setOpen(false)
}
return (
<div className={className} data-testid={testID}>
<P className="mb-1 text-sm text-gray-500 font-medium">{label}</P>
<button
type="button"
disabled={disabled}
onClick={() => setOpen(true)}
className={`flex w-full items-center justify-between rounded-md border bg-white px-3 py-2 text-sm text-left disabled:cursor-not-allowed disabled:opacity-50 ${error ? 'border-red-500' : 'border-gray-300'}`}
>
<span className={`truncate ${selectedLabel ? 'text-gray-800' : 'text-gray-400'}`}>
{displayText}
</span>
<ChevronDown className="h-4 w-4 shrink-0 text-gray-400" />
</button>
<BottomDialog open={open} onClose={() => setOpen(false)}>
<div className="p-4">
<P className="text-lg font-semibold mb-4">{label}</P>
<SearchBar
placeholder="Search..."
value={query}
onChange={(q) => {
setQuery(q)
onSearch?.(q)
}}
onSearch={onSearch}
className="mb-3"
testID={testID ? `${testID}-search` : undefined}
/>
<div className="overflow-y-auto" style={{ maxHeight: 320 }}>
{filtered.map((option) => {
const selected = String(option.value) === String(value)
return (
<button
key={String(option.value)}
type="button"
disabled={option.disabled}
onClick={() => handleSelect(option.value)}
data-testid={testID ? `${testID}-option-${option.value}` : undefined}
className={`flex flex-row items-center w-full p-3 border-b border-gray-100 text-left ${option.disabled ? 'opacity-50' : 'cursor-pointer hover:bg-gray-50'} ${selected ? 'bg-blue-50' : ''}`}
>
<span className={`text-sm flex-1 ${selected ? 'font-semibold text-blue-700' : 'text-gray-800'}`}>
{option.label}
</span>
{selected ? <Check className="h-4 w-4 text-blue-600" /> : null}
</button>
)
})}
{filtered.length === 0 ? (
<P className="text-center text-gray-500 text-sm p-4">No options found</P>
) : null}
</div>
</div>
</BottomDialog>
</div>
)
}
export default SearchableSelect

View file

@ -0,0 +1,235 @@
import { useState, useEffect, useMemo, useRef, type ChangeEvent } from 'react'
import { Formik } from 'formik'
import * as Yup from 'yup'
import { pInput as PInput, Dropdown, p as P, ImageUploader, Checkbox } from 'web-components'
import ProductsSelector from './ProductsSelector'
import { trpc } from '@/lib/trpc-client'
import { useUploadToObjectStorage } from '../hooks/useUploadToObjectStorage'
import type { CreateStoreInput } from '@packages/shared'
// Store form values — required description + product selection on top of CreateStoreInput
export type StoreFormData = Omit<CreateStoreInput, 'description'> & {
description: string
products: number[]
regionId?: number | null
}
interface StoreFormProps {
mode: 'create' | 'edit'
initialValues: StoreFormData
onSubmit: (values: StoreFormData) => void
isLoading: boolean
storeId?: number
}
const validationSchema = Yup.object().shape({
name: Yup.string().required('Name is required'),
description: Yup.string(),
imageUrl: Yup.string(),
owner: Yup.number().required('Owner is required'),
products: Yup.array().of(Yup.number()),
regionId: Yup.number().when('availableInAllRegions', {
is: false,
then: (schema) => schema.required('Region is required').min(1, 'Region is required'),
otherwise: (schema) => schema.notRequired().nullable(),
}),
})
function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreFormProps) {
const { data: staffData } = trpc.superadmin.staffUser.getStaff.useQuery()
const { data: productsData } = trpc.superadmin.product.getProducts.useQuery()
const { data: regionsData } = trpc.superadmin.region.getRegions.useQuery(undefined, { staleTime: Infinity })
const regions = (regionsData as any)?.regions ?? []
const [formInitialValues, setFormInitialValues] = useState<StoreFormData>(initialValues)
const [selectedImages, setSelectedImages] = useState<{ blob: Blob; mimeType: string }[]>([])
const [displayImages, setDisplayImages] = useState<{ uri?: string }[]>([])
const fileInputRef = useRef<HTMLInputElement>(null)
// For edit mode, pre-select SKUs belonging to this store's products
const initialSelectedProducts = useMemo(() => {
if (mode !== 'edit' || !productsData?.products) return []
return productsData.products
.filter(p => p.store?.id === storeId)
.flatMap(p => (p.skus || []).map(sku => sku.id))
}, [mode, productsData?.products, storeId])
useEffect(() => {
setFormInitialValues({
...initialValues,
products: initialSelectedProducts,
})
}, [initialValues, initialSelectedProducts])
const existingImageUrls = useMemo(
() => (formInitialValues.imageUrl ? [formInitialValues.imageUrl] : []),
[formInitialValues.imageUrl]
)
const staffOptions = staffData?.staff.map((staff: { id: number; name: string }) => ({
label: staff.name,
value: staff.id,
})) || []
const { uploadSingle, isUploading } = useUploadToObjectStorage()
const handleImagePick = () => {
fileInputRef.current?.click()
}
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || [])
if (files.length === 0) {
setSelectedImages([])
setDisplayImages([])
return
}
const file = files[0]
setSelectedImages([{ blob: file, mimeType: file.type || 'image/jpeg' }])
setDisplayImages([{ uri: URL.createObjectURL(file) }])
e.target.value = ''
}
const handleRemoveImage = (uri: string) => {
const index = displayImages.findIndex(img => img.uri === uri)
if (index !== -1) {
const newDisplay = displayImages.filter((_, i) => i !== index)
const newFiles = selectedImages.filter((_, i) => i !== index)
setDisplayImages(newDisplay)
setSelectedImages(newFiles)
}
}
return (
<Formik
initialValues={formInitialValues}
validationSchema={validationSchema}
onSubmit={onSubmit}
enableReinitialize
>
{({ handleChange, handleSubmit, values, setFieldValue, errors, touched }) => {
const submit = async () => {
try {
let imageUrl: string | undefined
if (selectedImages.length > 0) {
const { blob, mimeType } = selectedImages[0]
const { presignedUrl } = await uploadSingle(blob, mimeType, 'store')
imageUrl = presignedUrl
}
onSubmit({ ...values, imageUrl })
} catch (error) {
console.error('Upload error:', error)
window.alert('Error: Failed to upload image')
}
}
return (
<div>
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleFileChange}
className="hidden"
/>
<PInput
topLabel="Store Name"
placeholder="Enter store name"
value={values.name}
onChange={handleChange('name')}
error={!!(touched.name && errors.name)}
style={{ marginBottom: 16 }}
data-testid="store-name-input"
/>
<PInput
topLabel="Description"
placeholder="Enter store description"
multiline
numberOfLines={3}
value={values.description}
onChange={handleChange('description')}
error={!!(touched.description && errors.description)}
style={{ marginBottom: 16 }}
data-testid="store-description-input"
/>
<div className="mb-4">
<P className="mb-1 text-sm text-gray-500 font-medium">Owner</P>
<Dropdown
label="Select owner"
value={values.owner}
options={staffOptions}
onValueChange={(value) => setFieldValue('owner', Number(value))}
className="mb-4"
testID="store-owner-dropdown"
/>
</div>
<div className="flex flex-row items-center mb-4">
<Checkbox
checked={!!values.availableInAllRegions}
onPress={() => {
const next = !values.availableInAllRegions
setFieldValue('availableInAllRegions', next)
if (next) setFieldValue('regionId', null)
}}
testID="store-all-regions-checkbox"
/>
<P className="text-gray-700 font-medium ml-3">Available in all regions</P>
</div>
{!values.availableInAllRegions && (
<div className="mb-4">
<P className="mb-1 text-sm text-gray-500 font-medium">Home Region</P>
<Dropdown
label="Select home region"
value={(values as StoreFormData).regionId ?? ''}
options={regions.map((r: any) => ({ label: r.name, value: r.id }))}
onValueChange={(value) => setFieldValue('regionId', Number(value))}
className="mb-4"
testID="store-region-dropdown"
/>
</div>
)}
<ProductsSelector
value={values.products || []}
onChange={(value) => setFieldValue('products', value)}
multiple={true}
label="Products"
placeholder="Select products"
isDisabled={(sku) => sku.storeId !== null && sku.storeId !== storeId}
labelFormat={(sku) => `${sku.productName} - ₹${sku.price}`}
testID="store-products-selector"
/>
<div className="mb-6">
<P className="text-sm font-bold text-gray-700 mb-3 uppercase tracking-wider block">Store Image</P>
<ImageUploader
images={displayImages}
existingImageUrls={existingImageUrls}
onAddImage={handleImagePick}
onRemoveImage={handleRemoveImage}
onRemoveExistingImage={() =>
setFormInitialValues((prev) => ({
...prev,
imageUrl: undefined,
}))
}
allowMultiple={false}
/>
</div>
<button
type="button"
onClick={submit}
disabled={isLoading || isUploading}
data-testid="store-submit-button"
className={`px-4 py-2 rounded-lg shadow-lg items-center mt-2 text-white text-lg font-bold w-full disabled:opacity-70 ${isLoading || isUploading ? 'bg-gray-400' : 'bg-blue-500'}`}
>
{isUploading ? 'Uploading...' : isLoading ? (mode === 'create' ? 'Creating...' : 'Updating...') : (mode === 'create' ? 'Create Store' : 'Update Store')}
</button>
</div>
)
}}
</Formik>
)
}
export default StoreForm

Some files were not shown because too many files have changed in this diff Show more