147 lines
4.8 KiB
TypeScript
147 lines
4.8 KiB
TypeScript
import React from 'react'
|
|
import { createFileRoute } from '@tanstack/react-router'
|
|
import { AppContainer, type ImageUploaderNeoPayload } from 'web-components'
|
|
import ProductForm from '../components/ProductForm'
|
|
import { trpc } from '@/lib/trpc-client'
|
|
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStorage'
|
|
|
|
export const Route = createFileRoute('/dashboard/products/new')({
|
|
component: AddProduct,
|
|
})
|
|
|
|
function AddProduct() {
|
|
const createProduct = trpc.admin.product.createProduct.useMutation()
|
|
const { refetch: refetchProducts } = trpc.admin.product.getProducts.useQuery(undefined, {
|
|
enabled: false,
|
|
})
|
|
const { upload, isUploading } = useUploadToObjectStorage()
|
|
|
|
const handleSubmit = async (values: any, variantImages: ImageUploaderNeoPayload[][], _deletedImageKeys?: string[]) => {
|
|
try {
|
|
for (const variant of values.variants) {
|
|
const price = variant.price
|
|
if (price == null || 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
|
|
|
|
return {
|
|
name: variant.name || null,
|
|
price: variant.price as number,
|
|
marketPrice: variant.marketPrice ?? undefined,
|
|
images: variantUrls,
|
|
isFlashAvailable: variant.isFlashAvailable || false,
|
|
flashPrice: variant.flashPrice ?? undefined,
|
|
isOffer: variant.isOffer || false,
|
|
isComboOnly: variant.isComboOnly || false,
|
|
isDeleted: variant.isDeleted || false,
|
|
isSuspended: variant.isSuspended || false,
|
|
features: variant.features.map((attr: any) => ({
|
|
featureName: attr.featureName,
|
|
featureValue: attr.featureValue,
|
|
})),
|
|
comboItems: (variant.comboItems || []).map((ci: any) => ({
|
|
skuId: ci.skuId,
|
|
})),
|
|
}
|
|
})
|
|
|
|
await createProduct.mutateAsync({
|
|
name: values.name,
|
|
shortDescription: values.shortDescription || undefined,
|
|
longDescription: values.longDescription || undefined,
|
|
storeId: values.storeId,
|
|
productType: values.productType,
|
|
incrementStep: 1,
|
|
skus,
|
|
})
|
|
|
|
await refetchProducts()
|
|
window.alert('Product created successfully!')
|
|
} catch (error: any) {
|
|
window.alert(error.message || 'Failed to create product')
|
|
}
|
|
}
|
|
|
|
const initialValues = {
|
|
name: '',
|
|
shortDescription: '',
|
|
longDescription: '',
|
|
// 0 = "no store chosen yet"; ProductForm fills in the first available store
|
|
// (regional preferred) once the store list loads.
|
|
storeId: 0,
|
|
productType: 'item' as const,
|
|
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>
|
|
<ProductForm
|
|
mode="create"
|
|
initialValues={initialValues}
|
|
onSubmit={handleSubmit}
|
|
isLoading={createProduct.isPending || isUploading}
|
|
/>
|
|
</AppContainer>
|
|
)
|
|
}
|