79 lines
2.6 KiB
TypeScript
79 lines
2.6 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'
|
|
import { buildCustomerSnapshot, buildOrderSnapshot } from '@/lib/license-transform'
|
|
import type { Category, Order, Product, Profile, WizardSelections } from '@/lib/types'
|
|
|
|
// ─── submitOrder ──────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Speichert eine abgeschlossene Bestellung als versionierten Snapshot in der DB,
|
|
* generiert die PDF-Rechnung und lädt sie in den Supabase Storage hoch.
|
|
*/
|
|
export async function submitOrder(params: {
|
|
selections: WizardSelections
|
|
products: Product[]
|
|
categories: Category[]
|
|
customerProfile: Partial<Profile>
|
|
}): Promise<Order> {
|
|
const { selections, products, categories, customerProfile } = params
|
|
const supabase = await createClient()
|
|
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
if (!user) throw new Error('Not authenticated')
|
|
|
|
// 1. Snapshots aufbauen
|
|
const customerSnapshot = buildCustomerSnapshot(customerProfile)
|
|
const orderSnapshot = buildOrderSnapshot(selections, products, categories)
|
|
|
|
// 2. Bestellung in DB schreiben
|
|
const { data: order, error: orderError } = await supabase
|
|
.from('orders')
|
|
.insert([{
|
|
user_id: user.id,
|
|
total_price: orderSnapshot.total,
|
|
customer_data: customerSnapshot,
|
|
order_data: orderSnapshot,
|
|
status: 'pending',
|
|
}])
|
|
.select()
|
|
.single()
|
|
|
|
if (orderError) throw orderError
|
|
|
|
// 3. PDF generieren (greift auf Snapshot-Daten zu, nicht auf Live-Katalog)
|
|
try {
|
|
const buffer = await renderToBuffer(
|
|
React.createElement(InvoicePDF, {
|
|
order,
|
|
customer: customerSnapshot,
|
|
orderSnapshot,
|
|
})
|
|
)
|
|
|
|
// 4. PDF in Supabase Storage hochladen
|
|
const fileName = `invoice_${order.id}.pdf`
|
|
const { error: uploadError } = await supabase
|
|
.storage
|
|
.from('invoices')
|
|
.upload(fileName, buffer, { contentType: 'application/pdf', upsert: true })
|
|
|
|
if (uploadError) {
|
|
console.error('PDF Upload Error:', uploadError)
|
|
} else {
|
|
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 as Order
|
|
}
|
|
|