import React, { useRef, useMemo } from 'react' import { createFileRoute, useParams } from '@tanstack/react-router' import { AppContainer, p as MyText, type ImageUploaderNeoItem, type ImageUploaderNeoPayload } from 'web-components' import ProductForm, { type ProductFormRef } from '../components/ProductForm' import { trpc } from '../lib/trpc-client' import { useUploadToObjectStorage } from '../hooks/useUploadToObjectStorage' export const Route = createFileRoute('/products/$id/edit')({ component: EditProduct, }) function EditProduct() { const { id } = useParams({ from: '/products/$id/edit' }) const productId = Number(id) const productFormRef = useRef(null) const { data: productResponse, isLoading: isFetching, refetch } = trpc.superadmin.product.getProductById.useQuery( { id: productId }, { enabled: !!productId } ) const { refetch: refetchProducts } = trpc.superadmin.product.getProducts.useQuery(undefined, { enabled: false, }) const { data: regionsData } = trpc.superadmin.region.getRegions.useQuery(undefined, { staleTime: Infinity }) const updateProduct = trpc.superadmin.product.updateProduct.useMutation() const { upload, isUploading } = useUploadToObjectStorage() const productData = productResponse?.product const initialValues = useMemo(() => { if (!productData) { return { name: '', shortDescription: '', longDescription: '', regionId: undefined as number | undefined, availableInAllRegions: false, storeIdsByRegion: {} as Record, storeId: 0, productType: 'item' as const, matchForAll: false, regionStats: {} as Record, variants: [], } } // Per-region stats init, aligned with variants by index. Missing rows // fall back to blanks (the form fills from the primary tab on save). const regionStats: Record = {} for (const sku of (productData.skus || []) as any[]) { for (const row of (sku.marketStats || []) as any[]) { const key = String(row.regionId) if (!regionStats[key]) regionStats[key] = [] } } ;(productData.skus || []).forEach((sku: any, i: number) => { for (const key of Object.keys(regionStats)) { const row = ((sku as any).marketStats || []).find((r: any) => String(r.regionId) === key) regionStats[key][i] = row ? { price: row.ourPrice != null ? Number(row.ourPrice) : '', marketPrice: row.marketPrice != null ? Number(row.marketPrice) : '', flashPrice: row.flashPrice != null ? Number(row.flashPrice) : '', isFlashAvailable: !!row.isFlashAvailable, isOffer: !!row.isOffer, isSuspended: !!row.isSuspended, isOutOfStock: !!row.isOutOfStock, } : { price: '', marketPrice: '', flashPrice: '', isFlashAvailable: false, isOffer: false, isSuspended: false, isOutOfStock: false } } }) return { name: productData.name, shortDescription: productData.shortDescription || '', longDescription: productData.longDescription || '', regionId: productData.regionId, availableInAllRegions: productData.availableInAllRegions ?? false, storeIdsByRegion: {} as Record, storeId: productData.store?.id ?? 1, productType: (productData.productType as 'item' | 'combo') || 'item', matchForAll: false, regionStats, variants: (productData.skus || []).map((sku) => ({ id: sku.id, name: sku.name || '', price: sku.price ? parseFloat(sku.price) : undefined, marketPrice: sku.marketPrice ? parseFloat(sku.marketPrice) : null, isFlashAvailable: sku.isFlashAvailable || false, flashPrice: sku.flashPrice ? parseFloat(sku.flashPrice) : null, isOffer: sku.isOffer || false, isComboOnly: sku.isComboOnly || false, isDeleted: sku.isDeleted || false, isSuspended: sku.isSuspended || false, features: (sku.features || []).map((f) => ({ featureName: f.featureName, featureValue: f.featureValue, })), comboItems: (sku.comboItems || []).map((ci: any) => ({ skuId: ci.skuId, })), })), } }, [productData]) const existingVariantImages = useMemo(() => { if (!productData) return [] return (productData.skus || []).map((sku) => (sku.images || []).map((url) => ({ imgUrl: url, mimeType: null } as ImageUploaderNeoItem)) ) }, [productData]) const existingVariantImageKeys = useMemo(() => { if (!productData) return [] return (productData.skus || []).map((sku) => (sku.imageKeys || []).map(String) ) }, [productData]) const handleSubmit = async (values: any, variantImages: ImageUploaderNeoPayload[][], deletedImageKeys: string[]) => { try { const firstRegionId = regionsData?.regions?.[0]?.id const primaryRegionId = values.availableInAllRegions ? firstRegionId : values.regionId const primaryStats: any[] = (values.regionStats ?? {})[String(primaryRegionId)] ?? [] for (const entry of primaryStats) { const price = Number(entry?.price) if (entry == null || !Number.isFinite(price) || price <= 0) { window.alert('Please enter a valid price for every variant') return } } const seenSignatures = new Set() for (const variant of values.variants) { const features = variant.features || [] const hasQuantity = features.some( (a: any) => (a.featureName ?? '').trim().toLowerCase() === 'quantity' ) if (!hasQuantity) { window.alert('Every SKU must have a quantity feature') return } const signature = features .map((a: any) => `${(a.featureName ?? '').trim().toLowerCase()}::${a.featureValue.trim().toLowerCase()}`) .sort() .join('|') if (seenSignatures.has(signature)) { window.alert('Two variants have the same attributes') return } seenSignatures.add(signature) } const allBlobs: { blob: Blob, mimeType: string }[] = [] const imageCounts: number[] = variantImages.map((imgs) => imgs.filter((img) => img.mimeType !== null).length ) for (const imgs of variantImages) { for (const img of imgs) { if (img.mimeType === null) continue const response = await fetch(img.url) const blob = await response.blob() allBlobs.push({ blob, mimeType: img.mimeType || 'image/jpeg' }) } } let allUploadUrls: string[] = [] if (allBlobs.length > 0) { const result = await upload({ images: allBlobs, contextString: 'product_info' }) allUploadUrls = result.presignedUrls } let urlCursor = 0 const skus = values.variants.map((variant: any, vIndex: number) => { const count = imageCounts[vIndex] const newUrls = allUploadUrls.slice(urlCursor, urlCursor + count) urlCursor += count const existingUrls = variantImages[vIndex] ?.filter((img) => img.mimeType === null) .map((img) => img.url) || [] const allUrls = [...existingUrls, ...newUrls] const stats = primaryStats[vIndex] ?? {} const applicableRegionIds: number[] = values.availableInAllRegions ? (regionsData?.regions ?? []).map((r: any) => r.id) : (primaryRegionId != null ? [primaryRegionId] : []) const perRegion: Record = {} for (const rid of applicableRegionIds) { if (rid === primaryRegionId) continue const entry = ((values.regionStats ?? {})[String(rid)] ?? [])[vIndex] if (entry) { perRegion[rid] = { price: Number(entry.price), marketPrice: entry.marketPrice ?? undefined, flashPrice: entry.flashPrice ?? undefined, isFlashAvailable: !!entry.isFlashAvailable, isOffer: !!entry.isOffer, isSuspended: !!entry.isSuspended, isOutOfStock: !!entry.isOutOfStock, } } } return { id: variant.id, name: variant.name || null, price: Number(stats.price) as number, marketPrice: stats.marketPrice ?? undefined, images: allUrls, isFlashAvailable: stats.isFlashAvailable || false, flashPrice: stats.flashPrice ?? undefined, isOffer: stats.isOffer || false, isComboOnly: variant.isComboOnly || false, isDeleted: variant.isDeleted || false, isSuspended: stats.isSuspended || false, regionStats: Object.keys(perRegion).length > 0 ? perRegion : undefined, features: variant.features.map((attr: any) => ({ featureName: attr.featureName, featureValue: attr.featureValue, })), comboItems: (variant.comboItems || []).map((ci: any) => ({ skuId: ci.skuId, })), } }) const storeIdsByRegion = Object.entries(values.storeIdsByRegion || {}).reduce( (acc, [regionId, storeId]) => { const sid = Number(storeId) if (Number.isFinite(sid) && sid > 0) acc[Number(regionId)] = sid return acc }, {} as Record ) await updateProduct.mutateAsync({ id: productId, name: values.name, shortDescription: values.shortDescription || undefined, longDescription: values.longDescription || undefined, // Creator region scopes price/stock writes. A global product has no // region of its own, so fall back to the first region (same rule as // product creation); other regions' rows are left untouched. regionId: values.regionId ?? regionsData?.regions?.[0]?.id, productType: values.productType, incrementStep: 1, skus, deletedImageKeys, newImageUrls: allUploadUrls, availableInAllRegions: !!values.availableInAllRegions, storeIdsByRegion, } as any) await refetch() await refetchProducts() window.alert('Product updated successfully!') productFormRef.current?.clearImages() } catch (error: any) { window.alert(error.message || 'Failed to update product') } } if (isFetching) { return (
Loading product...
) } if (!productData) { return (
Product not found
) } return ( ) }