This commit is contained in:
shafi54 2026-10-10 16:30:18 +05:30
parent fd21196e1d
commit 05ba30ca30
14 changed files with 840 additions and 188 deletions

11
.pi/mcp.json Normal file
View file

@ -0,0 +1,11 @@
{
"mcpServers": {
"maestro": {
"command": "maestro",
"args": [
"mcp"
],
"description": "Maestro mobile/web UI automation: list devices, drive and inspect the screen, run YAML flows locally or on Maestro Cloud."
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -15,7 +15,7 @@ export const createApp = () => {
// CORS middleware
app.use(cors({
origin: ['http://localhost:5174', 'http://localhost:4174', 'http://localhost:4176', 'http://localhost:4175', 'https://ui.freshyo.in', 'https://www.freshyo.in', 'https://webui.freshyo.in', 'https://app.freshyo.in', 'https://admin.freshyo.in', 'https://superadmin.freshyo.in'],
origin: ['http://localhost:5174', 'http://localhost:4174', 'http://localhost:4176', 'http://localhost:4175', 'https://ui.freshyo.in', 'https://www.freshyo.in', 'https://webui.freshyo.in', 'https://app.freshyo.in', 'https://admin.freshyo.in', 'https://superadmin.freshyo.in', 'http://192.168.100.126:4175'],
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'Caller-Interface'],
credentials: true,

View file

@ -0,0 +1,34 @@
import { router, superadminProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import { ApiError } from '@/src/lib/api-error'
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
import { listAllProducts, elevateProductToGlobal } from '@/src/dbService'
export const superadminProductsRouter = router({
// Every product across all regions (global + regional), paginated + name search.
list: superadminProcedure
.input(z.object({
regionId: z.number().optional(),
search: z.string().optional(),
limit: z.number().int().min(1).max(100).optional().default(20),
offset: z.number().int().min(0).optional().default(0),
}))
.query(async ({ input }) => {
return listAllProducts(input)
}),
// Elevate a regional product to a global one attached to a global store.
elevate: superadminProcedure
.input(z.object({ productId: z.number(), storeId: z.number() }))
.mutation(async ({ input }) => {
let product
try {
product = await elevateProductToGlobal(input.productId, input.storeId)
} catch (e: any) {
throw new ApiError(e.message || 'Failed to elevate product', 400)
}
if (!product) throw new ApiError('Product not found', 404)
await scheduleStoreInitialization()
return { product, message: 'Product elevated to global successfully' }
}),
})

View file

@ -5,6 +5,7 @@ import { superadminStaffRouter } from '@/src/trpc/apis/superadmin-apis/apis/staf
import { superadminConstRouter } from '@/src/trpc/apis/superadmin-apis/apis/const'
import { superadminGlobalStoresRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-stores'
import { superadminGlobalProductsRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-products'
import { superadminProductsRouter } from '@/src/trpc/apis/superadmin-apis/apis/products'
export const superadminRouter = router({
auth: superadminAuthRouter,
@ -13,6 +14,7 @@ export const superadminRouter = router({
const: superadminConstRouter,
globalStores: superadminGlobalStoresRouter,
globalProducts: superadminGlobalProductsRouter,
products: superadminProductsRouter,
})
export type SuperadminRouter = typeof superadminRouter

View file

@ -1,5 +1,5 @@
import { createFileRoute } from '@tanstack/react-router'
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components'
import { Plus, Trash2, X } from 'lucide-react'
import { ProtectedRoute } from '../components/ProtectedRoute'
@ -17,6 +17,8 @@ export const Route = createFileRoute('/global-products')({
),
})
const PAGE_SIZE = 20
interface FeatureDraft {
featureName: string
featureValue: string
@ -76,6 +78,195 @@ const skuToDraft = (sku: any): SkuDraft => ({
})
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'}`
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.
</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>
{tab === 'global' ? <GlobalProductsTab /> : <AllProductsTab />}
</div>
</AppContainer>
)
}
function AllProductsTab() {
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)
// Debounce the search box; reset to page 0 when the query changes.
useEffect(() => {
const t = setTimeout(() => {
setSearch(searchInput)
setPage(0)
}, 300)
return () => clearTimeout(t)
}, [searchInput])
const listQuery = trpc.superadmin.products.list.useQuery({
regionId: regionId === '' ? undefined : Number(regionId),
search: search || undefined,
limit: PAGE_SIZE,
offset: page * PAGE_SIZE,
})
const elevate = trpc.superadmin.products.elevate.useMutation()
const [elevatingId, setElevatingId] = useState<number | null>(null)
const [storeChoice, setStoreChoice] = useState<number | ''>('')
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) => {
if (storeChoice === '') {
window.alert('Choose a global store')
return
}
try {
await elevate.mutateAsync({ productId, storeId: Number(storeChoice) })
setElevatingId(null)
setStoreChoice('')
await utils.superadmin.products.list.invalidate()
await utils.superadmin.globalProducts.list.invalidate()
} catch (e: any) {
window.alert(e.message || 'Failed to elevate product')
}
}
return (
<div>
<div className="mb-4 flex flex-wrap items-center gap-3">
<input
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
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>}
<div className="grid gap-3">
{products.map((product) => {
const isGlobal = product.regionId == null
return (
<div key={product.id} className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
<div className="flex items-start justify-between gap-2">
<div>
<MyText className="block font-semibold text-gray-900">{product.name}</MyText>
<MyText className="block text-sm text-gray-500">
{product.region?.name ?? 'Global'} · {product.store?.name ?? 'No store'} ·{' '}
{product.skus?.length ?? 0} SKU(s)
</MyText>
</div>
<div className="flex items-center gap-2">
<span
className={`rounded-full px-2 py-0.5 text-[10px] font-bold ${
isGlobal ? 'bg-purple-100 text-purple-700' : 'bg-gray-100 text-gray-600'
}`}
>
{isGlobal ? 'GLOBAL' : 'REGIONAL'}
</span>
{!isGlobal ? (
<MyButton
onClick={() => {
setElevatingId(elevatingId === product.id ? null : product.id)
setStoreChoice('')
}}
>
Elevate to global
</MyButton>
) : null}
</div>
</div>
{elevatingId === product.id && !isGlobal ? (
<div className="mt-3 flex flex-wrap items-center gap-2 border-t border-gray-100 pt-3">
<MyText className="text-sm text-gray-500">Attach to global store:</MyText>
<select
value={storeChoice}
onChange={(e) => setStoreChoice(e.target.value === '' ? '' : Number(e.target.value))}
className="rounded-lg border border-gray-200 px-3 py-2 text-gray-900"
>
<option value="">Select…</option>
{stores.map((s: any) => (
<option key={s.id} value={s.id}>{s.name}</option>
))}
</select>
<MyButton onClick={() => doElevate(product.id)} disabled={elevate.isPending}>
{elevate.isPending ? 'Elevating…' : 'Confirm'}
</MyButton>
<button type="button" onClick={() => setElevatingId(null)} className="text-sm text-gray-500">
Cancel
</button>
</div>
) : null}
</div>
)
})}
</div>
<div className="mt-4 flex items-center justify-between">
<MyText className="text-sm text-gray-500">
{total} product(s) · page {page + 1} of {pageCount}
</MyText>
<div className="flex gap-2">
<MyButton onClick={() => setPage((p) => Math.max(0, p - 1))} disabled={page === 0}>
Prev
</MyButton>
<MyButton
onClick={() => setPage((p) => Math.min(pageCount - 1, p + 1))}
disabled={page >= pageCount - 1}
>
Next
</MyButton>
</div>
</div>
</div>
)
}
function GlobalProductsTab() {
const listQuery = trpc.superadmin.globalProducts.list.useQuery()
const utils = trpc.useUtils()
const [editingId, setEditingId] = useState<number | null>(null)

View file

@ -2540,3 +2540,41 @@ user-ui
global-products.tsx adds per-SKU image picking (existing keys + new uploads with previews +
remove) and uploads on submit with contextString 'product_info'.
tsc --noEmit: superadmin-ui, backend PASS. No migrations run. No tests run.
[2026-10-10 15:01:22 +0530] Superadmin: list all products (all regions) + elevate a regional product
to global (attach to a global store).
- schema.ts: productInfoRelations gains `region` (one regions via productInfo.regionId).
- NEW packages/db_helper_sqlite/src/superadmin-apis/products.ts:
listAllProducts(regionId?) — global + regional products with store/region/skus.
elevateProductToGlobal(productId, globalStoreId) — set region_id NULL + store to the
global store, seed each other region's market-stats row from the source region
(copy price/stock/offer/flash, is_suspended_in_region=false), compensating revert.
- index.ts: export listAllProducts, elevateProductToGlobal.
- NEW apps/backend/.../superadmin-apis/apis/products.ts router (list, elevate) registered in
superadmin-trpc-index.ts; elevate regenerates ALL regions.
- apps/superadmin-ui/src/routes/global-products.tsx: "All Products" / "Global Products" tabs;
All tab lists every product (region + store + GLOBAL/REGIONAL badge) with an Elevate action
(pick global store + confirm).
No migrations run. No tests run.
[2026-10-10 16:16:11 +0530] Enable Maestro MCP server for pi in this project.
Planned diffs:
.pi/mcp.json (NEW)
+ {
+ "mcpServers": {
+ "maestro": {
+ "command": "maestro",
+ "args": ["mcp"],
+ "description": "Maestro mobile/web UI automation: list devices, drive and inspect
+ the screen, run YAML flows locally or on Maestro Cloud."
+ }
+ }
+ }
(pi equivalent of the opencode.jsonc "maestro" local MCP entry:
opencode `"type": "local", "command": ["maestro", "mcp"]`
-> pi stdio `command` + `args`. Project-scoped, so it needs project trust.)
No source files touched. No migrations run. No tests run.

View file

@ -2,6 +2,11 @@
-- 0006_regions_and_superadmins, 0007_region_columns_backfill,
-- 0008_region_cache_versions, and 0009_three_const_tables.
--
-- Also folds in the later standalone migrations that used to run after this file:
-- * 0007_addresses_bound_id -> addresses.bound_id (+ backfill to 1)
-- * 0008_user_creds_unique_and_min_order_cleanup -> user_creds unique index and
-- removal of the retired `minRegularOrderValue`
--
-- The originals created two throwaway staging tables purely to copy from and
-- then drop them:
-- * `region_bound_settings` (created + seeded in 0006, dropped in 0009)
@ -75,6 +80,10 @@ AND NOT EXISTS (SELECT 1 FROM `region_bounds` WHERE `priority` = '2' AND `region
INSERT INTO `superadmins` (`username`, `password_hash`)
SELECT 'superadmin', '$2a$12$pDL1ooXdvmdpCFpeXgEnB.7eRot4ygtL/Z9lSmW8ApjRLAhTiuOCu'
WHERE NOT EXISTS (SELECT 1 FROM `superadmins` WHERE `username` = 'superadmin');
-- To add (or re-add) a superadmin manually, run:
-- INSERT INTO `superadmins` (`username`, `password_hash`)
-- VALUES ('superadmin', '$2a$12$pDL1ooXdvmdpCFpeXgEnB.7eRot4ygtL/Z9lSmW8ApjRLAhTiuOCu');
-- (password_hash is a bcrypt hash stored as-is, never re-hashed; username must be unique)
--> statement-breakpoint
-- Migration: rebuild the region-ownership FK subgraph with `region_id NOT NULL`
@ -298,12 +307,14 @@ CREATE TABLE `__new_addresses` (
`zone_id` integer,
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
`region_id` integer NOT NULL,
`bound_id` integer,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`bound_id`) REFERENCES `region_bounds`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
INSERT INTO `__new_addresses` (`id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`pincode`,`is_default`,`latitude`,`longitude`,`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,`region_id`)
SELECT `id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`pincode`,`is_default`,`latitude`,`longitude`,`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `addresses`;
INSERT INTO `__new_addresses` (`id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`pincode`,`is_default`,`latitude`,`longitude`,`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,`region_id`,`bound_id`)
SELECT `id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`pincode`,`is_default`,`latitude`,`longitude`,`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar'),1 FROM `addresses`;
--> statement-breakpoint
CREATE TABLE `__new_coupons` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
@ -900,9 +911,6 @@ WHERE kv.`key` IN ('popularItems','allItemsOrder','tagsOrder','isFlashDeliveryEn
--> statement-breakpoint
-- Per-bound business keys (formerly seeded into region_bound_settings in 0006).
INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`)
SELECT b.`id`, b.`region_id`, 'minRegularOrderValue', '300' FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar';
--> statement-breakpoint
INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`)
SELECT b.`id`, b.`region_id`, 'freeDeliveryThreshold', '300' FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar';
--> statement-breakpoint
INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`)
@ -918,6 +926,16 @@ SELECT b.`id`, b.`region_id`, 'flashDeliveryCharge', '69' FROM `regions` r JOIN
DELETE FROM `key_val_store` WHERE `key` IN (
'versionNum','playStoreUrl','appStoreUrl','internalAppVersion',
'popularItems','allItemsOrder','tagsOrder','isFlashDeliveryEnabled','supportMobile','supportEmail','welcomeMessage',
'cache_version','availability_version_num','slots_version_num'
'cache_version','availability_version_num','slots_version_num',
'minRegularOrderValue'
);
--> statement-breakpoint
-- =====================================================================
-- Phase 4 (from 0008): user_creds uniqueness.
-- Collapse duplicate rows (keep the newest per user) before the unique index.
-- =====================================================================
DELETE FROM `user_creds`
WHERE `id` NOT IN (SELECT MAX(`id`) FROM `user_creds` GROUP BY `user_id`);
--> statement-breakpoint
CREATE UNIQUE INDEX IF NOT EXISTS `unique_user_creds_user` ON `user_creds` (`user_id`);

View file

@ -1,11 +0,0 @@
-- Migration: addresses.bound_id — the bound a saved address belongs to.
--
-- Every address is assigned to a bound; new addresses get the user's active
-- bound. Existing rows are backfilled to bound 1.
--
-- NOTE: SQLite has no ADD COLUMN IF NOT EXISTS; rely on the migration journal to
-- run this once.
ALTER TABLE `addresses` ADD COLUMN `bound_id` integer REFERENCES `region_bounds`(`id`);
--> statement-breakpoint
UPDATE `addresses` SET `bound_id` = 1 WHERE `bound_id` IS NULL;

View file

@ -1,26 +0,0 @@
-- Migration: user_creds uniqueness + removal of the retired `minRegularOrderValue`.
--
-- Two independent cleanups bundled into one migration (applied together).
--
-- 1) user_creds.user_id must be unique.
-- upsertUserPassword used to insert a fresh row on D1 (no UNIQUE(user_id) to
-- trip the Postgres 23505 fallback), so accounts accumulated duplicate rows and
-- login kept reading the stale one — a password change had no effect. The app
-- now selects-then-updates; this makes the invariant explicit. Existing
-- duplicates must be collapsed first (keep the newest row per user, which
-- carries the most recently set password) or CREATE UNIQUE INDEX aborts.
--
-- 2) Drop the retired `minRegularOrderValue` constant.
-- It was never enforced as a minimum order value, and the delivery threshold
-- now uses `freeDeliveryThreshold`. Delete its leftover rows. 0006 seeds
-- `region_bound_consts.minRegularOrderValue` for fresh installs; this migration
-- runs after it, so those seeded rows are removed too.
DELETE FROM `user_creds`
WHERE `id` NOT IN (SELECT MAX(`id`) FROM `user_creds` GROUP BY `user_id`);
--> statement-breakpoint
CREATE UNIQUE INDEX IF NOT EXISTS `unique_user_creds_user` ON `user_creds` (`user_id`);
--> statement-breakpoint
DELETE FROM `region_bound_consts` WHERE `key` = 'minRegularOrderValue';
--> statement-breakpoint
DELETE FROM `key_val_store` WHERE `key` = 'minRegularOrderValue';

View file

@ -50,13 +50,6 @@
"when": 1791367872000,
"tag": "0006_regions_and_superadmins",
"breakpoints": true
},
{
"idx": 7,
"version": "6",
"when": 1792010000000,
"tag": "0007_addresses_bound_id",
"breakpoints": true
}
]
}

View file

@ -431,3 +431,8 @@ export {
updateGlobalProduct,
deleteGlobalProductById,
} from './src/superadmin-apis/global-products'
export {
listAllProducts,
elevateProductToGlobal,
} from './src/superadmin-apis/products'

View file

@ -659,6 +659,7 @@ export const unitsRelations = relations(units, ({}) => ({
export const productInfoRelations = relations(productInfo, ({ one, many }) => ({
store: one(storeInfo, { fields: [productInfo.storeId], references: [storeInfo.id] }),
region: one(regions, { fields: [productInfo.regionId], references: [regions.id] }),
skus: many(productSkus),
tags: many(productTags),
reviews: many(productReviews),

View file

@ -0,0 +1,117 @@
import { db } from '../db/db_index'
import { productInfo } from '../db/schema'
import { and, eq, isNull, like, or, sql } from 'drizzle-orm'
import { isGlobalStore } from './global-stores'
const productWith = {
store: true,
region: true,
skus: {
with: {
features: true,
marketStats: true,
comboItems: true,
},
},
} as const
export interface ListAllProductsOptions {
regionId?: number
search?: string
limit?: number
offset?: number
}
/** All products (global + regional), paginated and searchable by name. */
export async function listAllProducts(opts: ListAllProductsOptions = {}) {
const { regionId, search } = opts
const limit = Math.min(Math.max(opts.limit ?? 20, 1), 100)
const offset = Math.max(opts.offset ?? 0, 0)
const filters: any[] = []
if (regionId != null) filters.push(eq(productInfo.regionId, regionId))
const term = search?.trim()
if (term) {
// Match the product name, its descriptions, or any of its SKU names.
const pattern = `%${term}%`
filters.push(or(
like(productInfo.name, pattern),
like(productInfo.shortDescription, pattern),
like(productInfo.longDescription, pattern),
sql`EXISTS (SELECT 1 FROM product_skus ps WHERE ps.product_id = ${productInfo.id} AND ps.name LIKE ${pattern})`,
))
}
const where = filters.length > 0 ? and(...filters) : undefined
const [rows, countRows] = await Promise.all([
db.query.productInfo.findMany({
where,
orderBy: productInfo.name,
limit,
offset,
with: productWith,
}),
db.select({ count: sql<number>`count(*)` }).from(productInfo).where(where),
])
return { products: rows, total: Number(countRows[0]?.count ?? 0) }
}
/**
* Elevate a regional product to a global one attached to `globalStoreId`:
* clears its region and seeds each OTHER region's market-stats row from the
* source region (price/stock/offer/flash copied; region-suspension reset to
* false). The source region's own row is kept unchanged.
*/
export async function elevateProductToGlobal(productId: number, globalStoreId: number) {
const product = await db.query.productInfo.findFirst({
where: eq(productInfo.id, productId),
columns: { id: true, regionId: true, storeId: true },
})
if (!product) throw new Error('Product not found')
if (product.regionId == null) throw new Error('Product is already global')
if (!(await isGlobalStore(globalStoreId))) throw new Error('Target store is not a global store')
const sourceRegionId = product.regionId
try {
return await db.transaction(async (tx) => {
await tx
.update(productInfo)
.set({ regionId: null, storeId: globalStoreId })
.where(eq(productInfo.id, productId))
await tx.run(sql`
INSERT INTO product_market_stats
(sku_id, region_id, market_price, our_price, is_flash_available, flash_price, is_out_of_stock, is_suspended_in_region, is_offer)
SELECT ms.sku_id, r.id, ms.market_price, ms.our_price, ms.is_flash_available, ms.flash_price,
ms.is_out_of_stock, false, ms.is_offer
FROM product_market_stats ms
CROSS JOIN regions r
WHERE ms.region_id = ${sourceRegionId}
AND ms.sku_id IN (SELECT id FROM product_skus WHERE product_id = ${productId})
AND NOT EXISTS (
SELECT 1 FROM product_market_stats x WHERE x.sku_id = ms.sku_id AND x.region_id = r.id
)
`)
const updated = await tx.query.productInfo.findFirst({
where: eq(productInfo.id, productId),
with: productWith,
})
return updated ?? null
})
} catch (error) {
// Compensate: D1 may leave the region_id change committed when the seed
// fails, so put the product back into its original region/store.
try {
await db
.update(productInfo)
.set({ regionId: sourceRegionId, storeId: product.storeId ?? null })
.where(and(eq(productInfo.id, productId), isNull(productInfo.regionId)))
} catch (cleanupError) {
console.error('Failed to revert elevateProductToGlobal', productId, cleanupError)
}
throw error
}
}