1459 lines
50 KiB
TypeScript
1459 lines
50 KiB
TypeScript
import { db } from '../db/db_index'
|
||
import {
|
||
productInfo,
|
||
productMarketStats,
|
||
productSkus,
|
||
skuFeatures,
|
||
productCombos,
|
||
units,
|
||
specialDeals,
|
||
deliverySlotInfo,
|
||
productTags,
|
||
productReviews,
|
||
productGroupInfo,
|
||
productGroupMembership,
|
||
productTagInfo,
|
||
users,
|
||
storeInfo,
|
||
regions,
|
||
cartItems,
|
||
orderItems,
|
||
coupons,
|
||
reservedCoupons,
|
||
vendorSnippets,
|
||
homeBanners,
|
||
keyValStore,
|
||
couponApplicableProducts,
|
||
} from '../db/schema'
|
||
import { and, desc, eq, inArray, isNull, or, sql, type SQL } from 'drizzle-orm'
|
||
import { runBatched } from '../lib/run-batched'
|
||
import { marketStatsForRegion, isSkuSuspended } from '../lib/market-stats'
|
||
import type { InferSelectModel } from 'drizzle-orm'
|
||
|
||
// Chunk sizes for multi-row inserts so no single statement exceeds SQLite's
|
||
// 999-bind-parameter limit (chunk size × params-per-row must stay under 999).
|
||
const SKU_INSERT_CHUNK_SIZE = 100 // 6 params per SKU row
|
||
const FEATURE_INSERT_CHUNK_SIZE = 200 // 3 params per feature row
|
||
const COMBO_ITEM_INSERT_CHUNK_SIZE = 400 // 2 params per combo-item row
|
||
|
||
// product_combos has a UNIQUE index on (comboSkuId, skuId) — drop duplicates
|
||
// (by skuId) before inserting so a repeated pick doesn't fail the insert.
|
||
const dedupeComboItems = (items: any[]): any[] => {
|
||
const seen = new Set<number>()
|
||
return (items || []).filter((ci: any) => {
|
||
const id = Number(ci.skuId)
|
||
if (!id || seen.has(id)) return false
|
||
seen.add(id)
|
||
return true
|
||
})
|
||
}
|
||
import type {
|
||
AdminProduct,
|
||
AdminProductGroupInfo,
|
||
AdminProductTagInfo,
|
||
AdminProductTagWithProducts,
|
||
AdminProductReview,
|
||
AdminProductWithDetails,
|
||
AdminProductWithRelations,
|
||
AdminSku,
|
||
AdminSkuFeature,
|
||
AdminSpecialDeal,
|
||
AdminUnit,
|
||
AdminUpdateSlotProductsResult,
|
||
CreateComboItemInput,
|
||
CreateProductInput,
|
||
CreateSkuInput,
|
||
ProductTagCore,
|
||
SkuFeatureLike,
|
||
Store,
|
||
} from '@packages/shared'
|
||
|
||
type ProductRow = InferSelectModel<typeof productInfo>
|
||
type SkuRow = InferSelectModel<typeof productSkus>
|
||
type MarketStatsRow = InferSelectModel<typeof productMarketStats>
|
||
type SkuFeatureRow = InferSelectModel<typeof skuFeatures>
|
||
type StoreRow = InferSelectModel<typeof storeInfo>
|
||
type SpecialDealRow = InferSelectModel<typeof specialDeals>
|
||
type ProductTagInfoRow = InferSelectModel<typeof productTagInfo>
|
||
type ProductTagRow = InferSelectModel<typeof productTags>
|
||
|
||
const getStringArray = (value: unknown): string[] | null => {
|
||
if (!Array.isArray(value)) return null
|
||
return value.map((item) => String(item))
|
||
}
|
||
|
||
// Region guards: SKUs resolve to a region through their parent product
|
||
// (productSkus.productId -> productInfo.regionId). A global SKU (its product's
|
||
// 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 } } },
|
||
columns: { id: true },
|
||
})
|
||
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> => {
|
||
const unique = [...new Set(skuIds.map(Number).filter((n) => Number.isFinite(n)))]
|
||
if (unique.length === 0) return
|
||
const regions = await resolveSkuRegions(txOrDb, unique)
|
||
const missing = unique.filter((id) => !regions.has(id))
|
||
if (missing.length > 0) {
|
||
throw new Error(`Invalid ${noun} IDs: ${missing.join(', ')}`)
|
||
}
|
||
const foreign = unique.filter((id) => {
|
||
const r = regions.get(id)!
|
||
// A global product (regionId null) may only contain global SKUs; a regional
|
||
// product may not contain another region's SKU.
|
||
if (regionId == null) return !r.isGlobal
|
||
return !r.isGlobal && r.regionId !== regionId
|
||
})
|
||
if (foreign.length > 0) {
|
||
throw new Error(`${noun} ${foreign.join(', ')} belongs to a different region`)
|
||
}
|
||
}
|
||
|
||
const assertStoreInRegion = async (txOrDb: any, storeId: number, regionId: number | null): Promise<void> => {
|
||
const store = await txOrDb.query.storeInfo.findFirst({
|
||
where: eq(storeInfo.id, storeId),
|
||
columns: { id: true, regionId: true, isGlobal: true },
|
||
})
|
||
if (!store) {
|
||
throw new Error(`Invalid store ID: ${storeId}`)
|
||
}
|
||
if (regionId == null) {
|
||
// A global product must belong to a global store.
|
||
if (!store.isGlobal) throw new Error('A global product must use a global store')
|
||
return
|
||
}
|
||
// A regional product may use its own region's store OR a global store (a
|
||
// global store is shared, so it serves every region). Only a non-global store
|
||
// from another region is rejected.
|
||
if (!store.isGlobal && store.regionId !== regionId) {
|
||
throw new Error('Store belongs to a different region')
|
||
}
|
||
}
|
||
|
||
const assertStoreIdsInRegion = async (txOrDb: any, storeIds: number[], regionId: number): Promise<void> => {
|
||
const unique = [...new Set(storeIds.map(Number).filter((n) => Number.isFinite(n)))]
|
||
if (unique.length === 0) return
|
||
const rows = await txOrDb.query.storeInfo.findMany({
|
||
where: inArray(storeInfo.id, unique),
|
||
columns: { id: true, regionId: true, isGlobal: true },
|
||
})
|
||
if (rows.length !== unique.length) {
|
||
const found = new Set(rows.map((r: { id: number }) => r.id))
|
||
throw new Error(`Invalid store IDs: ${unique.filter((id) => !found.has(id)).join(', ')}`)
|
||
}
|
||
if (rows.some((r: { regionId: number | null; isGlobal: boolean }) => !r.isGlobal && r.regionId !== regionId)) {
|
||
throw new Error('Store belongs to a different region')
|
||
}
|
||
}
|
||
|
||
const mapStore = (store: StoreRow): Store => ({
|
||
id: store.id,
|
||
name: store.name,
|
||
description: store.description,
|
||
imageUrl: store.imageUrl,
|
||
isGlobal: store.isGlobal,
|
||
createdAt: store.createdAt,
|
||
})
|
||
|
||
const mapProduct = (product: ProductRow): AdminProduct => ({
|
||
id: product.id,
|
||
name: product.name,
|
||
shortDescription: product.shortDescription ?? null,
|
||
longDescription: product.longDescription ?? null,
|
||
storeId: product.storeId,
|
||
incrementStep: product.incrementStep,
|
||
createdAt: product.createdAt,
|
||
productType: product.productType as 'item' | 'combo',
|
||
isGlobal: product.regionId == null,
|
||
})
|
||
|
||
const mapSkuFeature = (feature: SkuFeatureRow): AdminSkuFeature => ({
|
||
id: feature.id,
|
||
skuId: feature.skuId,
|
||
featureName: feature.featureName,
|
||
featureValue: feature.featureValue,
|
||
})
|
||
|
||
const mapSku = (
|
||
sku: SkuRow,
|
||
features: SkuFeatureRow[] = [],
|
||
comboItems: any[] = [],
|
||
marketStats: MarketStatsRow | null = null
|
||
): AdminSku => ({
|
||
id: sku.id,
|
||
productId: sku.productId,
|
||
name: sku.name ?? null,
|
||
price: marketStats?.ourPrice ? String(marketStats.ourPrice) : '0',
|
||
marketPrice: marketStats?.marketPrice ? String(marketStats.marketPrice) : null,
|
||
images: getStringArray(sku.images),
|
||
imageKeys: getStringArray(sku.images),
|
||
isOutOfStock: marketStats?.isOutOfStock ?? false,
|
||
isSuspended: sku.isSuspended,
|
||
isFlashAvailable: marketStats?.isFlashAvailable ?? false,
|
||
flashPrice: marketStats?.flashPrice ? String(marketStats.flashPrice) : null,
|
||
isOffer: marketStats?.isOffer ?? false,
|
||
isComboOnly: sku.isComboOnly,
|
||
isDeleted: sku.isDeleted ?? false,
|
||
createdAt: sku.createdAt,
|
||
features: features.map(mapSkuFeature),
|
||
comboItems: comboItems,
|
||
})
|
||
|
||
const mapSpecialDeal = (deal: SpecialDealRow): AdminSpecialDeal => ({
|
||
id: deal.id,
|
||
skuId: deal.skuId,
|
||
quantity: String(deal.quantity ?? '0'),
|
||
price: String(deal.price ?? '0'),
|
||
validTill: deal.validTill,
|
||
})
|
||
|
||
const mapTagInfo = (tag: ProductTagInfoRow): AdminProductTagInfo => ({
|
||
id: tag.id,
|
||
tagName: tag.tagName,
|
||
tagDescription: tag.tagDescription ?? null,
|
||
imageUrl: tag.imageUrl ?? null,
|
||
isDashboardTag: tag.isDashboardTag,
|
||
relatedStores: tag.relatedStores,
|
||
sortOrder: tag.sortOrder ?? [],
|
||
createdAt: tag.createdAt,
|
||
})
|
||
|
||
export async function getAllProducts(regionId: number): Promise<AdminProductWithRelations[]> {
|
||
type ProductWithRelationsRow = ProductRow & {
|
||
store: StoreRow | null
|
||
skus: Array<SkuRow & { features: SkuFeatureRow[]; comboItems: any[]; marketStats: MarketStatsRow[] }>
|
||
}
|
||
const products = await db.query.productInfo.findMany({
|
||
where: or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId)),
|
||
orderBy: productInfo.name,
|
||
with: {
|
||
store: true,
|
||
skus: {
|
||
with: {
|
||
features: true,
|
||
marketStats: true,
|
||
comboItems: {
|
||
with: {
|
||
sku: { with: { product: true, features: true, marketStats: true } },
|
||
},
|
||
},
|
||
},
|
||
},
|
||
},
|
||
}) as ProductWithRelationsRow[]
|
||
|
||
// Soft-deleted products keep their rows for order history but are hidden here.
|
||
return products
|
||
.filter((product) => product.skus.some((sku) => !sku.isDeleted))
|
||
.map((product) => ({
|
||
...mapProduct(product),
|
||
store: product.store ? mapStore(product.store) : null,
|
||
skus: product.skus.map((sku) => {
|
||
const comboItems = (sku.comboItems || []).map((ci: any) => {
|
||
const ciMarketStats = marketStatsForRegion(ci.sku?.marketStats, regionId)
|
||
return {
|
||
skuId: ci.skuId,
|
||
skuName: ci.sku?.name ?? null,
|
||
features: (ci.sku?.features || []).map((f: any) => ({ featureName: f.featureName, featureValue: f.featureValue })),
|
||
productName: ci.sku?.product?.name ?? 'Unknown',
|
||
images: getStringArray(ci.sku?.images),
|
||
price: ciMarketStats?.ourPrice ? String(ciMarketStats.ourPrice) : '0',
|
||
}
|
||
})
|
||
return mapSku(sku, sku.features, comboItems, marketStatsForRegion(sku.marketStats, regionId))
|
||
}),
|
||
}))
|
||
}
|
||
|
||
/**
|
||
* The image keys a product's SKUs currently reference. The admin update path re-sends a product's
|
||
* existing images on every edit, so this is what tells "already owned" apart from a new upload.
|
||
*/
|
||
export async function getProductImageKeys(regionId: number, productId: number): Promise<string[]> {
|
||
const product = await db.query.productInfo.findFirst({
|
||
where: and(eq(productInfo.id, productId), or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))),
|
||
columns: { id: true },
|
||
with: { skus: { columns: { images: true } } },
|
||
})
|
||
|
||
return (product?.skus ?? []).flatMap((sku) =>
|
||
((sku.images as string[] | null) ?? []).map(String)
|
||
)
|
||
}
|
||
|
||
export async function getProductById(regionId: number, id: number): Promise<AdminProductWithDetails | null> {
|
||
const product = await db.query.productInfo.findFirst({
|
||
where: and(eq(productInfo.id, id), or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))),
|
||
with: {
|
||
store: true,
|
||
skus: {
|
||
with: {
|
||
features: true,
|
||
marketStats: true,
|
||
comboItems: {
|
||
with: {
|
||
sku: { with: { product: true, features: true, marketStats: true } },
|
||
},
|
||
},
|
||
},
|
||
},
|
||
},
|
||
})
|
||
|
||
if (!product) {
|
||
return null
|
||
}
|
||
|
||
const skuIds = product.skus.map((sku) => sku.id)
|
||
|
||
const deals = skuIds.length > 0
|
||
? await db.query.specialDeals.findMany({
|
||
where: inArray(specialDeals.skuId, skuIds),
|
||
orderBy: specialDeals.quantity,
|
||
})
|
||
: []
|
||
|
||
const productTagsData = await db.query.productTags.findMany({
|
||
where: eq(productTags.productId, id),
|
||
with: {
|
||
tag: true,
|
||
},
|
||
}) as Array<ProductTagRow & { tag: ProductTagInfoRow }>
|
||
|
||
const skusWithCombos = product.skus.map((sku) => {
|
||
const comboItems = (sku.comboItems || []).map((ci: any) => {
|
||
const ciMarketStats = marketStatsForRegion(ci.sku?.marketStats, regionId)
|
||
return {
|
||
skuId: ci.skuId,
|
||
skuName: ci.sku?.name ?? null,
|
||
features: (ci.sku?.features || []).map((f: any) => ({ featureName: f.featureName, featureValue: f.featureValue })),
|
||
productName: ci.sku?.product?.name ?? 'Unknown',
|
||
images: getStringArray(ci.sku?.images),
|
||
price: ciMarketStats?.ourPrice ? String(ciMarketStats.ourPrice) : '0',
|
||
}
|
||
})
|
||
return mapSku(sku, sku.features, comboItems, marketStatsForRegion(sku.marketStats, regionId))
|
||
})
|
||
|
||
return {
|
||
...mapProduct(product),
|
||
store: product.store ? mapStore(product.store) : null,
|
||
skus: skusWithCombos,
|
||
deals: deals.map(mapSpecialDeal),
|
||
tags: productTagsData.map((tag) => mapTagInfo(tag.tag)),
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Soft delete. `order_items.sku_id` is a NOT NULL FK and order history renders
|
||
* each line by joining order_items -> product_skus -> product_info (+ sku_features),
|
||
* so the product and its SKUs are kept: the SKU is flagged `is_deleted` and only the
|
||
* state that keeps the product orderable/visible is removed. Deleting the rows instead
|
||
* would either trip D1's FK enforcement or blank out historical order lines.
|
||
*/
|
||
async function softDeleteProduct(where: SQL): Promise<AdminProduct | null> {
|
||
const product = await db.query.productInfo.findFirst({
|
||
where,
|
||
with: { skus: { columns: { id: true } } },
|
||
})
|
||
|
||
if (!product) {
|
||
return null
|
||
}
|
||
|
||
const skuIds = product.skus.map((sku) => sku.id)
|
||
|
||
if (skuIds.length > 0) {
|
||
await db.batch([
|
||
db.delete(productMarketStats).where(inArray(productMarketStats.skuId, skuIds)),
|
||
db.delete(cartItems).where(inArray(cartItems.skuId, skuIds)),
|
||
db.delete(couponApplicableProducts).where(inArray(couponApplicableProducts.skuId, skuIds)),
|
||
// product_tags / product_group_membership store SKU ids in their `product_id` column
|
||
db.delete(productTags).where(inArray(productTags.productId, skuIds)),
|
||
db.delete(productGroupMembership).where(inArray(productGroupMembership.productId, skuIds)),
|
||
db.delete(productCombos).where(inArray(productCombos.skuId, skuIds)),
|
||
db.delete(productCombos).where(inArray(productCombos.comboSkuId, skuIds)),
|
||
db.delete(specialDeals).where(inArray(specialDeals.skuId, skuIds)),
|
||
// sku_features are deliberately kept: order history composes the name/unit from them.
|
||
db.update(productSkus).set({ isDeleted: true }).where(inArray(productSkus.id, skuIds)),
|
||
] as any)
|
||
}
|
||
|
||
return mapProduct(product)
|
||
}
|
||
|
||
export async function deleteProduct(regionId: number, id: number): Promise<AdminProduct | null> {
|
||
const where = and(eq(productInfo.id, id), eq(productInfo.regionId, regionId))
|
||
if (!where) return null
|
||
return softDeleteProduct(where)
|
||
}
|
||
|
||
export async function deleteGlobalProduct(id: number): Promise<AdminProduct | null> {
|
||
const where = and(eq(productInfo.id, id), isNull(productInfo.regionId))
|
||
if (!where) return null
|
||
return softDeleteProduct(where)
|
||
}
|
||
|
||
export async function createProduct(input: CreateProductInput, regionId: number | null): Promise<AdminProductWithRelations> {
|
||
if (!input.skus || input.skus.length === 0) {
|
||
throw new Error('At least one SKU is required')
|
||
}
|
||
|
||
const featuresHaveQuantity = input.skus.every((sku) =>
|
||
sku.features.some((f) => f.featureName === 'quantity')
|
||
)
|
||
if (!featuresHaveQuantity) {
|
||
throw new Error('Every SKU must have a quantity feature')
|
||
}
|
||
|
||
// A global product (regionId null) seeds a market-stats row in EVERY region so
|
||
// each region gets the superadmin's initial values.
|
||
const targetRegionIds = regionId == null
|
||
? (await db.select({ id: regions.id }).from(regions)).map((r) => r.id)
|
||
: [regionId]
|
||
|
||
// Cross-region validation BEFORE the generic try/catch so the specific
|
||
// message reaches the caller instead of the masked generic failure.
|
||
if ((input as any).storeId != null) {
|
||
await assertStoreInRegion(db, (input as any).storeId, regionId)
|
||
}
|
||
await assertSkuIdsInRegion(
|
||
db,
|
||
(input.skus || []).flatMap((sku: any) => (sku.comboItems || []).map((ci: any) => Number(ci.skuId))),
|
||
regionId,
|
||
'Combo SKU'
|
||
)
|
||
|
||
try {
|
||
return await db.transaction(async (tx) => {
|
||
const { skus, ...productData } = input
|
||
|
||
const [product] = await tx.insert(productInfo).values({
|
||
regionId,
|
||
name: productData.name,
|
||
shortDescription: productData.shortDescription ?? null,
|
||
longDescription: productData.longDescription ?? null,
|
||
storeId: productData.storeId ?? null,
|
||
incrementStep: productData.incrementStep ?? 1,
|
||
productType: productData.productType ?? 'item',
|
||
}).returning()
|
||
|
||
const skuChunks = await runBatched(tx, skus, SKU_INSERT_CHUNK_SIZE, async (t, chunk) => {
|
||
return t.insert(productSkus).values(
|
||
chunk.map((sku) => ({
|
||
productId: product.id,
|
||
name: sku.name ?? null,
|
||
images: sku.images ?? null,
|
||
isComboOnly: sku.isComboOnly ?? false,
|
||
isDeleted: sku.isDeleted ?? false,
|
||
isSuspended: sku.isSuspended ?? false,
|
||
}))
|
||
).returning()
|
||
})
|
||
const skuRows = skuChunks.flat()
|
||
|
||
for (let i = 0; i < skuRows.length; i++) {
|
||
const skuRow = skuRows[i]
|
||
const sku = skus[i]
|
||
|
||
await tx.insert(productMarketStats).values(targetRegionIds.map((rid) => ({
|
||
skuId: skuRow.id,
|
||
regionId: rid,
|
||
marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null,
|
||
ourPrice: sku.price != null ? String(sku.price) : '0',
|
||
isFlashAvailable: sku.isFlashAvailable ?? false,
|
||
flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null,
|
||
isOutOfStock: sku.isOutOfStock ?? false,
|
||
isOffer: sku.isOffer ?? false,
|
||
})))
|
||
|
||
if (sku.features && sku.features.length > 0) {
|
||
await runBatched(tx, sku.features, FEATURE_INSERT_CHUNK_SIZE, async (t, chunk) => {
|
||
await t.insert(skuFeatures).values(
|
||
chunk.map((f) => ({
|
||
skuId: skuRow.id,
|
||
featureName: f.featureName,
|
||
featureValue: f.featureValue,
|
||
}))
|
||
)
|
||
})
|
||
}
|
||
|
||
if (sku.comboItems && sku.comboItems.length > 0) {
|
||
const comboItems = dedupeComboItems(sku.comboItems)
|
||
if (comboItems.length > 0) {
|
||
await runBatched(tx, comboItems, COMBO_ITEM_INSERT_CHUNK_SIZE, async (t, chunk) => {
|
||
await t.insert(productCombos).values(
|
||
chunk.map((ci: any) => ({
|
||
comboSkuId: skuRow.id,
|
||
skuId: ci.skuId,
|
||
}))
|
||
)
|
||
})
|
||
}
|
||
}
|
||
}
|
||
|
||
const createdSkus = await tx.query.productSkus.findMany({
|
||
where: eq(productSkus.productId, product.id),
|
||
with: { features: true, marketStats: true },
|
||
})
|
||
|
||
return {
|
||
...mapProduct(product),
|
||
store: null,
|
||
skus: createdSkus.map((s) => mapSku(s, s.features, [], marketStatsForRegion(s.marketStats, regionId ?? targetRegionIds[0]))),
|
||
}
|
||
})
|
||
} catch (error) {
|
||
console.error('createProduct failed:', error)
|
||
throw new Error('Failed to create product. Please check the SKU details and try again.')
|
||
}
|
||
}
|
||
|
||
// A regional admin editing a GLOBAL product may change only this region's market
|
||
// data — never the product's structure (owned by the superadmin).
|
||
async function updateProductMarketDataForRegion(regionId: number, id: number, input: any): Promise<void> {
|
||
const skus = input?.skus
|
||
if (!Array.isArray(skus) || skus.length === 0) return
|
||
const existingSkus = await db.query.productSkus.findMany({
|
||
where: eq(productSkus.productId, id),
|
||
columns: { id: true },
|
||
})
|
||
const existingSkuIdSet = new Set(existingSkus.map((s) => s.id))
|
||
await db.transaction(async (tx) => {
|
||
for (const sku of skus) {
|
||
if (sku?.id == null || !existingSkuIdSet.has(sku.id)) continue
|
||
const values = {
|
||
marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null,
|
||
ourPrice: sku.price != null ? String(sku.price) : '0',
|
||
isFlashAvailable: sku.isFlashAvailable ?? false,
|
||
flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null,
|
||
isOutOfStock: sku.isOutOfStock ?? false,
|
||
isSuspendedInRegion: sku.isSuspendedInRegion ?? sku.isSuspended ?? false,
|
||
isOffer: sku.isOffer ?? false,
|
||
}
|
||
const existing = await tx.query.productMarketStats.findFirst({
|
||
where: and(eq(productMarketStats.skuId, sku.id), eq(productMarketStats.regionId, regionId)),
|
||
columns: { id: true },
|
||
})
|
||
if (existing) {
|
||
await tx.update(productMarketStats).set(values)
|
||
.where(and(eq(productMarketStats.skuId, sku.id), eq(productMarketStats.regionId, regionId)))
|
||
} else {
|
||
await tx.insert(productMarketStats).values({ skuId: sku.id, regionId, ...values })
|
||
}
|
||
}
|
||
})
|
||
}
|
||
|
||
export async function updateProduct(regionId: number | null, id: number, input: any): Promise<AdminProductWithRelations | null> {
|
||
const product = await db.query.productInfo.findFirst({
|
||
where: eq(productInfo.id, id),
|
||
})
|
||
|
||
if (!product) {
|
||
return null
|
||
}
|
||
|
||
// A global product edited by a regional admin (regionId != null): market data
|
||
// only, for that region. A regional product may only be edited by its region.
|
||
if (regionId != null && product.regionId == null) {
|
||
await updateProductMarketDataForRegion(regionId, id, input)
|
||
return getProductById(regionId, id)
|
||
}
|
||
if (regionId != null && product.regionId !== regionId) {
|
||
return null
|
||
}
|
||
|
||
// Regions whose market stats this update writes: the caller's region, or every
|
||
// region for a superadmin structural edit of a global product (regionId null).
|
||
const targetRegionIds = regionId == null
|
||
? (await db.select({ id: regions.id }).from(regions)).map((r) => r.id)
|
||
: [regionId]
|
||
|
||
const { skus, ...productData } = input
|
||
|
||
// Input validation outside the transaction so specific messages reach the UI.
|
||
if (productData.storeId != null) {
|
||
await assertStoreInRegion(db, productData.storeId, regionId)
|
||
}
|
||
if (skus !== undefined) {
|
||
if (skus.length === 0) {
|
||
throw new Error('At least one SKU is required')
|
||
}
|
||
|
||
const featuresHaveQuantity = skus.every((sku: any) =>
|
||
sku.features?.some((f: any) => f.featureName === 'quantity')
|
||
)
|
||
if (!featuresHaveQuantity) {
|
||
throw new Error('Every SKU must have a quantity feature')
|
||
}
|
||
|
||
const existingSkus = await db.query.productSkus.findMany({
|
||
where: eq(productSkus.productId, id),
|
||
columns: { id: true },
|
||
})
|
||
const existingSkuIdSet = new Set(existingSkus.map((s) => s.id))
|
||
|
||
await assertSkuIdsInRegion(
|
||
db,
|
||
skus.flatMap((sku: any) => (sku.comboItems || []).map((ci: any) => Number(ci.skuId))),
|
||
regionId,
|
||
'Combo SKU'
|
||
)
|
||
|
||
const skusBeingSuspended = skus.filter(
|
||
(sku: any) => sku.isSuspended && sku.id != null && existingSkuIdSet.has(sku.id)
|
||
)
|
||
if (skusBeingSuspended.length > 0) {
|
||
const suspendingIds = skusBeingSuspended.map((sku: any) => sku.id)
|
||
const comboMemberships = await db.query.productCombos.findMany({
|
||
where: inArray(productCombos.skuId, suspendingIds),
|
||
columns: { comboSkuId: true },
|
||
})
|
||
const comboIds = Array.from(new Set(comboMemberships.map((c) => c.comboSkuId)))
|
||
|
||
if (comboIds.length > 0) {
|
||
const combos = await db.query.productSkus.findMany({
|
||
where: inArray(productSkus.id, comboIds),
|
||
columns: { id: true, isSuspended: true },
|
||
with: { marketStats: true },
|
||
})
|
||
const activeComboIds = combos
|
||
.filter((c) => !isSkuSuspended(c.isSuspended, marketStatsForRegion(c.marketStats, regionId)))
|
||
.map((c) => c.id)
|
||
if (activeComboIds.length > 0) {
|
||
throw new Error(
|
||
`Cannot suspend SKU(s): they are members of combo(s) ${activeComboIds.join(', ')} that are not suspended`
|
||
)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
try {
|
||
return await db.transaction(async (tx) => {
|
||
await tx.update(productInfo)
|
||
.set({
|
||
name: productData.name,
|
||
shortDescription: productData.shortDescription ?? null,
|
||
longDescription: productData.longDescription ?? null,
|
||
storeId: productData.storeId ?? null,
|
||
incrementStep: productData.incrementStep ?? 1,
|
||
productType: productData.productType,
|
||
})
|
||
.where(eq(productInfo.id, id))
|
||
|
||
if (skus !== undefined) {
|
||
const existingSkus = await tx.query.productSkus.findMany({
|
||
where: eq(productSkus.productId, id),
|
||
columns: { id: true },
|
||
})
|
||
const existingSkuIdSet = new Set(existingSkus.map((s) => s.id))
|
||
|
||
for (const sku of skus) {
|
||
if (sku.id != null && existingSkuIdSet.has(sku.id)) {
|
||
// Update existing SKU
|
||
await tx.update(productSkus)
|
||
.set({
|
||
name: sku.name ?? null,
|
||
images: sku.images ?? null,
|
||
isComboOnly: sku.isComboOnly ?? false,
|
||
isSuspended: sku.isSuspended ?? false,
|
||
...(sku.isDeleted !== undefined && { isDeleted: sku.isDeleted }),
|
||
})
|
||
.where(eq(productSkus.id, sku.id))
|
||
|
||
// Superadmin structural edit of a global product (regionId null) leaves
|
||
// each region's market data untouched; a regional edit writes its region.
|
||
if (regionId != null) {
|
||
const marketStatsValues = {
|
||
marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null,
|
||
ourPrice: sku.price != null ? String(sku.price) : '0',
|
||
isFlashAvailable: sku.isFlashAvailable ?? false,
|
||
flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null,
|
||
isOutOfStock: sku.isOutOfStock ?? false,
|
||
isOffer: sku.isOffer ?? false,
|
||
}
|
||
const existingMarketStats = await tx.query.productMarketStats.findFirst({
|
||
where: and(eq(productMarketStats.skuId, sku.id), eq(productMarketStats.regionId, regionId)),
|
||
columns: { id: true },
|
||
})
|
||
if (existingMarketStats) {
|
||
await tx.update(productMarketStats)
|
||
.set(marketStatsValues)
|
||
.where(and(eq(productMarketStats.skuId, sku.id), eq(productMarketStats.regionId, regionId)))
|
||
} else {
|
||
await tx.insert(productMarketStats).values({
|
||
skuId: sku.id,
|
||
regionId,
|
||
...marketStatsValues,
|
||
})
|
||
}
|
||
}
|
||
|
||
await tx.delete(skuFeatures).where(eq(skuFeatures.skuId, sku.id))
|
||
if (sku.features && sku.features.length > 0) {
|
||
await runBatched(tx, sku.features, FEATURE_INSERT_CHUNK_SIZE, async (t, chunk) => {
|
||
await t.insert(skuFeatures).values(
|
||
chunk.map((f: any) => ({
|
||
skuId: sku.id,
|
||
featureName: f.featureName,
|
||
featureValue: f.featureValue,
|
||
}))
|
||
)
|
||
})
|
||
}
|
||
|
||
await tx.delete(productCombos).where(eq(productCombos.comboSkuId, sku.id))
|
||
if (sku.comboItems && sku.comboItems.length > 0) {
|
||
const comboItems = dedupeComboItems(sku.comboItems)
|
||
if (comboItems.length > 0) {
|
||
await runBatched(tx, comboItems, COMBO_ITEM_INSERT_CHUNK_SIZE, async (t, chunk) => {
|
||
await t.insert(productCombos).values(
|
||
chunk.map((ci: any) => ({
|
||
comboSkuId: sku.id,
|
||
skuId: ci.skuId,
|
||
}))
|
||
)
|
||
})
|
||
}
|
||
}
|
||
} else {
|
||
// Insert new SKU
|
||
const [newSku] = await tx.insert(productSkus).values({
|
||
productId: id,
|
||
name: sku.name ?? null,
|
||
images: sku.images ?? null,
|
||
isComboOnly: sku.isComboOnly ?? false,
|
||
isDeleted: sku.isDeleted ?? false,
|
||
isSuspended: sku.isSuspended ?? false,
|
||
}).returning()
|
||
|
||
await tx.insert(productMarketStats).values(targetRegionIds.map((rid) => ({
|
||
skuId: newSku.id,
|
||
regionId: rid,
|
||
marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : null,
|
||
ourPrice: sku.price != null ? String(sku.price) : '0',
|
||
isFlashAvailable: sku.isFlashAvailable ?? false,
|
||
flashPrice: sku.flashPrice != null ? String(sku.flashPrice) : null,
|
||
isOutOfStock: sku.isOutOfStock ?? false,
|
||
isOffer: sku.isOffer ?? false,
|
||
})))
|
||
|
||
if (sku.features && sku.features.length > 0) {
|
||
await runBatched(tx, sku.features, FEATURE_INSERT_CHUNK_SIZE, async (t, chunk) => {
|
||
await t.insert(skuFeatures).values(
|
||
chunk.map((f: any) => ({
|
||
skuId: newSku.id,
|
||
featureName: f.featureName,
|
||
featureValue: f.featureValue,
|
||
}))
|
||
)
|
||
})
|
||
}
|
||
|
||
// New SKUs also save their combo items (with dedupe).
|
||
if (sku.comboItems && sku.comboItems.length > 0) {
|
||
const comboItems = dedupeComboItems(sku.comboItems)
|
||
if (comboItems.length > 0) {
|
||
await runBatched(tx, comboItems, COMBO_ITEM_INSERT_CHUNK_SIZE, async (t, chunk) => {
|
||
await t.insert(productCombos).values(
|
||
chunk.map((ci: any) => ({
|
||
comboSkuId: newSku.id,
|
||
skuId: ci.skuId,
|
||
}))
|
||
)
|
||
})
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
const updatedProduct = await tx.query.productInfo.findFirst({
|
||
where: eq(productInfo.id, id),
|
||
with: {
|
||
store: true,
|
||
skus: {
|
||
with: { features: true, marketStats: true },
|
||
},
|
||
},
|
||
})
|
||
|
||
if (!updatedProduct) {
|
||
return null
|
||
}
|
||
|
||
return {
|
||
...mapProduct(updatedProduct),
|
||
store: updatedProduct.store ? mapStore(updatedProduct.store) : null,
|
||
skus: updatedProduct.skus.map((s) => mapSku(s, s.features, [], marketStatsForRegion(s.marketStats, regionId ?? targetRegionIds[0]))),
|
||
}
|
||
})
|
||
} catch (error) {
|
||
console.error('updateProduct failed:', error)
|
||
throw new Error('Failed to update product. Please check the SKU details and try again.')
|
||
}
|
||
}
|
||
|
||
export async function getAllProductTags(regionId: number): Promise<AdminProductTagWithProducts[]> {
|
||
const tags = await db.query.productTagInfo.findMany({
|
||
where: eq(productTagInfo.regionId, regionId),
|
||
with: {
|
||
products: {
|
||
with: {
|
||
sku: {
|
||
with: { features: true, marketStats: true },
|
||
},
|
||
},
|
||
},
|
||
},
|
||
}) as Array<ProductTagInfoRow & { products: Array<ProductTagRow & { sku: SkuRow & { features: SkuFeatureRow[]; marketStats: MarketStatsRow[] } }> }>
|
||
|
||
return tags.map((tag: any) => ({
|
||
...mapTagInfo(tag),
|
||
products: tag.products.map((assignment: any) => ({
|
||
productId: assignment.productId,
|
||
tagId: assignment.tagId,
|
||
assignedAt: assignment.assignedAt,
|
||
product: mapSku(assignment.sku, assignment.sku.features, [], marketStatsForRegion(assignment.sku.marketStats, regionId)),
|
||
})),
|
||
productIds: tag.products.map((assignment: ProductTagRow) => assignment.productId),
|
||
}))
|
||
}
|
||
|
||
export async function getAllProductTagInfos(regionId: number): Promise<AdminProductTagInfo[]> {
|
||
const tags = await db.query.productTagInfo.findMany({
|
||
where: eq(productTagInfo.regionId, regionId),
|
||
orderBy: productTagInfo.tagName,
|
||
})
|
||
|
||
return tags.map(mapTagInfo)
|
||
}
|
||
|
||
export async function getProductTagInfoById(regionId: number, tagId: number): Promise<AdminProductTagInfo | null> {
|
||
const tag = await db.query.productTagInfo.findFirst({
|
||
where: and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)),
|
||
})
|
||
|
||
if (!tag) {
|
||
return null
|
||
}
|
||
|
||
return mapTagInfo(tag)
|
||
}
|
||
|
||
export interface CreateProductTagInput extends ProductTagCore {
|
||
sortOrder?: number[]
|
||
}
|
||
|
||
export async function createProductTag(input: CreateProductTagInput, regionId: number): Promise<AdminProductTagWithProducts> {
|
||
if (input.relatedStores && input.relatedStores.length > 0) {
|
||
await assertStoreIdsInRegion(db, input.relatedStores, regionId)
|
||
}
|
||
|
||
const [tag] = await db.insert(productTagInfo).values({
|
||
regionId,
|
||
tagName: input.tagName,
|
||
tagDescription: input.tagDescription || null,
|
||
imageUrl: input.imageUrl || null,
|
||
isDashboardTag: input.isDashboardTag || false,
|
||
relatedStores: input.relatedStores || [],
|
||
sortOrder: input.sortOrder || [],
|
||
}).returning()
|
||
|
||
return {
|
||
...mapTagInfo(tag),
|
||
products: [],
|
||
productIds: [],
|
||
}
|
||
}
|
||
|
||
export async function getProductTagById(regionId: number, tagId: number): Promise<AdminProductTagWithProducts | null> {
|
||
const tag = await db.query.productTagInfo.findFirst({
|
||
where: and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)),
|
||
with: {
|
||
products: {
|
||
with: {
|
||
sku: {
|
||
with: { features: true, marketStats: true },
|
||
},
|
||
},
|
||
},
|
||
},
|
||
})
|
||
|
||
if (!tag) {
|
||
return null
|
||
}
|
||
|
||
return {
|
||
...mapTagInfo(tag),
|
||
products: (tag.products || []).map((assignment: any) => ({
|
||
productId: assignment.productId,
|
||
tagId: assignment.tagId,
|
||
assignedAt: assignment.assignedAt,
|
||
product: mapSku(assignment.sku, assignment.sku.features, [], marketStatsForRegion(assignment.sku.marketStats, regionId)),
|
||
})),
|
||
productIds: (tag.products || []).map((assignment: ProductTagRow) => assignment.productId),
|
||
}
|
||
}
|
||
|
||
export type UpdateProductTagInput = Omit<ProductTagCore, 'tagName'> & {
|
||
tagName?: string
|
||
sortOrder?: number[]
|
||
}
|
||
|
||
export async function updateProductTag(regionId: number, tagId: number, input: UpdateProductTagInput): Promise<AdminProductTagWithProducts | null> {
|
||
if (input.relatedStores != null && input.relatedStores.length > 0) {
|
||
await assertStoreIdsInRegion(db, input.relatedStores, regionId)
|
||
}
|
||
|
||
const [tag] = await db.update(productTagInfo).set({
|
||
...(input.tagName !== undefined && { tagName: input.tagName }),
|
||
...(input.tagDescription !== undefined && { tagDescription: input.tagDescription }),
|
||
...(input.imageUrl !== undefined && { imageUrl: input.imageUrl }),
|
||
...(input.isDashboardTag !== undefined && { isDashboardTag: input.isDashboardTag }),
|
||
...(input.relatedStores !== undefined && { relatedStores: input.relatedStores }),
|
||
...(input.sortOrder !== undefined && { sortOrder: input.sortOrder }),
|
||
}).where(and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId))).returning()
|
||
|
||
if (!tag) {
|
||
return null
|
||
}
|
||
|
||
const fullTag = await db.query.productTagInfo.findFirst({
|
||
where: eq(productTagInfo.id, tagId),
|
||
with: {
|
||
products: {
|
||
with: {
|
||
sku: {
|
||
with: { features: true, marketStats: true },
|
||
},
|
||
},
|
||
},
|
||
},
|
||
})
|
||
|
||
return {
|
||
...mapTagInfo(tag),
|
||
products: (fullTag?.products || []).map((assignment: any) => ({
|
||
productId: assignment.productId,
|
||
tagId: assignment.tagId,
|
||
assignedAt: assignment.assignedAt,
|
||
product: mapSku(assignment.sku, assignment.sku.features, [], marketStatsForRegion(assignment.sku.marketStats, regionId)),
|
||
})),
|
||
productIds: (fullTag?.products || []).map((assignment: ProductTagRow) => assignment.productId) || [],
|
||
}
|
||
}
|
||
|
||
export async function deleteProductTag(regionId: number, tagId: number): Promise<boolean> {
|
||
return db.transaction(async (tx) => {
|
||
const tag = await tx.query.productTagInfo.findFirst({
|
||
where: and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)),
|
||
columns: { id: true },
|
||
})
|
||
if (!tag) return false
|
||
|
||
// Drop the product associations first; the product_tags FK blocks the tag
|
||
// delete otherwise.
|
||
await tx.delete(productTags).where(eq(productTags.tagId, tagId))
|
||
await tx
|
||
.delete(productTagInfo)
|
||
.where(and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)))
|
||
|
||
return true
|
||
})
|
||
}
|
||
|
||
export async function checkProductTagExistsByName(tagName: string): Promise<boolean> {
|
||
const tag = await db.query.productTagInfo.findFirst({
|
||
where: eq(productTagInfo.tagName, tagName),
|
||
})
|
||
return !!tag
|
||
}
|
||
|
||
export async function getProductReviews(regionId: number, productId: number, limit: number, offset: number) {
|
||
const reviews = await db
|
||
.select({
|
||
id: productReviews.id,
|
||
reviewBody: productReviews.reviewBody,
|
||
ratings: productReviews.ratings,
|
||
imageUrls: productReviews.imageUrls,
|
||
reviewTime: productReviews.reviewTime,
|
||
adminResponse: productReviews.adminResponse,
|
||
adminResponseImages: productReviews.adminResponseImages,
|
||
userName: users.name,
|
||
})
|
||
.from(productReviews)
|
||
.innerJoin(users, eq(productReviews.userId, users.id))
|
||
.innerJoin(productInfo, eq(productReviews.productId, productInfo.id))
|
||
.where(and(eq(productReviews.productId, productId), eq(productInfo.regionId, regionId)))
|
||
.orderBy(desc(productReviews.reviewTime))
|
||
.limit(limit)
|
||
.offset(offset)
|
||
|
||
const totalCountResult = await db
|
||
.select({ count: sql`count(*)` })
|
||
.from(productReviews)
|
||
.innerJoin(productInfo, eq(productReviews.productId, productInfo.id))
|
||
.where(and(eq(productReviews.productId, productId), eq(productInfo.regionId, regionId)))
|
||
|
||
const totalCount = Number(totalCountResult[0].count)
|
||
|
||
const mappedReviews: AdminProductReview[] = reviews.map((review: any) => ({
|
||
id: review.id,
|
||
reviewBody: review.reviewBody,
|
||
ratings: review.ratings,
|
||
imageUrls: review.imageUrls,
|
||
reviewTime: review.reviewTime,
|
||
adminResponse: review.adminResponse ?? null,
|
||
adminResponseImages: review.adminResponseImages,
|
||
userName: review.userName ?? null,
|
||
}))
|
||
|
||
return {
|
||
reviews: mappedReviews,
|
||
totalCount,
|
||
}
|
||
}
|
||
|
||
export async function respondToReview(
|
||
regionId: number,
|
||
reviewId: number,
|
||
adminResponse: string | undefined,
|
||
adminResponseImages: string[]
|
||
): Promise<AdminProductReview | null> {
|
||
const review = await db.query.productReviews.findFirst({
|
||
where: eq(productReviews.id, reviewId),
|
||
columns: { id: true, productId: true },
|
||
})
|
||
if (!review) {
|
||
return null
|
||
}
|
||
const product = await db.query.productInfo.findFirst({
|
||
where: and(eq(productInfo.id, review.productId), eq(productInfo.regionId, regionId)),
|
||
columns: { id: true },
|
||
})
|
||
if (!product) {
|
||
return null
|
||
}
|
||
|
||
const [updatedReview] = await db
|
||
.update(productReviews)
|
||
.set({
|
||
adminResponse,
|
||
adminResponseImages,
|
||
})
|
||
.where(eq(productReviews.id, reviewId))
|
||
.returning()
|
||
|
||
if (!updatedReview) {
|
||
return null
|
||
}
|
||
|
||
return {
|
||
id: updatedReview.id,
|
||
reviewBody: updatedReview.reviewBody,
|
||
ratings: updatedReview.ratings,
|
||
imageUrls: updatedReview.imageUrls,
|
||
reviewTime: updatedReview.reviewTime,
|
||
adminResponse: updatedReview.adminResponse ?? null,
|
||
adminResponseImages: updatedReview.adminResponseImages,
|
||
userName: null,
|
||
}
|
||
}
|
||
|
||
export async function getAllProductGroups(regionId: number) {
|
||
const groups = await db.query.productGroupInfo.findMany({
|
||
where: eq(productGroupInfo.regionId, regionId),
|
||
with: {
|
||
memberships: {
|
||
with: {
|
||
sku: {
|
||
with: { features: true, marketStats: true },
|
||
},
|
||
},
|
||
},
|
||
},
|
||
orderBy: desc(productGroupInfo.createdAt),
|
||
})
|
||
|
||
return groups.map((group: any) => ({
|
||
id: group.id,
|
||
groupName: group.groupName,
|
||
description: group.description ?? null,
|
||
createdAt: group.createdAt,
|
||
products: (group.memberships || []).map((membership: any) =>
|
||
mapSku(membership.sku, membership.sku.features, [], marketStatsForRegion(membership.sku.marketStats, regionId))
|
||
),
|
||
productCount: group.memberships.length,
|
||
memberships: group.memberships
|
||
}))
|
||
}
|
||
|
||
export async function createProductGroup(
|
||
groupName: string,
|
||
description: string | undefined,
|
||
productIds: number[],
|
||
regionId: number
|
||
): Promise<AdminProductGroupInfo> {
|
||
await assertSkuIdsInRegion(db, productIds, regionId, 'Product')
|
||
|
||
const [newGroup] = await db
|
||
.insert(productGroupInfo)
|
||
.values({
|
||
regionId,
|
||
groupName,
|
||
description,
|
||
})
|
||
.returning()
|
||
|
||
if (productIds.length > 0) {
|
||
const memberships = productIds.map((productId) => ({
|
||
productId,
|
||
groupId: newGroup.id,
|
||
}))
|
||
|
||
await db.insert(productGroupMembership).values(memberships)
|
||
}
|
||
|
||
return {
|
||
id: newGroup.id,
|
||
groupName: newGroup.groupName,
|
||
description: newGroup.description ?? null,
|
||
createdAt: newGroup.createdAt,
|
||
}
|
||
}
|
||
|
||
export async function updateProductGroup(
|
||
regionId: number,
|
||
id: number,
|
||
groupName: string | undefined,
|
||
description: string | undefined,
|
||
productIds: number[] | undefined
|
||
): Promise<AdminProductGroupInfo | null> {
|
||
if (productIds !== undefined) {
|
||
await assertSkuIdsInRegion(db, productIds, regionId, 'Product')
|
||
}
|
||
|
||
const updateData: Partial<{
|
||
groupName: string
|
||
description: string | null
|
||
}> = {}
|
||
|
||
if (groupName !== undefined) updateData.groupName = groupName
|
||
if (description !== undefined) updateData.description = description
|
||
|
||
const [updatedGroup] = await db
|
||
.update(productGroupInfo)
|
||
.set(updateData)
|
||
.where(and(eq(productGroupInfo.id, id), eq(productGroupInfo.regionId, regionId)))
|
||
.returning()
|
||
|
||
if (!updatedGroup) {
|
||
return null
|
||
}
|
||
|
||
if (productIds !== undefined) {
|
||
await db.delete(productGroupMembership).where(eq(productGroupMembership.groupId, id))
|
||
|
||
if (productIds.length > 0) {
|
||
const memberships = productIds.map((productId) => ({
|
||
productId,
|
||
groupId: id,
|
||
}))
|
||
|
||
await db.insert(productGroupMembership).values(memberships)
|
||
}
|
||
}
|
||
|
||
return {
|
||
id: updatedGroup.id,
|
||
groupName: updatedGroup.groupName,
|
||
description: updatedGroup.description ?? null,
|
||
createdAt: updatedGroup.createdAt,
|
||
}
|
||
}
|
||
|
||
export async function deleteProductGroup(regionId: number, id: number): Promise<AdminProductGroupInfo | null> {
|
||
const group = await db.query.productGroupInfo.findFirst({
|
||
where: and(eq(productGroupInfo.id, id), eq(productGroupInfo.regionId, regionId)),
|
||
columns: { id: true },
|
||
})
|
||
if (!group) {
|
||
return null
|
||
}
|
||
|
||
await db.delete(productGroupMembership).where(eq(productGroupMembership.groupId, id))
|
||
|
||
const [deletedGroup] = await db
|
||
.delete(productGroupInfo)
|
||
.where(eq(productGroupInfo.id, id))
|
||
.returning()
|
||
|
||
if (!deletedGroup) {
|
||
return null
|
||
}
|
||
|
||
return {
|
||
id: deletedGroup.id,
|
||
groupName: deletedGroup.groupName,
|
||
description: deletedGroup.description ?? null,
|
||
createdAt: deletedGroup.createdAt,
|
||
}
|
||
}
|
||
|
||
export async function updateProductPrices(regionId: number, updates: Array<{
|
||
skuId: number
|
||
price?: number
|
||
marketPrice?: number | null
|
||
flashPrice?: number | null
|
||
isFlashAvailable?: boolean
|
||
}>) {
|
||
if (updates.length === 0) {
|
||
return { updatedCount: 0, invalidIds: [], emptyIds: [] }
|
||
}
|
||
|
||
// An entry with no price field would "succeed" while writing nothing, so the caller would get a
|
||
// false confirmation. Reject the whole batch before anything is written.
|
||
const emptyIds = updates
|
||
.filter((update) =>
|
||
update.price === undefined &&
|
||
update.marketPrice === undefined &&
|
||
update.flashPrice === undefined &&
|
||
update.isFlashAvailable === undefined
|
||
)
|
||
.map((update) => update.skuId)
|
||
|
||
if (emptyIds.length > 0) {
|
||
return { updatedCount: 0, invalidIds: [], emptyIds }
|
||
}
|
||
|
||
const skuIds = updates.map((update) => update.skuId)
|
||
|
||
// 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),
|
||
with: { product: { columns: { regionId: true } } },
|
||
columns: { id: true },
|
||
})
|
||
})
|
||
const inRegionIds = new Set(
|
||
existingSkuChunks.flat()
|
||
.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))
|
||
|
||
if (invalidIds.length > 0) {
|
||
return { updatedCount: 0, invalidIds, emptyIds: [] }
|
||
}
|
||
|
||
// Apply updates in chunks inside a single transaction
|
||
let updatedCount = 0
|
||
await runBatched(db, updates, 10, async (tx, chunk) => {
|
||
for (const update of chunk) {
|
||
const { skuId, price, marketPrice, flashPrice, isFlashAvailable } = update
|
||
const updateData: any = {}
|
||
|
||
if (price !== undefined) updateData.ourPrice = price.toString()
|
||
if (marketPrice !== undefined) updateData.marketPrice = marketPrice === null ? null : marketPrice.toString()
|
||
if (flashPrice !== undefined) updateData.flashPrice = flashPrice === null ? null : flashPrice.toString()
|
||
if (isFlashAvailable !== undefined) updateData.isFlashAvailable = isFlashAvailable
|
||
|
||
if (Object.keys(updateData).length === 0) continue
|
||
|
||
const existingMarketStats = await tx.query.productMarketStats.findFirst({
|
||
where: and(eq(productMarketStats.skuId, skuId), eq(productMarketStats.regionId, regionId)),
|
||
columns: { id: true },
|
||
})
|
||
|
||
if (existingMarketStats) {
|
||
await tx
|
||
.update(productMarketStats)
|
||
.set(updateData)
|
||
.where(and(eq(productMarketStats.skuId, skuId), eq(productMarketStats.regionId, regionId)))
|
||
} else {
|
||
await tx.insert(productMarketStats).values({
|
||
skuId,
|
||
regionId,
|
||
ourPrice: updateData.ourPrice ?? '0',
|
||
marketPrice: updateData.marketPrice ?? null,
|
||
flashPrice: updateData.flashPrice ?? null,
|
||
isFlashAvailable: updateData.isFlashAvailable ?? false,
|
||
})
|
||
}
|
||
|
||
updatedCount++
|
||
}
|
||
})
|
||
|
||
return { updatedCount, invalidIds: [], emptyIds: [] }
|
||
}
|
||
|
||
export async function toggleProductOutOfStock(
|
||
regionId: number,
|
||
productId: number
|
||
): Promise<{ id: number; isOutOfStock: boolean } | null> {
|
||
const product = await db.query.productInfo.findFirst({
|
||
// 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) {
|
||
return null
|
||
}
|
||
|
||
const skus = await db.query.productSkus.findMany({
|
||
where: eq(productSkus.productId, productId),
|
||
with: { marketStats: true },
|
||
})
|
||
|
||
if (skus.length === 0) {
|
||
return null
|
||
}
|
||
|
||
// Product is "out" if any of its SKUs is out; toggle the whole product.
|
||
const nextIsOutOfStock = !skus.some((sku) => marketStatsForRegion(sku.marketStats, regionId)?.isOutOfStock)
|
||
|
||
await db
|
||
.update(productMarketStats)
|
||
.set({ isOutOfStock: nextIsOutOfStock })
|
||
.where(and(inArray(productMarketStats.skuId, skus.map((sku) => sku.id)), eq(productMarketStats.regionId, regionId)))
|
||
|
||
return { id: productId, isOutOfStock: nextIsOutOfStock }
|
||
}
|
||
|
||
/**
|
||
* Set the stock flag for specific variants of a product (per SKU, per region).
|
||
*
|
||
* The all-variants `toggleProductOutOfStock` cannot express "one variant is out" (the plan's PD-06
|
||
* case) and collapses a partial state on the next press. This writes exactly the given SKUs'
|
||
* `product_market_stats` rows for the region and reports their resulting states.
|
||
*/
|
||
export async function setProductSkusOutOfStock(
|
||
regionId: number,
|
||
productId: number,
|
||
skuIds: number[],
|
||
isOutOfStock: boolean
|
||
): Promise<{
|
||
id: number
|
||
/** Requested ids that are not variants of this product (caller should reject the request). */
|
||
ignoredSkuIds: number[]
|
||
skus: Array<{ id: number; name: string | null; isOutOfStock: boolean }>
|
||
isOutOfStock: boolean
|
||
} | null> {
|
||
const product = await db.query.productInfo.findFirst({
|
||
// 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) {
|
||
return null
|
||
}
|
||
|
||
const skus = await db.query.productSkus.findMany({
|
||
where: eq(productSkus.productId, productId),
|
||
with: { marketStats: true },
|
||
})
|
||
|
||
if (skus.length === 0) {
|
||
return null
|
||
}
|
||
|
||
const owned = new Set(skus.map((sku) => sku.id))
|
||
const requested = [...new Set(skuIds)]
|
||
const ignoredSkuIds = requested.filter((skuId) => !owned.has(skuId))
|
||
const targets = requested.filter((skuId) => owned.has(skuId))
|
||
|
||
if (targets.length > 0) {
|
||
await db
|
||
.update(productMarketStats)
|
||
.set({ isOutOfStock })
|
||
.where(and(inArray(productMarketStats.skuId, targets), eq(productMarketStats.regionId, regionId)))
|
||
}
|
||
|
||
const targetSet = new Set(targets)
|
||
const skuStates = skus.map((sku) => ({
|
||
id: sku.id,
|
||
name: sku.name ?? null,
|
||
isOutOfStock: targetSet.has(sku.id)
|
||
? isOutOfStock
|
||
: (marketStatsForRegion(sku.marketStats, regionId)?.isOutOfStock ?? false),
|
||
}))
|
||
|
||
return {
|
||
id: productId,
|
||
ignoredSkuIds,
|
||
skus: skuStates,
|
||
// Same convention as the all-variants toggle: out when any variant is out.
|
||
isOutOfStock: skuStates.some((sku) => sku.isOutOfStock),
|
||
}
|
||
}
|
||
|
||
|
||
// ==========================================================================
|
||
// Product Helpers for Admin Controller
|
||
// ==========================================================================
|
||
|
||
export async function checkProductExistsByName(name: string): Promise<boolean> {
|
||
// Ignore soft-deleted products so a deleted name can be reused.
|
||
const product = await db
|
||
.select({ id: productInfo.id })
|
||
.from(productInfo)
|
||
.innerJoin(productSkus, eq(productSkus.productId, productInfo.id))
|
||
.where(and(eq(productInfo.name, name), eq(productSkus.isDeleted, false)))
|
||
.limit(1)
|
||
|
||
return product.length > 0
|
||
}
|
||
|
||
export async function replaceTagProducts(regionId: number, tagId: number, productIds: number[]): Promise<void> {
|
||
const tag = await db.query.productTagInfo.findFirst({
|
||
where: and(eq(productTagInfo.id, tagId), eq(productTagInfo.regionId, regionId)),
|
||
columns: { id: true },
|
||
})
|
||
if (!tag) {
|
||
throw new Error('Tag belongs to a different region')
|
||
}
|
||
await assertSkuIdsInRegion(db, productIds, regionId, 'Product')
|
||
|
||
await db.delete(productTags).where(eq(productTags.tagId, tagId))
|
||
|
||
if (productIds.length === 0) {
|
||
return
|
||
}
|
||
|
||
const productAssociations = productIds.map((productId) => ({
|
||
productId,
|
||
tagId,
|
||
}))
|
||
|
||
await db.insert(productTags).values(productAssociations)
|
||
}
|