201 lines
7.2 KiB
TypeScript
201 lines
7.2 KiB
TypeScript
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
|
import { AppContainer, p as MyText } from 'web-components'
|
|
import ProductForm from '../components/ProductForm'
|
|
import type { ImageUploaderNeoPayload } from 'web-components'
|
|
import { trpc } from '../lib/trpc-client'
|
|
import { useUploadToObjectStorage } from '../hooks/useUploadToObjectStorage'
|
|
|
|
export const Route = createFileRoute('/products/new')({
|
|
component: AddProduct,
|
|
})
|
|
|
|
function AddProduct() {
|
|
const navigate = useNavigate()
|
|
|
|
const createProduct = trpc.superadmin.product.createProduct.useMutation()
|
|
const { data: regionsData } = trpc.superadmin.region.getRegions.useQuery()
|
|
const { refetch: refetchProducts } = trpc.superadmin.product.getProducts.useQuery(undefined, {
|
|
enabled: false,
|
|
})
|
|
const { upload, isUploading } = useUploadToObjectStorage()
|
|
|
|
const handleSubmit = async (values: any, variantImages: ImageUploaderNeoPayload[][], _deletedImageKeys?: string[]) => {
|
|
try {
|
|
// Creator/primary region: the picked region in single mode; the first
|
|
// region in all-regions mode (it gets the initial stock/prices).
|
|
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<string>()
|
|
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.length)
|
|
|
|
for (const imgs of variantImages) {
|
|
for (const img of imgs) {
|
|
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 variantUrls = allUploadUrls.slice(urlCursor, urlCursor + count)
|
|
urlCursor += count
|
|
const stats = primaryStats[vIndex] ?? {}
|
|
|
|
return {
|
|
name: variant.name || null,
|
|
price: Number(stats.price) as number,
|
|
marketPrice: stats.marketPrice ?? undefined,
|
|
images: variantUrls,
|
|
isFlashAvailable: stats.isFlashAvailable || false,
|
|
flashPrice: stats.flashPrice ?? undefined,
|
|
isOffer: stats.isOffer || false,
|
|
isComboOnly: variant.isComboOnly || false,
|
|
isDeleted: variant.isDeleted || false,
|
|
isSuspended: stats.isSuspended || false,
|
|
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<number, number>
|
|
)
|
|
|
|
// Per-region overrides for every applicable region except the primary
|
|
// (whose values travel as the base SKU fields above).
|
|
const applicableRegionIds: number[] = values.availableInAllRegions
|
|
? (regionsData?.regions ?? []).map((r: any) => r.id)
|
|
: (primaryRegionId != null ? [primaryRegionId] : [])
|
|
const toBackendEntry = (entry: any) => ({
|
|
price: Number(entry.price),
|
|
marketPrice: entry.marketPrice ?? undefined,
|
|
flashPrice: entry.flashPrice ?? undefined,
|
|
isFlashAvailable: !!entry.isFlashAvailable,
|
|
isOffer: !!entry.isOffer,
|
|
isSuspended: !!entry.isSuspended,
|
|
isOutOfStock: !!entry.isOutOfStock,
|
|
})
|
|
const skusWithStats = skus.map((sku: any, vIndex: number) => {
|
|
const perRegion: Record<number, any> = {}
|
|
for (const rid of applicableRegionIds) {
|
|
if (rid === primaryRegionId) continue
|
|
const entry = ((values.regionStats ?? {})[String(rid)] ?? [])[vIndex]
|
|
if (entry) perRegion[rid] = toBackendEntry(entry)
|
|
}
|
|
return { ...sku, regionStats: Object.keys(perRegion).length > 0 ? perRegion : undefined }
|
|
})
|
|
|
|
await createProduct.mutateAsync({
|
|
name: values.name,
|
|
shortDescription: values.shortDescription || undefined,
|
|
longDescription: values.longDescription || undefined,
|
|
productType: values.productType,
|
|
incrementStep: 1,
|
|
skus: skusWithStats,
|
|
regionId: primaryRegionId,
|
|
availableInAllRegions: !!values.availableInAllRegions,
|
|
storeIdsByRegion,
|
|
})
|
|
|
|
await refetchProducts()
|
|
window.alert('Product created successfully!')
|
|
navigate({ to: '/products' })
|
|
} catch (error: any) {
|
|
window.alert(error.message || 'Failed to create product')
|
|
}
|
|
}
|
|
|
|
const initialValues = {
|
|
name: '',
|
|
shortDescription: '',
|
|
longDescription: '',
|
|
regionId: undefined as number | undefined,
|
|
availableInAllRegions: false,
|
|
storeIdsByRegion: {} as Record<number, number>,
|
|
storeId: 1,
|
|
productType: 'item' as const,
|
|
matchForAll: true,
|
|
regionStats: {} as Record<string, any[]>,
|
|
variants: [
|
|
{
|
|
id: undefined as number | undefined,
|
|
name: '',
|
|
price: undefined,
|
|
marketPrice: null,
|
|
isFlashAvailable: false,
|
|
flashPrice: null,
|
|
isOffer: false,
|
|
isComboOnly: false,
|
|
isDeleted: false,
|
|
isSuspended: false,
|
|
features: [{ featureName: 'quantity', featureValue: '' }],
|
|
comboItems: [],
|
|
},
|
|
],
|
|
}
|
|
|
|
return (
|
|
<AppContainer>
|
|
<div>
|
|
<MyText className="mb-6 block text-2xl font-bold text-gray-800">Add New Product</MyText>
|
|
<ProductForm
|
|
mode="create"
|
|
initialValues={initialValues}
|
|
onSubmit={handleSubmit}
|
|
isLoading={createProduct.isPending || isUploading}
|
|
/>
|
|
</div>
|
|
</AppContainer>
|
|
)
|
|
}
|