enh
This commit is contained in:
parent
a09cb936c0
commit
ac31dc2010
224 changed files with 28342 additions and 11204 deletions
13
.gitignore
vendored
13
.gitignore
vendored
|
|
@ -140,4 +140,15 @@ apps/user-ui/android/
|
||||||
apps/admin-ui/android/
|
apps/admin-ui/android/
|
||||||
.maestro-output/*
|
.maestro-output/*
|
||||||
|
|
||||||
apps/admin-ui/.expo/cache/*
|
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
|
||||||
|
|
|
||||||
183
PRODUCT-REPORT.txt
Normal file
183
PRODUCT-REPORT.txt
Normal 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.
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
{
|
{
|
||||||
"dependencies": "4650ceb7c30aaa4d5fd17b9577e186af7a84b50d",
|
"dependencies": "0106f523449523fa8389ec59d4d1bcbce79e46ac",
|
||||||
"devDependencies": "b3b38265f32b99a8299270a292f38ca26288d53d"
|
"devDependencies": "ee6421f996bd5fd6168846996d47bafe1791fe2e"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,7 @@ const CONST_VISIBILITY: Record<string, boolean> = {
|
||||||
versionNum: false,
|
versionNum: false,
|
||||||
playStoreUrl: false,
|
playStoreUrl: false,
|
||||||
appStoreUrl: false,
|
appStoreUrl: false,
|
||||||
popularItems: true,
|
popularItems: false,
|
||||||
allItemsOrder: true,
|
allItemsOrder: true,
|
||||||
isFlashDeliveryEnabled: true,
|
isFlashDeliveryEnabled: true,
|
||||||
supportMobile: true,
|
supportMobile: true,
|
||||||
|
|
@ -194,7 +194,24 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
|
||||||
|
|
||||||
export default function CustomizeApp() {
|
export default function CustomizeApp() {
|
||||||
const router = useRouter();
|
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();
|
const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation();
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -214,7 +231,10 @@ export default function CustomizeApp() {
|
||||||
}
|
}
|
||||||
|
|
||||||
updateConstants(
|
updateConstants(
|
||||||
{ constants: changedConstants },
|
{
|
||||||
|
constants: changedConstants,
|
||||||
|
...(activeBoundId != null ? { boundId: activeBoundId } : {}),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
onSuccess: (response) => {
|
onSuccess: (response) => {
|
||||||
Alert.alert('Success', `Updated ${response.updatedCount} constants successfully.`);
|
Alert.alert('Success', `Updated ${response.updatedCount} constants successfully.`);
|
||||||
|
|
@ -259,7 +279,33 @@ export default function CustomizeApp() {
|
||||||
Modify application constants. Changes will take effect immediately.
|
Modify application constants. Changes will take effect immediately.
|
||||||
</MyText>
|
</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 }) => (
|
{({ handleSubmit, values, setFieldValue }) => (
|
||||||
<View>
|
<View>
|
||||||
{constants.map((constant) => {
|
{constants.map((constant) => {
|
||||||
|
|
|
||||||
|
|
@ -205,7 +205,7 @@ export default function PricesOverview() {
|
||||||
for (const product of allProducts) {
|
for (const product of allProducts) {
|
||||||
if (product.skus && product.skus.length > 0) {
|
if (product.skus && product.skus.length > 0) {
|
||||||
for (const sku of product.skus) {
|
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 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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({
|
await createProduct.mutateAsync({
|
||||||
name: values.name,
|
name: values.name,
|
||||||
shortDescription: values.shortDescription || undefined,
|
shortDescription: values.shortDescription || undefined,
|
||||||
longDescription: values.longDescription || undefined,
|
longDescription: values.longDescription || undefined,
|
||||||
storeId: values.storeId,
|
|
||||||
productType: values.productType,
|
productType: values.productType,
|
||||||
incrementStep: 1,
|
incrementStep: 1,
|
||||||
skus,
|
skus,
|
||||||
|
availableInAllRegions: !!values.availableInAllRegions,
|
||||||
|
...(values.availableInAllRegions
|
||||||
|
? { storeIdsByRegion }
|
||||||
|
: { storeId: values.storeId }),
|
||||||
})
|
})
|
||||||
|
|
||||||
await refetchProducts()
|
await refetchProducts()
|
||||||
|
|
@ -118,6 +130,9 @@ export default function AddProduct() {
|
||||||
name: '',
|
name: '',
|
||||||
shortDescription: '',
|
shortDescription: '',
|
||||||
longDescription: '',
|
longDescription: '',
|
||||||
|
regionId: undefined as number | undefined,
|
||||||
|
availableInAllRegions: false,
|
||||||
|
storeIdsByRegion: {} as Record<number, number>,
|
||||||
storeId: 1,
|
storeId: 1,
|
||||||
productType: 'item' as const,
|
productType: 'item' as const,
|
||||||
variants: [
|
variants: [
|
||||||
|
|
|
||||||
|
|
@ -41,6 +41,9 @@ export default function EditProduct() {
|
||||||
name: '',
|
name: '',
|
||||||
shortDescription: '',
|
shortDescription: '',
|
||||||
longDescription: '',
|
longDescription: '',
|
||||||
|
regionId: undefined as number | undefined,
|
||||||
|
availableInAllRegions: false,
|
||||||
|
storeIdsByRegion: {} as Record<number, number>,
|
||||||
storeId: 0,
|
storeId: 0,
|
||||||
productType: 'item' as const,
|
productType: 'item' as const,
|
||||||
variants: [],
|
variants: [],
|
||||||
|
|
@ -50,7 +53,10 @@ export default function EditProduct() {
|
||||||
name: productData.name,
|
name: productData.name,
|
||||||
shortDescription: productData.shortDescription || '',
|
shortDescription: productData.shortDescription || '',
|
||||||
longDescription: productData.longDescription || '',
|
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',
|
productType: (productData.productType as 'item' | 'combo') || 'item',
|
||||||
variants: (productData.skus || []).map((sku) => ({
|
variants: (productData.skus || []).map((sku) => ({
|
||||||
id: sku.id,
|
id: sku.id,
|
||||||
|
|
@ -176,17 +182,30 @@ 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({
|
await updateProduct.mutateAsync({
|
||||||
id: productId,
|
id: productId,
|
||||||
name: values.name,
|
name: values.name,
|
||||||
shortDescription: values.shortDescription || undefined,
|
shortDescription: values.shortDescription || undefined,
|
||||||
longDescription: values.longDescription || undefined,
|
longDescription: values.longDescription || undefined,
|
||||||
storeId: values.storeId,
|
regionId: values.regionId,
|
||||||
productType: values.productType,
|
productType: values.productType,
|
||||||
incrementStep: 1,
|
incrementStep: 1,
|
||||||
skus,
|
skus,
|
||||||
deletedImageKeys,
|
deletedImageKeys,
|
||||||
newImageUrls: allUploadUrls,
|
newImageUrls: allUploadUrls,
|
||||||
|
availableInAllRegions: !!values.availableInAllRegions,
|
||||||
|
...(values.availableInAllRegions
|
||||||
|
? { storeIdsByRegion }
|
||||||
|
: { storeId: values.storeId }),
|
||||||
} as any)
|
} as any)
|
||||||
|
|
||||||
await refetch()
|
await refetch()
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
|
||||||
const initialSelectedProducts = useMemo(() => {
|
const initialSelectedProducts = useMemo(() => {
|
||||||
if (mode !== 'edit' || !productsData?.products) return [];
|
if (mode !== 'edit' || !productsData?.products) return [];
|
||||||
return productsData.products
|
return productsData.products
|
||||||
.filter(p => p.storeId === storeId)
|
.filter(p => p.store?.id === storeId)
|
||||||
.flatMap(p => (p.skus || []).map(sku => sku.id));
|
.flatMap(p => (p.skus || []).map(sku => sku.id));
|
||||||
}, [mode, productsData?.products, storeId]);
|
}, [mode, productsData?.products, storeId]);
|
||||||
|
|
||||||
|
|
@ -128,6 +128,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
|
||||||
return (
|
return (
|
||||||
<View>
|
<View>
|
||||||
<MyTextInput
|
<MyTextInput
|
||||||
|
testID="store-name-input"
|
||||||
topLabel="Store Name"
|
topLabel="Store Name"
|
||||||
placeholder="Enter store name"
|
placeholder="Enter store name"
|
||||||
value={values.name}
|
value={values.name}
|
||||||
|
|
@ -136,6 +137,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
/>
|
/>
|
||||||
<MyTextInput
|
<MyTextInput
|
||||||
|
testID="store-description-input"
|
||||||
topLabel="Description"
|
topLabel="Description"
|
||||||
placeholder="Enter store description"
|
placeholder="Enter store description"
|
||||||
multiline
|
multiline
|
||||||
|
|
@ -146,6 +148,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
/>
|
/>
|
||||||
<BottomDropdown
|
<BottomDropdown
|
||||||
|
testID="store-owner-dropdown"
|
||||||
label="Owner"
|
label="Owner"
|
||||||
value={values.owner}
|
value={values.owner}
|
||||||
options={staffOptions}
|
options={staffOptions}
|
||||||
|
|
@ -155,6 +158,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
/>
|
/>
|
||||||
<ProductsSelector
|
<ProductsSelector
|
||||||
|
testID="store-products-selector"
|
||||||
value={values.products || []}
|
value={values.products || []}
|
||||||
onChange={(value) => setFieldValue('products', value)}
|
onChange={(value) => setFieldValue('products', value)}
|
||||||
multiple={true}
|
multiple={true}
|
||||||
|
|
@ -180,6 +184,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
<TouchableOpacity
|
<TouchableOpacity
|
||||||
|
testID="store-submit-button"
|
||||||
onPress={submit}
|
onPress={submit}
|
||||||
disabled={isLoading || isUploading}
|
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'}`}
|
style={tw`px-4 py-2 rounded-lg shadow-lg items-center mt-2 ${isLoading || isUploading ? 'bg-gray-400' : 'bg-blue-500'}`}
|
||||||
|
|
|
||||||
10
apps/admin-ui/hooks/useIsSuperAdmin.ts
Normal file
10
apps/admin-ui/hooks/useIsSuperAdmin.ts
Normal 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'
|
||||||
|
}
|
||||||
30
apps/admin-ui/ios/.gitignore
vendored
Normal file
30
apps/admin-ui/ios/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
# OSX
|
||||||
|
#
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# Xcode
|
||||||
|
#
|
||||||
|
build/
|
||||||
|
*.pbxuser
|
||||||
|
!default.pbxuser
|
||||||
|
*.mode1v3
|
||||||
|
!default.mode1v3
|
||||||
|
*.mode2v3
|
||||||
|
!default.mode2v3
|
||||||
|
*.perspectivev3
|
||||||
|
!default.perspectivev3
|
||||||
|
xcuserdata
|
||||||
|
*.xccheckout
|
||||||
|
*.moved-aside
|
||||||
|
DerivedData
|
||||||
|
*.hmap
|
||||||
|
*.ipa
|
||||||
|
*.xcuserstate
|
||||||
|
project.xcworkspace
|
||||||
|
.xcode.env.local
|
||||||
|
|
||||||
|
# Bundle artifacts
|
||||||
|
*.jsbundle
|
||||||
|
|
||||||
|
# CocoaPods
|
||||||
|
/Pods/
|
||||||
11
apps/admin-ui/ios/.xcode.env
Normal file
11
apps/admin-ui/ios/.xcode.env
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
# This `.xcode.env` file is versioned and is used to source the environment
|
||||||
|
# used when running script phases inside Xcode.
|
||||||
|
# To customize your local environment, you can create an `.xcode.env.local`
|
||||||
|
# file that is not versioned.
|
||||||
|
|
||||||
|
# NODE_BINARY variable contains the PATH to the node executable.
|
||||||
|
#
|
||||||
|
# Customize the NODE_BINARY variable here.
|
||||||
|
# For example, to use nvm with brew, add the following line
|
||||||
|
# . "$(brew --prefix nvm)/nvm.sh" --no-use
|
||||||
|
export NODE_BINARY=$(command -v node)
|
||||||
555
apps/admin-ui/ios/FreshyoAdmin.xcodeproj/project.pbxproj
Normal file
555
apps/admin-ui/ios/FreshyoAdmin.xcodeproj/project.pbxproj
Normal file
|
|
@ -0,0 +1,555 @@
|
||||||
|
// !$*UTF8*$!
|
||||||
|
{
|
||||||
|
archiveVersion = 1;
|
||||||
|
classes = {
|
||||||
|
};
|
||||||
|
objectVersion = 54;
|
||||||
|
objects = {
|
||||||
|
|
||||||
|
/* Begin PBXBuildFile section */
|
||||||
|
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
|
||||||
|
3600E50E647D2AB5602E4C5A /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = C3AE1E8BC1667055BBDF4408 /* PrivacyInfo.xcprivacy */; };
|
||||||
|
3E461D99554A48A4959DE609 /* SplashScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = AA286B85B6C04FC6940260E9 /* SplashScreen.storyboard */; };
|
||||||
|
87A288A0F5F7156FA6323043 /* ExpoModulesProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2F4911A595766C5F1C188E0 /* ExpoModulesProvider.swift */; };
|
||||||
|
BB2F792D24A3F905000567C9 /* Expo.plist in Resources */ = {isa = PBXBuildFile; fileRef = BB2F792C24A3F905000567C9 /* Expo.plist */; };
|
||||||
|
F11748422D0307B40044C1D9 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F11748412D0307B40044C1D9 /* AppDelegate.swift */; };
|
||||||
|
FBC089081ACEB42560FD9605 /* libPods-FreshyoAdmin.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 72F9434E2E25D4F6E3895340 /* libPods-FreshyoAdmin.a */; };
|
||||||
|
/* End PBXBuildFile section */
|
||||||
|
|
||||||
|
/* Begin PBXFileReference section */
|
||||||
|
13B07F961A680F5B00A75B9A /* FreshyoAdmin.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = FreshyoAdmin.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
|
13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = FreshyoAdmin/Images.xcassets; sourceTree = "<group>"; };
|
||||||
|
13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = FreshyoAdmin/Info.plist; sourceTree = "<group>"; };
|
||||||
|
72F9434E2E25D4F6E3895340 /* libPods-FreshyoAdmin.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-FreshyoAdmin.a"; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
|
8D1B7A489F8C992C37CA905E /* Pods-FreshyoAdmin.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-FreshyoAdmin.release.xcconfig"; path = "Target Support Files/Pods-FreshyoAdmin/Pods-FreshyoAdmin.release.xcconfig"; sourceTree = "<group>"; };
|
||||||
|
AA286B85B6C04FC6940260E9 /* SplashScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = SplashScreen.storyboard; path = FreshyoAdmin/SplashScreen.storyboard; sourceTree = "<group>"; };
|
||||||
|
B64C0365DD0A717B110770E3 /* Pods-FreshyoAdmin.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-FreshyoAdmin.debug.xcconfig"; path = "Target Support Files/Pods-FreshyoAdmin/Pods-FreshyoAdmin.debug.xcconfig"; sourceTree = "<group>"; };
|
||||||
|
BB2F792C24A3F905000567C9 /* Expo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Expo.plist; sourceTree = "<group>"; };
|
||||||
|
C3AE1E8BC1667055BBDF4408 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; includeInIndex = 1; name = PrivacyInfo.xcprivacy; path = FreshyoAdmin/PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
|
||||||
|
E2F4911A595766C5F1C188E0 /* ExpoModulesProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ExpoModulesProvider.swift; path = "Pods/Target Support Files/Pods-FreshyoAdmin/ExpoModulesProvider.swift"; sourceTree = "<group>"; };
|
||||||
|
ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; };
|
||||||
|
F11748412D0307B40044C1D9 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AppDelegate.swift; path = FreshyoAdmin/AppDelegate.swift; sourceTree = "<group>"; };
|
||||||
|
F11748442D0722820044C1D9 /* FreshyoAdmin-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "FreshyoAdmin-Bridging-Header.h"; path = "FreshyoAdmin/FreshyoAdmin-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||||
|
/* End PBXFileReference section */
|
||||||
|
|
||||||
|
/* Begin PBXFrameworksBuildPhase section */
|
||||||
|
13B07F8C1A680F5B00A75B9A /* Frameworks */ = {
|
||||||
|
isa = PBXFrameworksBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
FBC089081ACEB42560FD9605 /* libPods-FreshyoAdmin.a in Frameworks */,
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
};
|
||||||
|
/* End PBXFrameworksBuildPhase section */
|
||||||
|
|
||||||
|
/* Begin PBXGroup section */
|
||||||
|
13B07FAE1A68108700A75B9A /* FreshyoAdmin */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
F11748412D0307B40044C1D9 /* AppDelegate.swift */,
|
||||||
|
F11748442D0722820044C1D9 /* FreshyoAdmin-Bridging-Header.h */,
|
||||||
|
BB2F792B24A3F905000567C9 /* Supporting */,
|
||||||
|
13B07FB51A68108700A75B9A /* Images.xcassets */,
|
||||||
|
13B07FB61A68108700A75B9A /* Info.plist */,
|
||||||
|
AA286B85B6C04FC6940260E9 /* SplashScreen.storyboard */,
|
||||||
|
C3AE1E8BC1667055BBDF4408 /* PrivacyInfo.xcprivacy */,
|
||||||
|
);
|
||||||
|
name = FreshyoAdmin;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
2D16E6871FA4F8E400B85C8A /* Frameworks */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
ED297162215061F000B7C4FE /* JavaScriptCore.framework */,
|
||||||
|
72F9434E2E25D4F6E3895340 /* libPods-FreshyoAdmin.a */,
|
||||||
|
);
|
||||||
|
name = Frameworks;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
6B383365642FB5358C5BA8E5 /* Pods */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
B64C0365DD0A717B110770E3 /* Pods-FreshyoAdmin.debug.xcconfig */,
|
||||||
|
8D1B7A489F8C992C37CA905E /* Pods-FreshyoAdmin.release.xcconfig */,
|
||||||
|
);
|
||||||
|
name = Pods;
|
||||||
|
path = Pods;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
832341AE1AAA6A7D00B99B32 /* Libraries */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
);
|
||||||
|
name = Libraries;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
83CBB9F61A601CBA00E9B192 = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
13B07FAE1A68108700A75B9A /* FreshyoAdmin */,
|
||||||
|
832341AE1AAA6A7D00B99B32 /* Libraries */,
|
||||||
|
83CBBA001A601CBA00E9B192 /* Products */,
|
||||||
|
2D16E6871FA4F8E400B85C8A /* Frameworks */,
|
||||||
|
6B383365642FB5358C5BA8E5 /* Pods */,
|
||||||
|
B10F8EED5A983C6DE2E09661 /* ExpoModulesProviders */,
|
||||||
|
);
|
||||||
|
indentWidth = 2;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
tabWidth = 2;
|
||||||
|
usesTabs = 0;
|
||||||
|
};
|
||||||
|
83CBBA001A601CBA00E9B192 /* Products */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
13B07F961A680F5B00A75B9A /* FreshyoAdmin.app */,
|
||||||
|
);
|
||||||
|
name = Products;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
B10F8EED5A983C6DE2E09661 /* ExpoModulesProviders */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
C237E6A59D03E99F8AEF2B4B /* FreshyoAdmin */,
|
||||||
|
);
|
||||||
|
name = ExpoModulesProviders;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
BB2F792B24A3F905000567C9 /* Supporting */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
BB2F792C24A3F905000567C9 /* Expo.plist */,
|
||||||
|
);
|
||||||
|
name = Supporting;
|
||||||
|
path = FreshyoAdmin/Supporting;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
C237E6A59D03E99F8AEF2B4B /* FreshyoAdmin */ = {
|
||||||
|
isa = PBXGroup;
|
||||||
|
children = (
|
||||||
|
E2F4911A595766C5F1C188E0 /* ExpoModulesProvider.swift */,
|
||||||
|
);
|
||||||
|
name = FreshyoAdmin;
|
||||||
|
sourceTree = "<group>";
|
||||||
|
};
|
||||||
|
/* End PBXGroup section */
|
||||||
|
|
||||||
|
/* Begin PBXNativeTarget section */
|
||||||
|
13B07F861A680F5B00A75B9A /* FreshyoAdmin */ = {
|
||||||
|
isa = PBXNativeTarget;
|
||||||
|
buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "FreshyoAdmin" */;
|
||||||
|
buildPhases = (
|
||||||
|
08A4A3CD28434E44B6B9DE2E /* [CP] Check Pods Manifest.lock */,
|
||||||
|
8254F6B70850498144945872 /* [Expo] Configure project */,
|
||||||
|
13B07F871A680F5B00A75B9A /* Sources */,
|
||||||
|
13B07F8C1A680F5B00A75B9A /* Frameworks */,
|
||||||
|
13B07F8E1A680F5B00A75B9A /* Resources */,
|
||||||
|
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */,
|
||||||
|
800E24972A6A228C8D4807E9 /* [CP] Copy Pods Resources */,
|
||||||
|
E1A945B7F366C375E22EF118 /* [CP] Embed Pods Frameworks */,
|
||||||
|
);
|
||||||
|
buildRules = (
|
||||||
|
);
|
||||||
|
dependencies = (
|
||||||
|
);
|
||||||
|
name = FreshyoAdmin;
|
||||||
|
productName = FreshyoAdmin;
|
||||||
|
productReference = 13B07F961A680F5B00A75B9A /* FreshyoAdmin.app */;
|
||||||
|
productType = "com.apple.product-type.application";
|
||||||
|
};
|
||||||
|
/* End PBXNativeTarget section */
|
||||||
|
|
||||||
|
/* Begin PBXProject section */
|
||||||
|
83CBB9F71A601CBA00E9B192 /* Project object */ = {
|
||||||
|
isa = PBXProject;
|
||||||
|
attributes = {
|
||||||
|
LastUpgradeCheck = 1130;
|
||||||
|
TargetAttributes = {
|
||||||
|
13B07F861A680F5B00A75B9A = {
|
||||||
|
LastSwiftMigration = 1250;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "FreshyoAdmin" */;
|
||||||
|
compatibilityVersion = "Xcode 3.2";
|
||||||
|
developmentRegion = en;
|
||||||
|
hasScannedForEncodings = 0;
|
||||||
|
knownRegions = (
|
||||||
|
en,
|
||||||
|
Base,
|
||||||
|
);
|
||||||
|
mainGroup = 83CBB9F61A601CBA00E9B192;
|
||||||
|
productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */;
|
||||||
|
projectDirPath = "";
|
||||||
|
projectRoot = "";
|
||||||
|
targets = (
|
||||||
|
13B07F861A680F5B00A75B9A /* FreshyoAdmin */,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
/* End PBXProject section */
|
||||||
|
|
||||||
|
/* Begin PBXResourcesBuildPhase section */
|
||||||
|
13B07F8E1A680F5B00A75B9A /* Resources */ = {
|
||||||
|
isa = PBXResourcesBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
BB2F792D24A3F905000567C9 /* Expo.plist in Resources */,
|
||||||
|
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,
|
||||||
|
3E461D99554A48A4959DE609 /* SplashScreen.storyboard in Resources */,
|
||||||
|
3600E50E647D2AB5602E4C5A /* PrivacyInfo.xcprivacy in Resources */,
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
};
|
||||||
|
/* End PBXResourcesBuildPhase section */
|
||||||
|
|
||||||
|
/* Begin PBXShellScriptBuildPhase section */
|
||||||
|
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = {
|
||||||
|
isa = PBXShellScriptBuildPhase;
|
||||||
|
alwaysOutOfDate = 1;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
inputPaths = (
|
||||||
|
);
|
||||||
|
name = "Bundle React Native code and images";
|
||||||
|
outputPaths = (
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
shellPath = /bin/sh;
|
||||||
|
shellScript = "if [[ -f \"$PODS_ROOT/../.xcode.env\" ]]; then\n source \"$PODS_ROOT/../.xcode.env\"\nfi\nif [[ -f \"$PODS_ROOT/../.xcode.env.local\" ]]; then\n source \"$PODS_ROOT/../.xcode.env.local\"\nfi\n\n# The project root by default is one level up from the ios directory\nexport PROJECT_ROOT=\"$PROJECT_DIR\"/..\n\nif [[ \"$CONFIGURATION\" = *Debug* ]]; then\n export SKIP_BUNDLING=1\nfi\nif [[ -z \"$ENTRY_FILE\" ]]; then\n # Set the entry JS file using the bundler's entry resolution.\n export ENTRY_FILE=\"$(\"$NODE_BINARY\" -e \"require('expo/scripts/resolveAppEntry')\" \"$PROJECT_ROOT\" ios absolute | tail -n 1)\"\nfi\n\nif [[ -z \"$CLI_PATH\" ]]; then\n # Use Expo CLI\n export CLI_PATH=\"$(\"$NODE_BINARY\" --print \"require.resolve('@expo/cli', { paths: [require.resolve('expo/package.json')] })\")\"\nfi\nif [[ -z \"$BUNDLE_COMMAND\" ]]; then\n # Default Expo CLI command for bundling\n export BUNDLE_COMMAND=\"export:embed\"\nfi\n\n# Source .xcode.env.updates if it exists to allow\n# SKIP_BUNDLING to be unset if needed\nif [[ -f \"$PODS_ROOT/../.xcode.env.updates\" ]]; then\n source \"$PODS_ROOT/../.xcode.env.updates\"\nfi\n# Source local changes to allow overrides\n# if needed\nif [[ -f \"$PODS_ROOT/../.xcode.env.local\" ]]; then\n source \"$PODS_ROOT/../.xcode.env.local\"\nfi\n\n`\"$NODE_BINARY\" --print \"require('path').dirname(require.resolve('react-native/package.json')) + '/scripts/react-native-xcode.sh'\"`\n\n";
|
||||||
|
};
|
||||||
|
08A4A3CD28434E44B6B9DE2E /* [CP] Check Pods Manifest.lock */ = {
|
||||||
|
isa = PBXShellScriptBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
inputFileListPaths = (
|
||||||
|
);
|
||||||
|
inputPaths = (
|
||||||
|
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
|
||||||
|
"${PODS_ROOT}/Manifest.lock",
|
||||||
|
);
|
||||||
|
name = "[CP] Check Pods Manifest.lock";
|
||||||
|
outputFileListPaths = (
|
||||||
|
);
|
||||||
|
outputPaths = (
|
||||||
|
"$(DERIVED_FILE_DIR)/Pods-FreshyoAdmin-checkManifestLockResult.txt",
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
shellPath = /bin/sh;
|
||||||
|
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
|
||||||
|
showEnvVarsInLog = 0;
|
||||||
|
};
|
||||||
|
800E24972A6A228C8D4807E9 /* [CP] Copy Pods Resources */ = {
|
||||||
|
isa = PBXShellScriptBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
inputPaths = (
|
||||||
|
"${PODS_ROOT}/Target Support Files/Pods-FreshyoAdmin/Pods-FreshyoAdmin-resources.sh",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/EXApplication/ExpoApplication_privacy.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/EXConstants/EXConstants.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/EXConstants/ExpoConstants_privacy.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/EXNotifications/ExpoNotifications_privacy.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/EXUpdates/EXUpdates.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/ExpoDevice/ExpoDevice_privacy.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/ExpoFileSystem/ExpoFileSystem_privacy.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/ExpoSystemUI/ExpoSystemUI_privacy.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/RCT-Folly/RCT-Folly_privacy.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/ReachabilitySwift/ReachabilitySwift.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/React-Core/React-Core_privacy.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/React-cxxreact/React-cxxreact_privacy.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage/SDWebImage.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/boost/boost_privacy.bundle",
|
||||||
|
"${PODS_CONFIGURATION_BUILD_DIR}/glog/glog_privacy.bundle",
|
||||||
|
);
|
||||||
|
name = "[CP] Copy Pods Resources";
|
||||||
|
outputPaths = (
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/ExpoApplication_privacy.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/EXConstants.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/ExpoConstants_privacy.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/ExpoNotifications_privacy.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/EXUpdates.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/ExpoDevice_privacy.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/ExpoFileSystem_privacy.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/ExpoSystemUI_privacy.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/RCT-Folly_privacy.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/ReachabilitySwift.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/React-Core_privacy.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/React-cxxreact_privacy.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/SDWebImage.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/boost_privacy.bundle",
|
||||||
|
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/glog_privacy.bundle",
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
shellPath = /bin/sh;
|
||||||
|
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-FreshyoAdmin/Pods-FreshyoAdmin-resources.sh\"\n";
|
||||||
|
showEnvVarsInLog = 0;
|
||||||
|
};
|
||||||
|
8254F6B70850498144945872 /* [Expo] Configure project */ = {
|
||||||
|
isa = PBXShellScriptBuildPhase;
|
||||||
|
alwaysOutOfDate = 1;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
inputFileListPaths = (
|
||||||
|
);
|
||||||
|
inputPaths = (
|
||||||
|
);
|
||||||
|
name = "[Expo] Configure project";
|
||||||
|
outputFileListPaths = (
|
||||||
|
);
|
||||||
|
outputPaths = (
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
shellPath = /bin/sh;
|
||||||
|
shellScript = "# This script configures Expo modules and generates the modules provider file.\nbash -l -c \"./Pods/Target\\ Support\\ Files/Pods-FreshyoAdmin/expo-configure-project.sh\"\n";
|
||||||
|
};
|
||||||
|
E1A945B7F366C375E22EF118 /* [CP] Embed Pods Frameworks */ = {
|
||||||
|
isa = PBXShellScriptBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
inputPaths = (
|
||||||
|
"${PODS_ROOT}/Target Support Files/Pods-FreshyoAdmin/Pods-FreshyoAdmin-frameworks.sh",
|
||||||
|
"${PODS_XCFRAMEWORKS_BUILD_DIR}/hermes-engine/Pre-built/hermes.framework/hermes",
|
||||||
|
);
|
||||||
|
name = "[CP] Embed Pods Frameworks";
|
||||||
|
outputPaths = (
|
||||||
|
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/hermes.framework",
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
shellPath = /bin/sh;
|
||||||
|
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-FreshyoAdmin/Pods-FreshyoAdmin-frameworks.sh\"\n";
|
||||||
|
showEnvVarsInLog = 0;
|
||||||
|
};
|
||||||
|
/* End PBXShellScriptBuildPhase section */
|
||||||
|
|
||||||
|
/* Begin PBXSourcesBuildPhase section */
|
||||||
|
13B07F871A680F5B00A75B9A /* Sources */ = {
|
||||||
|
isa = PBXSourcesBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
F11748422D0307B40044C1D9 /* AppDelegate.swift in Sources */,
|
||||||
|
87A288A0F5F7156FA6323043 /* ExpoModulesProvider.swift in Sources */,
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
};
|
||||||
|
/* End PBXSourcesBuildPhase section */
|
||||||
|
|
||||||
|
/* Begin XCBuildConfiguration section */
|
||||||
|
13B07F941A680F5B00A75B9A /* Debug */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
baseConfigurationReference = B64C0365DD0A717B110770E3 /* Pods-FreshyoAdmin.debug.xcconfig */;
|
||||||
|
buildSettings = {
|
||||||
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
|
CLANG_ENABLE_MODULES = YES;
|
||||||
|
CODE_SIGN_ENTITLEMENTS = FreshyoAdmin/FreshyoAdmin.entitlements;
|
||||||
|
CURRENT_PROJECT_VERSION = 1;
|
||||||
|
ENABLE_BITCODE = NO;
|
||||||
|
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||||
|
"$(inherited)",
|
||||||
|
"FB_SONARKIT_ENABLED=1",
|
||||||
|
);
|
||||||
|
INFOPLIST_FILE = FreshyoAdmin/Info.plist;
|
||||||
|
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
|
||||||
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
|
"$(inherited)",
|
||||||
|
"@executable_path/Frameworks",
|
||||||
|
);
|
||||||
|
MARKETING_VERSION = 1.0;
|
||||||
|
OTHER_LDFLAGS = (
|
||||||
|
"$(inherited)",
|
||||||
|
"-ObjC",
|
||||||
|
"-lc++",
|
||||||
|
);
|
||||||
|
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_DEBUG";
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER = in.freshyo.adminui;
|
||||||
|
PRODUCT_NAME = FreshyoAdmin;
|
||||||
|
SWIFT_OBJC_BRIDGING_HEADER = "FreshyoAdmin/FreshyoAdmin-Bridging-Header.h";
|
||||||
|
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||||
|
SWIFT_VERSION = 5.0;
|
||||||
|
TARGETED_DEVICE_FAMILY = "1,2";
|
||||||
|
VERSIONING_SYSTEM = "apple-generic";
|
||||||
|
};
|
||||||
|
name = Debug;
|
||||||
|
};
|
||||||
|
13B07F951A680F5B00A75B9A /* Release */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
baseConfigurationReference = 8D1B7A489F8C992C37CA905E /* Pods-FreshyoAdmin.release.xcconfig */;
|
||||||
|
buildSettings = {
|
||||||
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
|
CLANG_ENABLE_MODULES = YES;
|
||||||
|
CODE_SIGN_ENTITLEMENTS = FreshyoAdmin/FreshyoAdmin.entitlements;
|
||||||
|
CURRENT_PROJECT_VERSION = 1;
|
||||||
|
INFOPLIST_FILE = FreshyoAdmin/Info.plist;
|
||||||
|
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
|
||||||
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
|
"$(inherited)",
|
||||||
|
"@executable_path/Frameworks",
|
||||||
|
);
|
||||||
|
MARKETING_VERSION = 1.0;
|
||||||
|
OTHER_LDFLAGS = (
|
||||||
|
"$(inherited)",
|
||||||
|
"-ObjC",
|
||||||
|
"-lc++",
|
||||||
|
);
|
||||||
|
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_RELEASE";
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER = in.freshyo.adminui;
|
||||||
|
PRODUCT_NAME = FreshyoAdmin;
|
||||||
|
SWIFT_OBJC_BRIDGING_HEADER = "FreshyoAdmin/FreshyoAdmin-Bridging-Header.h";
|
||||||
|
SWIFT_VERSION = 5.0;
|
||||||
|
TARGETED_DEVICE_FAMILY = "1,2";
|
||||||
|
VERSIONING_SYSTEM = "apple-generic";
|
||||||
|
};
|
||||||
|
name = Release;
|
||||||
|
};
|
||||||
|
83CBBA201A601CBA00E9B192 /* Debug */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
buildSettings = {
|
||||||
|
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||||
|
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
|
||||||
|
CLANG_CXX_LANGUAGE_STANDARD = "c++20";
|
||||||
|
CLANG_CXX_LIBRARY = "libc++";
|
||||||
|
CLANG_ENABLE_MODULES = YES;
|
||||||
|
CLANG_ENABLE_OBJC_ARC = YES;
|
||||||
|
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||||
|
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_COMMA = YES;
|
||||||
|
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||||
|
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||||
|
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||||
|
CLANG_WARN_EMPTY_BODY = YES;
|
||||||
|
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||||
|
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||||
|
CLANG_WARN_INT_CONVERSION = YES;
|
||||||
|
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||||
|
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||||
|
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||||
|
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||||
|
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||||
|
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||||
|
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||||
|
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||||
|
COPY_PHASE_STRIP = NO;
|
||||||
|
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||||
|
ENABLE_TESTABILITY = YES;
|
||||||
|
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||||
|
GCC_DYNAMIC_NO_PIC = NO;
|
||||||
|
GCC_NO_COMMON_BLOCKS = YES;
|
||||||
|
GCC_OPTIMIZATION_LEVEL = 0;
|
||||||
|
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||||
|
"DEBUG=1",
|
||||||
|
"$(inherited)",
|
||||||
|
);
|
||||||
|
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
|
||||||
|
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||||
|
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||||
|
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||||
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
|
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
|
||||||
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
|
/usr/lib/swift,
|
||||||
|
"$(inherited)",
|
||||||
|
);
|
||||||
|
LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";
|
||||||
|
MTL_ENABLE_DEBUG_INFO = YES;
|
||||||
|
ONLY_ACTIVE_ARCH = YES;
|
||||||
|
OTHER_LDFLAGS = (
|
||||||
|
"$(inherited)",
|
||||||
|
" ",
|
||||||
|
);
|
||||||
|
REACT_NATIVE_PATH = "${PODS_ROOT}/../../../../node_modules/react-native";
|
||||||
|
SDKROOT = iphoneos;
|
||||||
|
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";
|
||||||
|
USE_HERMES = true;
|
||||||
|
};
|
||||||
|
name = Debug;
|
||||||
|
};
|
||||||
|
83CBBA211A601CBA00E9B192 /* Release */ = {
|
||||||
|
isa = XCBuildConfiguration;
|
||||||
|
buildSettings = {
|
||||||
|
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||||
|
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
|
||||||
|
CLANG_CXX_LANGUAGE_STANDARD = "c++20";
|
||||||
|
CLANG_CXX_LIBRARY = "libc++";
|
||||||
|
CLANG_ENABLE_MODULES = YES;
|
||||||
|
CLANG_ENABLE_OBJC_ARC = YES;
|
||||||
|
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||||
|
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_COMMA = YES;
|
||||||
|
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||||
|
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||||
|
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||||
|
CLANG_WARN_EMPTY_BODY = YES;
|
||||||
|
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||||
|
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||||
|
CLANG_WARN_INT_CONVERSION = YES;
|
||||||
|
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||||
|
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||||
|
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||||
|
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||||
|
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||||
|
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||||
|
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||||
|
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||||
|
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||||
|
COPY_PHASE_STRIP = YES;
|
||||||
|
ENABLE_NS_ASSERTIONS = NO;
|
||||||
|
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||||
|
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||||
|
GCC_NO_COMMON_BLOCKS = YES;
|
||||||
|
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||||
|
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||||
|
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||||
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
|
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
|
||||||
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
|
/usr/lib/swift,
|
||||||
|
"$(inherited)",
|
||||||
|
);
|
||||||
|
LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";
|
||||||
|
MTL_ENABLE_DEBUG_INFO = NO;
|
||||||
|
OTHER_LDFLAGS = (
|
||||||
|
"$(inherited)",
|
||||||
|
" ",
|
||||||
|
);
|
||||||
|
REACT_NATIVE_PATH = "${PODS_ROOT}/../../../../node_modules/react-native";
|
||||||
|
SDKROOT = iphoneos;
|
||||||
|
USE_HERMES = true;
|
||||||
|
VALIDATE_PRODUCT = YES;
|
||||||
|
};
|
||||||
|
name = Release;
|
||||||
|
};
|
||||||
|
/* End XCBuildConfiguration section */
|
||||||
|
|
||||||
|
/* Begin XCConfigurationList section */
|
||||||
|
13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "FreshyoAdmin" */ = {
|
||||||
|
isa = XCConfigurationList;
|
||||||
|
buildConfigurations = (
|
||||||
|
13B07F941A680F5B00A75B9A /* Debug */,
|
||||||
|
13B07F951A680F5B00A75B9A /* Release */,
|
||||||
|
);
|
||||||
|
defaultConfigurationIsVisible = 0;
|
||||||
|
defaultConfigurationName = Release;
|
||||||
|
};
|
||||||
|
83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "FreshyoAdmin" */ = {
|
||||||
|
isa = XCConfigurationList;
|
||||||
|
buildConfigurations = (
|
||||||
|
83CBBA201A601CBA00E9B192 /* Debug */,
|
||||||
|
83CBBA211A601CBA00E9B192 /* Release */,
|
||||||
|
);
|
||||||
|
defaultConfigurationIsVisible = 0;
|
||||||
|
defaultConfigurationName = Release;
|
||||||
|
};
|
||||||
|
/* End XCConfigurationList section */
|
||||||
|
};
|
||||||
|
rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,88 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Scheme
|
||||||
|
LastUpgradeVersion = "1130"
|
||||||
|
version = "1.3">
|
||||||
|
<BuildAction
|
||||||
|
parallelizeBuildables = "YES"
|
||||||
|
buildImplicitDependencies = "YES">
|
||||||
|
<BuildActionEntries>
|
||||||
|
<BuildActionEntry
|
||||||
|
buildForTesting = "YES"
|
||||||
|
buildForRunning = "YES"
|
||||||
|
buildForProfiling = "YES"
|
||||||
|
buildForArchiving = "YES"
|
||||||
|
buildForAnalyzing = "YES">
|
||||||
|
<BuildableReference
|
||||||
|
BuildableIdentifier = "primary"
|
||||||
|
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
|
||||||
|
BuildableName = "FreshyoAdmin.app"
|
||||||
|
BlueprintName = "FreshyoAdmin"
|
||||||
|
ReferencedContainer = "container:FreshyoAdmin.xcodeproj">
|
||||||
|
</BuildableReference>
|
||||||
|
</BuildActionEntry>
|
||||||
|
</BuildActionEntries>
|
||||||
|
</BuildAction>
|
||||||
|
<TestAction
|
||||||
|
buildConfiguration = "Debug"
|
||||||
|
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||||
|
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||||
|
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||||
|
<Testables>
|
||||||
|
<TestableReference
|
||||||
|
skipped = "NO">
|
||||||
|
<BuildableReference
|
||||||
|
BuildableIdentifier = "primary"
|
||||||
|
BlueprintIdentifier = "00E356ED1AD99517003FC87E"
|
||||||
|
BuildableName = "FreshyoAdminTests.xctest"
|
||||||
|
BlueprintName = "FreshyoAdminTests"
|
||||||
|
ReferencedContainer = "container:FreshyoAdmin.xcodeproj">
|
||||||
|
</BuildableReference>
|
||||||
|
</TestableReference>
|
||||||
|
</Testables>
|
||||||
|
</TestAction>
|
||||||
|
<LaunchAction
|
||||||
|
buildConfiguration = "Debug"
|
||||||
|
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||||
|
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||||
|
launchStyle = "0"
|
||||||
|
useCustomWorkingDirectory = "NO"
|
||||||
|
ignoresPersistentStateOnLaunch = "NO"
|
||||||
|
debugDocumentVersioning = "YES"
|
||||||
|
debugServiceExtension = "internal"
|
||||||
|
allowLocationSimulation = "YES">
|
||||||
|
<BuildableProductRunnable
|
||||||
|
runnableDebuggingMode = "0">
|
||||||
|
<BuildableReference
|
||||||
|
BuildableIdentifier = "primary"
|
||||||
|
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
|
||||||
|
BuildableName = "FreshyoAdmin.app"
|
||||||
|
BlueprintName = "FreshyoAdmin"
|
||||||
|
ReferencedContainer = "container:FreshyoAdmin.xcodeproj">
|
||||||
|
</BuildableReference>
|
||||||
|
</BuildableProductRunnable>
|
||||||
|
</LaunchAction>
|
||||||
|
<ProfileAction
|
||||||
|
buildConfiguration = "Release"
|
||||||
|
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||||
|
savedToolIdentifier = ""
|
||||||
|
useCustomWorkingDirectory = "NO"
|
||||||
|
debugDocumentVersioning = "YES">
|
||||||
|
<BuildableProductRunnable
|
||||||
|
runnableDebuggingMode = "0">
|
||||||
|
<BuildableReference
|
||||||
|
BuildableIdentifier = "primary"
|
||||||
|
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
|
||||||
|
BuildableName = "FreshyoAdmin.app"
|
||||||
|
BlueprintName = "FreshyoAdmin"
|
||||||
|
ReferencedContainer = "container:FreshyoAdmin.xcodeproj">
|
||||||
|
</BuildableReference>
|
||||||
|
</BuildableProductRunnable>
|
||||||
|
</ProfileAction>
|
||||||
|
<AnalyzeAction
|
||||||
|
buildConfiguration = "Debug">
|
||||||
|
</AnalyzeAction>
|
||||||
|
<ArchiveAction
|
||||||
|
buildConfiguration = "Release"
|
||||||
|
revealArchiveInOrganizer = "YES">
|
||||||
|
</ArchiveAction>
|
||||||
|
</Scheme>
|
||||||
10
apps/admin-ui/ios/FreshyoAdmin.xcworkspace/contents.xcworkspacedata
generated
Normal file
10
apps/admin-ui/ios/FreshyoAdmin.xcworkspace/contents.xcworkspacedata
generated
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Workspace
|
||||||
|
version = "1.0">
|
||||||
|
<FileRef
|
||||||
|
location = "group:FreshyoAdmin.xcodeproj">
|
||||||
|
</FileRef>
|
||||||
|
<FileRef
|
||||||
|
location = "group:Pods/Pods.xcodeproj">
|
||||||
|
</FileRef>
|
||||||
|
</Workspace>
|
||||||
70
apps/admin-ui/ios/FreshyoAdmin/AppDelegate.swift
Normal file
70
apps/admin-ui/ios/FreshyoAdmin/AppDelegate.swift
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
import Expo
|
||||||
|
import React
|
||||||
|
import ReactAppDependencyProvider
|
||||||
|
|
||||||
|
@UIApplicationMain
|
||||||
|
public class AppDelegate: ExpoAppDelegate {
|
||||||
|
var window: UIWindow?
|
||||||
|
|
||||||
|
var reactNativeDelegate: ExpoReactNativeFactoryDelegate?
|
||||||
|
var reactNativeFactory: RCTReactNativeFactory?
|
||||||
|
|
||||||
|
public override func application(
|
||||||
|
_ application: UIApplication,
|
||||||
|
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
|
||||||
|
) -> Bool {
|
||||||
|
let delegate = ReactNativeDelegate()
|
||||||
|
let factory = ExpoReactNativeFactory(delegate: delegate)
|
||||||
|
delegate.dependencyProvider = RCTAppDependencyProvider()
|
||||||
|
|
||||||
|
reactNativeDelegate = delegate
|
||||||
|
reactNativeFactory = factory
|
||||||
|
bindReactNativeFactory(factory)
|
||||||
|
|
||||||
|
#if os(iOS) || os(tvOS)
|
||||||
|
window = UIWindow(frame: UIScreen.main.bounds)
|
||||||
|
factory.startReactNative(
|
||||||
|
withModuleName: "main",
|
||||||
|
in: window,
|
||||||
|
launchOptions: launchOptions)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Linking API
|
||||||
|
public override func application(
|
||||||
|
_ app: UIApplication,
|
||||||
|
open url: URL,
|
||||||
|
options: [UIApplication.OpenURLOptionsKey: Any] = [:]
|
||||||
|
) -> Bool {
|
||||||
|
return super.application(app, open: url, options: options) || RCTLinkingManager.application(app, open: url, options: options)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Universal Links
|
||||||
|
public override func application(
|
||||||
|
_ application: UIApplication,
|
||||||
|
continue userActivity: NSUserActivity,
|
||||||
|
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void
|
||||||
|
) -> Bool {
|
||||||
|
let result = RCTLinkingManager.application(application, continue: userActivity, restorationHandler: restorationHandler)
|
||||||
|
return super.application(application, continue: userActivity, restorationHandler: restorationHandler) || result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ReactNativeDelegate: ExpoReactNativeFactoryDelegate {
|
||||||
|
// Extension point for config-plugins
|
||||||
|
|
||||||
|
override func sourceURL(for bridge: RCTBridge) -> URL? {
|
||||||
|
// needed to return the correct URL for expo-dev-client.
|
||||||
|
bridge.bundleURL ?? bundleURL()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func bundleURL() -> URL? {
|
||||||
|
#if DEBUG
|
||||||
|
return RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: ".expo/.virtual-metro-entry")
|
||||||
|
#else
|
||||||
|
return Bundle.main.url(forResource: "main", withExtension: "jsbundle")
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,3 @@
|
||||||
|
//
|
||||||
|
// Use this file to import your target's public headers that you would like to expose to Swift.
|
||||||
|
//
|
||||||
8
apps/admin-ui/ios/FreshyoAdmin/FreshyoAdmin.entitlements
Normal file
8
apps/admin-ui/ios/FreshyoAdmin/FreshyoAdmin.entitlements
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>aps-environment</key>
|
||||||
|
<string>development</string>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 884 KiB |
|
|
@ -0,0 +1,14 @@
|
||||||
|
{
|
||||||
|
"images": [
|
||||||
|
{
|
||||||
|
"filename": "App-Icon-1024x1024@1x.png",
|
||||||
|
"idiom": "universal",
|
||||||
|
"platform": "ios",
|
||||||
|
"size": "1024x1024"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info": {
|
||||||
|
"version": 1,
|
||||||
|
"author": "expo"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
{
|
||||||
|
"info" : {
|
||||||
|
"version" : 1,
|
||||||
|
"author" : "expo"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,20 @@
|
||||||
|
{
|
||||||
|
"colors": [
|
||||||
|
{
|
||||||
|
"color": {
|
||||||
|
"components": {
|
||||||
|
"alpha": "1.000",
|
||||||
|
"blue": "1.00000000000000",
|
||||||
|
"green": "1.00000000000000",
|
||||||
|
"red": "1.00000000000000"
|
||||||
|
},
|
||||||
|
"color-space": "srgb"
|
||||||
|
},
|
||||||
|
"idiom": "universal"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info": {
|
||||||
|
"version": 1,
|
||||||
|
"author": "expo"
|
||||||
|
}
|
||||||
|
}
|
||||||
23
apps/admin-ui/ios/FreshyoAdmin/Images.xcassets/SplashScreenLogo.imageset/Contents.json
vendored
Normal file
23
apps/admin-ui/ios/FreshyoAdmin/Images.xcassets/SplashScreenLogo.imageset/Contents.json
vendored
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
{
|
||||||
|
"images": [
|
||||||
|
{
|
||||||
|
"idiom": "universal",
|
||||||
|
"filename": "image.png",
|
||||||
|
"scale": "1x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idiom": "universal",
|
||||||
|
"filename": "image@2x.png",
|
||||||
|
"scale": "2x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idiom": "universal",
|
||||||
|
"filename": "image@3x.png",
|
||||||
|
"scale": "3x"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info": {
|
||||||
|
"version": 1,
|
||||||
|
"author": "expo"
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
apps/admin-ui/ios/FreshyoAdmin/Images.xcassets/SplashScreenLogo.imageset/image.png
vendored
Normal file
BIN
apps/admin-ui/ios/FreshyoAdmin/Images.xcassets/SplashScreenLogo.imageset/image.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
BIN
apps/admin-ui/ios/FreshyoAdmin/Images.xcassets/SplashScreenLogo.imageset/image@2x.png
vendored
Normal file
BIN
apps/admin-ui/ios/FreshyoAdmin/Images.xcassets/SplashScreenLogo.imageset/image@2x.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 101 KiB |
BIN
apps/admin-ui/ios/FreshyoAdmin/Images.xcassets/SplashScreenLogo.imageset/image@3x.png
vendored
Normal file
BIN
apps/admin-ui/ios/FreshyoAdmin/Images.xcassets/SplashScreenLogo.imageset/image@3x.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 271 KiB |
132
apps/admin-ui/ios/FreshyoAdmin/Info.plist
Normal file
132
apps/admin-ui/ios/FreshyoAdmin/Info.plist
Normal file
|
|
@ -0,0 +1,132 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>CADisableMinimumFrameDurationOnPhone</key>
|
||||||
|
<true/>
|
||||||
|
<key>CFBundleDevelopmentRegion</key>
|
||||||
|
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||||
|
<key>CFBundleDisplayName</key>
|
||||||
|
<string>Freshyo Admin</string>
|
||||||
|
<key>CFBundleExecutable</key>
|
||||||
|
<string>$(EXECUTABLE_NAME)</string>
|
||||||
|
<key>CFBundleIdentifier</key>
|
||||||
|
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||||
|
<key>CFBundleInfoDictionaryVersion</key>
|
||||||
|
<string>6.0</string>
|
||||||
|
<key>CFBundleName</key>
|
||||||
|
<string>$(PRODUCT_NAME)</string>
|
||||||
|
<key>CFBundlePackageType</key>
|
||||||
|
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||||
|
<key>CFBundleShortVersionString</key>
|
||||||
|
<string>1.0.0</string>
|
||||||
|
<key>CFBundleSignature</key>
|
||||||
|
<string>????</string>
|
||||||
|
<key>CFBundleURLTypes</key>
|
||||||
|
<array>
|
||||||
|
<dict>
|
||||||
|
<key>CFBundleURLSchemes</key>
|
||||||
|
<array>
|
||||||
|
<string>freshyoadmin</string>
|
||||||
|
<string>in.freshyo.adminui</string>
|
||||||
|
</array>
|
||||||
|
</dict>
|
||||||
|
<dict>
|
||||||
|
<key>CFBundleURLSchemes</key>
|
||||||
|
<array>
|
||||||
|
<string>exp+freshyoadmin</string>
|
||||||
|
</array>
|
||||||
|
</dict>
|
||||||
|
</array>
|
||||||
|
<key>CFBundleVersion</key>
|
||||||
|
<string>1</string>
|
||||||
|
<key>ITSAppUsesNonExemptEncryption</key>
|
||||||
|
<false/>
|
||||||
|
<key>LSApplicationQueriesSchemes</key>
|
||||||
|
<array>
|
||||||
|
<string>ppemerchantsdkv1</string>
|
||||||
|
<string>ppemerchantsdkv2</string>
|
||||||
|
<string>ppemerchantsdkv3</string>
|
||||||
|
<string>paytmmp</string>
|
||||||
|
<string>gpay</string>
|
||||||
|
<string>ppemerchantsdkv1</string>
|
||||||
|
<string>ppemerchantsdkv2</string>
|
||||||
|
<string>ppemerchantsdkv3</string>
|
||||||
|
<string>paytmmp</string>
|
||||||
|
<string>gpay</string>
|
||||||
|
<string>ppemerchantsdkv1</string>
|
||||||
|
<string>ppemerchantsdkv2</string>
|
||||||
|
<string>ppemerchantsdkv3</string>
|
||||||
|
<string>paytmmp</string>
|
||||||
|
<string>gpay</string>
|
||||||
|
<string>ppemerchantsdkv1</string>
|
||||||
|
<string>ppemerchantsdkv2</string>
|
||||||
|
<string>ppemerchantsdkv3</string>
|
||||||
|
<string>paytmmp</string>
|
||||||
|
<string>gpay</string>
|
||||||
|
<string>ppemerchantsdkv1</string>
|
||||||
|
<string>ppemerchantsdkv2</string>
|
||||||
|
<string>ppemerchantsdkv3</string>
|
||||||
|
<string>paytmmp</string>
|
||||||
|
<string>gpay</string>
|
||||||
|
<string>ppemerchantsdkv1</string>
|
||||||
|
<string>ppemerchantsdkv2</string>
|
||||||
|
<string>ppemerchantsdkv3</string>
|
||||||
|
<string>paytmmp</string>
|
||||||
|
<string>gpay</string>
|
||||||
|
<string>ppemerchantsdkv1</string>
|
||||||
|
<string>ppemerchantsdkv2</string>
|
||||||
|
<string>ppemerchantsdkv3</string>
|
||||||
|
<string>paytmmp</string>
|
||||||
|
<string>gpay</string>
|
||||||
|
<string>ppemerchantsdkv1</string>
|
||||||
|
<string>ppemerchantsdkv2</string>
|
||||||
|
<string>ppemerchantsdkv3</string>
|
||||||
|
<string>paytmmp</string>
|
||||||
|
<string>gpay</string>
|
||||||
|
</array>
|
||||||
|
<key>LSMinimumSystemVersion</key>
|
||||||
|
<string>12.0</string>
|
||||||
|
<key>LSRequiresIPhoneOS</key>
|
||||||
|
<true/>
|
||||||
|
<key>NSAppTransportSecurity</key>
|
||||||
|
<dict>
|
||||||
|
<key>NSAllowsArbitraryLoads</key>
|
||||||
|
<false/>
|
||||||
|
<key>NSAllowsLocalNetworking</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
<key>NSFaceIDUsageDescription</key>
|
||||||
|
<string>Allow $(PRODUCT_NAME) to access your Face ID biometric data.</string>
|
||||||
|
<key>NSUserActivityTypes</key>
|
||||||
|
<array>
|
||||||
|
<string>$(PRODUCT_BUNDLE_IDENTIFIER).expo.index_route</string>
|
||||||
|
</array>
|
||||||
|
<key>UILaunchStoryboardName</key>
|
||||||
|
<string>SplashScreen</string>
|
||||||
|
<key>UIRequiredDeviceCapabilities</key>
|
||||||
|
<array>
|
||||||
|
<string>arm64</string>
|
||||||
|
</array>
|
||||||
|
<key>UIRequiresFullScreen</key>
|
||||||
|
<false/>
|
||||||
|
<key>UIStatusBarStyle</key>
|
||||||
|
<string>UIStatusBarStyleDefault</string>
|
||||||
|
<key>UISupportedInterfaceOrientations</key>
|
||||||
|
<array>
|
||||||
|
<string>UIInterfaceOrientationPortrait</string>
|
||||||
|
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||||
|
</array>
|
||||||
|
<key>UISupportedInterfaceOrientations~ipad</key>
|
||||||
|
<array>
|
||||||
|
<string>UIInterfaceOrientationPortrait</string>
|
||||||
|
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||||
|
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||||
|
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||||
|
</array>
|
||||||
|
<key>UIUserInterfaceStyle</key>
|
||||||
|
<string>Automatic</string>
|
||||||
|
<key>UIViewControllerBasedStatusBarAppearance</key>
|
||||||
|
<false/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
48
apps/admin-ui/ios/FreshyoAdmin/PrivacyInfo.xcprivacy
Normal file
48
apps/admin-ui/ios/FreshyoAdmin/PrivacyInfo.xcprivacy
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>NSPrivacyAccessedAPITypes</key>
|
||||||
|
<array>
|
||||||
|
<dict>
|
||||||
|
<key>NSPrivacyAccessedAPIType</key>
|
||||||
|
<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
|
||||||
|
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||||
|
<array>
|
||||||
|
<string>C617.1</string>
|
||||||
|
<string>0A2A.1</string>
|
||||||
|
<string>3B52.1</string>
|
||||||
|
</array>
|
||||||
|
</dict>
|
||||||
|
<dict>
|
||||||
|
<key>NSPrivacyAccessedAPIType</key>
|
||||||
|
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
|
||||||
|
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||||
|
<array>
|
||||||
|
<string>CA92.1</string>
|
||||||
|
</array>
|
||||||
|
</dict>
|
||||||
|
<dict>
|
||||||
|
<key>NSPrivacyAccessedAPIType</key>
|
||||||
|
<string>NSPrivacyAccessedAPICategorySystemBootTime</string>
|
||||||
|
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||||
|
<array>
|
||||||
|
<string>35F9.1</string>
|
||||||
|
</array>
|
||||||
|
</dict>
|
||||||
|
<dict>
|
||||||
|
<key>NSPrivacyAccessedAPIType</key>
|
||||||
|
<string>NSPrivacyAccessedAPICategoryDiskSpace</string>
|
||||||
|
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||||
|
<array>
|
||||||
|
<string>E174.1</string>
|
||||||
|
<string>85F4.1</string>
|
||||||
|
</array>
|
||||||
|
</dict>
|
||||||
|
</array>
|
||||||
|
<key>NSPrivacyCollectedDataTypes</key>
|
||||||
|
<array/>
|
||||||
|
<key>NSPrivacyTracking</key>
|
||||||
|
<false/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
42
apps/admin-ui/ios/FreshyoAdmin/SplashScreen.storyboard
Normal file
42
apps/admin-ui/ios/FreshyoAdmin/SplashScreen.storyboard
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="32700.99.1234" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="EXPO-VIEWCONTROLLER-1">
|
||||||
|
<device id="retina6_12" orientation="portrait" appearance="light"/>
|
||||||
|
<dependencies>
|
||||||
|
<deployment identifier="iOS"/>
|
||||||
|
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="22685"/>
|
||||||
|
<capability name="Named colors" minToolsVersion="9.0"/>
|
||||||
|
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
|
||||||
|
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
||||||
|
</dependencies>
|
||||||
|
<scenes>
|
||||||
|
<scene sceneID="EXPO-SCENE-1">
|
||||||
|
<objects>
|
||||||
|
<viewController storyboardIdentifier="SplashScreenViewController" id="EXPO-VIEWCONTROLLER-1" sceneMemberID="viewController">
|
||||||
|
<view key="view" userInteractionEnabled="NO" contentMode="scaleToFill" insetsLayoutMarginsFromSafeArea="NO" id="EXPO-ContainerView" userLabel="ContainerView">
|
||||||
|
<rect key="frame" x="0.0" y="0.0" width="393" height="852"/>
|
||||||
|
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||||
|
<subviews>
|
||||||
|
<imageView id="EXPO-SplashScreen" userLabel="SplashScreenLogo" image="SplashScreenLogo" contentMode="scaleAspectFit" clipsSubviews="true" userInteractionEnabled="false" translatesAutoresizingMaskIntoConstraints="false">
|
||||||
|
<rect key="frame" x="96.5" y="326" width="200" height="200"/>
|
||||||
|
</imageView>
|
||||||
|
</subviews>
|
||||||
|
<viewLayoutGuide key="safeArea" id="Rmq-lb-GrQ"/>
|
||||||
|
<constraints>
|
||||||
|
<constraint firstItem="EXPO-SplashScreen" firstAttribute="centerX" secondItem="EXPO-ContainerView" secondAttribute="centerX" id="cad2ab56f97c5429bf29decf850647a4216861d4"/>
|
||||||
|
<constraint firstItem="EXPO-SplashScreen" firstAttribute="centerY" secondItem="EXPO-ContainerView" secondAttribute="centerY" id="1a145271b085b6ce89b1405a310f5b1bb7656595"/>
|
||||||
|
</constraints>
|
||||||
|
<color key="backgroundColor" name="SplashScreenBackground"/>
|
||||||
|
</view>
|
||||||
|
</viewController>
|
||||||
|
<placeholder placeholderIdentifier="IBFirstResponder" id="EXPO-PLACEHOLDER-1" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||||
|
</objects>
|
||||||
|
<point key="canvasLocation" x="0.0" y="0.0"/>
|
||||||
|
</scene>
|
||||||
|
</scenes>
|
||||||
|
<resources>
|
||||||
|
<image name="SplashScreenLogo" width="200" height="200"/>
|
||||||
|
<namedColor name="SplashScreenBackground">
|
||||||
|
<color alpha="1.000" blue="1.00000000000000" green="1.00000000000000" red="1.00000000000000" customColorSpace="sRGB" colorSpace="custom"/>
|
||||||
|
</namedColor>
|
||||||
|
</resources>
|
||||||
|
</document>
|
||||||
16
apps/admin-ui/ios/FreshyoAdmin/Supporting/Expo.plist
Normal file
16
apps/admin-ui/ios/FreshyoAdmin/Supporting/Expo.plist
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>EXUpdatesCheckOnLaunch</key>
|
||||||
|
<string>ALWAYS</string>
|
||||||
|
<key>EXUpdatesEnabled</key>
|
||||||
|
<true/>
|
||||||
|
<key>EXUpdatesLaunchWaitMs</key>
|
||||||
|
<integer>0</integer>
|
||||||
|
<key>EXUpdatesRuntimeVersion</key>
|
||||||
|
<string>1.0.0</string>
|
||||||
|
<key>EXUpdatesURL</key>
|
||||||
|
<string>https://u.expo.dev/55e2f200-eb9d-4880-a193-70f59320e054</string>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
64
apps/admin-ui/ios/Podfile
Normal file
64
apps/admin-ui/ios/Podfile
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
require File.join(File.dirname(`node --print "require.resolve('expo/package.json')"`), "scripts/autolinking")
|
||||||
|
require File.join(File.dirname(`node --print "require.resolve('react-native/package.json')"`), "scripts/react_native_pods")
|
||||||
|
|
||||||
|
require 'json'
|
||||||
|
podfile_properties = JSON.parse(File.read(File.join(__dir__, 'Podfile.properties.json'))) rescue {}
|
||||||
|
|
||||||
|
ENV['RCT_NEW_ARCH_ENABLED'] = '0' if podfile_properties['newArchEnabled'] == 'false'
|
||||||
|
ENV['EX_DEV_CLIENT_NETWORK_INSPECTOR'] = podfile_properties['EX_DEV_CLIENT_NETWORK_INSPECTOR']
|
||||||
|
|
||||||
|
platform :ios, podfile_properties['ios.deploymentTarget'] || '15.1'
|
||||||
|
install! 'cocoapods',
|
||||||
|
:deterministic_uuids => false
|
||||||
|
|
||||||
|
prepare_react_native_project!
|
||||||
|
|
||||||
|
target 'FreshyoAdmin' do
|
||||||
|
use_expo_modules!
|
||||||
|
|
||||||
|
if ENV['EXPO_USE_COMMUNITY_AUTOLINKING'] == '1'
|
||||||
|
config_command = ['node', '-e', "process.argv=['', '', 'config'];require('@react-native-community/cli').run()"];
|
||||||
|
else
|
||||||
|
config_command = [
|
||||||
|
'npx',
|
||||||
|
'expo-modules-autolinking',
|
||||||
|
'react-native-config',
|
||||||
|
'--json',
|
||||||
|
'--platform',
|
||||||
|
'ios'
|
||||||
|
]
|
||||||
|
end
|
||||||
|
|
||||||
|
config = use_native_modules!(config_command)
|
||||||
|
|
||||||
|
use_frameworks! :linkage => podfile_properties['ios.useFrameworks'].to_sym if podfile_properties['ios.useFrameworks']
|
||||||
|
use_frameworks! :linkage => ENV['USE_FRAMEWORKS'].to_sym if ENV['USE_FRAMEWORKS']
|
||||||
|
|
||||||
|
use_react_native!(
|
||||||
|
:path => config[:reactNativePath],
|
||||||
|
:hermes_enabled => podfile_properties['expo.jsEngine'] == nil || podfile_properties['expo.jsEngine'] == 'hermes',
|
||||||
|
# An absolute path to your application root.
|
||||||
|
:app_path => "#{Pod::Config.instance.installation_root}/..",
|
||||||
|
:privacy_file_aggregation_enabled => podfile_properties['apple.privacyManifestAggregationEnabled'] != 'false',
|
||||||
|
)
|
||||||
|
|
||||||
|
post_install do |installer|
|
||||||
|
react_native_post_install(
|
||||||
|
installer,
|
||||||
|
config[:reactNativePath],
|
||||||
|
:mac_catalyst_enabled => false,
|
||||||
|
:ccache_enabled => podfile_properties['apple.ccacheEnabled'] == 'true',
|
||||||
|
)
|
||||||
|
|
||||||
|
# This is necessary for Xcode 14, because it signs resource bundles by default
|
||||||
|
# when building for devices.
|
||||||
|
installer.target_installation_results.pod_target_installation_results
|
||||||
|
.each do |pod_name, target_installation_result|
|
||||||
|
target_installation_result.resource_bundle_targets.each do |resource_bundle_target|
|
||||||
|
resource_bundle_target.build_configurations.each do |config|
|
||||||
|
config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
2669
apps/admin-ui/ios/Podfile.lock
Normal file
2669
apps/admin-ui/ios/Podfile.lock
Normal file
File diff suppressed because it is too large
Load diff
5
apps/admin-ui/ios/Podfile.properties.json
Normal file
5
apps/admin-ui/ios/Podfile.properties.json
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
{
|
||||||
|
"expo.jsEngine": "hermes",
|
||||||
|
"EX_DEV_CLIENT_NETWORK_INSPECTOR": "true",
|
||||||
|
"newArchEnabled": "true"
|
||||||
|
}
|
||||||
|
|
@ -1,10 +1,11 @@
|
||||||
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 { View, TouchableOpacity, ScrollView, Alert } from 'react-native'
|
||||||
import { Formik, FieldArray } from 'formik'
|
import { Formik, FieldArray, useFormikContext } from 'formik'
|
||||||
import * as Yup from 'yup'
|
import * as Yup from 'yup'
|
||||||
import { MyTextInput, BottomDropdown, MyText, tw, ImageUploaderNeo, ImageUploaderNeoItem, ImageUploaderNeoPayload, Checkbox, InfoDialog } from 'common-ui'
|
import { MyTextInput, BottomDropdown, MyText, tw, ImageUploaderNeo, ImageUploaderNeoItem, ImageUploaderNeoPayload, Checkbox, InfoDialog } from 'common-ui'
|
||||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||||
import { trpc } from '../trpc-client'
|
import { trpc } from '../trpc-client'
|
||||||
|
import { useIsSuperAdmin } from '../../hooks/useIsSuperAdmin'
|
||||||
import type { CreateComboItemInput, CreateSkuInput } from '@packages/shared'
|
import type { CreateComboItemInput, CreateSkuInput } from '@packages/shared'
|
||||||
import type { SkuFeatureLike } from '@packages/shared'
|
import type { SkuFeatureLike } from '@packages/shared'
|
||||||
|
|
||||||
|
|
@ -34,6 +35,9 @@ interface ProductFormData {
|
||||||
name: string
|
name: string
|
||||||
shortDescription: string
|
shortDescription: string
|
||||||
longDescription: string
|
longDescription: string
|
||||||
|
regionId?: number | null
|
||||||
|
availableInAllRegions?: boolean
|
||||||
|
storeIdsByRegion?: Record<number, number>
|
||||||
storeId: number
|
storeId: number
|
||||||
productType: 'item' | 'combo'
|
productType: 'item' | 'combo'
|
||||||
variants: Variant[]
|
variants: Variant[]
|
||||||
|
|
@ -83,7 +87,11 @@ const variantSignature = (attributes: Attribute[]): string =>
|
||||||
|
|
||||||
const productValidationSchema = Yup.object().shape({
|
const productValidationSchema = Yup.object().shape({
|
||||||
name: Yup.string().required('Product name is required'),
|
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'),
|
productType: Yup.string().oneOf(['item', 'combo'], 'Product type is required').required('Product type is required'),
|
||||||
variants: Yup.array()
|
variants: Yup.array()
|
||||||
.min(1, 'At least one variant is required')
|
.min(1, 'At least one variant is required')
|
||||||
|
|
@ -145,6 +153,29 @@ const productValidationSchema = Yup.object().shape({
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
// Collect every string message from a Formik errors tree (objects, arrays, strings).
|
// 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
|
// 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.
|
// hidden by Formik when index-level errors are also present, so we walk everything.
|
||||||
|
|
@ -158,6 +189,39 @@ const collectErrorMessages = (errors: unknown, depth = 0): string[] => {
|
||||||
return []
|
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>(({
|
const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
mode,
|
mode,
|
||||||
initialValues,
|
initialValues,
|
||||||
|
|
@ -176,11 +240,37 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
clearImages: () => setVariantImages(initialValues.variants.map(() => [])),
|
clearImages: () => setVariantImages(initialValues.variants.map(() => [])),
|
||||||
}), [initialValues.variants])
|
}), [initialValues.variants])
|
||||||
|
|
||||||
const { data: storesData } = trpc.common.getStoresSummary.useQuery()
|
const isSuperAdmin = useIsSuperAdmin()
|
||||||
const storeOptions = storesData?.stores.map((store) => ({
|
// Non-superadmins may not flip all-regions availability (backend 403s either
|
||||||
label: store.name,
|
// direction); lock the checkbox on all-region products.
|
||||||
value: store.id,
|
const allRegionsLocked = !isSuperAdmin && !!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 { data: skusData } = trpc.common.product.getAllSkusSummary.useQuery()
|
||||||
const skuOptions = (skusData?.skus || []).map((sku) => ({
|
const skuOptions = (skusData?.skus || []).map((sku) => ({
|
||||||
|
|
@ -193,6 +283,8 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
const formInitialValues = useMemo(() => {
|
const formInitialValues = useMemo(() => {
|
||||||
return {
|
return {
|
||||||
...initialValues,
|
...initialValues,
|
||||||
|
availableInAllRegions: initialValues.availableInAllRegions ?? false,
|
||||||
|
storeIdsByRegion: initialValues.storeIdsByRegion ?? {},
|
||||||
variants: (initialValues.variants || []).map((v) => {
|
variants: (initialValues.variants || []).map((v) => {
|
||||||
const hasQuantity = (v.features || []).some(
|
const hasQuantity = (v.features || []).some(
|
||||||
(a) => (a.featureName ?? '').trim().toLowerCase() === 'quantity'
|
(a) => (a.featureName ?? '').trim().toLowerCase() === 'quantity'
|
||||||
|
|
@ -206,7 +298,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
return (
|
return (
|
||||||
<Formik
|
<Formik
|
||||||
initialValues={formInitialValues}
|
initialValues={formInitialValues}
|
||||||
validationSchema={productValidationSchema}
|
validationSchema={validationSchema}
|
||||||
onSubmit={(values) => {
|
onSubmit={(values) => {
|
||||||
// Normalize feature names before sending to backend: the mandatory
|
// Normalize feature names before sending to backend: the mandatory
|
||||||
// 'quantity' feature must always go out lowercase (case-insensitive
|
// 'quantity' feature must always go out lowercase (case-insensitive
|
||||||
|
|
@ -252,6 +344,24 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
enableReinitialize
|
enableReinitialize
|
||||||
>
|
>
|
||||||
{({ handleChange, handleSubmit, values, setFieldValue, validateForm }) => {
|
{({ handleChange, handleSubmit, values, setFieldValue, validateForm }) => {
|
||||||
|
const currentStoreName = storeOptions.find((option) => option.value === values.storeId)?.label
|
||||||
|
const handleToggleAllRegions = () => {
|
||||||
|
if (allRegionsLocked) return
|
||||||
|
const next = !values.availableInAllRegions
|
||||||
|
setFieldValue('availableInAllRegions', next)
|
||||||
|
if (next) {
|
||||||
|
const prefill: Record<number, number> = {}
|
||||||
|
if (currentStoreName) {
|
||||||
|
for (const region of regions) {
|
||||||
|
const match = allStores.find(
|
||||||
|
(store) => store.regionId === region.id && store.name === currentStoreName
|
||||||
|
)
|
||||||
|
if (match) prefill[region.id] = match.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setFieldValue('storeIdsByRegion', prefill)
|
||||||
|
}
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<ScrollView style={tw`flex-1`} contentContainerStyle={tw`px-4 pt-4 pb-10`} keyboardShouldPersistTaps="handled">
|
<ScrollView style={tw`flex-1`} contentContainerStyle={tw`px-4 pt-4 pb-10`} keyboardShouldPersistTaps="handled">
|
||||||
<MyTextInput
|
<MyTextInput
|
||||||
|
|
@ -282,16 +392,56 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
onChangeText={handleChange('longDescription')}
|
onChangeText={handleChange('longDescription')}
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
/>
|
/>
|
||||||
<BottomDropdown
|
<View style={tw`flex-row items-center mb-4`}>
|
||||||
testID="product-store-dropdown"
|
<Checkbox
|
||||||
topLabel="Store"
|
testID="product-all-regions-checkbox"
|
||||||
label="Store"
|
checked={!!values.availableInAllRegions}
|
||||||
value={values.storeId}
|
onPress={handleToggleAllRegions}
|
||||||
options={storeOptions}
|
disabled={allRegionsLocked}
|
||||||
onValueChange={(value) => setFieldValue('storeId', value)}
|
style={tw`mr-3`}
|
||||||
placeholder="Select store"
|
/>
|
||||||
style={{ marginBottom: 16 }}
|
<MyText style={tw`text-gray-700 font-medium`}>Available in all regions</MyText>
|
||||||
/>
|
</View>
|
||||||
|
|
||||||
|
{!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 }}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
regions.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={regions} currentStoreName={currentStoreName} />
|
||||||
|
|
||||||
<BottomDropdown
|
<BottomDropdown
|
||||||
testID="product-type-dropdown"
|
testID="product-type-dropdown"
|
||||||
|
|
@ -546,6 +696,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
<View style={tw`flex-row justify-between items-center mb-2`}>
|
<View style={tw`flex-row justify-between items-center mb-2`}>
|
||||||
<MyText style={tw`font-medium text-gray-600`}>Included Items</MyText>
|
<MyText style={tw`font-medium text-gray-600`}>Included Items</MyText>
|
||||||
<TouchableOpacity
|
<TouchableOpacity
|
||||||
|
testID={`variant-${vIndex}-combo-add`}
|
||||||
onPress={() => {
|
onPress={() => {
|
||||||
const items = variant.comboItems || []
|
const items = variant.comboItems || []
|
||||||
items.push({ skuId: 0 })
|
items.push({ skuId: 0 })
|
||||||
|
|
@ -561,6 +712,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
<View key={cIndex} style={tw`flex-row items-center gap-2 mb-2`}>
|
<View key={cIndex} style={tw`flex-row items-center gap-2 mb-2`}>
|
||||||
<View style={tw`flex-1`}>
|
<View style={tw`flex-1`}>
|
||||||
<BottomDropdown
|
<BottomDropdown
|
||||||
|
testID={`variant-${vIndex}-combo-sku-${cIndex}`}
|
||||||
label="SKU"
|
label="SKU"
|
||||||
value={ci.skuId}
|
value={ci.skuId}
|
||||||
options={skuOptions.map((opt: { label: string; value: number }) => ({
|
options={skuOptions.map((opt: { label: string; value: number }) => ({
|
||||||
|
|
|
||||||
|
|
@ -61,17 +61,19 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
imageUrl: sku.images?.[0] || null,
|
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(() => {
|
useEffect(() => {
|
||||||
const ordered: SelectedProduct[] = [];
|
const ordered: SelectedProduct[] = [];
|
||||||
const skuMap = new Map<number, SelectedProduct>();
|
const skuMap = new Map<number, SelectedProduct>();
|
||||||
for (const sku of allSkus) {
|
for (const sku of allSkus) {
|
||||||
skuMap.set(sku.productId, sku);
|
skuMap.set(sku.skuId, sku);
|
||||||
}
|
}
|
||||||
for (const productId of initialValues.productIds || []) {
|
for (const productId of initialValues.productIds || []) {
|
||||||
const sku = skuMap.get(productId);
|
const sku = skuMap.get(productId);
|
||||||
if (sku) ordered.push(sku);
|
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);
|
setSelectedProducts(ordered);
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
|
@ -151,7 +153,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
<Formik
|
<Formik
|
||||||
initialValues={initialValues}
|
initialValues={initialValues}
|
||||||
validationSchema={validationSchema}
|
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
|
enableReinitialize
|
||||||
>
|
>
|
||||||
{({ handleChange, handleSubmit, values, setFieldValue, errors, touched, resetForm }) => {
|
{({ handleChange, handleSubmit, values, setFieldValue, errors, touched, resetForm }) => {
|
||||||
|
|
@ -171,6 +173,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
return (
|
return (
|
||||||
<View style={tw`p-4`}>
|
<View style={tw`p-4`}>
|
||||||
<MyTextInput
|
<MyTextInput
|
||||||
|
testID="tag-name-input"
|
||||||
topLabel="Tag Name"
|
topLabel="Tag Name"
|
||||||
placeholder="Enter tag name"
|
placeholder="Enter tag name"
|
||||||
value={values.tagName}
|
value={values.tagName}
|
||||||
|
|
@ -179,6 +182,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<MyTextInput
|
<MyTextInput
|
||||||
|
testID="tag-description-input"
|
||||||
topLabel="Description (Optional)"
|
topLabel="Description (Optional)"
|
||||||
placeholder="Enter tag description"
|
placeholder="Enter tag description"
|
||||||
multiline
|
multiline
|
||||||
|
|
@ -195,6 +199,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
</MyText>
|
</MyText>
|
||||||
|
|
||||||
<ImageUploaderNeo
|
<ImageUploaderNeo
|
||||||
|
testID="tag-image-add"
|
||||||
images={images}
|
images={images}
|
||||||
onImageAdd={(payload: ImageUploaderNeoPayload[]) => {
|
onImageAdd={(payload: ImageUploaderNeoPayload[]) => {
|
||||||
setImages((prev) => [...prev, ...payload.map((img) => ({
|
setImages((prev) => [...prev, ...payload.map((img) => ({
|
||||||
|
|
@ -215,6 +220,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
{/* Dashboard Tag Checkbox */}
|
{/* Dashboard Tag Checkbox */}
|
||||||
<View style={tw`flex-row items-center mb-6`}>
|
<View style={tw`flex-row items-center mb-6`}>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
|
testID="tag-dashboard-checkbox"
|
||||||
checked={isDashboardTagChecked}
|
checked={isDashboardTagChecked}
|
||||||
onPress={() => {
|
onPress={() => {
|
||||||
const newValue = !isDashboardTagChecked;
|
const newValue = !isDashboardTagChecked;
|
||||||
|
|
@ -231,6 +237,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
Related Stores
|
Related Stores
|
||||||
</MyText>
|
</MyText>
|
||||||
<BottomDropdown
|
<BottomDropdown
|
||||||
|
testID="tag-stores-dropdown"
|
||||||
label="Select Related Stores"
|
label="Select Related Stores"
|
||||||
placeholder="Select stores..."
|
placeholder="Select stores..."
|
||||||
value={values.relatedStores.map(id => id.toString())}
|
value={values.relatedStores.map(id => id.toString())}
|
||||||
|
|
@ -252,6 +259,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
Products
|
Products
|
||||||
</MyText>
|
</MyText>
|
||||||
<ProductsSelector
|
<ProductsSelector
|
||||||
|
testID="tag-products-selector"
|
||||||
value={[]}
|
value={[]}
|
||||||
onChange={handleProductSelect}
|
onChange={handleProductSelect}
|
||||||
multiple
|
multiple
|
||||||
|
|
@ -288,6 +296,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
<TouchableOpacity
|
<TouchableOpacity
|
||||||
|
testID="tag-submit-button"
|
||||||
onPress={() => handleSubmit()}
|
onPress={() => handleSubmit()}
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
style={tw`px-4 py-3 rounded-lg shadow-lg items-center ${isLoading ? 'bg-gray-400' : 'bg-blue-500'}`}
|
style={tw`px-4 py-3 rounded-lg shadow-lg items-center ${isLoading ? 'bg-gray-400' : 'bg-blue-500'}`}
|
||||||
|
|
|
||||||
|
|
@ -45,6 +45,7 @@ const existingGroup: ProductGroup = {
|
||||||
id: 5,
|
id: 5,
|
||||||
groupName: 'Beef Box',
|
groupName: 'Beef Box',
|
||||||
description: 'Bundle',
|
description: 'Bundle',
|
||||||
|
regionId: 1,
|
||||||
createdAt: '2024-01-01T00:00:00.000Z',
|
createdAt: '2024-01-01T00:00:00.000Z',
|
||||||
products: [{ id: 10 }, { id: 11 }],
|
products: [{ id: 10 }, { id: 11 }],
|
||||||
productCount: 2,
|
productCount: 2,
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,7 @@ export interface VendorSnippet {
|
||||||
|
|
||||||
// Vendor-snippet form row — anchored to the shared input (wire validTill);
|
// Vendor-snippet form row — anchored to the shared input (wire validTill);
|
||||||
// form requires slotId and carries the serialized createdAt.
|
// form requires slotId and carries the serialized createdAt.
|
||||||
export type VendorSnippetForm = Omit<AdminVendorSnippetInput, 'slotId'> & {
|
export type VendorSnippetForm = Omit<AdminVendorSnippetInput, 'slotId' | 'regionId'> & {
|
||||||
id: number;
|
id: number;
|
||||||
slotId: number;
|
slotId: number;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,12 @@
|
||||||
import { useState, useImperativeHandle, forwardRef, useMemo } from 'react'
|
import { useState, useImperativeHandle, forwardRef, useMemo, useEffect } from 'react'
|
||||||
import { Formik, FieldArray } from 'formik'
|
import { Formik, FieldArray, useFormikContext } from 'formik'
|
||||||
import * as Yup from 'yup'
|
import * as Yup from 'yup'
|
||||||
import { pInput as PInput, Dropdown, p as P, Checkbox, BottomDialog, ImageUploaderNeo } from 'web-components'
|
import { pInput as PInput, Dropdown, p as P, Checkbox, BottomDialog, ImageUploaderNeo } from 'web-components'
|
||||||
import type { ImageUploaderNeoItem, ImageUploaderNeoPayload } from 'web-components'
|
import type { ImageUploaderNeoItem, ImageUploaderNeoPayload } from 'web-components'
|
||||||
import SearchableSelect from './SearchableSelect'
|
import SearchableSelect from './SearchableSelect'
|
||||||
import { Plus, Trash2, X, RotateCcw, Info } from 'lucide-react'
|
import { Plus, Trash2, X, RotateCcw, Info } from 'lucide-react'
|
||||||
import { trpc } from '@/lib/trpc-client'
|
import { trpc } from '@/lib/trpc-client'
|
||||||
|
import { useIsSuperAdmin } from '../hooks/useIsSuperAdmin'
|
||||||
import type { CreateComboItemInput, CreateSkuInput } from '@packages/shared'
|
import type { CreateComboItemInput, CreateSkuInput } from '@packages/shared'
|
||||||
import type { SkuFeatureLike } from '@packages/shared'
|
import type { SkuFeatureLike } from '@packages/shared'
|
||||||
|
|
||||||
|
|
@ -35,6 +36,9 @@ interface ProductFormData {
|
||||||
name: string
|
name: string
|
||||||
shortDescription: string
|
shortDescription: string
|
||||||
longDescription: string
|
longDescription: string
|
||||||
|
regionId?: number | null
|
||||||
|
availableInAllRegions?: boolean
|
||||||
|
storeIdsByRegion?: Record<number, number>
|
||||||
storeId: number
|
storeId: number
|
||||||
productType: 'item' | 'combo'
|
productType: 'item' | 'combo'
|
||||||
variants: Variant[]
|
variants: Variant[]
|
||||||
|
|
@ -99,9 +103,36 @@ const variantSignature = (attributes: Attribute[]): string =>
|
||||||
.sort()
|
.sort()
|
||||||
.join('|')
|
.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({
|
const productValidationSchema = Yup.object().shape({
|
||||||
name: Yup.string().required('Product name is required'),
|
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'),
|
productType: Yup.string().oneOf(['item', 'combo'], 'Product type is required').required('Product type is required'),
|
||||||
variants: Yup.array()
|
variants: Yup.array()
|
||||||
.min(1, 'At least one variant is required')
|
.min(1, 'At least one variant is required')
|
||||||
|
|
@ -176,6 +207,39 @@ const collectErrorMessages = (errors: unknown, depth = 0): string[] => {
|
||||||
return []
|
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>(({
|
const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
mode,
|
mode,
|
||||||
initialValues,
|
initialValues,
|
||||||
|
|
@ -194,11 +258,37 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
clearImages: () => setVariantImages(initialValues.variants.map(() => [])),
|
clearImages: () => setVariantImages(initialValues.variants.map(() => [])),
|
||||||
}), [initialValues.variants])
|
}), [initialValues.variants])
|
||||||
|
|
||||||
const { data: storesData } = trpc.common.getStoresSummary.useQuery()
|
const isSuperAdmin = useIsSuperAdmin()
|
||||||
const storeOptions = storesData?.stores.map((store) => ({
|
// Non-superadmins may not flip all-regions availability (backend 403s either
|
||||||
label: store.name,
|
// direction); lock the checkbox on all-region products.
|
||||||
value: store.id,
|
const allRegionsLocked = !isSuperAdmin && !!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 { data: skusData } = trpc.common.product.getAllSkusSummary.useQuery()
|
||||||
const skuOptions = (skusData?.skus || []).map((sku) => ({
|
const skuOptions = (skusData?.skus || []).map((sku) => ({
|
||||||
|
|
@ -211,6 +301,8 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
const formInitialValues = useMemo(() => {
|
const formInitialValues = useMemo(() => {
|
||||||
return {
|
return {
|
||||||
...initialValues,
|
...initialValues,
|
||||||
|
availableInAllRegions: initialValues.availableInAllRegions ?? false,
|
||||||
|
storeIdsByRegion: initialValues.storeIdsByRegion ?? {},
|
||||||
variants: (initialValues.variants || []).map((v) => {
|
variants: (initialValues.variants || []).map((v) => {
|
||||||
const hasQuantity = (v.features || []).some(
|
const hasQuantity = (v.features || []).some(
|
||||||
(a) => (a.featureName ?? '').trim().toLowerCase() === 'quantity'
|
(a) => (a.featureName ?? '').trim().toLowerCase() === 'quantity'
|
||||||
|
|
@ -224,7 +316,7 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
return (
|
return (
|
||||||
<Formik
|
<Formik
|
||||||
initialValues={formInitialValues}
|
initialValues={formInitialValues}
|
||||||
validationSchema={productValidationSchema}
|
validationSchema={validationSchema}
|
||||||
onSubmit={(values) => {
|
onSubmit={(values) => {
|
||||||
// Normalize feature names before sending to backend: the mandatory
|
// Normalize feature names before sending to backend: the mandatory
|
||||||
// 'quantity' feature must always go out lowercase (case-insensitive
|
// 'quantity' feature must always go out lowercase (case-insensitive
|
||||||
|
|
@ -270,6 +362,24 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
enableReinitialize
|
enableReinitialize
|
||||||
>
|
>
|
||||||
{({ handleChange, handleSubmit, values, setFieldValue, validateForm }) => {
|
{({ handleChange, handleSubmit, values, setFieldValue, validateForm }) => {
|
||||||
|
const currentStoreName = storeOptions.find((option) => option.value === values.storeId)?.label
|
||||||
|
const handleToggleAllRegions = () => {
|
||||||
|
if (allRegionsLocked) return
|
||||||
|
const next = !values.availableInAllRegions
|
||||||
|
setFieldValue('availableInAllRegions', next)
|
||||||
|
if (next) {
|
||||||
|
const prefill: Record<number, number> = {}
|
||||||
|
if (currentStoreName) {
|
||||||
|
for (const region of regions) {
|
||||||
|
const match = allStores.find(
|
||||||
|
(store) => store.regionId === region.id && store.name === currentStoreName
|
||||||
|
)
|
||||||
|
if (match) prefill[region.id] = match.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setFieldValue('storeIdsByRegion', prefill)
|
||||||
|
}
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<div className="flex-1 overflow-auto pb-10">
|
<div className="flex-1 overflow-auto pb-10">
|
||||||
<PInput
|
<PInput
|
||||||
|
|
@ -297,17 +407,53 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
|
||||||
onChange={handleChange('longDescription')}
|
onChange={handleChange('longDescription')}
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
/>
|
/>
|
||||||
<div className="mb-4" data-testid="product-store-select">
|
<div className="flex flex-row items-center mb-4" data-testid="product-all-regions-row">
|
||||||
<P className="mb-1 text-sm text-gray-500 font-medium">Store</P>
|
<Checkbox
|
||||||
<Dropdown
|
checked={!!values.availableInAllRegions}
|
||||||
label="Select store"
|
onPress={handleToggleAllRegions}
|
||||||
value={values.storeId}
|
disabled={allRegionsLocked}
|
||||||
options={storeOptions}
|
|
||||||
onValueChange={(value) => setFieldValue('storeId', Number(value))}
|
|
||||||
className="w-full"
|
|
||||||
/>
|
/>
|
||||||
|
<P className="text-gray-700 font-medium ml-3">Available in all regions</P>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{!values.availableInAllRegions ? (
|
||||||
|
<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>
|
||||||
|
) : (
|
||||||
|
regions.map((region) => {
|
||||||
|
const regionStores = storesForRegion(region.id)
|
||||||
|
return (
|
||||||
|
<div key={region.id} className="mb-4" data-testid={`product-region-${region.id}-store-select`}>
|
||||||
|
<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"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
|
||||||
|
<RegionStorePrefill stores={allRegionsStores} regions={regions} currentStoreName={currentStoreName} />
|
||||||
|
|
||||||
<div className="mb-4" data-testid="product-type-select">
|
<div className="mb-4" data-testid="product-type-select">
|
||||||
<P className="mb-1 text-sm text-gray-500 font-medium">Product Type</P>
|
<P className="mb-1 text-sm text-gray-500 font-medium">Product Type</P>
|
||||||
<Dropdown
|
<Dropdown
|
||||||
|
|
|
||||||
|
|
@ -42,7 +42,7 @@ function StoreForm({ mode, initialValues, onSubmit, isLoading, storeId }: StoreF
|
||||||
const initialSelectedProducts = useMemo(() => {
|
const initialSelectedProducts = useMemo(() => {
|
||||||
if (mode !== 'edit' || !productsData?.products) return []
|
if (mode !== 'edit' || !productsData?.products) return []
|
||||||
return productsData.products
|
return productsData.products
|
||||||
.filter(p => p.storeId === storeId)
|
.filter(p => p.store?.id === storeId)
|
||||||
.flatMap(p => (p.skus || []).map(sku => sku.id))
|
.flatMap(p => (p.skus || []).map(sku => sku.id))
|
||||||
}, [mode, productsData?.products, storeId])
|
}, [mode, productsData?.products, storeId])
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -118,17 +118,19 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
imageUrl: sku.images?.[0] || null,
|
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(() => {
|
useEffect(() => {
|
||||||
const ordered: SelectedProduct[] = []
|
const ordered: SelectedProduct[] = []
|
||||||
const skuMap = new Map<number, SelectedProduct>()
|
const skuMap = new Map<number, SelectedProduct>()
|
||||||
for (const sku of allSkus) {
|
for (const sku of allSkus) {
|
||||||
skuMap.set(sku.productId, sku)
|
skuMap.set(sku.skuId, sku)
|
||||||
}
|
}
|
||||||
for (const productId of initialValues.productIds || []) {
|
for (const productId of initialValues.productIds || []) {
|
||||||
const sku = skuMap.get(productId)
|
const sku = skuMap.get(productId)
|
||||||
if (sku) ordered.push(sku)
|
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)
|
setSelectedProducts(ordered)
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
|
@ -187,7 +189,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
|
||||||
<Formik
|
<Formik
|
||||||
initialValues={initialValues}
|
initialValues={initialValues}
|
||||||
validationSchema={validationSchema}
|
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
|
enableReinitialize
|
||||||
>
|
>
|
||||||
{({ handleChange, handleSubmit, values, setFieldValue, errors, touched, resetForm }) => {
|
{({ handleChange, handleSubmit, values, setFieldValue, errors, touched, resetForm }) => {
|
||||||
|
|
|
||||||
10
apps/admin-web/src/hooks/useIsSuperAdmin.ts
Normal file
10
apps/admin-web/src/hooks/useIsSuperAdmin.ts
Normal 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'
|
||||||
|
}
|
||||||
|
|
@ -200,7 +200,7 @@ function PricesOverview() {
|
||||||
for (const product of allProducts) {
|
for (const product of allProducts) {
|
||||||
if (product.skus && product.skus.length > 0) {
|
if (product.skus && product.skus.length > 0) {
|
||||||
for (const sku of product.skus) {
|
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 })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -37,6 +37,9 @@ function EditProduct() {
|
||||||
name: '',
|
name: '',
|
||||||
shortDescription: '',
|
shortDescription: '',
|
||||||
longDescription: '',
|
longDescription: '',
|
||||||
|
regionId: undefined as number | undefined,
|
||||||
|
availableInAllRegions: false,
|
||||||
|
storeIdsByRegion: {} as Record<number, number>,
|
||||||
storeId: 0,
|
storeId: 0,
|
||||||
productType: 'item' as const,
|
productType: 'item' as const,
|
||||||
variants: [],
|
variants: [],
|
||||||
|
|
@ -46,7 +49,10 @@ function EditProduct() {
|
||||||
name: productData.name,
|
name: productData.name,
|
||||||
shortDescription: productData.shortDescription || '',
|
shortDescription: productData.shortDescription || '',
|
||||||
longDescription: productData.longDescription || '',
|
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',
|
productType: (productData.productType as 'item' | 'combo') || 'item',
|
||||||
variants: (productData.skus || []).map((sku) => ({
|
variants: (productData.skus || []).map((sku) => ({
|
||||||
id: sku.id,
|
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({
|
await updateProduct.mutateAsync({
|
||||||
id: productId,
|
id: productId,
|
||||||
name: values.name,
|
name: values.name,
|
||||||
shortDescription: values.shortDescription || undefined,
|
shortDescription: values.shortDescription || undefined,
|
||||||
longDescription: values.longDescription || undefined,
|
longDescription: values.longDescription || undefined,
|
||||||
storeId: values.storeId,
|
regionId: values.regionId,
|
||||||
productType: values.productType,
|
productType: values.productType,
|
||||||
incrementStep: 1,
|
incrementStep: 1,
|
||||||
skus,
|
skus,
|
||||||
deletedImageKeys,
|
deletedImageKeys,
|
||||||
newImageUrls: allUploadUrls,
|
newImageUrls: allUploadUrls,
|
||||||
|
availableInAllRegions: !!values.availableInAllRegions,
|
||||||
|
...(values.availableInAllRegions
|
||||||
|
? { storeIdsByRegion }
|
||||||
|
: { storeId: values.storeId }),
|
||||||
} as any)
|
} as any)
|
||||||
|
|
||||||
await refetch()
|
await refetch()
|
||||||
|
|
|
||||||
|
|
@ -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({
|
await createProduct.mutateAsync({
|
||||||
name: values.name,
|
name: values.name,
|
||||||
shortDescription: values.shortDescription || undefined,
|
shortDescription: values.shortDescription || undefined,
|
||||||
longDescription: values.longDescription || undefined,
|
longDescription: values.longDescription || undefined,
|
||||||
storeId: values.storeId,
|
|
||||||
productType: values.productType,
|
productType: values.productType,
|
||||||
incrementStep: 1,
|
incrementStep: 1,
|
||||||
skus,
|
skus,
|
||||||
|
availableInAllRegions: !!values.availableInAllRegions,
|
||||||
|
...(values.availableInAllRegions
|
||||||
|
? { storeIdsByRegion }
|
||||||
|
: { storeId: values.storeId }),
|
||||||
})
|
})
|
||||||
|
|
||||||
await refetchProducts()
|
await refetchProducts()
|
||||||
|
|
@ -112,6 +124,9 @@ function AddProduct() {
|
||||||
name: '',
|
name: '',
|
||||||
shortDescription: '',
|
shortDescription: '',
|
||||||
longDescription: '',
|
longDescription: '',
|
||||||
|
regionId: undefined as number | undefined,
|
||||||
|
availableInAllRegions: false,
|
||||||
|
storeIdsByRegion: {} as Record<number, number>,
|
||||||
storeId: 1,
|
storeId: 1,
|
||||||
productType: 'item' as const,
|
productType: 'item' as const,
|
||||||
variants: [
|
variants: [
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,7 @@ export interface VendorSnippet {
|
||||||
|
|
||||||
// Vendor-snippet form row — anchored to the shared input (wire validTill);
|
// Vendor-snippet form row — anchored to the shared input (wire validTill);
|
||||||
// form requires slotId and carries the serialized createdAt.
|
// form requires slotId and carries the serialized createdAt.
|
||||||
export type VendorSnippetForm = Omit<AdminVendorSnippetInput, 'slotId'> & {
|
export type VendorSnippetForm = Omit<AdminVendorSnippetInput, 'slotId' | 'regionId'> & {
|
||||||
id: number;
|
id: number;
|
||||||
slotId: number;
|
slotId: number;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
|
|
||||||
|
|
@ -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.
|
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
|
|
@ -2,10 +2,8 @@ import 'dotenv/config';
|
||||||
import { serve } from '@hono/node-server';
|
import { serve } from '@hono/node-server';
|
||||||
import initFunc from '@/src/lib/init';
|
import initFunc from '@/src/lib/init';
|
||||||
import { createApp } from '@/src/app'
|
import { createApp } from '@/src/app'
|
||||||
import { seed } from '@/src/lib/seed';
|
|
||||||
import '@/src/jobs/jobs-index';
|
import '@/src/jobs/jobs-index';
|
||||||
|
|
||||||
seed()
|
|
||||||
initFunc()
|
initFunc()
|
||||||
|
|
||||||
const app = createApp()
|
const app = createApp()
|
||||||
|
|
|
||||||
|
|
@ -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);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
@ -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;
|
|
||||||
|
|
@ -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;
|
|
||||||
|
|
@ -3,7 +3,7 @@ import type { Context } from 'hono'
|
||||||
import { cors } from 'hono/cors'
|
import { cors } from 'hono/cors'
|
||||||
import { logger } from 'hono/logger'
|
import { logger } from 'hono/logger'
|
||||||
import { trpcServer } from '@hono/trpc-server'
|
import { trpcServer } from '@hono/trpc-server'
|
||||||
import { getStaffUserById, isUserSuspended } from '@/src/dbService'
|
import { getStaffUserById, getStaffRoleById, isUserSuspended } from '@/src/dbService'
|
||||||
import mainRouter from '@/src/main-router'
|
import mainRouter from '@/src/main-router'
|
||||||
import { appRouter } from '@/src/trpc/router'
|
import { appRouter } from '@/src/trpc/router'
|
||||||
import { TRPCError } from '@trpc/server'
|
import { TRPCError } from '@trpc/server'
|
||||||
|
|
@ -62,10 +62,14 @@ export const createApp = () => {
|
||||||
const staff = await getStaffUserById(decoded.staffId)
|
const staff = await getStaffUserById(decoded.staffId)
|
||||||
|
|
||||||
if (staff) {
|
if (staff) {
|
||||||
|
const role = staff.staffRoleId != null ? await getStaffRoleById(staff.staffRoleId) : null
|
||||||
user = staffUser
|
user = staffUser
|
||||||
staffUser = {
|
staffUser = {
|
||||||
id: staff.id,
|
id: staff.id,
|
||||||
name: staff.name,
|
name: staff.name,
|
||||||
|
regionId: staff.regionId,
|
||||||
|
staffRoleId: staff.staffRoleId ?? null,
|
||||||
|
staffRoleName: role?.roleName ?? null,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
|
||||||
|
|
@ -14,8 +14,8 @@ export async function notifyAllAdmins(payload: {
|
||||||
body: string
|
body: string
|
||||||
imageUrl?: string | null
|
imageUrl?: string | null
|
||||||
orderId?: number | null
|
orderId?: number | null
|
||||||
}): Promise<number> {
|
}, regionId?: number | null): Promise<number> {
|
||||||
const tokens = (await getAllStaffNotifTokens()).map((t) => t.token)
|
const tokens = (await getAllStaffNotifTokens(regionId ?? undefined)).map((t) => t.token)
|
||||||
|
|
||||||
let queuedCount = 0
|
let queuedCount = 0
|
||||||
for (let i = 0; i < tokens.length; i += TOKENS_PER_QUEUE_MESSAGE) {
|
for (let i = 0; i < tokens.length; i += TOKENS_PER_QUEUE_MESSAGE) {
|
||||||
|
|
|
||||||
|
|
@ -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 { scaffoldSlotsWithProducts } from '@/src/trpc/apis/user-apis/apis/slots'
|
||||||
import { scaffoldBanners } from '@/src/trpc/apis/user-apis/apis/banners'
|
import { scaffoldBanners } from '@/src/trpc/apis/user-apis/apis/banners'
|
||||||
import { scaffoldStoreWithProducts } from '@/src/trpc/apis/user-apis/apis/stores'
|
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 { imageUploadS3 } from '@/src/lib/s3-client'
|
||||||
import { getApiCacheKey, getCloudflareApiToken, getCloudflareZoneId, getAssetsDomain } from '@/src/lib/env-exporter'
|
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 { retryWithExponentialBackoff } from '@/src/lib/retry'
|
||||||
import { refreshGenKv } from '@/src/lib/gen-store'
|
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 {
|
const buildSlotsPath = (version: number, regionId?: number) =>
|
||||||
return `${getAssetsDomain()}${getApiCacheKey()}/${buildCachePath(path, version)}`
|
`${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 {
|
function constructAvailabilityUrl(version: number, regionId?: number): string {
|
||||||
return `${getAssetsDomain()}${buildAvailabilityPath(version)}`
|
return `${getAssetsDomain()}${buildAvailabilityPath(version, regionId)}`
|
||||||
}
|
}
|
||||||
|
|
||||||
function constructSlotsUrl(version: number): string {
|
function constructSlotsUrl(version: number, regionId?: number): string {
|
||||||
return `${getAssetsDomain()}${buildSlotsPath(version)}`
|
return `${getAssetsDomain()}${buildSlotsPath(version, regionId)}`
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateAllCacheFilesResult {
|
export interface CreateAllCacheFilesResult {
|
||||||
|
|
@ -44,7 +50,23 @@ export interface CreateAllCacheFilesResult {
|
||||||
export async function createAllCacheFiles(): Promise<CreateAllCacheFilesResult> {
|
export async function createAllCacheFiles(): Promise<CreateAllCacheFilesResult> {
|
||||||
console.log('Starting creation of all cache files...')
|
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
|
// Create all global cache files in parallel
|
||||||
const [
|
const [
|
||||||
|
|
@ -56,40 +78,38 @@ export async function createAllCacheFiles(): Promise<CreateAllCacheFilesResult>
|
||||||
bannersKey,
|
bannersKey,
|
||||||
individualStoreKeys,
|
individualStoreKeys,
|
||||||
] = await Promise.all([
|
] = await Promise.all([
|
||||||
createProductsFileInternal(cacheVersion),
|
createProductsFileInternal(cacheVersion, regionId),
|
||||||
createEssentialConstsFileInternal(cacheVersion),
|
createEssentialConstsFileInternal(cacheVersion, regionId),
|
||||||
createStoresFileInternal(cacheVersion),
|
createStoresFileInternal(cacheVersion, regionId),
|
||||||
createSlotsCacheFile(false),
|
createSlotsCacheFile(false, regionId),
|
||||||
createAvailabilityCacheFile(false),
|
createAvailabilityCacheFile(false, regionId),
|
||||||
createBannersFileInternal(cacheVersion),
|
createBannersFileInternal(cacheVersion, regionId),
|
||||||
createAllStoresFilesInternal(cacheVersion),
|
createAllStoresFilesInternal(cacheVersion, regionId),
|
||||||
])
|
])
|
||||||
|
|
||||||
const stores = await getStoresSummary()
|
const stores = await getStoresSummary(regionId)
|
||||||
|
|
||||||
// Collect all URLs for batch cache purge
|
// Collect all URLs for batch cache purge
|
||||||
const urls = [
|
const urls = [
|
||||||
constructCacheUrl(CACHE_FILENAMES.products, cacheVersion),
|
constructCacheUrl(CACHE_FILENAMES.products, cacheVersion, regionId),
|
||||||
constructCacheUrl(CACHE_FILENAMES.essentialConsts, cacheVersion),
|
constructCacheUrl(CACHE_FILENAMES.essentialConsts, cacheVersion, regionId),
|
||||||
constructCacheUrl(CACHE_FILENAMES.stores, cacheVersion),
|
constructCacheUrl(CACHE_FILENAMES.stores, cacheVersion, regionId),
|
||||||
constructSlotsUrl(slotsVersion),
|
constructSlotsUrl(slotsVersion, regionId),
|
||||||
constructAvailabilityUrl(availabilityVersion),
|
constructAvailabilityUrl(availabilityVersion, regionId),
|
||||||
constructCacheUrl(CACHE_FILENAMES.banners, cacheVersion),
|
constructCacheUrl(CACHE_FILENAMES.banners, cacheVersion, regionId),
|
||||||
...stores.map((store) => constructCacheUrl(`stores/${store.id}.json`, cacheVersion)),
|
...stores.map((store) => constructCacheUrl(`stores/${store.id}.json`, cacheVersion, regionId)),
|
||||||
]
|
]
|
||||||
|
|
||||||
// Purge all caches in one batch with retry
|
// Purge all caches in one batch with retry
|
||||||
try {
|
try {
|
||||||
await retryWithExponentialBackoff(() => clearUrlCache(urls))
|
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) {
|
} 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 this region (all counters bumped above).
|
||||||
|
await refreshGenKv(regionId)
|
||||||
// Single awaited mirror refresh for the whole cycle (all counters bumped above).
|
|
||||||
await refreshGenKv()
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
cacheVersion,
|
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)
|
// Internal versions that skip cache purging (for batch operations)
|
||||||
async function createProductsFileInternal(version: number): Promise<string> {
|
async function createProductsFileInternal(version: number, regionId?: number): Promise<string> {
|
||||||
const productsData = await scaffoldProducts()
|
const productsData = await scaffoldProducts(regionId)
|
||||||
const jsonContent = JSON.stringify(productsData, null, 2)
|
const jsonContent = JSON.stringify(productsData, null, 2)
|
||||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
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)
|
console.log(filePath)
|
||||||
return await imageUploadS3(
|
return await imageUploadS3(
|
||||||
|
|
@ -119,12 +145,21 @@ async function createProductsFileInternal(version: number): Promise<string> {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createAvailabilityCacheFile(refresh = true): Promise<number> {
|
export async function createAvailabilityCacheFile(refresh = true, regionId?: number): Promise<number> {
|
||||||
const version = await incrementAvailabilityVersionNum()
|
if (regionId == null) {
|
||||||
const availabilityData = await scaffoldAvailability()
|
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 jsonContent = JSON.stringify(availabilityData, null, 2)
|
||||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||||
const filePath = buildAvailabilityPath(version)
|
const filePath = buildAvailabilityPath(version, regionId)
|
||||||
|
|
||||||
console.log(filePath)
|
console.log(filePath)
|
||||||
await imageUploadS3(
|
await imageUploadS3(
|
||||||
|
|
@ -133,39 +168,48 @@ export async function createAvailabilityCacheFile(refresh = true): Promise<numbe
|
||||||
filePath
|
filePath
|
||||||
)
|
)
|
||||||
|
|
||||||
if (refresh) await refreshGenKv()
|
if (refresh) await refreshGenKv(regionId)
|
||||||
|
|
||||||
return version
|
return version
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createEssentialConstsFileInternal(version: number): Promise<string> {
|
async function createEssentialConstsFileInternal(version: number, regionId?: number): Promise<string> {
|
||||||
const essentialConstsData = await scaffoldEssentialConsts()
|
const essentialConstsData = await scaffoldEssentialConsts(regionId)
|
||||||
const jsonContent = JSON.stringify(essentialConstsData, null, 2)
|
const jsonContent = JSON.stringify(essentialConstsData, null, 2)
|
||||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||||
return await imageUploadS3(
|
return await imageUploadS3(
|
||||||
buffer,
|
buffer,
|
||||||
'application/json',
|
'application/json',
|
||||||
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.essentialConsts, version)}`
|
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.essentialConsts, version, regionId)}`
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createStoresFileInternal(version: number): Promise<string> {
|
async function createStoresFileInternal(version: number, regionId?: number): Promise<string> {
|
||||||
const storesData = await scaffoldStores()
|
const storesData = await scaffoldStores(regionId)
|
||||||
const jsonContent = JSON.stringify(storesData, null, 2)
|
const jsonContent = JSON.stringify(storesData, null, 2)
|
||||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||||
return await imageUploadS3(
|
return await imageUploadS3(
|
||||||
buffer,
|
buffer,
|
||||||
'application/json',
|
'application/json',
|
||||||
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.stores, version)}`
|
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.stores, version, regionId)}`
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createSlotsCacheFile(refresh = true): Promise<number> {
|
export async function createSlotsCacheFile(refresh = true, regionId?: number): Promise<number> {
|
||||||
const version = await incrementSlotsVersionNum()
|
if (regionId == null) {
|
||||||
const slotsData = await scaffoldSlotsWithProducts()
|
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 jsonContent = JSON.stringify(slotsData, null, 2)
|
||||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||||
const filePath = buildSlotsPath(version)
|
const filePath = buildSlotsPath(version, regionId)
|
||||||
|
|
||||||
console.log(filePath)
|
console.log(filePath)
|
||||||
await imageUploadS3(
|
await imageUploadS3(
|
||||||
|
|
@ -174,35 +218,35 @@ export async function createSlotsCacheFile(refresh = true): Promise<number> {
|
||||||
filePath
|
filePath
|
||||||
)
|
)
|
||||||
|
|
||||||
if (refresh) await refreshGenKv()
|
if (refresh) await refreshGenKv(regionId)
|
||||||
|
|
||||||
return version
|
return version
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createBannersFileInternal(version: number): Promise<string> {
|
async function createBannersFileInternal(version: number, regionId?: number): Promise<string> {
|
||||||
const bannersData = await scaffoldBanners()
|
const bannersData = await scaffoldBanners(regionId)
|
||||||
const jsonContent = JSON.stringify(bannersData, null, 2)
|
const jsonContent = JSON.stringify(bannersData, null, 2)
|
||||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||||
return await imageUploadS3(
|
return await imageUploadS3(
|
||||||
buffer,
|
buffer,
|
||||||
'application/json',
|
'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[] = []
|
const results: string[] = []
|
||||||
|
|
||||||
for (const store of stores) {
|
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 jsonContent = JSON.stringify(storeData, null, 2)
|
||||||
const buffer = Buffer.from(jsonContent, 'utf-8')
|
const buffer = Buffer.from(jsonContent, 'utf-8')
|
||||||
const s3Key = await imageUploadS3(
|
const s3Key = await imageUploadS3(
|
||||||
buffer,
|
buffer,
|
||||||
'application/json',
|
'application/json',
|
||||||
`${getApiCacheKey()}/${buildCachePath(`stores/${store.id}.json`, version)}`
|
`${getApiCacheKey()}/${buildCachePath(`stores/${store.id}.json`, version, regionId)}`
|
||||||
)
|
)
|
||||||
results.push(s3Key)
|
results.push(s3Key)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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[];
|
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> = {
|
export const CONST_TYPES: Record<ConstKey, ConstValueType> = {
|
||||||
minRegularOrderValue: 'number',
|
minRegularOrderValue: 'number',
|
||||||
freeDeliveryThreshold: 'number',
|
freeDeliveryThreshold: 'number',
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { getAllKeyValStore } from '@/src/dbService'
|
import { getAllKeyValStore, getAllRegionConsts } from '@/src/dbService'
|
||||||
// import redisClient from '@/src/lib/redis-client'
|
// import redisClient from '@/src/lib/redis-client'
|
||||||
import { CONST_KEYS, CONST_KEYS_ARRAY, type ConstKey } from '@/src/lib/const-keys'
|
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:';
|
// 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 redisKey = `${CONST_REDIS_PREFIX}${key}`;
|
||||||
// const value = await redisClient.get(redisKey);
|
// 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);
|
const entry = constants.find(c => c.key === key);
|
||||||
|
|
||||||
if (!entry) {
|
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 redisKeys = keys.map(key => `${CONST_REDIS_PREFIX}${key}`);
|
||||||
// const values = await redisClient.MGET(redisKeys);
|
// const values = await redisClient.MGET(redisKeys);
|
||||||
//
|
//
|
||||||
|
|
@ -67,8 +85,7 @@ export const getConstants = async <T = any>(keys: string[]): Promise<Record<stri
|
||||||
//
|
//
|
||||||
// return result;
|
// return result;
|
||||||
|
|
||||||
const constants = await getAllKeyValStore();
|
const constantsMap = await mergedConstMap(regionId, boundId);
|
||||||
const constantsMap = new Map(constants.map(c => [c.key, c.value]));
|
|
||||||
|
|
||||||
const result: Record<string, T | null> = {};
|
const result: Record<string, T | null> = {};
|
||||||
for (const key of keys) {
|
for (const key of keys) {
|
||||||
|
|
@ -79,7 +96,7 @@ export const getConstants = async <T = any>(keys: string[]): Promise<Record<stri
|
||||||
return result;
|
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> = {};
|
// const result: Record<string, any> = {};
|
||||||
//
|
//
|
||||||
// for (const key of CONST_KEYS_ARRAY) {
|
// 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>;
|
// return result as Record<ConstKey, any>;
|
||||||
|
|
||||||
const constants = await getAllKeyValStore();
|
const constantsMap = await mergedConstMap(regionId, boundId);
|
||||||
const constantsMap = new Map(constants.map(c => [c.key, c.value]));
|
|
||||||
|
|
||||||
const result: Record<string, any> = {};
|
const result: Record<string, any> = {};
|
||||||
for (const key of CONST_KEYS_ARRAY) {
|
for (const key of CONST_KEYS_ARRAY) {
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,23 @@
|
||||||
import { getGenKvNamespace } from '@/src/lib/env-exporter'
|
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'
|
import type { scaffoldEssentialConsts } from '@/src/trpc/apis/common-apis/common-trpc-index'
|
||||||
|
|
||||||
export const GEN_KV_KEY = 'essential_consts'
|
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>>
|
export type EssentialConstsPayload = Awaited<ReturnType<typeof scaffoldEssentialConsts>>
|
||||||
|
|
||||||
// Dynamic import: gen-store must not statically import common-trpc-index, because
|
// Dynamic import: gen-store must not statically import common-trpc-index, because
|
||||||
// that module imports readEssentialConstsFromKv from here (cycle).
|
// 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(
|
const { scaffoldEssentialConsts } = await import(
|
||||||
'../trpc/apis/common-apis/common-trpc-index'
|
'../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.
|
* 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).
|
* 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 {
|
try {
|
||||||
const kv = getGenKvNamespace()
|
const kv = getGenKvNamespace()
|
||||||
if (!kv) return
|
if (!kv) return
|
||||||
|
|
||||||
const payload = await buildEssentialConsts()
|
const payload = await buildEssentialConsts(regionId, boundId)
|
||||||
await kv.put(GEN_KV_KEY, JSON.stringify(payload))
|
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) {
|
} catch (error) {
|
||||||
console.error('refreshGenKv failed:', 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
|
* Client read path: serve the precomputed response from KV. On a miss, build it
|
||||||
* from D1/env, backfill KV, and return.
|
* 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 {
|
try {
|
||||||
const kv = getGenKvNamespace()
|
const kv = getGenKvNamespace()
|
||||||
if (kv) {
|
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
|
if (cached) return cached
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('readEssentialConstsFromKv failed:', error)
|
console.error('readEssentialConstsFromKv failed:', error)
|
||||||
}
|
}
|
||||||
|
|
||||||
const payload = await buildEssentialConsts()
|
const payload = await buildEssentialConsts(regionId, boundId)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const kv = getGenKvNamespace()
|
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) {
|
} catch (error) {
|
||||||
console.error('backfill essential_consts failed:', error)
|
console.error('backfill essential_consts failed:', error)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,11 @@
|
||||||
import {
|
import {
|
||||||
getOrdersByIdsWithFullData,
|
getOrdersByIdsWithFullData,
|
||||||
getOrderByIdWithFullData,
|
getOrderByIdWithFullData,
|
||||||
|
getRegionTelegramCreds,
|
||||||
composeSkuName,
|
composeSkuName,
|
||||||
composeUnitNotation,
|
composeUnitNotation,
|
||||||
} from '@/src/dbService'
|
} 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 { queueDataPusher } from '@/src/lib/queue-data-pusher'
|
||||||
import { notifyAllAdmins } from '@/src/lib/admin-notif'
|
import { notifyAllAdmins } from '@/src/lib/admin-notif'
|
||||||
import { ensureWorkerInit } from './worker-init';
|
import { ensureWorkerInit } from './worker-init';
|
||||||
|
|
@ -112,18 +113,21 @@ export const handleOrderPlaced = async (orderIds: number[], rawMessage?: string)
|
||||||
try {
|
try {
|
||||||
const ordersData = await getOrdersByIdsWithFullData(orderIds)
|
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).
|
// details page (data.orderId is the numeric order id).
|
||||||
for (const order of ordersData) {
|
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({
|
await notifyAllAdmins({
|
||||||
title: '🛒 New Order Placed',
|
title: '🛒 New Order Placed',
|
||||||
body: `${order.address?.name || 'A customer'} • ₹${order.totalAmount}`,
|
body: `${order.address?.name || 'A customer'} • ₹${order.totalAmount}`,
|
||||||
orderId: order.id,
|
orderId: order.id,
|
||||||
})
|
}, orderRegionId)
|
||||||
}
|
}
|
||||||
|
|
||||||
const telegramMessage = formatOrderMessageWithFullData(ordersData)
|
await sendOrderMessagePerRegion(ordersData, (group) => formatOrderMessageWithFullData(group))
|
||||||
await sendTelegramMessage(telegramMessage)
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to process order message:', error)
|
console.error('Failed to process order message:', error)
|
||||||
const fallback = rawMessage ? `⚠️ Error parsing order: ${rawMessage}` : '⚠️ Error parsing order'
|
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 (
|
export const handleOrderCancelled = async (
|
||||||
cancellationData: CancellationMessage,
|
cancellationData: CancellationMessage,
|
||||||
rawMessage?: string
|
rawMessage?: string
|
||||||
|
|
@ -147,9 +187,9 @@ export const handleOrderCancelled = async (
|
||||||
|
|
||||||
const refundStatus = orderData.refunds?.[0]?.refundStatus || 'pending'
|
const refundStatus = orderData.refunds?.[0]?.refundStatus || 'pending'
|
||||||
|
|
||||||
|
await sendOrderMessagePerRegion([orderData], (group) =>
|
||||||
const telegramMessage = formatCancellationMessage({ ...orderData, refundStatus }, cancellationData)
|
formatCancellationMessage({ ...group[0], refundStatus }, cancellationData)
|
||||||
await sendTelegramMessage(telegramMessage)
|
)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to process cancellation message:', error)
|
console.error('Failed to process cancellation message:', error)
|
||||||
const fallback = rawMessage ? `⚠️ Error processing cancellation: ${rawMessage}` : '⚠️ Error processing cancellation'
|
const fallback = rawMessage ? `⚠️ Error processing cancellation: ${rawMessage}` : '⚠️ Error processing cancellation'
|
||||||
|
|
|
||||||
67
apps/backend/src/lib/region-resolver.ts
Normal file
67
apps/backend/src/lib/region-resolver.ts
Normal 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 };
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,32 @@
|
||||||
import { getIsDevMode, getTelegramBotToken, getTelegramChatIds } from '@/src/lib/env-exporter'
|
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> => {
|
export const sendTelegramMessage = async (message: string): Promise<boolean | null> => {
|
||||||
if (getIsDevMode()) {
|
if (getIsDevMode()) {
|
||||||
return null;
|
return null;
|
||||||
|
|
@ -10,30 +37,35 @@ export const sendTelegramMessage = async (message: string): Promise<boolean | nu
|
||||||
console.warn('Telegram credentials not configured, skipping notification')
|
console.warn('Telegram credentials not configured, skipping notification')
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
const telegramApiUrl = `https://api.telegram.org/bot${botToken}`
|
|
||||||
try {
|
try {
|
||||||
const results = await Promise.all(
|
const results = await Promise.all(
|
||||||
chatIds.map(async (chatId) => {
|
chatIds.map(async (chatId) => postToChat(botToken, chatId, message))
|
||||||
try {
|
)
|
||||||
const response = await fetch(`${telegramApiUrl}/sendMessage`, {
|
|
||||||
method: 'POST',
|
console.log('sent telegram message successfully')
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ chat_id: chatId, text: message, parse_mode: 'HTML' }),
|
return results.some((result) => result)
|
||||||
})
|
} catch (error) {
|
||||||
const data = await response.json() as { ok: boolean }
|
console.error('Failed to send Telegram message:', error)
|
||||||
|
return false
|
||||||
if (data.ok) {
|
}
|
||||||
console.log(`Telegram message sent successfully to ${chatId}`)
|
}
|
||||||
return true
|
|
||||||
} else {
|
/** Region-scoped fan-out: one message to every cred of the order's region. */
|
||||||
console.error(`Telegram API error for ${chatId}:`, data)
|
export const sendTelegramMessageToCreds = async (
|
||||||
return false
|
message: string,
|
||||||
}
|
creds: TelegramCred[]
|
||||||
} catch (error) {
|
): Promise<boolean | null> => {
|
||||||
console.error(`Failed to send Telegram message to ${chatId}:`, error)
|
if (getIsDevMode()) {
|
||||||
return false
|
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')
|
console.log('sent telegram message successfully')
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import v1Router from "@/src/v1-router"
|
|
||||||
import testController from "@/src/test-controller"
|
import testController from "@/src/test-controller"
|
||||||
import { authenticateUser } from "@/src/middleware/auth.middleware"
|
import { authenticateUser } from "@/src/middleware/auth.middleware"
|
||||||
|
|
||||||
|
|
@ -26,7 +25,6 @@ router.get('/seed', (c) => {
|
||||||
// Apply authentication middleware to all subsequent routes
|
// Apply authentication middleware to all subsequent routes
|
||||||
router.use('*', authenticateUser);
|
router.use('*', authenticateUser);
|
||||||
|
|
||||||
router.route('/v1', v1Router);
|
|
||||||
router.route('/test', testController);
|
router.route('/test', testController);
|
||||||
|
|
||||||
const mainRouter = router;
|
const mainRouter = router;
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,9 @@ export {
|
||||||
// Admin - Constants
|
// Admin - Constants
|
||||||
getAllConstants,
|
getAllConstants,
|
||||||
upsertConstants,
|
upsertConstants,
|
||||||
|
getRegionConstants,
|
||||||
|
upsertRegionConstants,
|
||||||
|
getAllRegionConsts,
|
||||||
// Admin - Coupon
|
// Admin - Coupon
|
||||||
getAllCoupons,
|
getAllCoupons,
|
||||||
getCouponById,
|
getCouponById,
|
||||||
|
|
@ -59,6 +62,17 @@ export {
|
||||||
rebalanceSlots,
|
rebalanceSlots,
|
||||||
cancelOrder,
|
cancelOrder,
|
||||||
deleteOrderById,
|
deleteOrderById,
|
||||||
|
// Admin - Region
|
||||||
|
getRegions,
|
||||||
|
getRegionById,
|
||||||
|
getRegionSummaries,
|
||||||
|
createRegion,
|
||||||
|
updateRegion,
|
||||||
|
deleteRegion,
|
||||||
|
addRegionBound,
|
||||||
|
deleteRegionBound,
|
||||||
|
getRegionTelegramCreds,
|
||||||
|
getDefaultBoundId,
|
||||||
// Admin - Product
|
// Admin - Product
|
||||||
getAllProducts,
|
getAllProducts,
|
||||||
getProductById,
|
getProductById,
|
||||||
|
|
@ -83,9 +97,10 @@ export {
|
||||||
deleteProductGroup,
|
deleteProductGroup,
|
||||||
updateProductPrices,
|
updateProductPrices,
|
||||||
toggleProductOutOfStock,
|
toggleProductOutOfStock,
|
||||||
|
getSkuProductRegions,
|
||||||
|
backfillMarketStatsForRegion,
|
||||||
// Admin - Slots
|
// Admin - Slots
|
||||||
getActiveSlotsWithProducts,
|
getActiveSlotsWithProducts,
|
||||||
getSlotsAfterDate,
|
|
||||||
getSlotByIdWithRelations,
|
getSlotByIdWithRelations,
|
||||||
createSlotWithRelations,
|
createSlotWithRelations,
|
||||||
updateSlotWithRelations,
|
updateSlotWithRelations,
|
||||||
|
|
@ -101,6 +116,7 @@ export {
|
||||||
checkStaffRoleExists,
|
checkStaffRoleExists,
|
||||||
createStaffUser,
|
createStaffUser,
|
||||||
getAllRoles,
|
getAllRoles,
|
||||||
|
getStaffRoleById,
|
||||||
// Admin - Store
|
// Admin - Store
|
||||||
getAllStores,
|
getAllStores,
|
||||||
getStoreById,
|
getStoreById,
|
||||||
|
|
@ -160,8 +176,6 @@ export {
|
||||||
getUserProductReviews,
|
getUserProductReviews,
|
||||||
getUserProductByIdBasic,
|
getUserProductByIdBasic,
|
||||||
createUserProductReview,
|
createUserProductReview,
|
||||||
getAllProductsWithUnits,
|
|
||||||
type ProductSummaryData,
|
|
||||||
// User - Slots
|
// User - Slots
|
||||||
getUserActiveSlotsList,
|
getUserActiveSlotsList,
|
||||||
getUserProductAvailability,
|
getUserProductAvailability,
|
||||||
|
|
@ -246,6 +260,7 @@ export {
|
||||||
// Post-order handler helpers
|
// Post-order handler helpers
|
||||||
getOrdersByIdsWithFullData,
|
getOrdersByIdsWithFullData,
|
||||||
getOrderByIdWithFullData,
|
getOrderByIdWithFullData,
|
||||||
|
getOrderAddressRegion,
|
||||||
// Common API helpers
|
// Common API helpers
|
||||||
getSuspendedSkuIds,
|
getSuspendedSkuIds,
|
||||||
getNextDeliveryDateWithCapacity,
|
getNextDeliveryDateWithCapacity,
|
||||||
|
|
|
||||||
|
|
@ -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 {
|
try {
|
||||||
const allProducts = await getAllProducts()
|
const allProducts = await getAllProducts(regionId)
|
||||||
const product = allProducts.find(p => p.id === id)
|
const product = allProducts.find(p => p.id === id)
|
||||||
return product || null
|
return product || null
|
||||||
} catch (error) {
|
} 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 {
|
try {
|
||||||
// Get all keys matching the pattern "product:*"
|
// Get all keys matching the pattern "product:*"
|
||||||
// const keys = await redisClient.KEYS('product:*')
|
// const keys = await redisClient.KEYS('product:*')
|
||||||
|
|
@ -159,12 +159,12 @@ export async function getAllProducts(): Promise<Product[]> {
|
||||||
//
|
//
|
||||||
// return products
|
// 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 storeMap = new Map(allStores.map((s) => [s.id, s]))
|
||||||
|
|
||||||
const allDeliverySlots = await getAllDeliverySlotsForCache()
|
const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
|
||||||
const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
|
const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
|
||||||
for (const slot of allDeliverySlots) {
|
for (const slot of allDeliverySlots) {
|
||||||
if (!deliverySlotsMap.has(slot.skuId))
|
if (!deliverySlotsMap.has(slot.skuId))
|
||||||
|
|
@ -180,7 +180,7 @@ export async function getAllProducts(): Promise<Product[]> {
|
||||||
specialDealsMap.get(deal.skuId)!.push(deal)
|
specialDealsMap.get(deal.skuId)!.push(deal)
|
||||||
}
|
}
|
||||||
|
|
||||||
const allProductTags = await getAllProductTagsForCache()
|
const allProductTags = await getAllProductTagsForCache(regionId)
|
||||||
const productTagsMap = new Map<number, string[]>()
|
const productTagsMap = new Map<number, string[]>()
|
||||||
for (const tag of allProductTags) {
|
for (const tag of allProductTags) {
|
||||||
if (!productTagsMap.has(tag.productId))
|
if (!productTagsMap.has(tag.productId))
|
||||||
|
|
@ -189,7 +189,7 @@ export async function getAllProducts(): Promise<Product[]> {
|
||||||
}
|
}
|
||||||
|
|
||||||
const products: Product[] = []
|
const products: Product[] = []
|
||||||
const allProductCombos = await getAllProductCombosForCache()
|
const allProductCombos = await getAllProductCombosForCache(regionId)
|
||||||
const productCombosMap = new Map<number, ProductComboCacheData[]>()
|
const productCombosMap = new Map<number, ProductComboCacheData[]>()
|
||||||
for (const comboItem of allProductCombos) {
|
for (const comboItem of allProductCombos) {
|
||||||
if (!productCombosMap.has(comboItem.comboSkuId))
|
if (!productCombosMap.has(comboItem.comboSkuId))
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import {
|
||||||
} from '@/src/dbService'
|
} from '@/src/dbService'
|
||||||
import { scaffoldAssetUrl } from '@/src/lib/s3-client'
|
import { scaffoldAssetUrl } from '@/src/lib/s3-client'
|
||||||
import type { ProductTagCore } from '@packages/shared'
|
import type { ProductTagCore } from '@packages/shared'
|
||||||
|
import { DEFAULT_REGION_ID } from '@packages/shared'
|
||||||
|
|
||||||
// Tag Type (matches getDashboardTags return) — anchored to the shared tag core
|
// Tag Type (matches getDashboardTags return) — anchored to the shared tag core
|
||||||
interface Tag extends ProductTagCore {
|
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 {
|
try {
|
||||||
// Get all keys matching the pattern "tag:*"
|
// Get all keys matching the pattern "tag:*"
|
||||||
// const keys = await redisClient.KEYS('tag:*')
|
// const keys = await redisClient.KEYS('tag:*')
|
||||||
|
|
@ -109,7 +110,7 @@ export async function getTagsByStoreId(storeId: number): Promise<Tag[]> {
|
||||||
//
|
//
|
||||||
// return storeTags
|
// return storeTags
|
||||||
|
|
||||||
const tags = await getAllProductTags()
|
const tags = await getAllProductTags(regionId)
|
||||||
|
|
||||||
const result: Tag[] = []
|
const result: Tag[] = []
|
||||||
for (const tag of tags) {
|
for (const tag of tags) {
|
||||||
|
|
|
||||||
|
|
@ -63,8 +63,8 @@ function extractSlotInfo(slot: SlotWithProductsData): SlotInfo {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchAllTransformedSlots(): Promise<SlotWithProducts[]> {
|
async function fetchAllTransformedSlots(regionId?: number): Promise<SlotWithProducts[]> {
|
||||||
const slots = await getAllSlotsWithProductsForCache()
|
const slots = await getAllSlotsWithProductsForCache(regionId)
|
||||||
return Promise.all(slots.map(transformSlotToStoreSlot))
|
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> {
|
export async function getAllSlots(regionId?: number): Promise<SlotWithProducts[]> {
|
||||||
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[]> {
|
|
||||||
try {
|
try {
|
||||||
// Get all keys matching the pattern "slot:*"
|
// Get all keys matching the pattern "slot:*"
|
||||||
// const keys = await redisClient.KEYS('slot:*')
|
// const keys = await redisClient.KEYS('slot:*')
|
||||||
|
|
@ -177,7 +159,7 @@ export async function getAllSlots(): Promise<SlotWithProducts[]> {
|
||||||
//
|
//
|
||||||
// return slots
|
// return slots
|
||||||
|
|
||||||
return fetchAllTransformedSlots()
|
return fetchAllTransformedSlots(regionId)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error getting all slots:', error)
|
console.error('Error getting all slots:', error)
|
||||||
return []
|
return []
|
||||||
|
|
@ -185,7 +167,8 @@ export async function getAllSlots(): Promise<SlotWithProducts[]> {
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getMultipleProductsSlots(
|
export async function getMultipleProductsSlots(
|
||||||
productIds: number[]
|
productIds: number[],
|
||||||
|
regionId?: number
|
||||||
): Promise<Record<number, SlotInfo[]>> {
|
): Promise<Record<number, SlotInfo[]>> {
|
||||||
try {
|
try {
|
||||||
if (productIds.length === 0) return {}
|
if (productIds.length === 0) return {}
|
||||||
|
|
@ -208,7 +191,7 @@ export async function getMultipleProductsSlots(
|
||||||
//
|
//
|
||||||
// return result
|
// return result
|
||||||
|
|
||||||
const slots = await getAllSlotsWithProductsForCache()
|
const slots = await getAllSlotsWithProductsForCache(regionId)
|
||||||
const productIdSet = new Set(productIds)
|
const productIdSet = new Set(productIds)
|
||||||
const result: Record<number, SlotInfo[]> = {}
|
const result: Record<number, SlotInfo[]> = {}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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 { bannerRouter } from '@/src/trpc/apis/admin-apis/apis/banner'
|
||||||
import { userRouter } from '@/src/trpc/apis/admin-apis/apis/user'
|
import { userRouter } from '@/src/trpc/apis/admin-apis/apis/user'
|
||||||
import { constRouter } from '@/src/trpc/apis/admin-apis/apis/const'
|
import { constRouter } from '@/src/trpc/apis/admin-apis/apis/const'
|
||||||
|
import { regionRouter } from '@/src/trpc/apis/admin-apis/apis/region'
|
||||||
|
|
||||||
export const adminRouter = router({
|
export const adminRouter = router({
|
||||||
complaint: complaintRouter,
|
complaint: complaintRouter,
|
||||||
|
|
@ -26,6 +27,7 @@ export const adminRouter = router({
|
||||||
banner: bannerRouter,
|
banner: bannerRouter,
|
||||||
user: userRouter,
|
user: userRouter,
|
||||||
const: constRouter,
|
const: constRouter,
|
||||||
|
region: regionRouter,
|
||||||
});
|
});
|
||||||
|
|
||||||
export type AdminRouter = typeof adminRouter;
|
export type AdminRouter = typeof adminRouter;
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { z } from 'zod';
|
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 { extractKeyFromPresignedUrl, scaffoldAssetUrl } from '@/src/lib/s3-client'
|
||||||
import { ApiError } from '@/src/lib/api-error';
|
import { ApiError } from '@/src/lib/api-error';
|
||||||
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
|
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
|
||||||
|
|
@ -14,12 +14,12 @@ import type { Banner } from '@packages/shared'
|
||||||
|
|
||||||
export const bannerRouter = router({
|
export const bannerRouter = router({
|
||||||
// Get all banners
|
// Get all banners
|
||||||
getBanners: protectedProcedure
|
getBanners: adminProcedure
|
||||||
.query(async (): Promise<{ banners: Banner[] }> => {
|
.query(async ({ ctx }): Promise<{ banners: Banner[] }> => {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
// Using dbService helper (new implementation)
|
// Using dbService helper (new implementation)
|
||||||
const banners = await getBannersFromDb();
|
const banners = await getBannersFromDb(ctx.staffUser!.regionId);
|
||||||
|
|
||||||
// Convert S3 keys to signed URLs for client
|
// Convert S3 keys to signed URLs for client
|
||||||
const bannersWithSignedUrls = await Promise.all(
|
const bannersWithSignedUrls = await Promise.all(
|
||||||
|
|
@ -82,7 +82,7 @@ export const bannerRouter = router({
|
||||||
}),
|
}),
|
||||||
|
|
||||||
// Create new banner
|
// Create new banner
|
||||||
createBanner: protectedProcedure
|
createBanner: adminProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
name: z.string().min(1),
|
name: z.string().min(1),
|
||||||
imageUrl: z.string().url(),
|
imageUrl: z.string().url(),
|
||||||
|
|
@ -91,7 +91,7 @@ export const bannerRouter = router({
|
||||||
redirectUrl: z.string().url().optional(),
|
redirectUrl: z.string().url().optional(),
|
||||||
// serialNum removed completely
|
// serialNum removed completely
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input }): Promise<Banner> => {
|
.mutation(async ({ input, ctx }): Promise<Banner> => {
|
||||||
try {
|
try {
|
||||||
// Using dbService helper (new implementation)
|
// Using dbService helper (new implementation)
|
||||||
const imageUrl = extractKeyFromPresignedUrl(input.imageUrl)
|
const imageUrl = extractKeyFromPresignedUrl(input.imageUrl)
|
||||||
|
|
@ -103,6 +103,7 @@ export const bannerRouter = router({
|
||||||
redirectUrl: input.redirectUrl ?? null,
|
redirectUrl: input.redirectUrl ?? null,
|
||||||
serialNum: 999, // Default value, not used
|
serialNum: 999, // Default value, not used
|
||||||
isActive: false, // Default to inactive
|
isActive: false, // Default to inactive
|
||||||
|
regionId: ctx.staffUser!.regionId,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Reinitialize stores to reflect changes
|
// Reinitialize stores to reflect changes
|
||||||
|
|
|
||||||
|
|
@ -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 { z } from 'zod';
|
||||||
import { computeConstants } from '@/src/lib/const-store'
|
import { computeConstants } from '@/src/lib/const-store'
|
||||||
import { refreshGenKv } from '@/src/lib/gen-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 { 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'
|
import type { Constant, ConstantUpdateResult } from '@packages/shared'
|
||||||
|
|
||||||
// Constants that are baked into the versioned cache files (products.json etc.)
|
// 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({
|
export const constRouter = router({
|
||||||
getConstants: protectedProcedure
|
getConstants: adminProcedure
|
||||||
.query(async (): Promise<Constant[]> => {
|
.input(z.object({ boundId: z.number().int().positive().optional() }).optional())
|
||||||
// Using dbService helper (new implementation)
|
.query(async ({ ctx, input }): Promise<Constant[]> => {
|
||||||
const constants = await getAllConstantsFromDb();
|
// 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({
|
.input(z.object({
|
||||||
constants: z.array(z.object({
|
constants: z.array(z.object({
|
||||||
key: z.string(),
|
key: z.string(),
|
||||||
value: z.any(),
|
value: z.any(),
|
||||||
})),
|
})),
|
||||||
|
boundId: z.number().int().positive().optional(),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input }): Promise<ConstantUpdateResult> => {
|
.mutation(async ({ input, ctx }): Promise<ConstantUpdateResult> => {
|
||||||
const { constants } = input;
|
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 validKeys = Object.values(CONST_KEYS) as string[];
|
||||||
const invalidKeys = constants
|
const invalidKeys = constants
|
||||||
|
|
@ -42,14 +73,25 @@ export const constRouter = router({
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(input)
|
console.log(input)
|
||||||
// Using dbService helper (new implementation)
|
const regional = constants.filter((c) => REGION_CONST_KEYS_ARRAY.includes(c.key));
|
||||||
await upsertConstantsInDb(constants);
|
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
|
// Refresh all constants in Redis after database update
|
||||||
await computeConstants();
|
await computeConstants();
|
||||||
|
|
||||||
// Mirror the full essentialConsts response into KV for client reads.
|
// 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.
|
// Constants like tagsOrder are baked into the versioned cache files.
|
||||||
// Regenerate the cache (bumps cacheVersion) so the user app fetches the
|
// Regenerate the cache (bumps cacheVersion) so the user app fetches the
|
||||||
|
|
|
||||||
|
|
@ -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 { z } from "zod";
|
||||||
import { ApiError } from "@/src/lib/api-error"
|
import { ApiError } from "@/src/lib/api-error"
|
||||||
import {
|
import {
|
||||||
|
|
@ -167,12 +167,17 @@ export const orderRouter = router({
|
||||||
return result
|
return result
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getSlotOrders: protectedProcedure
|
getSlotOrders: adminProcedure
|
||||||
.input(getSlotOrdersSchema)
|
.input(getSlotOrdersSchema)
|
||||||
.query(async ({ input }): Promise<AdminGetSlotOrdersResult> => {
|
.query(async ({ input, ctx }): Promise<AdminGetSlotOrdersResult> => {
|
||||||
const { slotId } = input;
|
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 userIds = [...new Set(result.data.map((order) => order.userId))]
|
||||||
const firstOrderIdByUser = new Map<number, number | null>()
|
const firstOrderIdByUser = new Map<number, number | null>()
|
||||||
|
|
@ -210,11 +215,15 @@ export const orderRouter = router({
|
||||||
return result
|
return result
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getAll: protectedProcedure
|
getAll: adminProcedure
|
||||||
.input(getAllOrdersSchema)
|
.input(getAllOrdersSchema)
|
||||||
.query(async ({ input }): Promise<AdminGetAllOrdersResult | undefined> => {
|
.query(async ({ input, ctx }): Promise<AdminGetAllOrdersResult | undefined> => {
|
||||||
try {
|
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 userIds = [...new Set(result.orders.map((order) => order.userId))]
|
||||||
const negativityScores = await getMultipleUserNegativityScores(userIds)
|
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) }))
|
.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 slotIds = input.slotIds;
|
||||||
|
|
||||||
const result = await rebalanceSlotsInDb(slotIds)
|
const result = await rebalanceSlotsInDb(slotIds, ctx.staffUser!.regionId)
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}),
|
}),
|
||||||
|
|
|
||||||
|
|
@ -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 { z } from 'zod'
|
||||||
import { ApiError } from '@/src/lib/api-error'
|
import { ApiError } from '@/src/lib/api-error'
|
||||||
import { scaffoldAssetUrl, claimUploadUrl, extractKeyFromPresignedUrl, deleteImageUtil } from '@/src/lib/s3-client'
|
import { scaffoldAssetUrl, claimUploadUrl, extractKeyFromPresignedUrl, deleteImageUtil } from '@/src/lib/s3-client'
|
||||||
|
|
@ -16,6 +16,7 @@ import {
|
||||||
deleteProductGroup as deleteProductGroupInDb,
|
deleteProductGroup as deleteProductGroupInDb,
|
||||||
updateProductPrices as updateProductPricesInDb,
|
updateProductPrices as updateProductPricesInDb,
|
||||||
toggleProductOutOfStock as toggleProductOutOfStockInDb,
|
toggleProductOutOfStock as toggleProductOutOfStockInDb,
|
||||||
|
getSkuProductRegions as getSkuProductRegionsInDb,
|
||||||
checkProductExistsByName,
|
checkProductExistsByName,
|
||||||
createProduct as createProductInDb,
|
createProduct as createProductInDb,
|
||||||
replaceTagProducts,
|
replaceTagProducts,
|
||||||
|
|
@ -41,10 +42,39 @@ import type {
|
||||||
AdminToggleOutOfStockResult,
|
AdminToggleOutOfStockResult,
|
||||||
} from '@packages/shared'
|
} 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({
|
export const productRouter = router({
|
||||||
getProducts: protectedProcedure
|
getProducts: adminProcedure
|
||||||
.query(async (): Promise<AdminProductListResponse> => {
|
.query(async ({ ctx }): Promise<AdminProductListResponse> => {
|
||||||
const products = await getAllProductsInDb()
|
const products = await getAllProductsInDb(scopedRegion(ctx))
|
||||||
|
|
||||||
const productsWithImageUrls = products.map((product) => ({
|
const productsWithImageUrls = products.map((product) => ({
|
||||||
...product,
|
...product,
|
||||||
|
|
@ -60,14 +90,14 @@ export const productRouter = router({
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getProductById: protectedProcedure
|
getProductById: adminProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
id: z.number(),
|
id: z.number(),
|
||||||
}))
|
}))
|
||||||
.query(async ({ input }): Promise<AdminProductResponse> => {
|
.query(async ({ input, ctx }): Promise<AdminProductResponse> => {
|
||||||
const { id } = input;
|
const { id } = input;
|
||||||
|
|
||||||
const product = await getProductByIdInDb(id)
|
const product = await getProductByIdInDb(id, scopedRegion(ctx))
|
||||||
|
|
||||||
if (!product) {
|
if (!product) {
|
||||||
throw new ApiError('Product not found', 404)
|
throw new ApiError('Product not found', 404)
|
||||||
|
|
@ -90,9 +120,22 @@ export const productRouter = router({
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
id: z.number(),
|
id: z.number(),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input }): Promise<AdminDeleteProductResult> => {
|
.mutation(async ({ input, ctx }): Promise<AdminDeleteProductResult> => {
|
||||||
const { id } = input;
|
const { id } = input;
|
||||||
|
|
||||||
|
const currentProduct = await getProductByIdInDb(id, undefined)
|
||||||
|
if (!currentProduct) {
|
||||||
|
throw new ApiError('Product not found', 404)
|
||||||
|
}
|
||||||
|
if (!isSuperAdmin(ctx)) {
|
||||||
|
if (currentProduct.availableInAllRegions) {
|
||||||
|
throw new ApiError('Only super admins can delete all-regions products', 403)
|
||||||
|
}
|
||||||
|
if (currentProduct.regionId !== ctx.staffUser?.regionId) {
|
||||||
|
throw new ApiError('Product does not belong to your region', 403)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const deletedProduct = await deleteProductInDb(id)
|
const deletedProduct = await deleteProductInDb(id)
|
||||||
|
|
||||||
if (!deletedProduct) {
|
if (!deletedProduct) {
|
||||||
|
|
@ -107,14 +150,16 @@ export const productRouter = router({
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
toggleOutOfStock: protectedProcedure
|
toggleOutOfStock: adminProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
id: z.number(),
|
id: z.number(),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input }): Promise<AdminToggleOutOfStockResult> => {
|
.mutation(async ({ input, ctx }): Promise<AdminToggleOutOfStockResult> => {
|
||||||
const { id } = input;
|
const { id } = input;
|
||||||
|
|
||||||
const result = await toggleProductOutOfStockInDb(id)
|
assertOwnRestrictedProduct(ctx, await getProductByIdInDb(id, undefined))
|
||||||
|
|
||||||
|
const result = await toggleProductOutOfStockInDb(id, ctxRegion(ctx))
|
||||||
|
|
||||||
if (!result) {
|
if (!result) {
|
||||||
throw new ApiError('Product not found', 404)
|
throw new ApiError('Product not found', 404)
|
||||||
|
|
@ -132,12 +177,15 @@ export const productRouter = router({
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
createProduct: protectedProcedure
|
createProduct: adminProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
name: z.string().min(1, 'Name is required'),
|
name: z.string().min(1, 'Name is required'),
|
||||||
shortDescription: z.string().optional(),
|
shortDescription: z.string().optional(),
|
||||||
longDescription: 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),
|
incrementStep: z.number().optional().default(1),
|
||||||
productType: z.enum(['item', 'combo']).optional().default('item'),
|
productType: z.enum(['item', 'combo']).optional().default('item'),
|
||||||
skus: z.array(z.object({
|
skus: z.array(z.object({
|
||||||
|
|
@ -161,8 +209,12 @@ export const productRouter = router({
|
||||||
})).optional(),
|
})).optional(),
|
||||||
})).min(1, 'At least one SKU is required'),
|
})).min(1, 'At least one SKU is required'),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
.mutation(async ({ input, ctx }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
||||||
const { name, shortDescription, longDescription, storeId, incrementStep, productType, skus } = input
|
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())
|
const existingProduct = await checkProductExistsByName(name.trim())
|
||||||
if (existingProduct) {
|
if (existingProduct) {
|
||||||
|
|
@ -195,6 +247,10 @@ export const productRouter = router({
|
||||||
shortDescription,
|
shortDescription,
|
||||||
longDescription,
|
longDescription,
|
||||||
storeId,
|
storeId,
|
||||||
|
// Only super_admins may target another region; others are forced to ctx region.
|
||||||
|
regionId: writeRegion(ctx, regionId),
|
||||||
|
availableInAllRegions,
|
||||||
|
storeIdsByRegion: normalizedStoreIdsByRegion,
|
||||||
incrementStep,
|
incrementStep,
|
||||||
productType,
|
productType,
|
||||||
skus: skuInputs,
|
skus: skuInputs,
|
||||||
|
|
@ -220,13 +276,16 @@ export const productRouter = router({
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
updateProduct: protectedProcedure
|
updateProduct: adminProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
id: z.number(),
|
id: z.number(),
|
||||||
name: z.string().min(1, 'Name is required'),
|
name: z.string().min(1, 'Name is required'),
|
||||||
shortDescription: z.string().optional(),
|
shortDescription: z.string().optional(),
|
||||||
longDescription: 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),
|
incrementStep: z.number().optional().default(1),
|
||||||
productType: z.enum(['item', 'combo']).optional(),
|
productType: z.enum(['item', 'combo']).optional(),
|
||||||
skus: z.array(z.object({
|
skus: z.array(z.object({
|
||||||
|
|
@ -253,8 +312,21 @@ export const productRouter = router({
|
||||||
deletedImageKeys: z.array(z.string()).optional().default([]),
|
deletedImageKeys: z.array(z.string()).optional().default([]),
|
||||||
newImageUrls: z.array(z.string()).optional().default([]),
|
newImageUrls: z.array(z.string()).optional().default([]),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
.mutation(async ({ input, ctx }): Promise<{ product: AdminProductWithRelations; message: string }> => {
|
||||||
const { id, name, shortDescription, longDescription, storeId, incrementStep, productType, skus, deletedImageKeys, newImageUrls } = input
|
const { id, name, shortDescription, longDescription, storeId, regionId, availableInAllRegions, storeIdsByRegion, incrementStep, productType, skus, deletedImageKeys, newImageUrls } = input
|
||||||
|
|
||||||
|
const currentProduct = await getProductByIdInDb(id, undefined)
|
||||||
|
assertOwnRestrictedProduct(ctx, currentProduct)
|
||||||
|
if (!isSuperAdmin(ctx)) {
|
||||||
|
const nextAllRegions = availableInAllRegions ?? currentProduct!.availableInAllRegions
|
||||||
|
if (nextAllRegions !== currentProduct!.availableInAllRegions) {
|
||||||
|
throw new ApiError('Only super admins can change all-regions availability', 403)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedStoreIdsByRegion = storeIdsByRegion
|
||||||
|
? Object.fromEntries(Object.entries(storeIdsByRegion).map(([k, v]) => [Number(k), v]))
|
||||||
|
: undefined
|
||||||
|
|
||||||
if (deletedImageKeys.length > 0) {
|
if (deletedImageKeys.length > 0) {
|
||||||
await deleteImageUtil({ keys: deletedImageKeys })
|
await deleteImageUtil({ keys: deletedImageKeys })
|
||||||
|
|
@ -285,6 +357,10 @@ export const productRouter = router({
|
||||||
shortDescription,
|
shortDescription,
|
||||||
longDescription,
|
longDescription,
|
||||||
storeId,
|
storeId,
|
||||||
|
// Only super_admins may target another region; others are forced to ctx region.
|
||||||
|
regionId: writeRegion(ctx, regionId),
|
||||||
|
availableInAllRegions,
|
||||||
|
storeIdsByRegion: normalizedStoreIdsByRegion,
|
||||||
incrementStep,
|
incrementStep,
|
||||||
productType,
|
productType,
|
||||||
skus: skuInputs,
|
skus: skuInputs,
|
||||||
|
|
@ -359,27 +435,27 @@ export const productRouter = router({
|
||||||
return { success: true, review: updatedReview }
|
return { success: true, review: updatedReview }
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getGroups: protectedProcedure
|
getGroups: adminProcedure
|
||||||
.query(async (): Promise<AdminProductGroupsResult> => {
|
.query(async ({ ctx }): Promise<AdminProductGroupsResult> => {
|
||||||
// getAllProductGroupsInDb already returns groups with products mapped
|
// getAllProductGroupsInDb already returns groups with products mapped
|
||||||
// as AdminSku[] (SKU ids per the ProductsSelector).
|
// as AdminSku[] (SKU ids per the ProductsSelector).
|
||||||
const groups = await getAllProductGroupsInDb()
|
const groups = await getAllProductGroupsInDb(scopedRegion(ctx))
|
||||||
|
|
||||||
return {
|
return {
|
||||||
groups,
|
groups,
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
createGroup: protectedProcedure
|
createGroup: adminProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
group_name: z.string().min(1),
|
group_name: z.string().min(1),
|
||||||
description: z.string().optional(),
|
description: z.string().optional(),
|
||||||
product_ids: z.array(z.number()).default([]),
|
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 { 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()
|
await scheduleStoreInitialization()
|
||||||
|
|
||||||
|
|
@ -433,7 +509,7 @@ export const productRouter = router({
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
updateProductPrices: protectedProcedure
|
updateProductPrices: adminProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
updates: z.array(z.object({
|
updates: z.array(z.object({
|
||||||
productId: z.number(),
|
productId: z.number(),
|
||||||
|
|
@ -443,17 +519,36 @@ export const productRouter = router({
|
||||||
isFlashAvailable: z.boolean().optional(),
|
isFlashAvailable: z.boolean().optional(),
|
||||||
})),
|
})),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input }): Promise<AdminUpdateProductPricesResult> => {
|
.mutation(async ({ input, ctx }): Promise<AdminUpdateProductPricesResult> => {
|
||||||
const { updates } = input;
|
const { updates } = input;
|
||||||
|
|
||||||
if (updates.length === 0) {
|
if (updates.length === 0) {
|
||||||
throw new ApiError('No updates provided', 400)
|
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) {
|
const result = await updateProductPricesInDb(scopedUpdates, ctxRegion(ctx))
|
||||||
throw new ApiError(`Invalid product IDs: ${result.invalidIds.join(', ')}`, 400)
|
|
||||||
|
const invalidIds = [...result.invalidIds, ...foreignIds]
|
||||||
|
if (invalidIds.length > 0) {
|
||||||
|
throw new ApiError(`Invalid product IDs: ${invalidIds.join(', ')}`, 400)
|
||||||
}
|
}
|
||||||
|
|
||||||
await createAvailabilityCacheFile().catch((err) => {
|
await createAvailabilityCacheFile().catch((err) => {
|
||||||
|
|
@ -466,9 +561,9 @@ export const productRouter = router({
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getProductTags: protectedProcedure
|
getProductTags: adminProcedure
|
||||||
.query(async (): Promise<{ tags: Array<{ id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: number[] | null; createdAt: Date }>; message: string }> => {
|
.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()
|
const tags = await getAllProductTagInfosInDb(scopedRegion(ctx))
|
||||||
|
|
||||||
const tagsWithImageUrls = tags.map((tag) => ({
|
const tagsWithImageUrls = tags.map((tag) => ({
|
||||||
...tag,
|
...tag,
|
||||||
|
|
@ -481,10 +576,10 @@ export const productRouter = router({
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getProductTagById: protectedProcedure
|
getProductTagById: adminProcedure
|
||||||
.input(z.object({ id: z.number() }))
|
.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 }> => {
|
.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)
|
const tag = await getProductTagByIdInDb(input.id, ctxRegion(ctx))
|
||||||
|
|
||||||
if (!tag) {
|
if (!tag) {
|
||||||
throw new ApiError('Tag not found', 404)
|
throw new ApiError('Tag not found', 404)
|
||||||
|
|
@ -501,7 +596,7 @@ export const productRouter = router({
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
createProductTag: protectedProcedure
|
createProductTag: adminProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
tagName: z.string().min(1, 'Tag name is required'),
|
tagName: z.string().min(1, 'Tag name is required'),
|
||||||
tagDescription: z.string().optional(),
|
tagDescription: z.string().optional(),
|
||||||
|
|
@ -511,10 +606,10 @@ export const productRouter = router({
|
||||||
productIds: z.array(z.number()).optional().default([]),
|
productIds: z.array(z.number()).optional().default([]),
|
||||||
uploadUrls: z.array(z.string()).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 { 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) {
|
if (existingTag) {
|
||||||
throw new ApiError('A tag with this name already exists', 400)
|
throw new ApiError('A tag with this name already exists', 400)
|
||||||
}
|
}
|
||||||
|
|
@ -526,6 +621,7 @@ export const productRouter = router({
|
||||||
isDashboardTag,
|
isDashboardTag,
|
||||||
relatedStores,
|
relatedStores,
|
||||||
sortOrder: productIds,
|
sortOrder: productIds,
|
||||||
|
regionId: ctx.staffUser?.regionId,
|
||||||
})
|
})
|
||||||
|
|
||||||
await replaceTagProducts(createdTag.id, productIds)
|
await replaceTagProducts(createdTag.id, productIds)
|
||||||
|
|
@ -547,7 +643,7 @@ export const productRouter = router({
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|
||||||
updateProductTag: protectedProcedure
|
updateProductTag: adminProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
id: z.number(),
|
id: z.number(),
|
||||||
tagName: z.string().min(1).optional(),
|
tagName: z.string().min(1).optional(),
|
||||||
|
|
@ -558,7 +654,7 @@ export const productRouter = router({
|
||||||
productIds: z.array(z.number()).optional(),
|
productIds: z.array(z.number()).optional(),
|
||||||
uploadUrls: z.array(z.string()).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 { id, tagName, tagDescription, imageUrl, isDashboardTag, relatedStores, productIds, uploadUrls } = input
|
const { id, tagName, tagDescription, imageUrl, isDashboardTag, relatedStores, productIds, uploadUrls } = input
|
||||||
|
|
||||||
const currentTag = await getProductTagInfoByIdInDb(id)
|
const currentTag = await getProductTagInfoByIdInDb(id)
|
||||||
|
|
@ -580,7 +676,7 @@ export const productRouter = router({
|
||||||
isDashboardTag,
|
isDashboardTag,
|
||||||
relatedStores,
|
relatedStores,
|
||||||
sortOrder: productIds,
|
sortOrder: productIds,
|
||||||
})
|
}, ctxRegion(ctx))
|
||||||
|
|
||||||
if (productIds !== undefined) {
|
if (productIds !== undefined) {
|
||||||
await replaceTagProducts(id, productIds)
|
await replaceTagProducts(id, productIds)
|
||||||
|
|
|
||||||
155
apps/backend/src/trpc/apis/admin-apis/apis/region.ts
Normal file
155
apps/backend/src/trpc/apis/admin-apis/apis/region.ts
Normal 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' }
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
@ -80,7 +80,7 @@ export const slotsRouter = router({
|
||||||
throw new TRPCError({ code: "UNAUTHORIZED", message: "Access denied" });
|
throw new TRPCError({ code: "UNAUTHORIZED", message: "Access denied" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const slots = await getActiveSlotsWithProductsInDb(20)
|
const slots = await getActiveSlotsWithProductsInDb(20, ctx.staffUser!.regionId)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
slots,
|
slots,
|
||||||
|
|
@ -109,6 +109,7 @@ export const slotsRouter = router({
|
||||||
freezeTime,
|
freezeTime,
|
||||||
isActive,
|
isActive,
|
||||||
skuIds,
|
skuIds,
|
||||||
|
regionId: ctx.staffUser!.regionId,
|
||||||
// Complete SlotSnippetInput payloads — groupIds unused by sqlite but
|
// Complete SlotSnippetInput payloads — groupIds unused by sqlite but
|
||||||
// always sent; absent validTill becomes null.
|
// always sent; absent validTill becomes null.
|
||||||
vendorSnippets: snippets?.map((snippet) => ({
|
vendorSnippets: snippets?.map((snippet) => ({
|
||||||
|
|
|
||||||
|
|
@ -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 { z } from 'zod';
|
||||||
import bcrypt from 'bcryptjs';
|
import bcrypt from 'bcryptjs';
|
||||||
import { SignJWT } from 'jose';
|
import { SignJWT } from 'jose';
|
||||||
|
|
@ -6,11 +6,13 @@ import { getEncodedJwtSecret } from '@/src/lib/env-exporter';
|
||||||
import { ApiError } from '@/src/lib/api-error'
|
import { ApiError } from '@/src/lib/api-error'
|
||||||
import {
|
import {
|
||||||
getStaffUserByName,
|
getStaffUserByName,
|
||||||
|
getStaffUserById,
|
||||||
getAllStaff,
|
getAllStaff,
|
||||||
checkStaffUserExists,
|
checkStaffUserExists,
|
||||||
checkStaffRoleExists,
|
checkStaffRoleExists,
|
||||||
createStaffUser,
|
createStaffUser,
|
||||||
getAllRoles,
|
getAllRoles,
|
||||||
|
getStaffRoleById,
|
||||||
upsertStaffNotifCred,
|
upsertStaffNotifCred,
|
||||||
} from '@/src/dbService'
|
} from '@/src/dbService'
|
||||||
import { notifyAllAdmins } from '@/src/lib/admin-notif'
|
import { notifyAllAdmins } from '@/src/lib/admin-notif'
|
||||||
|
|
@ -44,10 +46,18 @@ export const staffUserRouter = router({
|
||||||
.setExpirationTime('30d')
|
.setExpirationTime('30d')
|
||||||
.sign(getEncodedJwtSecret());
|
.sign(getEncodedJwtSecret());
|
||||||
|
|
||||||
|
const role = staff.staffRoleId != null ? await getStaffRoleById(staff.staffRoleId) : null
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: 'Login successful',
|
message: 'Login successful',
|
||||||
token,
|
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) => ({
|
const transformedStaff = staff.map((user) => ({
|
||||||
id: user.id,
|
id: user.id,
|
||||||
name: user.name,
|
name: user.name,
|
||||||
|
regionId: user.regionId,
|
||||||
role: user.role ? {
|
role: user.role ? {
|
||||||
id: user.role.id,
|
id: user.role.id,
|
||||||
name: user.role.roleName,
|
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({
|
.input(z.object({
|
||||||
name: z.string().min(1, 'Name is required'),
|
name: z.string().min(1, 'Name is required'),
|
||||||
password: z.string().min(6, 'Password must be at least 6 characters'),
|
password: z.string().min(6, 'Password must be at least 6 characters'),
|
||||||
roleId: z.number().int().positive('Role is required'),
|
roleId: z.number().int().positive('Role is required'),
|
||||||
|
regionId: z.number().int().positive().optional(),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input, ctx }) => {
|
.mutation(async ({ input, ctx }) => {
|
||||||
const { name, password, roleId } = input;
|
const { name, password, roleId } = input;
|
||||||
|
|
@ -97,13 +131,20 @@ export const staffUserRouter = router({
|
||||||
throw new ApiError('Invalid role selected', 400);
|
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
|
// Hash password
|
||||||
const hashedPassword = await bcrypt.hash(password, 12);
|
const hashedPassword = await bcrypt.hash(password, 12);
|
||||||
|
|
||||||
// Create staff user
|
// 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
|
getRoles: protectedProcedure
|
||||||
|
|
|
||||||
|
|
@ -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 { z } from 'zod';
|
||||||
import { ApiError } from '@/src/lib/api-error'
|
import { ApiError } from '@/src/lib/api-error'
|
||||||
import { extractKeyFromPresignedUrl, deleteImageUtil, scaffoldAssetUrl } from '@/src/lib/s3-client'
|
import { extractKeyFromPresignedUrl, deleteImageUtil, scaffoldAssetUrl } from '@/src/lib/s3-client'
|
||||||
|
|
@ -12,10 +12,38 @@ import {
|
||||||
} from '@/src/dbService'
|
} from '@/src/dbService'
|
||||||
import type { Store } from '@packages/shared'
|
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({
|
export const storeRouter = router({
|
||||||
getStores: protectedProcedure
|
getStores: adminProcedure
|
||||||
.query(async ({ ctx }): Promise<{ stores: any[]; count: number }> => {
|
.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 => {
|
await Promise.all(stores.map(async store => {
|
||||||
if(store.imageUrl)
|
if(store.imageUrl)
|
||||||
|
|
@ -48,13 +76,14 @@ export const storeRouter = router({
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
|
|
||||||
createStore: protectedProcedure
|
createStore: adminProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
name: z.string().min(1, "Name is required"),
|
name: z.string().min(1, "Name is required"),
|
||||||
description: z.string().optional(),
|
description: z.string().optional(),
|
||||||
imageUrl: z.string().optional(),
|
imageUrl: z.string().optional(),
|
||||||
owner: z.number().min(1, "Owner is required"),
|
owner: z.number().min(1, "Owner is required"),
|
||||||
products: z.array(z.number()).optional(),
|
products: z.array(z.number()).optional(),
|
||||||
|
regionId: z.number().int().positive().optional(),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input, ctx }): Promise<{ store: Store; message: string }> => {
|
.mutation(async ({ input, ctx }): Promise<{ store: Store; message: string }> => {
|
||||||
const { name, description, imageUrl, owner, products } = input;
|
const { name, description, imageUrl, owner, products } = input;
|
||||||
|
|
@ -67,6 +96,7 @@ export const storeRouter = router({
|
||||||
description,
|
description,
|
||||||
imageUrl: imageKey,
|
imageUrl: imageKey,
|
||||||
owner,
|
owner,
|
||||||
|
regionId: writeRegion(ctx, input.regionId),
|
||||||
},
|
},
|
||||||
products
|
products
|
||||||
);
|
);
|
||||||
|
|
@ -80,7 +110,7 @@ export const storeRouter = router({
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
|
|
||||||
updateStore: protectedProcedure
|
updateStore: adminProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
id: z.number(),
|
id: z.number(),
|
||||||
name: z.string().min(1, "Name is required"),
|
name: z.string().min(1, "Name is required"),
|
||||||
|
|
@ -88,6 +118,7 @@ export const storeRouter = router({
|
||||||
imageUrl: z.string().optional(),
|
imageUrl: z.string().optional(),
|
||||||
owner: z.number().min(1, "Owner is required"),
|
owner: z.number().min(1, "Owner is required"),
|
||||||
products: z.array(z.number()).optional(),
|
products: z.array(z.number()).optional(),
|
||||||
|
regionId: z.number().int().positive().optional(),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input, ctx }): Promise<{ store: Store; message: string }> => {
|
.mutation(async ({ input, ctx }): Promise<{ store: Store; message: string }> => {
|
||||||
const { id, name, description, imageUrl, owner, products } = input;
|
const { id, name, description, imageUrl, owner, products } = input;
|
||||||
|
|
@ -97,7 +128,12 @@ export const storeRouter = router({
|
||||||
if (!existingStore) {
|
if (!existingStore) {
|
||||||
throw new ApiError("Store not found", 404);
|
throw new ApiError("Store not found", 404);
|
||||||
}
|
}
|
||||||
|
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 oldImageKey = existingStore.imageUrl;
|
||||||
const newImageKey = imageUrl ? extractKeyFromPresignedUrl(imageUrl) : oldImageKey;
|
const newImageKey = imageUrl ? extractKeyFromPresignedUrl(imageUrl) : oldImageKey;
|
||||||
|
|
||||||
|
|
@ -123,6 +159,7 @@ export const storeRouter = router({
|
||||||
description,
|
description,
|
||||||
imageUrl: newImageKey,
|
imageUrl: newImageKey,
|
||||||
owner,
|
owner,
|
||||||
|
regionId: writeRegion(ctx, input.regionId),
|
||||||
},
|
},
|
||||||
products
|
products
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -186,15 +186,17 @@ export const userRouter = {
|
||||||
text: z.string().min(1, 'Message is required'),
|
text: z.string().min(1, 'Message is required'),
|
||||||
imageUrl: z.string().optional(),
|
imageUrl: z.string().optional(),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input }) => {
|
.mutation(async ({ input, ctx }) => {
|
||||||
const { userIds, title, text, imageUrl } = input;
|
const { userIds, title, text, imageUrl } = input;
|
||||||
|
const regionId = ctx.staffUser?.regionId;
|
||||||
|
|
||||||
let tokens: string[] = [];
|
let tokens: string[] = [];
|
||||||
|
|
||||||
if (userIds.length === 0) {
|
if (userIds.length === 0) {
|
||||||
// Send to all users - get tokens from both logged-in and unlogged users
|
// Broadcast: only this admin's region. Region-less tokens (older app
|
||||||
const loggedInTokens = await getAllNotifCreds();
|
// versions) are excluded.
|
||||||
const unloggedTokens = await getAllUnloggedTokens();
|
const loggedInTokens = await getAllNotifCreds(regionId);
|
||||||
|
const unloggedTokens = await getAllUnloggedTokens(regionId);
|
||||||
|
|
||||||
tokens = [
|
tokens = [
|
||||||
...loggedInTokens.map(t => t.token),
|
...loggedInTokens.map(t => t.token),
|
||||||
|
|
|
||||||
|
|
@ -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 { z } from 'zod'
|
||||||
import dayjs from 'dayjs'
|
|
||||||
import { getAppUrl } from '@/src/lib/env-exporter'
|
import { getAppUrl } from '@/src/lib/env-exporter'
|
||||||
import {
|
import {
|
||||||
checkVendorSnippetExists as checkVendorSnippetExistsInDb,
|
checkVendorSnippetExists as checkVendorSnippetExistsInDb,
|
||||||
|
|
@ -14,7 +13,6 @@ import {
|
||||||
getVendorSlotById as getVendorSlotByIdInDb,
|
getVendorSlotById as getVendorSlotByIdInDb,
|
||||||
getVendorOrdersBySlotId as getVendorOrdersBySlotIdInDb,
|
getVendorOrdersBySlotId as getVendorOrdersBySlotIdInDb,
|
||||||
updateVendorOrderItemPackaging as updateVendorOrderItemPackagingInDb,
|
updateVendorOrderItemPackaging as updateVendorOrderItemPackagingInDb,
|
||||||
getSlotsAfterDate as getSlotsAfterDateInDb,
|
|
||||||
composeSkuName,
|
composeSkuName,
|
||||||
composeUnitNotation,
|
composeUnitNotation,
|
||||||
} from '@/src/dbService'
|
} from '@/src/dbService'
|
||||||
|
|
@ -24,7 +22,6 @@ import type {
|
||||||
AdminVendorSnippetDeleteResult,
|
AdminVendorSnippetDeleteResult,
|
||||||
AdminVendorSnippetOrdersResult,
|
AdminVendorSnippetOrdersResult,
|
||||||
AdminVendorSnippetOrdersWithSlotResult,
|
AdminVendorSnippetOrdersWithSlotResult,
|
||||||
AdminUpcomingSlotsResult,
|
|
||||||
AdminVendorUpdatePackagingResult,
|
AdminVendorUpdatePackagingResult,
|
||||||
} from '@packages/shared'
|
} from '@packages/shared'
|
||||||
|
|
||||||
|
|
@ -46,7 +43,7 @@ const updateSnippetSchema = z.object({
|
||||||
});
|
});
|
||||||
|
|
||||||
export const vendorSnippetsRouter = router({
|
export const vendorSnippetsRouter = router({
|
||||||
create: protectedProcedure
|
create: adminProcedure
|
||||||
.input(createSnippetSchema)
|
.input(createSnippetSchema)
|
||||||
.mutation(async ({ input, ctx }): Promise<AdminVendorSnippet> => {
|
.mutation(async ({ input, ctx }): Promise<AdminVendorSnippet> => {
|
||||||
const { snippetCode, slotId, skuIds, validTill, isPermanent } = input;
|
const { snippetCode, slotId, skuIds, validTill, isPermanent } = input;
|
||||||
|
|
@ -80,17 +77,22 @@ export const vendorSnippetsRouter = router({
|
||||||
skuIds,
|
skuIds,
|
||||||
isPermanent,
|
isPermanent,
|
||||||
validTill: validTill ? new Date(validTill) : undefined,
|
validTill: validTill ? new Date(validTill) : undefined,
|
||||||
|
regionId: ctx.staffUser?.regionId,
|
||||||
})
|
})
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getAll: protectedProcedure
|
getAll: adminProcedure
|
||||||
.query(async (): Promise<AdminVendorSnippetWithProducts[]> => {
|
.query(async ({ ctx }): Promise<AdminVendorSnippetWithProducts[]> => {
|
||||||
console.log('from the vendor snipptes methods')
|
console.log('from the vendor snipptes methods')
|
||||||
|
|
||||||
try {
|
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(
|
const snippetsWithProducts = await Promise.all(
|
||||||
result.map(async (snippet) => {
|
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
|
getOrdersBySnippetAndSlot: publicProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
snippetCode: z.string().min(1, "Snippet code is required"),
|
snippetCode: z.string().min(1, "Snippet code is required"),
|
||||||
|
|
|
||||||
|
|
@ -6,10 +6,14 @@ import {
|
||||||
getCacheVersion,
|
getCacheVersion,
|
||||||
getAvailabilityVersionNum,
|
getAvailabilityVersionNum,
|
||||||
getSlotsVersionNum,
|
getSlotsVersionNum,
|
||||||
|
getRegionSummaries,
|
||||||
|
getRegions,
|
||||||
} from '@/src/dbService'
|
} from '@/src/dbService'
|
||||||
|
import { DEFAULT_REGION_ID } from '@packages/shared'
|
||||||
import type { StoresSummaryResponse } from '@packages/shared'
|
import type { StoresSummaryResponse } from '@packages/shared'
|
||||||
import { polygon as turfPolygon, point as turfPoint } from '@turf/helpers';
|
import { polygon as turfPolygon, point as turfPoint } from '@turf/helpers';
|
||||||
import { booleanPointInPolygon } from '@turf/boolean-point-in-polygon';
|
import { booleanPointInPolygon } from '@turf/boolean-point-in-polygon';
|
||||||
|
import { extractPolygonRings, resolveBoundForPoint, type ResolvedBound } from '@/src/lib/region-resolver';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { mbnrGeoJson } from '@/src/lib/mbnr-geojson'
|
import { mbnrGeoJson } from '@/src/lib/mbnr-geojson'
|
||||||
import { generateUploadUrl } from '@/src/lib/s3-client'
|
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);
|
const polygon = turfPolygon(mbnrGeoJson.features[0].geometry.coordinates);
|
||||||
|
|
||||||
export async function scaffoldEssentialConsts() {
|
export async function scaffoldEssentialConsts(regionId?: number, boundId?: number | null) {
|
||||||
const consts = await getAllConstValues();
|
const consts = await getAllConstValues(regionId, boundId);
|
||||||
const cacheVersion = await getCacheVersion()
|
const cacheVersion = await getCacheVersion(regionId)
|
||||||
const availabilityVersionNum = await getAvailabilityVersionNum()
|
const availabilityVersionNum = await getAvailabilityVersionNum(regionId)
|
||||||
const slotsVersionNum = await getSlotsVersionNum()
|
const slotsVersionNum = await getSlotsVersionNum(regionId)
|
||||||
|
|
||||||
|
const cachePathPrefix =
|
||||||
|
regionId == null || regionId === DEFAULT_REGION_ID ? '' : `r-${regionId}/`
|
||||||
|
|
||||||
return {
|
return {
|
||||||
freeDeliveryThreshold: consts[CONST_KEYS.freeDeliveryThreshold] ?? 200,
|
freeDeliveryThreshold: consts[CONST_KEYS.freeDeliveryThreshold] ?? 200,
|
||||||
|
|
@ -48,22 +55,33 @@ export async function scaffoldEssentialConsts() {
|
||||||
cacheVersion,
|
cacheVersion,
|
||||||
availabilityVersionNum,
|
availabilityVersionNum,
|
||||||
slotsVersionNum,
|
slotsVersionNum,
|
||||||
|
cachePathPrefix,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type { ResolvedBound } from '@/src/lib/region-resolver';
|
||||||
|
export { resolveBoundForPoint } from '@/src/lib/region-resolver';
|
||||||
|
|
||||||
export const commonApiRouter = router({
|
export const commonApiRouter = router({
|
||||||
product: commonRouter,
|
product: commonRouter,
|
||||||
|
|
||||||
getStoresSummary: publicProcedure
|
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 {
|
return {
|
||||||
stores,
|
stores,
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
getRegions: publicProcedure
|
||||||
|
.query(async () => {
|
||||||
|
const regions = await getRegionSummaries();
|
||||||
|
return { regions };
|
||||||
|
}),
|
||||||
|
|
||||||
checkLocationInPolygon: publicProcedure
|
checkLocationInPolygon: publicProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
lat: z.number().min(-90).max(90),
|
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
|
generateUploadUrls: protectedProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
contextString: z.enum(['review', 'review_response', 'product_info', 'notification', 'store', 'complaint', 'profile', 'tags']),
|
contextString: z.enum(['review', 'review_response', 'product_info', 'notification', 'store', 'complaint', 'profile', 'tags']),
|
||||||
|
|
@ -138,16 +165,19 @@ export const commonApiRouter = router({
|
||||||
}),
|
}),
|
||||||
|
|
||||||
essentialConsts: publicProcedure
|
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 requestUrl = ctx.req.url
|
||||||
const host = new URL(requestUrl).host
|
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%;">
|
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: 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>
|
<h1 style="font-size: 36px; margin-top: 48px">With love, from Freshyo</h5>
|
||||||
</div>`
|
</div>`
|
||||||
|
|
||||||
const response = await readEssentialConstsFromKv();
|
const response = await readEssentialConstsFromKv(regionId, boundId);
|
||||||
const shouldShowNotice = host.includes('raw') || host.includes('mf')
|
const shouldShowNotice = host.includes('raw') || host.includes('mf')
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { router, publicProcedure } from '@/src/trpc/trpc-index'
|
import { router, publicProcedure, adminProcedure } from '@/src/trpc/trpc-index'
|
||||||
import {
|
import {
|
||||||
getSuspendedSkuIds,
|
getSuspendedSkuIds,
|
||||||
getNextDeliveryDateWithCapacity,
|
getNextDeliveryDateWithCapacity,
|
||||||
|
|
@ -7,21 +7,19 @@ import {
|
||||||
getAllTagsForCache,
|
getAllTagsForCache,
|
||||||
getAllTagProductMappings,
|
getAllTagProductMappings,
|
||||||
getAvailabilityForCache,
|
getAvailabilityForCache,
|
||||||
|
getRegionSummaries,
|
||||||
} from '@/src/dbService'
|
} from '@/src/dbService'
|
||||||
import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url, scaffoldAssetUrl } from '@/src/lib/s3-client'
|
import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url, scaffoldAssetUrl } from '@/src/lib/s3-client'
|
||||||
import { getAllProducts as getAllProductsFromCache } from '@/src/stores/product-store'
|
import { getAllProducts as getAllProductsFromCache } from '@/src/stores/product-store'
|
||||||
import { getConstant } from '@/src/lib/const-store'
|
import { getConstant } from '@/src/lib/const-store'
|
||||||
import { CONST_KEYS } from '@/src/lib/const-keys'
|
import { CONST_KEYS } from '@/src/lib/const-keys'
|
||||||
|
|
||||||
// Re-export with original name for backwards compatibility
|
export async function scaffoldProducts(regionId?: number) {
|
||||||
export const getNextDeliveryDate = getNextDeliveryDateWithCapacity
|
|
||||||
|
|
||||||
export async function scaffoldProducts() {
|
|
||||||
// Get all products from cache
|
// Get all products from cache
|
||||||
let products = await getAllProductsFromCache();
|
let products = await getAllProductsFromCache(regionId);
|
||||||
products = products.filter(item => Boolean(item.id))
|
products = products.filter(item => Boolean(item.id))
|
||||||
|
|
||||||
const suspendedSkuIds = new Set(await getSuspendedSkuIds());
|
const suspendedSkuIds = new Set(await getSuspendedSkuIds(regionId));
|
||||||
|
|
||||||
// Filter out suspended products
|
// Filter out suspended products
|
||||||
products = products.filter(product => !suspendedSkuIds.has(product.id));
|
products = products.filter(product => !suspendedSkuIds.has(product.id));
|
||||||
|
|
@ -29,7 +27,7 @@ export async function scaffoldProducts() {
|
||||||
// Format products to match the expected response structure
|
// Format products to match the expected response structure
|
||||||
const formattedProducts = await Promise.all(
|
const formattedProducts = await Promise.all(
|
||||||
products.map(async (product) => {
|
products.map(async (product) => {
|
||||||
const nextDeliveryDate = await getNextDeliveryDateWithCapacity(product.id);
|
const nextDeliveryDate = await getNextDeliveryDateWithCapacity(product.id, regionId);
|
||||||
return {
|
return {
|
||||||
id: product.id,
|
id: product.id,
|
||||||
name: product.name,
|
name: product.name,
|
||||||
|
|
@ -55,8 +53,8 @@ export async function scaffoldProducts() {
|
||||||
|
|
||||||
// Fetch all product tags with their mapped product ids
|
// Fetch all product tags with their mapped product ids
|
||||||
const [allTags, tagMappings] = await Promise.all([
|
const [allTags, tagMappings] = await Promise.all([
|
||||||
getAllTagsForCache(),
|
getAllTagsForCache(regionId),
|
||||||
getAllTagProductMappings(),
|
getAllTagProductMappings(regionId),
|
||||||
])
|
])
|
||||||
|
|
||||||
// Order tags by the admin-defined tagsOrder (unknown tags go to the end).
|
// 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() {
|
export async function scaffoldAvailability(regionId?: number) {
|
||||||
const availability = await getAvailabilityForCache()
|
const availability = await getAvailabilityForCache(regionId)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
availability,
|
availability,
|
||||||
|
|
@ -127,15 +125,41 @@ export async function scaffoldAvailability() {
|
||||||
}
|
}
|
||||||
|
|
||||||
export const commonRouter = router({
|
export const commonRouter = router({
|
||||||
getAllProductsSummary: publicProcedure
|
getAllProductsSummary: adminProcedure
|
||||||
.query(async () => {
|
.query(async ({ ctx }) => {
|
||||||
const response = await scaffoldProducts();
|
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;
|
return response;
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getAllSkusSummary: publicProcedure
|
getAllSkusSummary: adminProcedure
|
||||||
.query(async () => {
|
.query(async ({ ctx }) => {
|
||||||
const skus = await getAllSkusSummaryInDb()
|
const skus = await getAllSkusSummaryInDb(
|
||||||
|
ctx.staffUser?.staffRoleName === 'super_admin' ? undefined : ctx.staffUser?.regionId
|
||||||
|
)
|
||||||
return { skus }
|
return { skus }
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -48,10 +48,11 @@ export const addressRouter = router({
|
||||||
latitude: z.number().optional(),
|
latitude: z.number().optional(),
|
||||||
longitude: z.number().optional(),
|
longitude: z.number().optional(),
|
||||||
googleMapsUrl: z.string().optional(),
|
googleMapsUrl: z.string().optional(),
|
||||||
|
regionId: z.number().int().positive().optional(),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input, ctx }): Promise<UserAddressResponse> => {
|
.mutation(async ({ input, ctx }): Promise<UserAddressResponse> => {
|
||||||
const userId = ctx.user.userId;
|
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;
|
let { latitude, longitude } = input;
|
||||||
|
|
||||||
|
|
@ -86,6 +87,7 @@ export const addressRouter = router({
|
||||||
latitude,
|
latitude,
|
||||||
longitude,
|
longitude,
|
||||||
googleMapsUrl,
|
googleMapsUrl,
|
||||||
|
regionId,
|
||||||
})
|
})
|
||||||
|
|
||||||
return { success: true, data: newAddress }
|
return { success: true, data: newAddress }
|
||||||
|
|
@ -105,10 +107,11 @@ export const addressRouter = router({
|
||||||
latitude: z.number().optional(),
|
latitude: z.number().optional(),
|
||||||
longitude: z.number().optional(),
|
longitude: z.number().optional(),
|
||||||
googleMapsUrl: z.string().optional(),
|
googleMapsUrl: z.string().optional(),
|
||||||
|
regionId: z.number().int().positive().optional(),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input, ctx }): Promise<UserAddressResponse> => {
|
.mutation(async ({ input, ctx }): Promise<UserAddressResponse> => {
|
||||||
const userId = ctx.user.userId;
|
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;
|
let { latitude, longitude } = input;
|
||||||
|
|
||||||
|
|
@ -145,6 +148,7 @@ export const addressRouter = router({
|
||||||
googleMapsUrl,
|
googleMapsUrl,
|
||||||
latitude,
|
latitude,
|
||||||
longitude,
|
longitude,
|
||||||
|
regionId,
|
||||||
})
|
})
|
||||||
|
|
||||||
return { success: true, data: updatedAddress }
|
return { success: true, data: updatedAddress }
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,8 @@ import { scaffoldAssetUrl } from '@/src/lib/s3-client'
|
||||||
import { getUserActiveBanners as getUserActiveBannersInDb } from '@/src/dbService'
|
import { getUserActiveBanners as getUserActiveBannersInDb } from '@/src/dbService'
|
||||||
import type { UserBannersResponse } from '@packages/shared'
|
import type { UserBannersResponse } from '@packages/shared'
|
||||||
|
|
||||||
export async function scaffoldBanners(): Promise<UserBannersResponse> {
|
export async function scaffoldBanners(regionId?: number): Promise<UserBannersResponse> {
|
||||||
const banners = await getUserActiveBannersInDb()
|
const banners = await getUserActiveBannersInDb(regionId)
|
||||||
|
|
||||||
const bannersWithSignedUrls = banners.map((banner) => ({
|
const bannersWithSignedUrls = banners.map((banner) => ({
|
||||||
...banner,
|
...banner,
|
||||||
|
|
|
||||||
|
|
@ -6,15 +6,16 @@ export const cartRouter = router({
|
||||||
// Cache-based getCartSlots
|
// Cache-based getCartSlots
|
||||||
getCartSlots: publicProcedure
|
getCartSlots: publicProcedure
|
||||||
.input(z.object({
|
.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 }) => {
|
.query(async ({ input }) => {
|
||||||
const { productIds } = input;
|
const { productIds, regionId } = input;
|
||||||
|
|
||||||
if (productIds.length === 0) {
|
if (productIds.length === 0) {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
return await getMultipleProductsSlots(productIds);
|
return await getMultipleProductsSlots(productIds, regionId);
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,10 @@ import { z } from 'zod'
|
||||||
import {
|
import {
|
||||||
getUserComplaints as getUserComplaintsInDb,
|
getUserComplaints as getUserComplaintsInDb,
|
||||||
createUserComplaint as createUserComplaintInDb,
|
createUserComplaint as createUserComplaintInDb,
|
||||||
|
getOrderAddressRegion as getOrderAddressRegionInDb,
|
||||||
|
getUserDefaultAddress as getDefaultAddressInDb,
|
||||||
} from '@/src/dbService'
|
} from '@/src/dbService'
|
||||||
|
import { notifyAllAdmins } from '@/src/lib/admin-notif'
|
||||||
import type { UserComplaintsResponse, UserRaiseComplaintResponse } from '@packages/shared'
|
import type { UserComplaintsResponse, UserRaiseComplaintResponse } from '@packages/shared'
|
||||||
|
|
||||||
export const complaintRouter = router({
|
export const complaintRouter = router({
|
||||||
|
|
@ -44,6 +47,30 @@ export const complaintRouter = router({
|
||||||
imageUrls && imageUrls.length > 0 ? imageUrls : null
|
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' }
|
return { success: true, message: 'Complaint raised successfully' }
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,7 @@ import { scaffoldAssetUrl } from "@/src/lib/s3-client";
|
||||||
import { ApiError } from "@/src/lib/api-error";
|
import { ApiError } from "@/src/lib/api-error";
|
||||||
import type { DeliveryStatus, OrderStatus } from "@packages/shared";
|
import type { DeliveryStatus, OrderStatus } from "@packages/shared";
|
||||||
import { CONST_KEYS, getConstant, getConstants } from "@/src/lib/const-store";
|
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 { publishFormattedOrder, publishCancellation } from "@/src/lib/post-order-handler";
|
||||||
import { trackIfFirstOrder, clearFirstOrderIfMatches } from "@/src/lib/order-tracker";
|
import { trackIfFirstOrder, clearFirstOrderIfMatches } from "@/src/lib/order-tracker";
|
||||||
import type {
|
import type {
|
||||||
|
|
@ -58,12 +59,27 @@ const placeOrderUtil = async (params: {
|
||||||
userNotes,
|
userNotes,
|
||||||
} = params;
|
} = 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 constants = await getConstants<number>([
|
||||||
CONST_KEYS.minRegularOrderValue,
|
CONST_KEYS.minRegularOrderValue,
|
||||||
CONST_KEYS.deliveryCharge,
|
CONST_KEYS.deliveryCharge,
|
||||||
CONST_KEYS.flashFreeDeliveryThreshold,
|
CONST_KEYS.flashFreeDeliveryThreshold,
|
||||||
CONST_KEYS.flashDeliveryCharge,
|
CONST_KEYS.flashDeliveryCharge,
|
||||||
]);
|
], address.regionId, addressBoundId);
|
||||||
|
|
||||||
const isFlashDelivery = params.isFlash;
|
const isFlashDelivery = params.isFlash;
|
||||||
const minOrderValue = (isFlashDelivery ? constants[CONST_KEYS.flashFreeDeliveryThreshold] : constants[CONST_KEYS.minRegularOrderValue]) || 0;
|
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 orderGroupId = `${Date.now()}-${userId}`;
|
||||||
|
|
||||||
const address = await getUserAddressByIdAndUser(addressId, userId);
|
|
||||||
if (!address) {
|
|
||||||
throw new ApiError("Invalid address", 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const ordersBySlot = new Map<
|
const ordersBySlot = new Map<
|
||||||
number | null,
|
number | null,
|
||||||
Array<{
|
Array<{
|
||||||
|
|
@ -87,7 +98,7 @@ const placeOrderUtil = async (params: {
|
||||||
>();
|
>();
|
||||||
|
|
||||||
for (const item of selectedItems) {
|
for (const item of selectedItems) {
|
||||||
const product = await getOrderProductById(item.skuId);
|
const product = await getOrderProductById(item.skuId, address.regionId);
|
||||||
if (!product) {
|
if (!product) {
|
||||||
throw new ApiError(`Product ${item.skuId} not found`, 400);
|
throw new ApiError(`Product ${item.skuId} not found`, 400);
|
||||||
}
|
}
|
||||||
|
|
@ -100,7 +111,7 @@ const placeOrderUtil = async (params: {
|
||||||
|
|
||||||
if (params.isFlash) {
|
if (params.isFlash) {
|
||||||
for (const item of selectedItems) {
|
for (const item of selectedItems) {
|
||||||
const product = await getOrderProductById(item.skuId);
|
const product = await getOrderProductById(item.skuId, address.regionId);
|
||||||
if (!product?.isFlashAvailable) {
|
if (!product?.isFlashAvailable) {
|
||||||
throw new ApiError(`Product ${item.skuId} is not available for flash delivery`, 400);
|
throw new ApiError(`Product ${item.skuId} is not available for flash delivery`, 400);
|
||||||
}
|
}
|
||||||
|
|
@ -275,7 +286,19 @@ export const orderRouter = router({
|
||||||
} = input;
|
} = input;
|
||||||
|
|
||||||
if (isFlashDelivery) {
|
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) {
|
if (!isFlashDeliveryEnabled) {
|
||||||
throw new ApiError("Flash delivery is currently unavailable. Please opt for scheduled delivery.", 403);
|
throw new ApiError("Flash delivery is currently unavailable. Please opt for scheduled delivery.", 403);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -27,9 +27,10 @@ export const productRouter = router({
|
||||||
getProductDetails: publicProcedure
|
getProductDetails: publicProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
id: z.string().regex(/^\d+$/, 'Invalid product ID'),
|
id: z.string().regex(/^\d+$/, 'Invalid product ID'),
|
||||||
|
regionId: z.number().int().positive().optional(),
|
||||||
}))
|
}))
|
||||||
.query(async ({ input }): Promise<UserProductDetail> => {
|
.query(async ({ input }): Promise<UserProductDetail> => {
|
||||||
const { id } = input;
|
const { id, regionId } = input;
|
||||||
const productId = parseInt(id);
|
const productId = parseInt(id);
|
||||||
|
|
||||||
if (isNaN(productId)) {
|
if (isNaN(productId)) {
|
||||||
|
|
@ -39,7 +40,7 @@ export const productRouter = router({
|
||||||
console.log('from the api to get product details')
|
console.log('from the api to get product details')
|
||||||
|
|
||||||
// First, try to get the product from Redis cache
|
// First, try to get the product from Redis cache
|
||||||
const cachedProduct = await getProductByIdFromCache(productId);
|
const cachedProduct = await getProductByIdFromCache(productId, regionId);
|
||||||
|
|
||||||
if (cachedProduct) {
|
if (cachedProduct) {
|
||||||
// Filter delivery slots to only include those with future freeze times and not at full capacity
|
// 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)
|
// If not in cache, fetch from database (fallback)
|
||||||
const productData = await getUserProductDetailByIdInDb(productId)
|
const productData = await getUserProductDetailByIdInDb(productId, regionId)
|
||||||
|
|
||||||
if (!productData) {
|
if (!productData) {
|
||||||
throw new Error('Product not found')
|
throw new Error('Product not found')
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,12 @@
|
||||||
import { router, publicProcedure } from "@/src/trpc/trpc-index"
|
import { router, publicProcedure } from "@/src/trpc/trpc-index"
|
||||||
|
import { z } from "zod"
|
||||||
import { getAllSlots as getAllSlotsFromCache } from "@/src/stores/slot-store"
|
import { getAllSlots as getAllSlotsFromCache } from "@/src/stores/slot-store"
|
||||||
import dayjs from 'dayjs'
|
import dayjs from 'dayjs'
|
||||||
import { getUserActiveSlotsList as getUserActiveSlotsListInDb, getUserProductAvailability as getUserProductAvailabilityInDb } from '@/src/dbService'
|
import { getUserActiveSlotsList as getUserActiveSlotsListInDb, getUserProductAvailability as getUserProductAvailabilityInDb } from '@/src/dbService'
|
||||||
import type { UserSlotsListResponse, UserSlotsWithProductsResponse } from '@packages/shared'
|
import type { UserSlotsListResponse, UserSlotsWithProductsResponse } from '@packages/shared'
|
||||||
|
|
||||||
export async function scaffoldSlotsWithProducts(): Promise<UserSlotsWithProductsResponse> {
|
export async function scaffoldSlotsWithProducts(regionId?: number): Promise<UserSlotsWithProductsResponse> {
|
||||||
const allSlots = await getAllSlotsFromCache();
|
const allSlots = await getAllSlotsFromCache(regionId);
|
||||||
const currentTime = new Date();
|
const currentTime = new Date();
|
||||||
const validSlots = allSlots
|
const validSlots = allSlots
|
||||||
.filter((slot) => {
|
.filter((slot) => {
|
||||||
|
|
@ -15,7 +16,7 @@ export async function scaffoldSlotsWithProducts(): Promise<UserSlotsWithProducts
|
||||||
})
|
})
|
||||||
.sort((a, b) => dayjs(a.deliveryTime).valueOf() - dayjs(b.deliveryTime).valueOf());
|
.sort((a, b) => dayjs(a.deliveryTime).valueOf() - dayjs(b.deliveryTime).valueOf());
|
||||||
|
|
||||||
const productAvailability = await getUserProductAvailabilityInDb()
|
const productAvailability = await getUserProductAvailabilityInDb(regionId)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
slots: validSlots.map((slot) => ({
|
slots: validSlots.map((slot) => ({
|
||||||
|
|
@ -33,8 +34,10 @@ export async function scaffoldSlotsWithProducts(): Promise<UserSlotsWithProducts
|
||||||
}
|
}
|
||||||
|
|
||||||
export const slotsRouter = router({
|
export const slotsRouter = router({
|
||||||
getSlots: publicProcedure.query(async (): Promise<UserSlotsListResponse> => {
|
getSlots: publicProcedure
|
||||||
const slots = await getUserActiveSlotsListInDb()
|
.input(z.object({ regionId: z.number().int().positive().optional() }).optional())
|
||||||
|
.query(async ({ input }): Promise<UserSlotsListResponse> => {
|
||||||
|
const slots = await getUserActiveSlotsListInDb(input?.regionId)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
slots,
|
slots,
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,8 @@ import type {
|
||||||
UserStoreSummary,
|
UserStoreSummary,
|
||||||
} from '@packages/shared'
|
} from '@packages/shared'
|
||||||
|
|
||||||
export async function scaffoldStores(): Promise<UserStoresResponse> {
|
export async function scaffoldStores(regionId?: number): Promise<UserStoresResponse> {
|
||||||
const storesData = await getUserStoreSummariesInDb()
|
const storesData = await getUserStoreSummariesInDb(regionId)
|
||||||
|
|
||||||
const storesWithDetails: UserStoreSummary[] = storesData.map((store) => {
|
const storesWithDetails: UserStoreSummary[] = storesData.map((store) => {
|
||||||
const signedImageUrl = store.imageUrl ? scaffoldAssetUrl(store.imageUrl) : null
|
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> {
|
export async function scaffoldStoreWithProducts(storeId: number, regionId?: number): Promise<UserStoreDetail> {
|
||||||
const storeDetail = await getUserStoreDetailInDb(storeId)
|
const storeDetail = await getUserStoreDetailInDb(storeId, regionId)
|
||||||
|
|
||||||
if (!storeDetail) {
|
if (!storeDetail) {
|
||||||
throw new ApiError('Store not found', 404)
|
throw new ApiError('Store not found', 404)
|
||||||
|
|
@ -64,7 +64,7 @@ export async function scaffoldStoreWithProducts(storeId: number): Promise<UserSt
|
||||||
productQuantity: product.productQuantity,
|
productQuantity: product.productQuantity,
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const tags = await getTagsByStoreId(storeId)
|
const tags = await getTagsByStoreId(storeId, regionId)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
store: {
|
store: {
|
||||||
|
|
|
||||||
|
|
@ -68,15 +68,15 @@ export const userRouter = router({
|
||||||
}),
|
}),
|
||||||
|
|
||||||
savePushToken: publicProcedure
|
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> => {
|
.mutation(async ({ input, ctx }): Promise<UserSavePushTokenResponse> => {
|
||||||
const { token } = input;
|
const { token, regionId } = input;
|
||||||
const userId = ctx.user?.userId;
|
const userId = ctx.user?.userId;
|
||||||
|
|
||||||
if (userId) {
|
if (userId) {
|
||||||
// AUTHENTICATED USER
|
// AUTHENTICATED USER
|
||||||
// Check if token exists in notif_creds for this user
|
// Check if token exists in notif_creds for this user
|
||||||
await upsertUserNotifCredInDb(userId, token)
|
await upsertUserNotifCredInDb(userId, token, regionId)
|
||||||
await deleteUserUnloggedTokenInDb(token)
|
await deleteUserUnloggedTokenInDb(token)
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -84,9 +84,9 @@ export const userRouter = router({
|
||||||
// Save/update in unlogged_user_tokens
|
// Save/update in unlogged_user_tokens
|
||||||
const existing = await getUserUnloggedTokenInDb(token)
|
const existing = await getUserUnloggedTokenInDb(token)
|
||||||
if (existing) {
|
if (existing) {
|
||||||
await upsertUserUnloggedTokenInDb(token)
|
await upsertUserUnloggedTokenInDb(token, regionId)
|
||||||
} else {
|
} else {
|
||||||
await upsertUserUnloggedTokenInDb(token)
|
await upsertUserUnloggedTokenInDb(token, regionId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,9 @@ export interface Context {
|
||||||
staffUser?: {
|
staffUser?: {
|
||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
|
regionId: number;
|
||||||
|
staffRoleId: number | null;
|
||||||
|
staffRoleName: string | null;
|
||||||
} | null;
|
} | null;
|
||||||
callerInterface?: string | null;
|
callerInterface?: string | null;
|
||||||
}
|
}
|
||||||
|
|
@ -69,3 +72,39 @@ export const protectedProcedure = t.procedure.use(errorLoggerMiddleware).use(
|
||||||
return next();
|
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 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,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
|
||||||
|
|
@ -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;
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useMemo, useState, useEffect } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import { useSearch } from "@tanstack/react-router";
|
import { useSearch } from "@tanstack/react-router";
|
||||||
import { trpc } from "../trpc/client";
|
import { trpc } from "../trpc/client";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
@ -21,63 +21,22 @@ interface VendorOrder {
|
||||||
}>;
|
}>;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface DeliverySlot {
|
|
||||||
id: number;
|
|
||||||
deliveryTime: string;
|
|
||||||
freezeTime: string;
|
|
||||||
deliverySequence: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function VendorOrderListRoute() {
|
export function VendorOrderListRoute() {
|
||||||
const { id } = useSearch({ from: "/vendor-order-list" });
|
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 {
|
const {
|
||||||
data: slotOrdersData,
|
data: snippetOrders,
|
||||||
error,
|
error,
|
||||||
isLoading: isLoadingOrders,
|
isLoading: isLoadingOrders,
|
||||||
isFetching,
|
isFetching,
|
||||||
refetch,
|
refetch,
|
||||||
} = trpc.admin.vendorSnippets.getOrdersBySnippetAndSlot.useQuery(
|
} = trpc.admin.vendorSnippets.getOrdersBySnippet.useQuery(
|
||||||
{ snippetCode: id!, slotId: selectedSlotId! },
|
{ snippetCode: id! },
|
||||||
{ enabled: !!id && !!selectedSlotId && isPermanent },
|
{ enabled: !!id },
|
||||||
);
|
);
|
||||||
|
|
||||||
const { data: regularOrders } =
|
const orders = snippetOrders?.data || [];
|
||||||
trpc.admin.vendorSnippets.getOrdersBySnippet.useQuery(
|
const isLoadingCurrent = isLoadingOrders;
|
||||||
{ snippetCode: id! },
|
|
||||||
{ enabled: !!id && !isPermanent },
|
|
||||||
);
|
|
||||||
|
|
||||||
const orders = slotOrdersData?.data || regularOrders?.data || [];
|
|
||||||
const isLoadingCurrent = isPermanent ? isLoadingOrders : isLoadingSnippet;
|
|
||||||
|
|
||||||
const updatePackagingMutation =
|
const updatePackagingMutation =
|
||||||
trpc.admin.vendorSnippets.updateOrderItemPackaging.useMutation();
|
trpc.admin.vendorSnippets.updateOrderItemPackaging.useMutation();
|
||||||
|
|
@ -152,41 +111,19 @@ export function VendorOrderListRoute() {
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-sm text-slate-500">
|
<p className="text-sm text-slate-500">
|
||||||
Track incoming orders and fulfilment progress for vendor partners.
|
Track incoming orders and fulfilment progress for vendor partners.
|
||||||
{id && <span className="block mt-1 text-xs">Snippet: {id}</span>}
|
{id && <span className="block mt-1 text-xs">Snippet: {id}</span>}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{isPermanent && upcomingSlots?.data && (
|
<Button
|
||||||
<div className="flex items-center gap-2">
|
variant="outline"
|
||||||
<label
|
onClick={() => {
|
||||||
htmlFor="slot-select"
|
void refetch();
|
||||||
className="text-sm font-medium text-slate-700"
|
}}
|
||||||
>
|
disabled={isFetching}
|
||||||
Select Slot:
|
>
|
||||||
</label>
|
{isFetching ? "Refreshing…" : "Refresh"}
|
||||||
<select
|
</Button>
|
||||||
id="slot-select"
|
</div>
|
||||||
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>
|
|
||||||
|
|
||||||
<div className="mt-6">
|
<div className="mt-6">
|
||||||
{isLoadingCurrent ? (
|
{isLoadingCurrent ? (
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,12 @@
|
||||||
import React, { useState } from 'react'
|
import React, { useState } from 'react'
|
||||||
import { Link } from '@tanstack/react-router'
|
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 } from 'lucide-react'
|
||||||
import { useAuth } from '../lib/auth-context'
|
import { useAuth } from '../lib/auth-context'
|
||||||
|
|
||||||
const NAV = [
|
const NAV = [
|
||||||
{ to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
{ to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
||||||
|
{ to: '/admins', label: 'Create Admin', icon: UserPlus },
|
||||||
|
{ to: '/regions', label: 'Regions', icon: MapPin },
|
||||||
{ to: '/send-notifications', label: 'Send Admin Notifications', icon: Send },
|
{ to: '/send-notifications', label: 'Send Admin Notifications', icon: Send },
|
||||||
{ to: '/constants', label: 'App Constants', icon: Settings2 },
|
{ to: '/constants', label: 'App Constants', icon: Settings2 },
|
||||||
] as const
|
] as const
|
||||||
|
|
|
||||||
|
|
@ -10,16 +10,25 @@
|
||||||
|
|
||||||
import { Route as rootRouteImport } from './routes/__root'
|
import { Route as rootRouteImport } from './routes/__root'
|
||||||
import { Route as IndexRouteImport } from './routes/index'
|
import { Route as IndexRouteImport } from './routes/index'
|
||||||
|
import { Route as AdminsRouteImport } from './routes/admins'
|
||||||
import { Route as ConstantsRouteImport } from './routes/constants'
|
import { Route as ConstantsRouteImport } from './routes/constants'
|
||||||
import { Route as DashboardRouteImport } from './routes/dashboard'
|
import { Route as DashboardRouteImport } from './routes/dashboard'
|
||||||
import { Route as LoginRouteImport } from './routes/login'
|
import { Route as LoginRouteImport } from './routes/login'
|
||||||
|
import { Route as RegionsRouteImport } from './routes/regions'
|
||||||
import { Route as SendNotificationsRouteImport } from './routes/send-notifications'
|
import { Route as SendNotificationsRouteImport } from './routes/send-notifications'
|
||||||
|
import { Route as RegionsNewRouteImport } from './routes/regions.new'
|
||||||
|
import { Route as RegionsIdEditRouteImport } from './routes/regions.$id.edit'
|
||||||
|
|
||||||
const IndexRoute = IndexRouteImport.update({
|
const IndexRoute = IndexRouteImport.update({
|
||||||
id: '/',
|
id: '/',
|
||||||
path: '/',
|
path: '/',
|
||||||
getParentRoute: () => rootRouteImport,
|
getParentRoute: () => rootRouteImport,
|
||||||
} as any)
|
} as any)
|
||||||
|
const AdminsRoute = AdminsRouteImport.update({
|
||||||
|
id: '/admins',
|
||||||
|
path: '/admins',
|
||||||
|
getParentRoute: () => rootRouteImport,
|
||||||
|
} as any)
|
||||||
const ConstantsRoute = ConstantsRouteImport.update({
|
const ConstantsRoute = ConstantsRouteImport.update({
|
||||||
id: '/constants',
|
id: '/constants',
|
||||||
path: '/constants',
|
path: '/constants',
|
||||||
|
|
@ -35,54 +44,104 @@ const LoginRoute = LoginRouteImport.update({
|
||||||
path: '/login',
|
path: '/login',
|
||||||
getParentRoute: () => rootRouteImport,
|
getParentRoute: () => rootRouteImport,
|
||||||
} as any)
|
} as any)
|
||||||
|
const RegionsRoute = RegionsRouteImport.update({
|
||||||
|
id: '/regions',
|
||||||
|
path: '/regions',
|
||||||
|
getParentRoute: () => rootRouteImport,
|
||||||
|
} as any)
|
||||||
const SendNotificationsRoute = SendNotificationsRouteImport.update({
|
const SendNotificationsRoute = SendNotificationsRouteImport.update({
|
||||||
id: '/send-notifications',
|
id: '/send-notifications',
|
||||||
path: '/send-notifications',
|
path: '/send-notifications',
|
||||||
getParentRoute: () => rootRouteImport,
|
getParentRoute: () => rootRouteImport,
|
||||||
} as any)
|
} as any)
|
||||||
|
const RegionsNewRoute = RegionsNewRouteImport.update({
|
||||||
|
id: '/new',
|
||||||
|
path: '/new',
|
||||||
|
getParentRoute: () => RegionsRoute,
|
||||||
|
} as any)
|
||||||
|
const RegionsIdEditRoute = RegionsIdEditRouteImport.update({
|
||||||
|
id: '/$id/edit',
|
||||||
|
path: '/$id/edit',
|
||||||
|
getParentRoute: () => RegionsRoute,
|
||||||
|
} as any)
|
||||||
|
|
||||||
export interface FileRoutesByFullPath {
|
export interface FileRoutesByFullPath {
|
||||||
'/': typeof IndexRoute
|
'/': typeof IndexRoute
|
||||||
|
'/admins': typeof AdminsRoute
|
||||||
'/constants': typeof ConstantsRoute
|
'/constants': typeof ConstantsRoute
|
||||||
'/dashboard': typeof DashboardRoute
|
'/dashboard': typeof DashboardRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
|
'/regions': typeof RegionsRouteWithChildren
|
||||||
'/send-notifications': typeof SendNotificationsRoute
|
'/send-notifications': typeof SendNotificationsRoute
|
||||||
|
'/regions/new': typeof RegionsNewRoute
|
||||||
|
'/regions/$id/edit': typeof RegionsIdEditRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesByTo {
|
export interface FileRoutesByTo {
|
||||||
'/': typeof IndexRoute
|
'/': typeof IndexRoute
|
||||||
|
'/admins': typeof AdminsRoute
|
||||||
'/constants': typeof ConstantsRoute
|
'/constants': typeof ConstantsRoute
|
||||||
'/dashboard': typeof DashboardRoute
|
'/dashboard': typeof DashboardRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
|
'/regions': typeof RegionsRouteWithChildren
|
||||||
'/send-notifications': typeof SendNotificationsRoute
|
'/send-notifications': typeof SendNotificationsRoute
|
||||||
|
'/regions/new': typeof RegionsNewRoute
|
||||||
|
'/regions/$id/edit': typeof RegionsIdEditRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesById {
|
export interface FileRoutesById {
|
||||||
__root__: typeof rootRouteImport
|
__root__: typeof rootRouteImport
|
||||||
'/': typeof IndexRoute
|
'/': typeof IndexRoute
|
||||||
|
'/admins': typeof AdminsRoute
|
||||||
'/constants': typeof ConstantsRoute
|
'/constants': typeof ConstantsRoute
|
||||||
'/dashboard': typeof DashboardRoute
|
'/dashboard': typeof DashboardRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
|
'/regions': typeof RegionsRouteWithChildren
|
||||||
'/send-notifications': typeof SendNotificationsRoute
|
'/send-notifications': typeof SendNotificationsRoute
|
||||||
|
'/regions/new': typeof RegionsNewRoute
|
||||||
|
'/regions/$id/edit': typeof RegionsIdEditRoute
|
||||||
}
|
}
|
||||||
export interface FileRouteTypes {
|
export interface FileRouteTypes {
|
||||||
fileRoutesByFullPath: FileRoutesByFullPath
|
fileRoutesByFullPath: FileRoutesByFullPath
|
||||||
fullPaths:
|
fullPaths:
|
||||||
'/' | '/constants' | '/dashboard' | '/login' | '/send-notifications'
|
|
||||||
fileRoutesByTo: FileRoutesByTo
|
|
||||||
to: '/' | '/constants' | '/dashboard' | '/login' | '/send-notifications'
|
|
||||||
id:
|
|
||||||
| '__root__'
|
|
||||||
| '/'
|
| '/'
|
||||||
|
| '/admins'
|
||||||
| '/constants'
|
| '/constants'
|
||||||
| '/dashboard'
|
| '/dashboard'
|
||||||
| '/login'
|
| '/login'
|
||||||
|
| '/regions'
|
||||||
| '/send-notifications'
|
| '/send-notifications'
|
||||||
|
| '/regions/new'
|
||||||
|
| '/regions/$id/edit'
|
||||||
|
fileRoutesByTo: FileRoutesByTo
|
||||||
|
to:
|
||||||
|
| '/'
|
||||||
|
| '/admins'
|
||||||
|
| '/constants'
|
||||||
|
| '/dashboard'
|
||||||
|
| '/login'
|
||||||
|
| '/regions'
|
||||||
|
| '/send-notifications'
|
||||||
|
| '/regions/new'
|
||||||
|
| '/regions/$id/edit'
|
||||||
|
id:
|
||||||
|
| '__root__'
|
||||||
|
| '/'
|
||||||
|
| '/admins'
|
||||||
|
| '/constants'
|
||||||
|
| '/dashboard'
|
||||||
|
| '/login'
|
||||||
|
| '/regions'
|
||||||
|
| '/send-notifications'
|
||||||
|
| '/regions/new'
|
||||||
|
| '/regions/$id/edit'
|
||||||
fileRoutesById: FileRoutesById
|
fileRoutesById: FileRoutesById
|
||||||
}
|
}
|
||||||
export interface RootRouteChildren {
|
export interface RootRouteChildren {
|
||||||
IndexRoute: typeof IndexRoute
|
IndexRoute: typeof IndexRoute
|
||||||
|
AdminsRoute: typeof AdminsRoute
|
||||||
ConstantsRoute: typeof ConstantsRoute
|
ConstantsRoute: typeof ConstantsRoute
|
||||||
DashboardRoute: typeof DashboardRoute
|
DashboardRoute: typeof DashboardRoute
|
||||||
LoginRoute: typeof LoginRoute
|
LoginRoute: typeof LoginRoute
|
||||||
|
RegionsRoute: typeof RegionsRouteWithChildren
|
||||||
SendNotificationsRoute: typeof SendNotificationsRoute
|
SendNotificationsRoute: typeof SendNotificationsRoute
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -95,6 +154,13 @@ declare module '@tanstack/react-router' {
|
||||||
preLoaderRoute: typeof IndexRouteImport
|
preLoaderRoute: typeof IndexRouteImport
|
||||||
parentRoute: typeof rootRouteImport
|
parentRoute: typeof rootRouteImport
|
||||||
}
|
}
|
||||||
|
'/admins': {
|
||||||
|
id: '/admins'
|
||||||
|
path: '/admins'
|
||||||
|
fullPath: '/admins'
|
||||||
|
preLoaderRoute: typeof AdminsRouteImport
|
||||||
|
parentRoute: typeof rootRouteImport
|
||||||
|
}
|
||||||
'/constants': {
|
'/constants': {
|
||||||
id: '/constants'
|
id: '/constants'
|
||||||
path: '/constants'
|
path: '/constants'
|
||||||
|
|
@ -116,6 +182,13 @@ declare module '@tanstack/react-router' {
|
||||||
preLoaderRoute: typeof LoginRouteImport
|
preLoaderRoute: typeof LoginRouteImport
|
||||||
parentRoute: typeof rootRouteImport
|
parentRoute: typeof rootRouteImport
|
||||||
}
|
}
|
||||||
|
'/regions': {
|
||||||
|
id: '/regions'
|
||||||
|
path: '/regions'
|
||||||
|
fullPath: '/regions'
|
||||||
|
preLoaderRoute: typeof RegionsRouteImport
|
||||||
|
parentRoute: typeof rootRouteImport
|
||||||
|
}
|
||||||
'/send-notifications': {
|
'/send-notifications': {
|
||||||
id: '/send-notifications'
|
id: '/send-notifications'
|
||||||
path: '/send-notifications'
|
path: '/send-notifications'
|
||||||
|
|
@ -123,14 +196,43 @@ declare module '@tanstack/react-router' {
|
||||||
preLoaderRoute: typeof SendNotificationsRouteImport
|
preLoaderRoute: typeof SendNotificationsRouteImport
|
||||||
parentRoute: typeof rootRouteImport
|
parentRoute: typeof rootRouteImport
|
||||||
}
|
}
|
||||||
|
'/regions/new': {
|
||||||
|
id: '/regions/new'
|
||||||
|
path: '/new'
|
||||||
|
fullPath: '/regions/new'
|
||||||
|
preLoaderRoute: typeof RegionsNewRouteImport
|
||||||
|
parentRoute: typeof RegionsRoute
|
||||||
|
}
|
||||||
|
'/regions/$id/edit': {
|
||||||
|
id: '/regions/$id/edit'
|
||||||
|
path: '/$id/edit'
|
||||||
|
fullPath: '/regions/$id/edit'
|
||||||
|
preLoaderRoute: typeof RegionsIdEditRouteImport
|
||||||
|
parentRoute: typeof RegionsRoute
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface RegionsRouteChildren {
|
||||||
|
RegionsNewRoute: typeof RegionsNewRoute
|
||||||
|
RegionsIdEditRoute: typeof RegionsIdEditRoute
|
||||||
|
}
|
||||||
|
|
||||||
|
const RegionsRouteChildren: RegionsRouteChildren = {
|
||||||
|
RegionsNewRoute: RegionsNewRoute,
|
||||||
|
RegionsIdEditRoute: RegionsIdEditRoute,
|
||||||
|
}
|
||||||
|
|
||||||
|
const RegionsRouteWithChildren =
|
||||||
|
RegionsRoute._addFileChildren(RegionsRouteChildren)
|
||||||
|
|
||||||
const rootRouteChildren: RootRouteChildren = {
|
const rootRouteChildren: RootRouteChildren = {
|
||||||
IndexRoute: IndexRoute,
|
IndexRoute: IndexRoute,
|
||||||
|
AdminsRoute: AdminsRoute,
|
||||||
ConstantsRoute: ConstantsRoute,
|
ConstantsRoute: ConstantsRoute,
|
||||||
DashboardRoute: DashboardRoute,
|
DashboardRoute: DashboardRoute,
|
||||||
LoginRoute: LoginRoute,
|
LoginRoute: LoginRoute,
|
||||||
|
RegionsRoute: RegionsRouteWithChildren,
|
||||||
SendNotificationsRoute: SendNotificationsRoute,
|
SendNotificationsRoute: SendNotificationsRoute,
|
||||||
}
|
}
|
||||||
export const routeTree = rootRouteImport
|
export const routeTree = rootRouteImport
|
||||||
|
|
|
||||||
142
apps/superadmin-ui/src/routes/admins.tsx
Normal file
142
apps/superadmin-ui/src/routes/admins.tsx
Normal file
|
|
@ -0,0 +1,142 @@
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
|
import { UserPlus } from 'lucide-react'
|
||||||
|
import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { ProtectedRoute } from '../components/ProtectedRoute'
|
||||||
|
import { AppShell } from '../components/AppShell'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/admins')({
|
||||||
|
component: () => (
|
||||||
|
<ProtectedRoute>
|
||||||
|
<AppShell>
|
||||||
|
<CreateAdmin />
|
||||||
|
</AppShell>
|
||||||
|
</ProtectedRoute>
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
|
function CreateAdmin() {
|
||||||
|
const [name, setName] = useState('')
|
||||||
|
const [password, setPassword] = useState('')
|
||||||
|
const [roleId, setRoleId] = useState<number | ''>('')
|
||||||
|
const [regionId, setRegionId] = useState<number | ''>('')
|
||||||
|
|
||||||
|
const { data: rolesData } = trpc.admin.staffUser.getRoles.useQuery()
|
||||||
|
const { data: regionsData } = trpc.admin.region.getRegions.useQuery()
|
||||||
|
|
||||||
|
const roles = rolesData?.roles ?? []
|
||||||
|
const regions = regionsData?.regions ?? []
|
||||||
|
|
||||||
|
const createStaffUser = trpc.admin.staffUser.createStaffUser.useMutation({
|
||||||
|
onSuccess: (res) => {
|
||||||
|
window.alert('Success\n\nAdmin created successfully.')
|
||||||
|
setName('')
|
||||||
|
setPassword('')
|
||||||
|
setRoleId('')
|
||||||
|
setRegionId('')
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
window.alert(`Error\n\n${err.message || 'Failed to create admin'}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const handleSubmit = () => {
|
||||||
|
if (!name.trim()) {
|
||||||
|
window.alert('Validation\n\nName is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (password.length < 6) {
|
||||||
|
window.alert('Validation\n\nPassword must be at least 6 characters.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!roleId) {
|
||||||
|
window.alert('Validation\n\nRole is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!regionId) {
|
||||||
|
window.alert('Validation\n\nRegion is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
createStaffUser.mutate({
|
||||||
|
name: name.trim(),
|
||||||
|
password,
|
||||||
|
roleId: Number(roleId),
|
||||||
|
regionId: Number(regionId),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="bg-gray-50 p-4">
|
||||||
|
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Create Admin</MyText>
|
||||||
|
<MyText className="mb-6 block text-gray-600">
|
||||||
|
Create a staff user and assign them to a region.
|
||||||
|
</MyText>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<PInput
|
||||||
|
topLabel="Name"
|
||||||
|
placeholder="e.g. ravi"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<PInput
|
||||||
|
topLabel="Password"
|
||||||
|
placeholder="At least 6 characters"
|
||||||
|
value={password}
|
||||||
|
type="password"
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<MyText className="mb-1 block text-sm font-medium text-gray-700">Role</MyText>
|
||||||
|
<select
|
||||||
|
value={roleId}
|
||||||
|
onChange={(e) => setRoleId(e.target.value ? Number(e.target.value) : '')}
|
||||||
|
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
||||||
|
>
|
||||||
|
<option value="">Select a role</option>
|
||||||
|
{roles.map((role) => (
|
||||||
|
<option key={role.id} value={role.id}>
|
||||||
|
{role.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-6">
|
||||||
|
<MyText className="mb-1 block text-sm font-medium text-gray-700">Region</MyText>
|
||||||
|
<select
|
||||||
|
value={regionId}
|
||||||
|
onChange={(e) => setRegionId(e.target.value ? Number(e.target.value) : '')}
|
||||||
|
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900"
|
||||||
|
>
|
||||||
|
<option value="">Select a region</option>
|
||||||
|
{regions.map((region) => (
|
||||||
|
<option key={region.id} value={region.id}>
|
||||||
|
{region.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<MyButton
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={createStaffUser.isPending}
|
||||||
|
fullWidth
|
||||||
|
className={`flex items-center justify-center gap-2 rounded-lg bg-blue-600 p-4 text-base text-white hover:bg-blue-700 ${
|
||||||
|
createStaffUser.isPending ? 'opacity-50' : ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<UserPlus className="h-4 w-4" />
|
||||||
|
{createStaffUser.isPending ? 'Creating...' : 'Create Admin'}
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||||
import { AppContainer, p as MyText } from 'web-components'
|
import { AppContainer, p as MyText } from 'web-components'
|
||||||
import { Send, Settings2, ChevronRight } from 'lucide-react'
|
import { Send, Settings2, MapPin, UserPlus, ChevronRight } from 'lucide-react'
|
||||||
import { ProtectedRoute } from '../components/ProtectedRoute'
|
import { ProtectedRoute } from '../components/ProtectedRoute'
|
||||||
import { AppShell } from '../components/AppShell'
|
import { AppShell } from '../components/AppShell'
|
||||||
|
|
||||||
|
|
@ -15,6 +15,18 @@ export const Route = createFileRoute('/dashboard')({
|
||||||
})
|
})
|
||||||
|
|
||||||
const CARDS = [
|
const CARDS = [
|
||||||
|
{
|
||||||
|
to: '/admins',
|
||||||
|
title: 'Create Admin',
|
||||||
|
description: 'Create a staff user and assign them to a region.',
|
||||||
|
icon: UserPlus,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
to: '/regions',
|
||||||
|
title: 'Regions',
|
||||||
|
description: 'Create regions and attach delivery bounding polygons.',
|
||||||
|
icon: MapPin,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
to: '/send-notifications',
|
to: '/send-notifications',
|
||||||
title: 'Send Admin Notifications',
|
title: 'Send Admin Notifications',
|
||||||
|
|
|
||||||
234
apps/superadmin-ui/src/routes/regions.$id.edit.tsx
Normal file
234
apps/superadmin-ui/src/routes/regions.$id.edit.tsx
Normal file
|
|
@ -0,0 +1,234 @@
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { createFileRoute, useNavigate, useParams } from '@tanstack/react-router'
|
||||||
|
import { Plus, Trash2, ArrowLeft } from 'lucide-react'
|
||||||
|
import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/regions/$id/edit')({
|
||||||
|
component: EditRegion,
|
||||||
|
})
|
||||||
|
|
||||||
|
function EditRegion() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const { id } = useParams({ from: '/regions/$id/edit' })
|
||||||
|
const regionId = Number(id)
|
||||||
|
|
||||||
|
const [name, setName] = useState('')
|
||||||
|
const [description, setDescription] = useState('')
|
||||||
|
const [bounds, setBounds] = useState<
|
||||||
|
{ id?: number; geojson: string; name: string; description: string; priority: number }[]
|
||||||
|
>([])
|
||||||
|
const [hydrated, setHydrated] = useState(false)
|
||||||
|
|
||||||
|
const { data, isLoading, error } = trpc.admin.region.getRegionById.useQuery(
|
||||||
|
{ id: regionId },
|
||||||
|
{ enabled: Number.isFinite(regionId) }
|
||||||
|
)
|
||||||
|
|
||||||
|
const updateRegion = trpc.admin.region.updateRegion.useMutation({
|
||||||
|
onSuccess: () => {
|
||||||
|
navigate({ to: '/regions' })
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
window.alert(`Error\n\n${err.message || 'Failed to update region'}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (data?.region && !hydrated) {
|
||||||
|
setName(data.region.name)
|
||||||
|
setDescription(data.region.description ?? '')
|
||||||
|
setBounds(
|
||||||
|
data.region.bounds.length > 0
|
||||||
|
? data.region.bounds.map((b) => ({
|
||||||
|
id: b.id,
|
||||||
|
geojson: b.geojson,
|
||||||
|
name: b.name ?? '',
|
||||||
|
description: b.description ?? '',
|
||||||
|
priority: b.priority ?? 0,
|
||||||
|
}))
|
||||||
|
: [{ geojson: '', name: '', description: '', priority: 1 }]
|
||||||
|
)
|
||||||
|
setHydrated(true)
|
||||||
|
}
|
||||||
|
}, [data, hydrated])
|
||||||
|
|
||||||
|
const updateBound = (index: number, field: 'geojson' | 'name' | 'description' | 'priority', value: string | number) => {
|
||||||
|
setBounds((prev) => prev.map((b, i) => (i === index ? { ...b, [field]: value } : b)))
|
||||||
|
}
|
||||||
|
|
||||||
|
const addBound = () =>
|
||||||
|
setBounds((prev) => [
|
||||||
|
...prev,
|
||||||
|
{
|
||||||
|
geojson: '',
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
priority: Math.max(0, ...prev.map((b) => b.priority)) + 1,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
const removeBound = (index: number) =>
|
||||||
|
setBounds((prev) => prev.filter((_, i) => i !== index))
|
||||||
|
|
||||||
|
const handleSubmit = () => {
|
||||||
|
if (!name.trim()) {
|
||||||
|
window.alert('Validation\n\nName is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const cleanedBounds = bounds
|
||||||
|
.map((b) => ({
|
||||||
|
...(b.id != null ? { id: b.id } : {}),
|
||||||
|
geojson: b.geojson.trim(),
|
||||||
|
name: b.name.trim(),
|
||||||
|
description: b.description.trim(),
|
||||||
|
priority: Number(b.priority) || 0,
|
||||||
|
}))
|
||||||
|
.filter((b) => b.geojson.length > 0)
|
||||||
|
for (const bound of cleanedBounds) {
|
||||||
|
if (!bound.name || !bound.description) {
|
||||||
|
window.alert('Validation\n\nEvery bound needs a name and a description.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const priorities = cleanedBounds.map((b) => b.priority)
|
||||||
|
if (new Set(priorities).size !== priorities.length) {
|
||||||
|
window.alert('Validation\n\nBound priorities must be unique within a region.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
updateRegion.mutate({
|
||||||
|
id: regionId,
|
||||||
|
name: name.trim(),
|
||||||
|
description: description.trim() || null,
|
||||||
|
bounds: cleanedBounds,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<MyText className="block py-8 text-center text-gray-500">Loading region...</MyText>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<MyText className="block py-8 text-center text-red-600">Error loading region</MyText>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="bg-gray-50 p-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => navigate({ to: '/regions' })}
|
||||||
|
className="mb-4 flex items-center gap-1.5 text-sm font-medium text-gray-600 hover:text-gray-900"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4" />
|
||||||
|
Back to Regions
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Edit Region</MyText>
|
||||||
|
<MyText className="mb-6 block text-gray-600">
|
||||||
|
Update the region details and its bounding GeoJSONs.
|
||||||
|
</MyText>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<PInput
|
||||||
|
topLabel="Name"
|
||||||
|
placeholder="e.g. Mahabubnagar Town"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-6">
|
||||||
|
<PInput
|
||||||
|
topLabel="Description"
|
||||||
|
placeholder="Optional description"
|
||||||
|
value={description}
|
||||||
|
multiline
|
||||||
|
numberOfLines={3}
|
||||||
|
onChange={(e) => setDescription(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-2 flex items-center justify-between">
|
||||||
|
<MyText className="block text-sm font-semibold text-gray-700">
|
||||||
|
Bounds (GeoJSON)
|
||||||
|
</MyText>
|
||||||
|
<MyButton
|
||||||
|
onClick={addBound}
|
||||||
|
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
Add Bound
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{bounds.map((bound, index) => (
|
||||||
|
<div key={bound.id ?? `new-${index}`} className="mb-3 rounded-lg border border-gray-200 p-3">
|
||||||
|
<div className="mb-1 flex items-center justify-between">
|
||||||
|
<MyText className="block text-xs font-medium text-gray-500">
|
||||||
|
Bound {index + 1}
|
||||||
|
</MyText>
|
||||||
|
{bounds.length > 1 && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => removeBound(index)}
|
||||||
|
className="flex items-center gap-1 text-xs font-medium text-red-600 hover:text-red-700"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mb-2 grid grid-cols-2 gap-2">
|
||||||
|
<PInput
|
||||||
|
topLabel="Name (required)"
|
||||||
|
placeholder="e.g. Mbnr-1"
|
||||||
|
value={bound.name}
|
||||||
|
onChange={(e) => updateBound(index, 'name', e.target.value)}
|
||||||
|
/>
|
||||||
|
<PInput
|
||||||
|
topLabel="Priority"
|
||||||
|
placeholder="e.g. 1"
|
||||||
|
value={String(bound.priority)}
|
||||||
|
onChange={(e) => updateBound(index, 'priority', Number(e.target.value) || 0)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="mb-2">
|
||||||
|
<PInput
|
||||||
|
topLabel="Description (required)"
|
||||||
|
placeholder="e.g. Town core coverage area"
|
||||||
|
value={bound.description}
|
||||||
|
onChange={(e) => updateBound(index, 'description', e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<PInput
|
||||||
|
placeholder='Paste GeoJSON, e.g. {"type":"Polygon","coordinates":[...]}'
|
||||||
|
value={bound.geojson}
|
||||||
|
multiline
|
||||||
|
numberOfLines={6}
|
||||||
|
onChange={(e) => updateBound(index, 'geojson', e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<MyButton
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={updateRegion.isPending}
|
||||||
|
fullWidth
|
||||||
|
className={`mt-6 rounded-lg bg-blue-600 p-4 text-base text-white hover:bg-blue-700 ${
|
||||||
|
updateRegion.isPending ? 'opacity-50' : ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{updateRegion.isPending ? 'Saving...' : 'Save Changes'}
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
259
apps/superadmin-ui/src/routes/regions.new.tsx
Normal file
259
apps/superadmin-ui/src/routes/regions.new.tsx
Normal file
|
|
@ -0,0 +1,259 @@
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||||
|
import { Plus, Trash2, ArrowLeft } from 'lucide-react'
|
||||||
|
import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/regions/new')({
|
||||||
|
component: NewRegion,
|
||||||
|
})
|
||||||
|
|
||||||
|
function NewRegion() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const [name, setName] = useState('')
|
||||||
|
const [description, setDescription] = useState('')
|
||||||
|
const [bounds, setBounds] = useState<
|
||||||
|
{ geojson: string; name: string; description: string; priority: number }[]
|
||||||
|
>([{ geojson: '', name: '', description: '', priority: 1 }])
|
||||||
|
const [creds, setCreds] = useState<{ botToken: string; chatId: string }[]>([
|
||||||
|
{ botToken: '', chatId: '' },
|
||||||
|
])
|
||||||
|
|
||||||
|
const createRegion = trpc.admin.region.createRegion.useMutation({
|
||||||
|
onSuccess: () => {
|
||||||
|
navigate({ to: '/regions' })
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
window.alert(`Error\n\n${err.message || 'Failed to create region'}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const updateBound = (index: number, field: 'geojson' | 'name' | 'description' | 'priority', value: string | number) => {
|
||||||
|
setBounds((prev) => prev.map((b, i) => (i === index ? { ...b, [field]: value } : b)))
|
||||||
|
}
|
||||||
|
|
||||||
|
const addBound = () =>
|
||||||
|
setBounds((prev) => [
|
||||||
|
...prev,
|
||||||
|
{
|
||||||
|
geojson: '',
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
priority: Math.max(0, ...prev.map((b) => b.priority)) + 1,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
const removeBound = (index: number) =>
|
||||||
|
setBounds((prev) => prev.filter((_, i) => i !== index))
|
||||||
|
|
||||||
|
const updateCred = (index: number, field: 'botToken' | 'chatId', value: string) => {
|
||||||
|
setCreds((prev) => prev.map((c, i) => (i === index ? { ...c, [field]: value } : c)))
|
||||||
|
}
|
||||||
|
|
||||||
|
const addCred = () => setCreds((prev) => [...prev, { botToken: '', chatId: '' }])
|
||||||
|
const removeCred = (index: number) =>
|
||||||
|
setCreds((prev) => (prev.length > 1 ? prev.filter((_, i) => i !== index) : prev))
|
||||||
|
|
||||||
|
const handleSubmit = () => {
|
||||||
|
if (!name.trim()) {
|
||||||
|
window.alert('Validation\n\nName is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const cleanedCreds = creds
|
||||||
|
.map((c) => ({ botToken: c.botToken.trim(), chatId: c.chatId.trim() }))
|
||||||
|
.filter((c) => c.botToken.length > 0 || c.chatId.length > 0)
|
||||||
|
if (cleanedCreds.length === 0) {
|
||||||
|
window.alert('Validation\n\nAt least one Telegram cred (bot token + chat ID) is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const incomplete = cleanedCreds.find((c) => c.botToken.length === 0 || c.chatId.length === 0)
|
||||||
|
if (incomplete) {
|
||||||
|
window.alert('Validation\n\nEvery Telegram cred needs both a bot token and a chat ID.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const cleanedBounds = bounds
|
||||||
|
.map((b) => ({
|
||||||
|
geojson: b.geojson.trim(),
|
||||||
|
name: b.name.trim(),
|
||||||
|
description: b.description.trim(),
|
||||||
|
priority: Number(b.priority) || 0,
|
||||||
|
}))
|
||||||
|
.filter((b) => b.geojson.length > 0)
|
||||||
|
for (const bound of cleanedBounds) {
|
||||||
|
if (!bound.name || !bound.description) {
|
||||||
|
window.alert('Validation\n\nEvery bound needs a name and a description.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const priorities = cleanedBounds.map((b) => b.priority)
|
||||||
|
if (new Set(priorities).size !== priorities.length) {
|
||||||
|
window.alert('Validation\n\nBound priorities must be unique within a region.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
createRegion.mutate({
|
||||||
|
name: name.trim(),
|
||||||
|
description: description.trim() || null,
|
||||||
|
bounds: cleanedBounds,
|
||||||
|
creds: cleanedCreds,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="bg-gray-50 p-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => navigate({ to: '/regions' })}
|
||||||
|
className="mb-4 flex items-center gap-1.5 text-sm font-medium text-gray-600 hover:text-gray-900"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4" />
|
||||||
|
Back to Regions
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Add Region</MyText>
|
||||||
|
<MyText className="mb-6 block text-gray-600">
|
||||||
|
A region needs a name and can have any number of bounding GeoJSONs.
|
||||||
|
</MyText>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<PInput
|
||||||
|
topLabel="Name"
|
||||||
|
placeholder="e.g. Mahabubnagar Town"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-6">
|
||||||
|
<PInput
|
||||||
|
topLabel="Description"
|
||||||
|
placeholder="Optional description"
|
||||||
|
value={description}
|
||||||
|
multiline
|
||||||
|
numberOfLines={3}
|
||||||
|
onChange={(e) => setDescription(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-2 flex items-center justify-between">
|
||||||
|
<MyText className="block text-sm font-semibold text-gray-700">
|
||||||
|
Bounds (GeoJSON)
|
||||||
|
</MyText>
|
||||||
|
<MyButton
|
||||||
|
onClick={addBound}
|
||||||
|
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
Add Bound
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{bounds.map((bound, index) => (
|
||||||
|
<div key={index} className="mb-3 rounded-lg border border-gray-200 p-3">
|
||||||
|
<div className="mb-1 flex items-center justify-between">
|
||||||
|
<MyText className="block text-xs font-medium text-gray-500">
|
||||||
|
Bound {index + 1}
|
||||||
|
</MyText>
|
||||||
|
{bounds.length > 1 && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => removeBound(index)}
|
||||||
|
className="flex items-center gap-1 text-xs font-medium text-red-600 hover:text-red-700"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mb-2 grid grid-cols-2 gap-2">
|
||||||
|
<PInput
|
||||||
|
topLabel="Name (required)"
|
||||||
|
placeholder="e.g. Mbnr-1"
|
||||||
|
value={bound.name}
|
||||||
|
onChange={(e) => updateBound(index, 'name', e.target.value)}
|
||||||
|
/>
|
||||||
|
<PInput
|
||||||
|
topLabel="Priority"
|
||||||
|
placeholder="e.g. 1"
|
||||||
|
value={String(bound.priority)}
|
||||||
|
onChange={(e) => updateBound(index, 'priority', Number(e.target.value) || 0)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="mb-2">
|
||||||
|
<PInput
|
||||||
|
topLabel="Description (required)"
|
||||||
|
placeholder="e.g. Town core coverage area"
|
||||||
|
value={bound.description}
|
||||||
|
onChange={(e) => updateBound(index, 'description', e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<PInput
|
||||||
|
placeholder='Paste GeoJSON, e.g. {"type":"Polygon","coordinates":[...]}'
|
||||||
|
value={bound.geojson}
|
||||||
|
multiline
|
||||||
|
numberOfLines={6}
|
||||||
|
onChange={(e) => updateBound(index, 'geojson', e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<div className="mb-2 mt-6 flex items-center justify-between">
|
||||||
|
<MyText className="block text-sm font-semibold text-gray-700">
|
||||||
|
Telegram Creds (at least 1 required)
|
||||||
|
</MyText>
|
||||||
|
<MyButton
|
||||||
|
onClick={addCred}
|
||||||
|
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
Add Cred
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{creds.map((cred, index) => (
|
||||||
|
<div key={index} className="mb-3 rounded-lg border border-gray-200 p-3">
|
||||||
|
<div className="mb-2 flex items-center justify-between">
|
||||||
|
<MyText className="block text-xs font-medium text-gray-500">
|
||||||
|
Cred {index + 1}
|
||||||
|
</MyText>
|
||||||
|
{creds.length > 1 && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => removeCred(index)}
|
||||||
|
className="flex items-center gap-1 text-xs font-medium text-red-600 hover:text-red-700"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mb-2">
|
||||||
|
<PInput
|
||||||
|
topLabel="Bot Token"
|
||||||
|
placeholder="e.g. 123456:ABC-DEF..."
|
||||||
|
value={cred.botToken}
|
||||||
|
onChange={(e) => updateCred(index, 'botToken', e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<PInput
|
||||||
|
topLabel="Chat ID"
|
||||||
|
placeholder="e.g. 5147760058 or -1001234567890"
|
||||||
|
value={cred.chatId}
|
||||||
|
onChange={(e) => updateCred(index, 'chatId', e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<MyButton
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={createRegion.isPending}
|
||||||
|
fullWidth
|
||||||
|
className={`mt-6 rounded-lg bg-blue-600 p-4 text-base text-white hover:bg-blue-700 ${
|
||||||
|
createRegion.isPending ? 'opacity-50' : ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{createRegion.isPending ? 'Creating...' : 'Create Region'}
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
130
apps/superadmin-ui/src/routes/regions.tsx
Normal file
130
apps/superadmin-ui/src/routes/regions.tsx
Normal file
|
|
@ -0,0 +1,130 @@
|
||||||
|
import { createFileRoute, Link, Outlet, useLocation, useNavigate } from '@tanstack/react-router'
|
||||||
|
import { MapPin, Pencil, Plus } from 'lucide-react'
|
||||||
|
import { AppContainer, MyButton, p as MyText } from 'web-components'
|
||||||
|
import { trpc } from '../lib/trpc-client'
|
||||||
|
import { ProtectedRoute } from '../components/ProtectedRoute'
|
||||||
|
import { AppShell } from '../components/AppShell'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/regions')({
|
||||||
|
component: () => (
|
||||||
|
<ProtectedRoute>
|
||||||
|
<AppShell>
|
||||||
|
<Regions />
|
||||||
|
</AppShell>
|
||||||
|
</ProtectedRoute>
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
|
function formatDate(value: string | Date) {
|
||||||
|
const date = value instanceof Date ? value : new Date(value)
|
||||||
|
if (isNaN(date.getTime())) return '—'
|
||||||
|
return date.toLocaleString()
|
||||||
|
}
|
||||||
|
|
||||||
|
// This route is the layout for /regions plus its children
|
||||||
|
// (/regions/new and /regions/$id/edit). Render the list only on the exact
|
||||||
|
// /regions path; otherwise hand off to the child route.
|
||||||
|
function Regions() {
|
||||||
|
const location = useLocation()
|
||||||
|
|
||||||
|
if (location.pathname !== '/regions') {
|
||||||
|
return <Outlet />
|
||||||
|
}
|
||||||
|
|
||||||
|
return <RegionsList />
|
||||||
|
}
|
||||||
|
|
||||||
|
function RegionsList() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
|
const { data, isLoading, error, refetch } = trpc.admin.region.getRegions.useQuery()
|
||||||
|
|
||||||
|
const regions = data?.regions ?? []
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="bg-gray-50 p-4">
|
||||||
|
<div className="mb-6 flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Regions</MyText>
|
||||||
|
<MyText className="block text-gray-600">
|
||||||
|
Group delivery areas and attach one or more bounding GeoJSONs.
|
||||||
|
</MyText>
|
||||||
|
</div>
|
||||||
|
<MyButton
|
||||||
|
onClick={() => navigate({ to: '/regions/new' })}
|
||||||
|
className="flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2.5 text-white hover:bg-blue-700"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
Add Region
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isLoading && (
|
||||||
|
<MyText className="block py-8 text-center text-gray-500">Loading regions...</MyText>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="flex flex-col items-center py-8">
|
||||||
|
<MyText className="mb-4 block text-red-600">Error loading regions</MyText>
|
||||||
|
<MyButton
|
||||||
|
onClick={() => refetch()}
|
||||||
|
className="rounded-lg bg-blue-500 px-4 py-2 text-white"
|
||||||
|
>
|
||||||
|
Retry
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isLoading && !error && regions.length === 0 && (
|
||||||
|
<div className="flex flex-col items-center rounded-xl border border-dashed border-gray-300 bg-white py-12">
|
||||||
|
<MapPin className="mb-3 h-8 w-8 text-gray-400" />
|
||||||
|
<MyText className="block text-gray-600">No regions yet.</MyText>
|
||||||
|
<MyText className="block text-sm text-gray-400">
|
||||||
|
Click "Add Region" to create your first one.
|
||||||
|
</MyText>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
{regions.map((region) => (
|
||||||
|
<div
|
||||||
|
key={region.id}
|
||||||
|
className="flex flex-col rounded-xl border border-gray-200 bg-white p-5 shadow-sm"
|
||||||
|
>
|
||||||
|
<div className="mb-1 flex items-start gap-3">
|
||||||
|
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-blue-50">
|
||||||
|
<MapPin className="h-5 w-5 text-blue-600" />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<MyText className="block truncate font-semibold text-gray-900">
|
||||||
|
{region.name}
|
||||||
|
</MyText>
|
||||||
|
<MyText className="block text-sm text-gray-500">
|
||||||
|
{region.description || 'No description'}
|
||||||
|
</MyText>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4 mt-2 text-xs text-gray-400">
|
||||||
|
{region.bounds.length} bound{region.bounds.length === 1 ? '' : 's'} · added{' '}
|
||||||
|
{formatDate(region.addedAt)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-auto flex gap-2">
|
||||||
|
<Link
|
||||||
|
to="/regions/$id/edit"
|
||||||
|
params={{ id: String(region.id) }}
|
||||||
|
className="flex flex-1 items-center justify-center gap-2 rounded-lg border border-gray-200 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
<Pencil className="h-4 w-4" />
|
||||||
|
Edit
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import React, { useState, useCallback, useMemo, memo, useRef, useEffect } from "react";
|
import React, { useState, useCallback, useMemo, memo, useRef, useEffect } from "react";
|
||||||
import { View, Dimensions, Image, RefreshControl } from "react-native";
|
import { View, Dimensions, Image, RefreshControl, Animated } from "react-native";
|
||||||
import { ScrollView } from "react-native-gesture-handler";
|
import { ScrollView } from "react-native-gesture-handler";
|
||||||
import { useRouter } from "expo-router";
|
import { useRouter } from "expo-router";
|
||||||
import {
|
import {
|
||||||
|
|
@ -27,6 +27,7 @@ import { useCentralSlotStore } from "@/src/store/centralSlotStore";
|
||||||
import { useCentralProductStore } from "@/src/store/centralProductStore";
|
import { useCentralProductStore } from "@/src/store/centralProductStore";
|
||||||
import FloatingCartBar from "@/components/floating-cart-bar";
|
import FloatingCartBar from "@/components/floating-cart-bar";
|
||||||
import { useUserDetails } from "@/src/contexts/AuthContext";
|
import { useUserDetails } from "@/src/contexts/AuthContext";
|
||||||
|
import RegionBar from "@/components/RegionBar";
|
||||||
import TabLayoutWrapper from "@/components/TabLayoutWrapper";
|
import TabLayoutWrapper from "@/components/TabLayoutWrapper";
|
||||||
import { useNavigationStore } from "@/src/store/navigationStore";
|
import { useNavigationStore } from "@/src/store/navigationStore";
|
||||||
import NextOrderGlimpse from "@/components/NextOrderGlimpse";
|
import NextOrderGlimpse from "@/components/NextOrderGlimpse";
|
||||||
|
|
@ -501,6 +502,7 @@ export default function Dashboard() {
|
||||||
const refetchProducts = useCentralProductStore((state) => state.refetchProducts);
|
const refetchProducts = useCentralProductStore((state) => state.refetchProducts);
|
||||||
const refetchSlotsFromStore = useCentralSlotStore((state) => state.refetchSlots);
|
const refetchSlotsFromStore = useCentralSlotStore((state) => state.refetchSlots);
|
||||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||||
|
const scrollY = useRef(new Animated.Value(0)).current;
|
||||||
|
|
||||||
const {
|
const {
|
||||||
data: productsData,
|
data: productsData,
|
||||||
|
|
@ -694,6 +696,7 @@ export default function Dashboard() {
|
||||||
return (
|
return (
|
||||||
<TabLayoutWrapper style={{ backgroundColor: '#FFFFFF' }}>
|
<TabLayoutWrapper style={{ backgroundColor: '#FFFFFF' }}>
|
||||||
<View style={pageTintStyle}>
|
<View style={pageTintStyle}>
|
||||||
|
<RegionBar scrollY={scrollY} testID="home-region-bar" />
|
||||||
<View
|
<View
|
||||||
style={searchBarContainerStyle}
|
style={searchBarContainerStyle}
|
||||||
>
|
>
|
||||||
|
|
@ -749,6 +752,11 @@ export default function Dashboard() {
|
||||||
<MyText style={tw`text-gray-500`}>No products available</MyText>
|
<MyText style={tw`text-gray-500`}>No products available</MyText>
|
||||||
</View>
|
</View>
|
||||||
}
|
}
|
||||||
|
onScroll={Animated.event(
|
||||||
|
[{ nativeEvent: { contentOffset: { y: scrollY } } }],
|
||||||
|
{ useNativeDriver: false }
|
||||||
|
)}
|
||||||
|
scrollEventThrottle={16}
|
||||||
// NOTE: do not add removeClippedSubviews here - it breaks touch
|
// NOTE: do not add removeClippedSubviews here - it breaks touch
|
||||||
// delivery to the nested horizontal scrollables in ListHeaderComponent
|
// delivery to the nested horizontal scrollables in ListHeaderComponent
|
||||||
// (tag tabs / slots) on Android.
|
// (tag tabs / slots) on Android.
|
||||||
|
|
|
||||||
|
|
@ -258,6 +258,7 @@ export default function Addresses() {
|
||||||
latitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.latitude ?? undefined),
|
latitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.latitude ?? undefined),
|
||||||
longitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.longitude ?? undefined),
|
longitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.longitude ?? undefined),
|
||||||
googleMapsUrl: editingAddress.googleMapsUrl ?? undefined,
|
googleMapsUrl: editingAddress.googleMapsUrl ?? undefined,
|
||||||
|
regionId: (editingAddress as { regionId?: number }).regionId ?? undefined,
|
||||||
} : undefined}
|
} : undefined}
|
||||||
isEdit={!!editingAddress}
|
isEdit={!!editingAddress}
|
||||||
/>
|
/>
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,10 @@
|
||||||
import React from 'react';
|
import React, { useRef } from 'react';
|
||||||
import { View, ScrollView } from 'react-native';
|
import { Animated, View, ScrollView } from 'react-native';
|
||||||
import { useRouter } from 'expo-router';
|
import { useRouter } from 'expo-router';
|
||||||
import { useFocusEffect } from '@react-navigation/native';
|
import { useFocusEffect } from '@react-navigation/native';
|
||||||
import { AppContainer, MyText, tw, MyTouchableOpacity, ProfileImage, colors } from 'common-ui';
|
import { AppContainer, MyText, tw, MyTouchableOpacity, ProfileImage, colors } from 'common-ui';
|
||||||
import TabLayoutWrapper from '@/components/TabLayoutWrapper';
|
import TabLayoutWrapper from '@/components/TabLayoutWrapper';
|
||||||
|
import RegionBar from '@/components/RegionBar';
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
import { LinearGradient } from 'expo-linear-gradient';
|
||||||
import { Ionicons } from '@expo/vector-icons';
|
import { Ionicons } from '@expo/vector-icons';
|
||||||
import NextOrderGlimpse from '@/components/NextOrderGlimpse';
|
import NextOrderGlimpse from '@/components/NextOrderGlimpse';
|
||||||
|
|
@ -12,6 +13,7 @@ import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget';
|
||||||
|
|
||||||
export default function Me() {
|
export default function Me() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const scrollY = useRef(new Animated.Value(0)).current;
|
||||||
const { logout } = useAuth();
|
const { logout } = useAuth();
|
||||||
const { getNavigationTarget } = useNavigationTarget();
|
const { getNavigationTarget } = useNavigationTarget();
|
||||||
|
|
||||||
|
|
@ -93,10 +95,16 @@ export default function Me() {
|
||||||
return (
|
return (
|
||||||
<TabLayoutWrapper>
|
<TabLayoutWrapper>
|
||||||
<View style={tw`flex-1 bg-gray-50`}>
|
<View style={tw`flex-1 bg-gray-50`}>
|
||||||
|
<RegionBar scrollY={scrollY} testID="me-region-bar" />
|
||||||
<ScrollView
|
<ScrollView
|
||||||
style={tw`flex-1`}
|
style={tw`flex-1`}
|
||||||
showsVerticalScrollIndicator={false}
|
showsVerticalScrollIndicator={false}
|
||||||
contentContainerStyle={tw`pb-8`}
|
contentContainerStyle={tw`pb-8`}
|
||||||
|
onScroll={Animated.event(
|
||||||
|
[{ nativeEvent: { contentOffset: { y: scrollY } } }],
|
||||||
|
{ useNativeDriver: false }
|
||||||
|
)}
|
||||||
|
scrollEventThrottle={16}
|
||||||
>
|
>
|
||||||
{/* Minimal Header Section */}
|
{/* Minimal Header Section */}
|
||||||
<View style={tw`px-6 pt-8 pb-10 flex-row items-center justify-between`}>
|
<View style={tw`px-6 pt-8 pb-10 flex-row items-center justify-between`}>
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue