diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/stores.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/stores.ts new file mode 100644 index 0000000..8bef3db --- /dev/null +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/stores.ts @@ -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' } + }), +}) diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts index e0bac92..e0a7cb4 100644 --- a/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts @@ -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, diff --git a/apps/superadmin-ui/src/components/AppShell.tsx b/apps/superadmin-ui/src/components/AppShell.tsx index 0575f9a..5946a0f 100644 --- a/apps/superadmin-ui/src/components/AppShell.tsx +++ b/apps/superadmin-ui/src/components/AppShell.tsx @@ -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 }) { /> )} -
{children}
+
{children}
) diff --git a/apps/superadmin-ui/src/components/RegionTabs.tsx b/apps/superadmin-ui/src/components/RegionTabs.tsx new file mode 100644 index 0000000..5f7fdbd --- /dev/null +++ b/apps/superadmin-ui/src/components/RegionTabs.tsx @@ -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 ( +
+ + {regions.map((region) => ( + + ))} + {regions.length === 0 ? ( + No regions yet + ) : null} +
+ ) +} + +export default RegionTabs diff --git a/apps/superadmin-ui/src/routes/dashboard.tsx b/apps/superadmin-ui/src/routes/dashboard.tsx index 58f43aa..27595b0 100644 --- a/apps/superadmin-ui/src/routes/dashboard.tsx +++ b/apps/superadmin-ui/src/routes/dashboard.tsx @@ -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, }, diff --git a/apps/superadmin-ui/src/routes/global-products.tsx b/apps/superadmin-ui/src/routes/global-products.tsx index 9ce3f8d..31418f9 100644 --- a/apps/superadmin-ui/src/routes/global-products.tsx +++ b/apps/superadmin-ui/src/routes/global-products.tsx @@ -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: () => ( - + ), @@ -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('global') return (
Products - 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). -
- - -
+ - {tab === 'global' ? : } + {tab === 'global' ? : }
) } -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('') 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" /> -
- Region: - -
{listQuery.isLoading && Loading products…} + {!listQuery.isLoading && products.length === 0 && ( + No products in this region yet. + )} +
{products.map((product) => { const isGlobal = product.regionId == null @@ -281,13 +266,11 @@ function GlobalProductsTab() { const editing = products.find((p) => p.id === editingId) ?? null return ( - -
- Global Products - - Products shared across every region. Creating one seeds the initial price & stock into - each region; editing the structure leaves each region's market data untouched. - +
+ + Products shared across every region. Creating one seeds the initial price & stock into + each region; editing the structure leaves each region's market data untouched. + {editing ? ( ))}
-
-
+
) } diff --git a/apps/superadmin-ui/src/routes/global-stores.tsx b/apps/superadmin-ui/src/routes/global-stores.tsx index 984f6f3..f16c2f4 100644 --- a/apps/superadmin-ui/src/routes/global-stores.tsx +++ b/apps/superadmin-ui/src/routes/global-stores.tsx @@ -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: () => ( - + ), }) -function GlobalStoresPage() { +function StoresPage() { + const regionsQuery = trpc.superadmin.regions.list.useQuery() + const regions = (regionsQuery.data ?? []) as { id: number; name: string }[] + const [tab, setTab] = useState('global') + + return ( + +
+ Stores + + The Global tab lists the stores available in every region; each region tab lists that + region's own stores. + + + + + {tab === 'global' ? : } +
+
+ ) +} + +function GlobalStoresTab() { const listQuery = trpc.superadmin.globalStores.list.useQuery() const utils = trpc.useUtils() const [editingId, setEditingId] = useState(null) @@ -29,59 +52,116 @@ function GlobalStoresPage() { const stores = listQuery.data ?? [] return ( - -
- Global Stores - - Stores available in every region. Regional admins can view them but not edit them. - +
+ + Stores available in every region. Regional admins can view them but not edit them. + - + - {listQuery.isLoading && Loading stores…} + {listQuery.isLoading && Loading stores…} -
- {stores.map((store: any) => ( -
-
- {store.name} - - GLOBAL - -
- {store.imageUrl ? ( - - ) : null} - {store.description || 'No description'} - -
- setEditingId(editingId === store.id ? null : store.id)}> - {editingId === store.id ? 'Close' : 'Edit'} - - -
- - {editingId === store.id ? ( -
- { setEditingId(null); refresh() }} - /> -
- ) : null} +
+ {stores.map((store: any) => ( +
+
+ {store.name} + + GLOBAL +
- ))} -
+ {store.imageUrl ? ( + + ) : null} + {store.description || 'No description'} + +
+ setEditingId(editingId === store.id ? null : store.id)}> + {editingId === store.id ? 'Close' : 'Edit'} + + +
+ + {editingId === store.id ? ( +
+ { setEditingId(null); refresh() }} + /> +
+ ) : null} +
+ ))}
- +
+ ) +} + +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 Loading stores… + } + + if (stores.length === 0) { + return No stores in this region yet. + } + + return ( +
+ {stores.map((store: any) => ( +
+
+ {store.name} + + REGIONAL + +
+ {store.imageUrl ? ( + + ) : null} + {store.description || 'No description'} + +
+ doElevate(store)} disabled={elevate.isPending}> + {elevatingId === store.id ? 'Elevating…' : 'Elevate to global'} + +
+
+ ))} +
) } diff --git a/apps/superadmin-ui/src/routes/send-notifications.tsx b/apps/superadmin-ui/src/routes/send-notifications.tsx index 402d00f..93abe39 100644 --- a/apps/superadmin-ui/src/routes/send-notifications.tsx +++ b/apps/superadmin-ui/src/routes/send-notifications.tsx @@ -50,7 +50,7 @@ function SendAdminNotifications() {
- Send Admin Notifications + Admin Notifs This push notification is delivered to every admin device. diff --git a/change-log.txt b/change-log.txt index 00c9008..021090d 100644 --- a/change-log.txt +++ b/change-log.txt @@ -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 = ` only, while the + read path (getProductById) already matches `region_id IS NULL OR region_id = `. 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. diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts index 51a83c0..e93a5c0 100644 --- a/packages/db_helper_sqlite/index.ts +++ b/packages/db_helper_sqlite/index.ts @@ -432,6 +432,11 @@ export { deleteGlobalStore, } from './src/superadmin-apis/global-stores' +export { + listRegionStores, + elevateStoreToGlobal, +} from './src/superadmin-apis/stores' + export { listGlobalProducts, getGlobalProduct, diff --git a/packages/db_helper_sqlite/src/admin-apis/product.ts b/packages/db_helper_sqlite/src/admin-apis/product.ts index 58eced3..87ee5dd 100644 --- a/packages/db_helper_sqlite/src/admin-apis/product.ts +++ b/packages/db_helper_sqlite/src/admin-apis/product.ts @@ -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> => { 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 => { @@ -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) { diff --git a/packages/db_helper_sqlite/src/stores/store-helpers.ts b/packages/db_helper_sqlite/src/stores/store-helpers.ts index 05e7274..2fb1af6 100644 --- a/packages/db_helper_sqlite/src/stores/store-helpers.ts +++ b/packages/db_helper_sqlite/src/stores/store-helpers.ts @@ -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> { 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> { 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 ({ @@ -228,7 +229,7 @@ export async function getAllProductTagsForCache(regionId: number): Promise 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 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)) ) } diff --git a/packages/db_helper_sqlite/src/superadmin-apis/stores.ts b/packages/db_helper_sqlite/src/superadmin-apis/stores.ts new file mode 100644 index 0000000..027db42 --- /dev/null +++ b/packages/db_helper_sqlite/src/superadmin-apis/stores.ts @@ -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 { + 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) +} diff --git a/packages/db_helper_sqlite/src/user-apis/product.ts b/packages/db_helper_sqlite/src/user-apis/product.ts index c80345b..13a0955 100644 --- a/packages/db_helper_sqlite/src/user-apis/product.ts +++ b/packages/db_helper_sqlite/src/user-apis/product.ts @@ -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 { .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)) )) diff --git a/packages/db_helper_sqlite/src/user-apis/slots.ts b/packages/db_helper_sqlite/src/user-apis/slots.ts index 3eaf7fe..8879c11 100644 --- a/packages/db_helper_sqlite/src/user-apis/slots.ts +++ b/packages/db_helper_sqlite/src/user-apis/slots.ts @@ -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 (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,