stuff done
This commit is contained in:
77
actions/admin/place-order.ts
Normal file
77
actions/admin/place-order.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
'use server'
|
||||
|
||||
import {DeliveryOption, Lang, Order} from '@prisma/client'
|
||||
import {z} from 'zod'
|
||||
|
||||
import {sendMail} from '@/actions/admin/mailer'
|
||||
import {STORE_ID} from '@/lib/config/constants'
|
||||
import dayjs from '@/lib/config/dayjs'
|
||||
import {db} from '@/lib/db/prisma/client'
|
||||
import {createOrderFormSchema} from '@/lib/schemas/admin/order'
|
||||
import {dbErrorHandling} from '@/lib/utils'
|
||||
|
||||
const generateOrderNo = (): string => {
|
||||
const hex = Math.floor(Math.random() * 16777215)
|
||||
.toString(16)
|
||||
.slice(0, 3)
|
||||
.toUpperCase()
|
||||
|
||||
return `${dayjs().format('YYMM')}-${hex}`
|
||||
}
|
||||
|
||||
export const onPlacingOrder = async (
|
||||
formData: z.infer<typeof createOrderFormSchema>
|
||||
) => {
|
||||
const fields = createOrderFormSchema.parse(formData)
|
||||
if (!fields) return {error: 'Недійсні вхідні дані'}
|
||||
|
||||
const orderNo = generateOrderNo()
|
||||
|
||||
try {
|
||||
const newOrder: Order = await db.order.create({
|
||||
data: {
|
||||
storeId: STORE_ID,
|
||||
lang: fields.lang as Lang,
|
||||
orderNo,
|
||||
isQuick: fields.is_quick,
|
||||
userId: fields.user_id ? parseInt(fields.user_id) : null,
|
||||
firstName: fields.first_name,
|
||||
surname: fields.surname,
|
||||
deliveryOption: fields.delivery_option as DeliveryOption,
|
||||
phone: fields.phone,
|
||||
email: fields.email,
|
||||
address: fields.address.length > 10 ? JSON.parse(fields.address) : null,
|
||||
notes: fields.notes?.toString().trim() !== '' ? fields.notes : null,
|
||||
details: fields.details ? JSON.parse(fields.details) : null
|
||||
}
|
||||
})
|
||||
|
||||
const text = JSON.stringify(newOrder, null, 2)
|
||||
|
||||
const result = await sendMail({
|
||||
email: `${newOrder.firstName} ${newOrder.surname} <${newOrder.email as string}>`,
|
||||
subject: `Замовлення № ${orderNo}`,
|
||||
text,
|
||||
html: `<pre>${text}</pre>`
|
||||
})
|
||||
|
||||
const updated = await db.order.update({
|
||||
where: {
|
||||
id: newOrder.id
|
||||
},
|
||||
data: {
|
||||
emailSent: result.ok
|
||||
}
|
||||
})
|
||||
|
||||
if (result.ok) {
|
||||
return {success: newOrder.orderNo}
|
||||
} else {
|
||||
return {
|
||||
error: result.message
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
return dbErrorHandling(error)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user