Skapat order och notiser

X-Lovable-Edit-ID: edt-e5cea22e-14f1-4e8b-a6e9-38caa6e92f44
Co-authored-by: wolfoftyreso-debug <250630591+wolfoftyreso-debug@users.noreply.github.com>
This commit is contained in:
gpt-engineer-app[bot]
2026-07-11 13:19:32 +00:00
@@ -1,6 +1,56 @@
import { z } from "npm:zod@3.23.8";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.45.0";
import { type StripeEnv, createStripeClient } from "../_shared/stripe.ts";
const supabaseAdmin = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
);
async function insertOrder(row: {
method: "card" | "invoice";
b: any;
cleaned: string;
monthlyAmountOre: number;
stripeSessionId?: string | null;
stripeSubscriptionId?: string | null;
stripeCustomerId: string;
}) {
const { b, method, cleaned, monthlyAmountOre } = row;
const orderNumber = `ABO-${Date.now().toString(36).toUpperCase()}`;
const totalKr = monthlyAmountOre / 100;
const { error } = await supabaseAdmin.from("orders").insert({
order_number: orderNumber,
customer_email: b.email,
customer_name: b.company,
total_amount: totalKr,
currency: "SEK",
status: method === "invoice" ? "invoiced" : "pending",
items: [
{
typ: "Kakabonnemang",
betalning: method === "card" ? "Kort (månadsvis)" : "Faktura (månadsvis)",
antal_anställda: b.employees,
kg_per_vecka: b.kg_per_week,
pris_per_månad_exkl_moms: totalKr,
valuta: "SEK",
leverans: {
adress: b.address,
postnummer: cleaned,
stad: "Storstockholm",
},
telefon: b.phone,
kommentarer: b.comments,
stripe_session_id: row.stripeSessionId ?? null,
stripe_subscription_id: row.stripeSubscriptionId ?? null,
stripe_customer_id: row.stripeCustomerId,
},
],
});
if (error) console.error("Order insert failed:", error);
}
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, x-supabase-client-platform, x-supabase-api-version, apikey, content-type",
@@ -131,6 +181,16 @@ Deno.serve(async (req) => {
},
} as any);
await insertOrder({
method: "card",
b,
cleaned,
monthlyAmountOre,
stripeSessionId: session.id,
stripeSubscriptionId: null,
stripeCustomerId: customer.id,
});
return new Response(JSON.stringify({ clientSecret: session.client_secret }), {
status: 200,
headers: { ...corsHeaders, "Content-Type": "application/json" },
@@ -163,6 +223,17 @@ Deno.serve(async (req) => {
},
} as any);
await insertOrder({
method: "invoice",
b,
cleaned,
monthlyAmountOre,
stripeSessionId: null,
stripeSubscriptionId: subscription.id,
stripeCustomerId: customer.id,
});
return new Response(
JSON.stringify({
invoice: true,