This commit is contained in:
shafi54 2026-10-14 00:10:07 +05:30
parent 0838038fad
commit 934b9f4caf
15 changed files with 427 additions and 133 deletions

View file

@ -0,0 +1,35 @@
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import { ApiError } from '@/src/lib/api-error'
import { scaffoldAssetUrl } from '@/src/lib/s3-client'
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
import { listRegionStores, elevateStoreToGlobal } from '@/src/dbService'
const withImageUrl = (store: any) => ({
...store,
imageUrl: store.imageUrl ? scaffoldAssetUrl(store.imageUrl) : null,
})
export const superadminStoresRouter = router({
// Stores owned by one region. Global stores live in superadmin.globalStores.
list: superadminProcedure
.input(z.object({ regionId: z.number().int().positive() }))
.query(async ({ input }) => {
const stores = await listRegionStores(input.regionId)
return stores.map(withImageUrl)
}),
// Elevate a regional store to global (its products are left untouched).
elevate: superadminProcedure
.input(z.object({ storeId: z.number().int().positive() }))
.mutation(async ({ input }) => {
let store
try {
store = await elevateStoreToGlobal(input.storeId)
} catch (e: any) {
throw new ApiError(e.message || 'Failed to elevate store', 400)
}
await scheduleStoreInitialization()
return { store: withImageUrl(store), message: 'Store elevated to global successfully' }
}),
})

View file

