Files
webshop/shop/lib/actions/orders.ts

94 lines
2.4 KiB
TypeScript

'use server'
import { createClient } from '@/lib/supabase/server'
import { revalidatePath } from 'next/cache'
import { InvoicePDF } from '@/components/invoice-pdf'
import { renderToBuffer } from '@react-pdf/renderer'
import React from 'react'
export async function submitOrder(orderData: {
product_id: string;
selected_modules: string[];
total_amount: number;
customer_details: any;
}) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) throw new Error('Not authenticated')
// 1. Fetch Product and Module Details for Invoice
const { data: product } = await supabase
.from('products')
.select('*')
.eq('id', orderData.product_id)
.single()
const { data: modules } = await supabase
.from('product_modules')
.select('*')
.in('id', orderData.selected_modules)
if (!product) throw new Error('Product not found')
// 2. Create the Order in DB
const { data: order, error: orderError } = await supabase
.from('orders')
.insert([{
user_id: user.id,
total_price: orderData.total_amount, // Matched column name in initial_schema.sql
order_data: {
product_id: orderData.product_id,
modules: orderData.selected_modules
},
customer_data: orderData.customer_details,
status: 'pending'
}])
.select()
.single()
if (orderError) throw orderError
// 3. Generate PDF
try {
const buffer = await renderToBuffer(
React.createElement(InvoicePDF, {
order: order,
product: product,
modules: modules || [],
customer: orderData.customer_details
})
)
// 4. Upload to Supabase Storage
const fileName = `invoice_${order.id}.pdf`
const { data: uploadData, error: uploadError } = await supabase
.storage
.from('invoices')
.upload(fileName, buffer, {
contentType: 'application/pdf',
upsert: true
})
if (uploadError) {
console.error('PDF Upload Error:', uploadError)
} else {
// 5. Update Order with PDF URL
const { data: publicUrlData } = supabase
.storage
.from('invoices')
.getPublicUrl(fileName)
await supabase
.from('orders')
.update({ pdf_url: publicUrlData.publicUrl })
.eq('id', order.id)
}
} catch (pdfError) {
console.error('PDF Generation Error:', pdfError)
}
revalidatePath('/protected')
return order
}