+ )
+}
+
+function GlobalProductsTab() {
const listQuery = trpc.superadmin.globalProducts.list.useQuery()
const utils = trpc.useUtils()
const [editingId, setEditingId] = useState(null)
diff --git a/change-log.txt b/change-log.txt
index ad6d407..5581f94 100644
--- a/change-log.txt
+++ b/change-log.txt
@@ -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.
diff --git a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
index 0e81e33..f48fe0c 100644
--- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
+++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
@@ -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`);
diff --git a/packages/db_helper_sqlite/drizzle/0007_addresses_bound_id.sql b/packages/db_helper_sqlite/drizzle/0007_addresses_bound_id.sql
deleted file mode 100644
index 9a1dfd2..0000000
--- a/packages/db_helper_sqlite/drizzle/0007_addresses_bound_id.sql
+++ /dev/null
@@ -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;
diff --git a/packages/db_helper_sqlite/drizzle/0008_user_creds_unique_and_min_order_cleanup.sql b/packages/db_helper_sqlite/drizzle/0008_user_creds_unique_and_min_order_cleanup.sql
deleted file mode 100644
index 7896e1e..0000000
--- a/packages/db_helper_sqlite/drizzle/0008_user_creds_unique_and_min_order_cleanup.sql
+++ /dev/null
@@ -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';
diff --git a/packages/db_helper_sqlite/drizzle/meta/_journal.json b/packages/db_helper_sqlite/drizzle/meta/_journal.json
index 41b53c5..27c7c18 100644
--- a/packages/db_helper_sqlite/drizzle/meta/_journal.json
+++ b/packages/db_helper_sqlite/drizzle/meta/_journal.json
@@ -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
}
]
}
diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts
index 653a324..f7b7796 100644
--- a/packages/db_helper_sqlite/index.ts
+++ b/packages/db_helper_sqlite/index.ts
@@ -431,3 +431,8 @@ export {
updateGlobalProduct,
deleteGlobalProductById,
} from './src/superadmin-apis/global-products'
+
+export {
+ listAllProducts,
+ elevateProductToGlobal,
+} from './src/superadmin-apis/products'
diff --git a/packages/db_helper_sqlite/src/db/schema.ts b/packages/db_helper_sqlite/src/db/schema.ts
index 6f5c542..0095002 100644
--- a/packages/db_helper_sqlite/src/db/schema.ts
+++ b/packages/db_helper_sqlite/src/db/schema.ts
@@ -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),
diff --git a/packages/db_helper_sqlite/src/superadmin-apis/products.ts b/packages/db_helper_sqlite/src/superadmin-apis/products.ts
new file mode 100644
index 0000000..75d7045
--- /dev/null
+++ b/packages/db_helper_sqlite/src/superadmin-apis/products.ts
@@ -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`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
+ }
+}