@ -4,6 +4,7 @@ import { superadminRegionsRouter } from '@/src/trpc/apis/superadmin-apis/apis/re
import { superadminStaffRouter } from '@/src/trpc/apis/superadmin-apis/apis/staff'
import { superadminConstRouter } from '@/src/trpc/apis/superadmin-apis/apis/const'
import { superadminGlobalStoresRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-stores'
import { superadminStoresRouter } from '@/src/trpc/apis/superadmin-apis/apis/stores'
import { superadminGlobalProductsRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-products'
import { superadminProductsRouter } from '@/src/trpc/apis/superadmin-apis/apis/products'
import { superadminGlobalCouponsRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-coupons'
@ -14,6 +15,7 @@ export const superadminRouter = router({
staff: superadminStaffRouter,
const: superadminConstRouter,
globalStores: superadminGlobalStoresRouter,
stores: superadminStoresRouter,
globalProducts: superadminGlobalProductsRouter,
globalCoupons: superadminGlobalCouponsRouter,
products: superadminProductsRouter,

View file

@ -6,10 +6,10 @@ import { useAuth } from '../lib/auth-context'
const NAV = [
{ to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
{ to: '/regions', label: 'Regions', icon: Map },
{ to: '/global-stores', label: 'Global Stores', icon: Store },
{ to: '/global-products', label: 'Global Products', icon: Package },
{ to: '/global-stores', label: 'Stores', icon: Store },
{ to: '/global-products', label: 'Products', icon: Package },
{ to: '/staff', label: 'Admin Users', icon: UserCog },
{ to: '/send-notifications', label: 'Send Admin Notifications', icon: Send },
{ to: '/send-notifications', label: 'Admin Notifs', icon: Send },
{ to: '/constants', label: 'App Constants', icon: Settings2 },
] as const
@ -80,7 +80,7 @@ export function AppShell({ children }: { children: React.ReactNode }) {
/>
)}
<main className="min-h-[calc(100vh-3.5rem)] flex-1">{children}</main>
<main className="min-h-[calc(100vh-3.5rem)] min-w-0 flex-1">{children}</main>
</div>
</div>
)

View file

@ -0,0 +1,45 @@
import React from 'react'
import { p as MyText } from 'web-components'
/** `'global'` for the shared catalogue, otherwise the region id. */
export type RegionTabKey = 'global' | number
interface RegionTabsProps {
regions: { id: number; name: string }[]
value: RegionTabKey
onChange: (value: RegionTabKey) => void
}
/**
* Tab bar shared by the Products and Stores pages: the Global tab first, then
* one tab per region.
*/
export function RegionTabs({ regions, value, onChange }: RegionTabsProps) {
const tabClass = (active: boolean) =>
`shrink-0 whitespace-nowrap rounded-lg px-4 py-2 text-sm font-semibold ${
active ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
}`
return (
<div className="mb-4 flex gap-2 overflow-x-auto pb-1">
<button type="button" onClick={() => onChange('global')} className={tabClass(value === 'global')}>
Global
</button>
{regions.map((region) => (
<button
key={region.id}
type="button"
onClick={() => onChange(region.id)}
className={tabClass(value === region.id)}
>
{region.name}
</button>
))}
{regions.length === 0 ? (
<MyText className="shrink-0 self-center text-sm text-gray-400">No regions yet</MyText>
) : null}
</div>
)
}
export default RegionTabs

View file

@ -23,19 +23,19 @@ const CARDS = [
},
{
to: '/global-stores',
title: 'Global Stores',
description: 'Create stores that are available in every region.',
title: 'Stores',
description: 'Global stores plus each region’s own stores.',
icon: Store,
},
{
to: '/global-products',
title: 'Global Products',
description: 'Create products that are shared across every region.',
title: 'Products',
description: 'Global products plus each region’s own products.',
icon: Package,
},
{
to: '/send-notifications',
title: 'Send Admin Notifications',
title: 'Admin Notifs',
description: 'Push a message to every admin device.',
icon: Send,
},

View file

@ -4,6 +4,7 @@ import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-compo
import { Plus, Trash2, X } from 'lucide-react'
import { ProtectedRoute } from '../components/ProtectedRoute'
import { AppShell } from '../components/AppShell'
import { RegionTabs, type RegionTabKey } from '../components/RegionTabs'
import { trpc } from '../lib/trpc-client'
import { useUploadToObjectStorage } from '../hooks/useUploadToObjectStorage'
@ -11,7 +12,7 @@ export const Route = createFileRoute('/global-products')({
component: () => (
<ProtectedRoute>
<AppShell>
<GlobalProductsPage />
<ProductsPage />
</AppShell>
</ProtectedRoute>
),
@ -77,40 +78,32 @@ const skuToDraft = (sku: any): SkuDraft => ({
comboItems: (sku.comboItems ?? []).map((ci: any) => ({ skuId: ci.skuId })),
})
function GlobalProductsPage() {
const [tab, setTab] = useState<'global' | 'all'>('global')
const tabClass = (active: boolean) =>
`rounded-lg px-4 py-2 text-sm font-semibold ${active ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700'}`
function ProductsPage() {
const regionsQuery = trpc.superadmin.regions.list.useQuery()
const regions = (regionsQuery.data ?? []) as { id: number; name: string }[]
const [tab, setTab] = useState<RegionTabKey>('global')
return (
<AppContainer>
<div className="bg-gray-50 p-4">
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Products</MyText>
<MyText className="mb-4 block text-gray-600">
Create and manage global products, or elevate a regional product to global.
The Global tab holds the catalogue shared across every region; each region tab lists that
region's own products (which can be elevated to global).
</MyText>
<div className="mb-4 flex gap-2">
<button type="button" onClick={() => setTab('global')} className={tabClass(tab === 'global')}>
Global Products
</button>
<button type="button" onClick={() => setTab('all')} className={tabClass(tab === 'all')}>
All Products
</button>
</div>
<RegionTabs regions={regions} value={tab} onChange={setTab} />
{tab === 'global' ? <GlobalProductsTab /> : <AllProductsTab />}
{tab === 'global' ? <GlobalProductsTab /> : <RegionProductsTab regionId={tab} />}
</div>
</AppContainer>
)
}
function AllProductsTab() {
function RegionProductsTab({ regionId }: { regionId: number }) {
const utils = trpc.useUtils()
const regionsQuery = trpc.superadmin.regions.list.useQuery()
const storesQuery = trpc.superadmin.globalStores.list.useQuery()
const [regionId, setRegionId] = useState<number | ''>('')
const [searchInput, setSearchInput] = useState('')
const [search, setSearch] = useState('')
const [page, setPage] = useState(0)
@ -124,8 +117,13 @@ function AllProductsTab() {
return () => clearTimeout(t)
}, [searchInput])
// Tabs reuse this component, so start each region on its first page.
useEffect(() => {
setPage(0)
}, [regionId])
const listQuery = trpc.superadmin.products.list.useQuery({
regionId: regionId === '' ? undefined : Number(regionId),
regionId,
search: search || undefined,
limit: PAGE_SIZE,
offset: page * PAGE_SIZE,
@ -138,7 +136,6 @@ function AllProductsTab() {
const products = (listQuery.data?.products ?? []) as any[]
const total = listQuery.data?.total ?? 0
const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE))
const regions = regionsQuery.data ?? []
const stores = storesQuery.data ?? []
const doElevate = async (productId: number) => {
@ -166,26 +163,14 @@ function AllProductsTab() {
placeholder="Search by product name, SKU or description…"
className="min-w-[220px] flex-1 rounded-lg border border-gray-200 px-3 py-2 text-gray-900"
/>
<div className="flex items-center gap-2">
<MyText className="text-sm text-gray-500">Region:</MyText>
<select
value={regionId}
onChange={(e) => {
setRegionId(e.target.value === '' ? '' : Number(e.target.value))
setPage(0)
}}
className="rounded-lg border border-gray-200 px-3 py-2 text-gray-900"
>
<option value="">All regions</option>
{regions.map((r: any) => (
<option key={r.id} value={r.id}>{r.name}</option>
))}
</select>
</div>
</div>
{listQuery.isLoading && <MyText className="text-gray-500">Loading products…</MyText>}
{!listQuery.isLoading && products.length === 0 && (
<MyText className="text-gray-500">No products in this region yet.</MyText>
)}
<div className="grid gap-3">
{products.map((product) => {
const isGlobal = product.regionId == null
@ -281,13 +266,11 @@ function GlobalProductsTab() {
const editing = products.find((p) => p.id === editingId) ?? null
return (
<AppContainer>
<div className="bg-gray-50 p-4">
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Global Products</MyText>
<MyText className="mb-6 block text-gray-600">
Products shared across every region. Creating one seeds the initial price &amp; stock into
each region; editing the structure leaves each region's market data untouched.
</MyText>
<div>
<MyText className="mb-4 block text-gray-600">
Products shared across every region. Creating one seeds the initial price &amp; stock into
each region; editing the structure leaves each region's market data untouched.
</MyText>
{editing ? (
<GlobalProductForm
@ -342,8 +325,7 @@ function GlobalProductsTab() {
</div>
))}
</div>
</div>
</AppContainer>
</div>
)
}

View file

@ -3,19 +3,42 @@ import { useState } from 'react'
import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
import { ProtectedRoute } from '../components/ProtectedRoute'
import { AppShell } from '../components/AppShell'
import { RegionTabs, type RegionTabKey } from '../components/RegionTabs'
import { trpc } from '../lib/trpc-client'
export const Route = createFileRoute('/global-stores')({
component: () => (
<ProtectedRoute>
<AppShell>
<GlobalStoresPage />
<StoresPage />
</AppShell>
</ProtectedRoute>
),
})
function GlobalStoresPage() {
function StoresPage() {
const regionsQuery = trpc.superadmin.regions.list.useQuery()
const regions = (regionsQuery.data ?? []) as { id: number; name: string }[]
const [tab, setTab] = useState<RegionTabKey>('global')
return (
<AppContainer>
<div className="bg-gray-50 p-4">
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Stores</MyText>
<MyText className="mb-4 block text-gray-600">
The Global tab lists the stores available in every region; each region tab lists that
region's own stores.
</MyText>
<RegionTabs regions={regions} value={tab} onChange={setTab} />
{tab === 'global' ? <GlobalStoresTab /> : <RegionStoresTab regionId={tab} />}
</div>
</AppContainer>
)
}
function GlobalStoresTab() {
const listQuery = trpc.superadmin.globalStores.list.useQuery()
const utils = trpc.useUtils()
const [editingId, setEditingId] = useState<number | null>(null)
@ -29,59 +52,116 @@ function GlobalStoresPage() {
const stores = listQuery.data ?? []
return (
<AppContainer>
<div className="bg-gray-50 p-4">
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Global Stores</MyText>
<MyText className="mb-6 block text-gray-600">
Stores available in every region. Regional admins can view them but not edit them.
</MyText>
<div>
<MyText className="mb-6 block text-gray-600">
Stores available in every region. Regional admins can view them but not edit them.
</MyText>
<GlobalStoreForm onSaved={refresh} />
<GlobalStoreForm onSaved={refresh} />
{listQuery.isLoading && <MyText className="text-gray-500">Loading stores…</MyText>}
{listQuery.isLoading && <MyText className="text-gray-500">Loading stores…</MyText>}
<div className="mt-6 grid gap-3 sm:grid-cols-2">
{stores.map((store: any) => (
<div key={store.id} className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
<div className="mb-2 flex items-start justify-between gap-2">
<MyText className="block font-semibold text-gray-900">{store.name}</MyText>
<span className="rounded-full bg-purple-100 px-2 py-0.5 text-[10px] font-bold text-purple-700">
GLOBAL
</span>
</div>
{store.imageUrl ? (
<img src={store.imageUrl} alt="" className="mb-2 h-28 w-full rounded-lg object-cover" />
) : null}
<MyText className="block text-sm text-gray-500">{store.description || 'No description'}</MyText>
<div className="mt-3 flex gap-2">
<MyButton onClick={() => setEditingId(editingId === store.id ? null : store.id)}>
{editingId === store.id ? 'Close' : 'Edit'}
</MyButton>
<button
type="button"
onClick={() => {
if (window.confirm(`Delete global store "${store.name}"?`)) remove.mutate({ id: store.id })
}}
className="rounded-lg bg-red-500 px-4 py-2 text-sm font-semibold text-white"
>
Delete
</button>
</div>
{editingId === store.id ? (
<div className="mt-4 border-t border-gray-100 pt-4">
<GlobalStoreForm
store={store}
onSaved={() => { setEditingId(null); refresh() }}
/>
</div>
) : null}
<div className="mt-6 grid gap-3 sm:grid-cols-2">
{stores.map((store: any) => (
<div key={store.id} className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
<div className="mb-2 flex items-start justify-between gap-2">
<MyText className="block font-semibold text-gray-900">{store.name}</MyText>
<span className="rounded-full bg-purple-100 px-2 py-0.5 text-[10px] font-bold text-purple-700">
GLOBAL
</span>
</div>
))}
</div>
{store.imageUrl ? (
<img src={store.imageUrl} alt="" className="mb-2 h-28 w-full rounded-lg object-cover" />
) : null}
<MyText className="block text-sm text-gray-500">{store.description || 'No description'}</MyText>
<div className="mt-3 flex gap-2">
<MyButton onClick={() => setEditingId(editingId === store.id ? null : store.id)}>
{editingId === store.id ? 'Close' : 'Edit'}
</MyButton>
<button
type="button"
onClick={() => {
if (window.confirm(`Delete global store "${store.name}"?`)) remove.mutate({ id: store.id })
}}
className="rounded-lg bg-red-500 px-4 py-2 text-sm font-semibold text-white"
>
Delete
</button>
</div>
{editingId === store.id ? (
<div className="mt-4 border-t border-gray-100 pt-4">
<GlobalStoreForm
store={store}
onSaved={() => { setEditingId(null); refresh() }}
/>
</div>
) : null}
</div>
))}
</div>
</AppContainer>
</div>
)
}
function RegionStoresTab({ regionId }: { regionId: number }) {
const utils = trpc.useUtils()
const listQuery = trpc.superadmin.stores.list.useQuery({ regionId })
const elevate = trpc.superadmin.stores.elevate.useMutation({
onSuccess: async () => {
await utils.superadmin.stores.list.invalidate()
await utils.superadmin.globalStores.list.invalidate()
},
onError: (e) => window.alert(e.message),
})
const stores = (listQuery.data ?? []) as any[]
const elevatingId = elevate.isPending ? elevate.variables?.storeId ?? null : null
const doElevate = (store: any) => {
if (
!window.confirm(
`Elevate store "${store.name}" to global? It becomes available in every region. Its products stay in their own region.`
)
) {
return
}
elevate.mutate({ storeId: store.id })
}
if (listQuery.isLoading) {
return <MyText className="text-gray-500">Loading stores…</MyText>
}
if (stores.length === 0) {
return <MyText className="text-gray-500">No stores in this region yet.</MyText>
}
return (
<div className="grid gap-3 sm:grid-cols-2">
{stores.map((store: any) => (
<div key={store.id} className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
<div className="mb-2 flex items-start justify-between gap-2">
<MyText className="block font-semibold text-gray-900">{store.name}</MyText>
<span className="rounded-full bg-gray-100 px-2 py-0.5 text-[10px] font-bold text-gray-600">
REGIONAL
</span>
</div>
{store.imageUrl ? (
<img src={store.imageUrl} alt="" className="mb-2 h-28 w-full rounded-lg object-cover" />
) : null}
<MyText className="block text-sm text-gray-500">{store.description || 'No description'}</MyText>
<div className="mt-3">
<MyButton onClick={() => doElevate(store)} disabled={elevate.isPending}>
{elevatingId === store.id ? 'Elevating…' : 'Elevate to global'}
</MyButton>
</div>
</div>
))}
</div>
)
}

View file

@ -50,7 +50,7 @@ function SendAdminNotifications() {
<AppContainer>
<div className="bg-gray-50 p-4">
<MyText className="mb-1 block text-2xl font-bold text-gray-900">
Send Admin Notifications
Admin Notifs
</MyText>
<MyText className="mb-6 block text-gray-600">
This push notification is delivered to every admin device.

View file

@ -4047,8 +4047,85 @@ user-ui
apps/user-ui/test-case-info.md: updated the address-form / cart-screen / location-wrapper entries
and added the new suites.
No dependency added. No migration. No tests run (typecheck only).
2026-10-13 23:06:50 Superadmin: region tabs for Products and Stores + nav label cleanup.
1/9 packages/db_helper_sqlite/src/superadmin-apis/stores.ts (NEW): listRegionStores(regionId) —
stores owned by one region (regionId = X AND isGlobal = false), name-ordered, Store shape.
2/9 packages/db_helper_sqlite/index.ts: export listRegionStores (superadmin section).
3/9 apps/backend/.../superadmin-apis/apis/stores.ts (NEW): superadmin.stores.list({regionId}) →
region stores with scaffolded imageUrl (mirrors the global-stores router).
4/9 apps/backend/.../superadmin-apis/apis/superadmin-trpc-index.ts: register the stores router.
5/9 apps/superadmin-ui/src/components/RegionTabs.tsx (NEW): shared Global + one-tab-per-region tab bar.
6/9 apps/superadmin-ui/src/routes/global-products.tsx: Products page is now tabbed (Global first,
then every region). Global keeps the create/edit form; each region lists its own products via
superadmin.products.list({regionId}) with search, pagination and Elevate-to-global.
7/9 apps/superadmin-ui/src/routes/global-stores.tsx: Stores page is now tabbed (Global first, then
every region). Global keeps the create/edit form; each region lists its stores via
superadmin.stores.list({regionId}).
8/9 apps/superadmin-ui/src/components/AppShell.tsx: left-panel labels "Global Stores" → "Stores",
"Global Products" → "Products".
9/9 apps/superadmin-ui/src/routes/dashboard.tsx: matching card titles dropped "Global".
No dependency added. No migration. No tests run.
2026-10-13 23:07:22 Superadmin: rename "Send Admin Notifications" to "Admin Notifs".
apps/superadmin-ui/src/components/AppShell.tsx: left-panel label.
apps/superadmin-ui/src/routes/dashboard.tsx: matching dashboard card title.
apps/superadmin-ui/src/routes/send-notifications.tsx: page heading.
No dependency added. No migration. No tests run.
2026-10-13 23:15:01 Superadmin: elevate a regional store to global.
1/4 packages/db_helper_sqlite/src/superadmin-apis/stores.ts: add elevateStoreToGlobal(storeId) —
region_id -> NULL, is_global -> true (products untouched). Rejects missing/already-global.
2/4 packages/db_helper_sqlite/index.ts: export elevateStoreToGlobal.
3/4 apps/backend/.../superadmin-apis/apis/stores.ts: superadmin.stores.elevate({storeId}) mutation
+ scheduleStoreInitialization (mirrors superadmin.products.elevate).
4/4 apps/superadmin-ui/src/routes/global-stores.tsx: "Elevate to global" action on each store in a
region tab (confirm + invalidate the region list and the global list).
NOTE: per the chosen behaviour the store's products keep their region and storeId. Since a global
store may only hold global products (assertStoreInRegion), regional edits that submit storeId
for those products will be rejected. No dependency added. No migration. No tests run.
2026-10-13 23:13:00 Superadmin: horizonally scrollable region tabs.
apps/superadmin-ui/src/components/RegionTabs.tsx: tab bar is now a single-row
overflow-x-auto strip (was flex-wrap); buttons get shrink-0 so they stay on one
line instead of wrapping when there are many regions.
+ apps/superadmin-ui/src/components/AppShell.tsx: added min-w-0 to the main flex item so the
nowrap tab strip scrolls inside itself instead of widening the page horizontally.
No dependency added. No migration. No tests run.
2026-10-13 23:53:07 Fix: admin stock toggles / bulk prices rejected global products ("Product not found").
Root cause: the write guards matched `product_info.region_id = <staff region>` only, while the
read path (getProductById) already matches `region_id IS NULL OR region_id = <region>`. So a
global product showed up in the admin list but every stock write 404'd.
packages/db_helper_sqlite/src/admin-apis/product.ts:
+ toggleProductOutOfStock: accept isNull(productInfo.regionId) (global products)
+ setProductSkusOutOfStock: same
+ updateProductPrices: a global SKU (product.regionId == null) is now valid instead of being
reported in invalidIds (the catalogued "Global SKU rejected by bulk prices" defect)
Market writes still target product_market_stats for the caller's region only, so a global
product's stock/price stays per-region.
No dependency added. No migration. No tests run.
- Added apps/backend/scripts/create-user.ts: creates/updates a user + bcrypt password.
Hashes with bcryptjs (12 rounds, matches signup) and writes via `wrangler d1 execute`
(--local default, --remote optional). Auto-detects existing user by mobile/email;
refuses to clobber unless --update. Supports --show-sql. No tests run.
- apps/backend/package.json: added "create-user" script -> bun run scripts/create-user.ts.
2026-10-14 00:04:05 Global products: serve them across every region (storefront caches) + fix SKU ownership.
Same "region = X only" guard class as the stock-toggle bug, but on the read/cache path: global
products (product_info.region_id IS NULL) were dropped from every region's slots/tags/deals/combos,
so they landed in the catalogue with no slots (unorderable / "No delivery slots available").
packages/db_helper_sqlite/src/stores/store-helpers.ts:
+ getInRegionSkuIds: include region_id IS NULL (this feeds slot skuIds AND banner skuIds)
+ getInRegionStoreIds: include isGlobal stores (tag relatedStores)
+ getAllSpecialDealsForCache / getAllProductTagsForCache / getAllTagProductMappings: include globals
+ getAllProductCombosForCache: allow global combo parts, and include globals in the suspended set
+ getAllSlotsWithProductsForCache: allow global products
packages/db_helper_sqlite/src/user-apis/slots.ts: getProductAvailability includes globals.
packages/db_helper_sqlite/src/user-apis/product.ts: getSuspendedSkuIds includes globals.
packages/db_helper_sqlite/src/admin-apis/product.ts: resolveSkuRegions derives isGlobal from
product_info.region_id (NULL) instead of the store's is_global flag, so a regional product in a
(possibly elevated) global store is no longer treated as global by the tag/combo guards.
Reviews deliberately left as-is (regional admins still can't see global products' reviews).
No dependency added. No migration. No tests run.

View file

@ -432,6 +432,11 @@ export {
deleteGlobalStore,
} from './src/superadmin-apis/global-stores'
export {
listRegionStores,
elevateStoreToGlobal,
} from './src/superadmin-apis/stores'
export {
listGlobalProducts,
getGlobalProduct,

View file

@ -84,19 +84,19 @@ const getStringArray = (value: unknown): string[] | null => {
// Region guards: SKUs resolve to a region through their parent product
// (productSkus.productId -> productInfo.regionId). A global SKU (its product's
// store is global) is valid in every region. Throws on unknown ids or ids whose
// region is null) is valid in every region. Throws on unknown ids or ids whose
// parent product lives in another (non-global) region.
const resolveSkuRegions = async (txOrDb: any, skuIds: number[]): Promise<Map<number, { regionId: number | null; isGlobal: boolean }>> => {
if (skuIds.length === 0) return new Map()
const rows = await txOrDb.query.productSkus.findMany({
where: inArray(productSkus.id, skuIds),
with: { product: { columns: { regionId: true }, with: { store: { columns: { isGlobal: true } } } } },
with: { product: { columns: { regionId: true } } },
columns: { id: true },
})
return new Map(rows.map((r: any) => [
r.id,
{ regionId: r.product?.regionId ?? null, isGlobal: r.product?.store?.isGlobal ?? false },
]))
return new Map(rows.map((r: any) => {
const regionId = r.product?.regionId ?? null
return [r.id, { regionId, isGlobal: regionId == null }]
}))
}
const assertSkuIdsInRegion = async (txOrDb: any, skuIds: number[], regionId: number | null, noun = 'SKU'): Promise<void> => {
@ -1242,9 +1242,9 @@ export async function updateProductPrices(regionId: number, updates: Array<{
const skuIds = updates.map((update) => update.skuId)
// Validate all SKU IDs exist AND belong to the staff region (in chunks to
// avoid large IN clauses). Out-of-region SKUs are reported as invalid so no
// cross-region existence leaks through this bulk path.
// Validate all SKU IDs exist AND belong to the staff region (or to a global
// product, which is visible in every region). Out-of-region SKUs are reported
// as invalid so no cross-region existence leaks through this bulk path.
const existingSkuChunks = await runBatched(db, skuIds, 10, async (tx, chunk) => {
return tx.query.productSkus.findMany({
where: inArray(productSkus.id, chunk),
@ -1254,7 +1254,9 @@ export async function updateProductPrices(regionId: number, updates: Array<{
})
const inRegionIds = new Set(
existingSkuChunks.flat()
.filter((sku: { id: number; product?: { regionId: number | null } | null }) => sku.product?.regionId === regionId)
.filter((sku: { id: number; product?: { regionId: number | null } | null }) =>
sku.product?.regionId === regionId || sku.product?.regionId == null
)
.map((sku: { id: number }) => sku.id)
)
const invalidIds = skuIds.filter((id) => !inRegionIds.has(id))
@ -1310,7 +1312,12 @@ export async function toggleProductOutOfStock(
productId: number
): Promise<{ id: number; isOutOfStock: boolean } | null> {
const product = await db.query.productInfo.findFirst({
where: and(eq(productInfo.id, productId), eq(productInfo.regionId, regionId)),
// Global products (region_id null) belong to every region; a regional admin
// may still flip their market data for their own region.
where: and(
eq(productInfo.id, productId),
or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))
),
columns: { id: true },
})
if (!product) {
@ -1357,7 +1364,12 @@ export async function setProductSkusOutOfStock(
isOutOfStock: boolean
} | null> {
const product = await db.query.productInfo.findFirst({
where: and(eq(productInfo.id, productId), eq(productInfo.regionId, regionId)),
// Global products (region_id null) belong to every region; a regional admin
// may still flip their market data for their own region.
where: and(
eq(productInfo.id, productId),
or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))
),
columns: { id: true },
})
if (!product) {

View file

@ -15,7 +15,7 @@ import {
productTagInfo,
userIncidents,
} from '../db/schema'
import { eq, and, gt, sql, isNotNull, asc, or } from 'drizzle-orm'
import { eq, and, gt, sql, isNotNull, isNull, asc, or } from 'drizzle-orm'
import { composeSkuName, composeUnitNotation } from '../lib/sku-features'
import { marketStatsForRegion, isSkuSuspended } from '../lib/market-stats'
import type { ProductTagData, TagProductMapping, UserNegativityData, StoreSummary, BannerData, SpecialDealCore, ProductDetailCore, ProductPriceFlags, ProductTagCore, UserProductDeliverySlot, UserProductComboItem } from '@packages/shared'
@ -27,15 +27,16 @@ export type { ProductTagData, TagProductMapping, UserNegativityData, BannerData
// StoreBasicData is exactly the shared StoreSummary shape — single source, same export name.
export type StoreBasicData = StoreSummary
// In-region SKU ids (SKUs whose parent product_info row belongs to the region).
// SKU-linked rows (slots skuIds, banner skuIds, combo/tag mappings) are filtered
// through this set so scoped outputs contain ONLY in-region SKUs.
// In-region SKU ids (SKUs whose parent product_info row belongs to the region,
// plus global SKUs which are servable in every region). SKU-linked rows (slots
// skuIds, banner skuIds) are filtered through this set so scoped outputs contain
// only SKUs this region can actually serve.
async function getInRegionSkuIds(regionId: number): Promise<Set<number>> {
const rows = await db
.select({ skuId: productSkus.id })
.from(productSkus)
.innerJoin(productInfo, eq(productSkus.productId, productInfo.id))
.where(eq(productInfo.regionId, regionId))
.where(or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId)))
return new Set(rows.map((r) => r.skuId))
}
@ -43,7 +44,7 @@ async function getInRegionStoreIds(regionId: number): Promise<Set<number>> {
const rows = await db
.select({ id: storeInfo.id })
.from(storeInfo)
.where(eq(storeInfo.regionId, regionId))
.where(or(eq(storeInfo.regionId, regionId), eq(storeInfo.isGlobal, true)))
return new Set(rows.map((r) => r.id))
}
@ -104,7 +105,7 @@ export async function getAllSpecialDealsForCache(regionId: number): Promise<Spec
.innerJoin(productInfo, eq(productSkus.productId, productInfo.id))
.where(and(
gt(specialDeals.validTill, sql`CURRENT_TIMESTAMP`),
eq(productInfo.regionId, regionId)
or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))
))
return results.map((deal) => ({
@ -228,7 +229,7 @@ export async function getAllProductTagsForCache(regionId: number): Promise<Produ
.innerJoin(productInfo, eq(productSkus.productId, productInfo.id))
.where(and(
eq(productTagInfo.regionId, regionId),
eq(productInfo.regionId, regionId)
or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))
))
return rows
}
@ -257,14 +258,18 @@ export async function getAllProductCombosForCache(regionId: number): Promise<Pro
.innerJoin(productInfo, eq(productSkus.productId, productInfo.id))
.where(and(
eq(productMarketStats.regionId, regionId),
eq(productInfo.regionId, regionId),
or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId)),
or(eq(productSkus.isSuspended, true), eq(productMarketStats.isSuspendedInRegion, true))
))).map((r) => r.id)
)
return results
.filter((ci) => !suspendedSkuIds.has(ci.comboSkuId))
.filter((ci) => ci.comboSku?.product?.regionId === regionId && ci.sku?.product?.regionId === regionId)
.filter(
(ci) =>
(ci.comboSku?.product?.regionId === regionId || ci.comboSku?.product?.regionId == null) &&
(ci.sku?.product?.regionId === regionId || ci.sku?.product?.regionId == null)
)
.map((ci) => {
const features = ci.sku?.features || []
const marketStats = marketStatsForRegion(ci.sku?.marketStats, regionId)
@ -330,7 +335,7 @@ export async function getAllTagProductMappings(regionId: number): Promise<TagPro
.innerJoin(productInfo, eq(productSkus.productId, productInfo.id))
.where(and(
eq(productTagInfo.regionId, regionId),
eq(productInfo.regionId, regionId)
or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))
))
}
@ -396,7 +401,7 @@ export async function getAllSlotsWithProductsForCache(regionId: number): Promise
skusData = skusData.filter((item: any) =>
skuIdSet.has(item.id) &&
!item.isDeleted &&
item.product?.regionId === regionId &&
(item.product?.regionId === regionId || item.product?.regionId == null) &&
!isSkuSuspended(item.isSuspended, marketStatsForRegion(item.marketStats, regionId))
)
}

View file

@ -0,0 +1,47 @@
import { db } from '../db/db_index'
import { storeInfo } from '../db/schema'
import { and, eq } from 'drizzle-orm'
import type { Store } from '@packages/shared'
const toStore = (s: any): Store => ({
id: s.id,
name: s.name,
description: s.description,
imageUrl: s.imageUrl,
isGlobal: s.isGlobal,
createdAt: s.createdAt,
})
/**
* Stores owned by a single region. Global stores (available in every region)
* are listed separately via `listGlobalStores`.
*/
export async function listRegionStores(regionId: number): Promise<Store[]> {
const rows = await db.query.storeInfo.findMany({
where: and(eq(storeInfo.regionId, regionId), eq(storeInfo.isGlobal, false)),
orderBy: storeInfo.name,
})
return rows.map(toStore)
}
/**
* Elevate a regional store to a global one: clear its region and set isGlobal.
* The store's products are left untouched (they keep their own region/storeId).
* Throws when the store is missing or is already global.
*/
export async function elevateStoreToGlobal(storeId: number) {
const store = await db.query.storeInfo.findFirst({
where: eq(storeInfo.id, storeId),
columns: { id: true, regionId: true, isGlobal: true },
})
if (!store) throw new Error('Store not found')
if (store.isGlobal || store.regionId == null) throw new Error('Store is already global')
const [updated] = await db
.update(storeInfo)
.set({ regionId: null, isGlobal: true })
.where(and(eq(storeInfo.id, storeId), eq(storeInfo.isGlobal, false)))
.returning()
return toStore(updated)
}

View file

@ -1,6 +1,6 @@
import { db } from '../db/db_index'
import { deliverySlotInfo, productInfo, productCombos, productSkus, productMarketStats, productReviews, productTags, specialDeals, storeInfo, users } from '../db/schema'
import { and, desc, eq, gt, inArray, or, sql } from 'drizzle-orm'
import { and, desc, eq, gt, inArray, isNull, or, sql } from 'drizzle-orm'
import type { UserProductDetailData, UserProductReview } from '@packages/shared'
import { composeSkuName, composeUnitNotation } from '../lib/sku-features'
import { marketStatsForRegion, isSkuSuspended } from '../lib/market-stats'
@ -280,7 +280,7 @@ export async function getSuspendedSkuIds(regionId: number): Promise<number[]> {
.innerJoin(productInfo, eq(productSkus.productId, productInfo.id))
.where(and(
eq(productMarketStats.regionId, regionId),
eq(productInfo.regionId, regionId),
or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId)),
or(eq(productSkus.isSuspended, true), eq(productMarketStats.isSuspendedInRegion, true))
))

View file

@ -1,6 +1,6 @@
import { db } from '../db/db_index'
import { deliverySlotInfo, productMarketStats } from '../db/schema'
import { and, asc, eq } from 'drizzle-orm'
import { and, asc, eq, isNull, or } from 'drizzle-orm'
import type { InferSelectModel } from 'drizzle-orm'
import type { UserDeliverySlot, UserSlotAvailability } from '@packages/shared'
@ -56,7 +56,11 @@ export async function getProductAvailability(regionId: number): Promise<UserSlot
})
return stats
.filter((stat) => (stat as typeof stat & { sku?: { isSuspended?: boolean; product?: { regionId: number | null } | null } | null }).sku?.product?.regionId === regionId)
.filter((stat) => {
const productRegionId = (stat as typeof stat & { sku?: { product?: { regionId: number | null } | null } | null }).sku?.product?.regionId
// Global products (null region) are servable in every region.
return productRegionId === regionId || productRegionId == null
})
.filter((stat) => !(stat as typeof stat & { sku?: { isSuspended?: boolean } | null }).sku?.isSuspended)
.map((stat) => ({
id: stat.skuId,