Billing voor achteraf betalen

This commit is contained in:
Mark Pinkster 2025-12-31 14:03:12 +01:00
parent a7032891e2
commit de4a531553
2 changed files with 209 additions and 172 deletions

200
api.php
View File

@ -1,6 +1,6 @@
<?php
/**
* TELVERO BACKOFFICE - API PROXY (ENV VERSION)
* TELVERO BACKOFFICE - API PROXY (V6.9 - SERVER-SAFE ATTRIBUTION)
*/
session_start();
ini_set('display_errors', 0);
@ -8,33 +8,20 @@ error_reporting(E_ALL);
require __DIR__ . '/vendor/autoload.php';
// Laad .env configuratie
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
if (file_exists(__DIR__ . '/.env')) {
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
}
use Automattic\WooCommerce\Client;
use Mollie\Api\MollieApiClient;
header('Content-Type: application/json');
// --- DATABASE CONNECTIE VIA ENV ---
$db = new mysqli($_ENV['DB_HOST'], $_ENV['DB_USER'], $_ENV['DB_PASS'], $_ENV['DB_NAME']);
if ($db->connect_error) {
die(json_encode(['error' => 'Database connectie mislukt']));
}
function writeLog($action, $details) {
global $db;
$user = $_SESSION['user'] ?? 'system';
$stmt = $db->prepare("INSERT INTO sales_logs (username, action, details, created_at) VALUES (?, ?, ?, NOW())");
$stmt->bind_param("sss", $user, $action, $details);
$stmt->execute();
}
$action = $_GET['action'] ?? '';
// --- AUTH ACTIONS ---
// --- AUTH ---
if ($action === 'login') {
$input = json_decode(file_get_contents('php://input'), true);
$stmt = $db->prepare("SELECT password, full_name FROM sales_users WHERE username = ?");
@ -44,7 +31,7 @@ if ($action === 'login') {
if ($res && password_verify($input['password'], $res['password'])) {
$_SESSION['user'] = $input['username'];
$_SESSION['full_name'] = $res['full_name'];
writeLog('LOGIN', 'Gebruiker ingelogd');
session_write_close();
echo json_encode(['success' => true, 'user' => $res['full_name']]);
} else {
http_response_code(401); echo json_encode(['error' => 'Login mislukt']);
@ -52,19 +39,104 @@ if ($action === 'login') {
exit;
}
if (!isset($_SESSION['user']) && $action !== 'login') {
http_response_code(403); echo json_encode(['error' => 'Auth required']); exit;
if (!isset($_SESSION['user'])) { http_response_code(403); exit; }
$woocommerce = new Client($_ENV['WC_URL'], $_ENV['WC_KEY'], $_ENV['WC_SECRET'], ['version' => 'wc/v3', 'verify_ssl' => false, 'timeout' => 400]);
// --- CREATE ORDER ---
if ($action === 'create_order') {
$input = json_decode(file_get_contents('php://input'), true);
try {
$mediacode = $input['mediacode_internal'] ?? 'Geen';
$wc_gateway_id = $input['payment_method'];
$mollie_method = str_replace(['mollie_wc_gateway_', 'rve_'], '', $wc_gateway_id);
$input['payment_method'] = $wc_gateway_id;
// Compacte meta_data om WAF blokkades te voorkomen
$input['meta_data'] = [
['key' => '_wc_order_attribution_source_type', 'value' => 'utm'],
['key' => '_wc_order_attribution_utm_source', 'value' => 'SalesPanel'],
['key' => '_wc_order_attribution_utm_campaign', 'value' => $mediacode],
['key' => 'Mediacode', 'value' => $mediacode]
];
// 1. Order aanmaken (Hier gaat de 500 error vaak mis door WAF)
$order = $woocommerce->post('orders', $input);
$mollie = new MollieApiClient();
$mollie->setApiKey($_ENV['MOLLIE_KEY']);
$paymentData = [
"amount" => ["currency" => "EUR", "value" => number_format((float)$order->total, 2, '.', '')],
"description" => "Order #{$order->id}",
"redirectUrl" => $_ENV['WC_URL'] . "/checkout/order-received/{$order->id}/?key={$order->order_key}&order_id={$order->id}&utm_source=SalesPanel&utm_campaign={$mediacode}",
"webhookUrl" => $_ENV['WC_URL'] . "/wc-api/{$wc_gateway_id}/?key={$order->order_key}&order_id={$order->id}",
"method" => $mollie_method,
"metadata" => ["order_id" => (string)$order->id, "mediacode" => $mediacode]
];
// Verplichte adresvelden voor achteraf betalen
if (in_array($mollie_method, ['in3', 'klarna', 'klarnapaylater', 'klarnasliceit', 'riverty'])) {
$paymentData["billingAddress"] = [
"givenName" => $input['billing']['first_name'],
"familyName" => $input['billing']['last_name'],
"email" => $input['billing']['email'],
"streetAndNumber" => $input['billing']['address_1'],
"city" => $input['billing']['city'],
"postalCode" => $input['billing']['postcode'],
"country" => "NL"
];
$paymentData["lines"] = [[
"name" => "Bestelling #" . $order->id,
"quantity" => 1,
"unitPrice" => ["currency" => "EUR", "value" => number_format((float)$order->total, 2, '.', '')],
"totalAmount" => ["currency" => "EUR", "value" => number_format((float)$order->total, 2, '.', '')],
"vatRate" => "21.00",
"vatAmount" => ["currency" => "EUR", "value" => number_format((float)$order->total_tax, 2, '.', '')]
]];
}
$payment = $mollie->payments->create($paymentData);
// Update meta in aparte call om de eerste POST klein te houden
$woocommerce->put("orders/{$order->id}", ['meta_data' => [['key' => '_transaction_id', 'value' => $payment->id]]]);
echo json_encode(['payment_url' => $payment->getCheckoutUrl()]);
} catch (Exception $e) {
http_response_code(422); echo json_encode(['error' => $e->getMessage()]);
}
exit;
}
// --- WOOCOMMERCE CLIENT VIA ENV ---
$woocommerce = new Client(
$_ENV['WC_URL'],
$_ENV['WC_KEY'],
$_ENV['WC_SECRET'],
['version' => 'wc/v3', 'timeout' => 400, 'verify_ssl' => false]
);
// --- OVERIGE ACTIES (POSTCODE, PRODUCTS, LOGOUT) ---
if ($action === 'get_payment_methods') {
try {
$gateways = $woocommerce->get('payment_gateways');
$output = [];
foreach ($gateways as $gw) {
if ($gw->enabled && (str_contains($gw->id, 'mollie') || str_contains($gw->id, 'riverty') || str_contains($gw->id, 'klarna'))) {
$output[] = ['id' => $gw->id, 'title' => $gw->method_title];
}
}
echo json_encode($output);
} catch (Exception $e) { echo json_encode([]); }
exit;
}
if ($action === 'get_products') {
try {
$products = $woocommerce->get('products', ['status' => 'publish', 'per_page' => 100]);
$enriched = [];
foreach ($products as $product) {
$p = (array)$product;
$p['variation_details'] = ($product->type === 'variable') ? (array)$woocommerce->get("products/{$product->id}/variations", ['per_page' => 50]) : [];
$enriched[] = $p;
}
echo json_encode($enriched);
} catch (Exception $e) { echo json_encode([]); }
exit;
}
// --- POSTCODE CHECK ---
if ($action === 'postcode_check') {
$postcode = str_replace(' ', '', $_GET['postcode']);
$url = "https://postcode.tech/api/v1/postcode?postcode={$postcode}&number=" . $_GET['number'];
@ -73,70 +145,4 @@ if ($action === 'postcode_check') {
echo curl_exec($ch); exit;
}
// --- GET PRODUCTS (FIX VOOR VARIATIES & UPSELLS) ---
if ($action === 'get_products') {
try {
$products = $woocommerce->get('products', ['status' => 'publish', 'per_page' => 100]);
$enriched = [];
foreach ($products as $product) {
$p = (array)$product;
if ($product->type === 'variable') {
$p['variation_details'] = (array)$woocommerce->get("products/{$product->id}/variations", ['per_page' => 100]);
} else {
$p['variation_details'] = [];
}
$enriched[] = $p;
}
echo json_encode($enriched);
} catch (Exception $e) { echo json_encode(['error' => $e->getMessage()]); }
exit;
}
// --- CREATE ORDER ---
if ($action === 'create_order') {
$input = json_decode(file_get_contents('php://input'), true);
try {
$mediacode = $input['mediacode_internal'] ?? 'Geen';
$method_input = $input['payment_method'];
$map = [
'mollie_methods_ideal' => ['wc' => 'mollie_wc_gateway_ideal', 'm' => 'ideal'],
'rve_riverty' => ['wc' => 'mollie_wc_gateway_riverty', 'm' => 'riverty'],
'mollie_methods_creditcard' => ['wc' => 'mollie_wc_gateway_creditcard', 'm' => 'creditcard']
];
$gw = $map[$method_input];
$input['payment_method'] = $gw['wc'];
$input['payment_method_title'] = 'iDEAL (via Mollie)';
$input['customer_note'] = "Agent: {$_SESSION['user']} | Mediacode: $mediacode";
$input['meta_data'][] = ['key' => 'Mediacode', 'value' => $mediacode];
$input['meta_data'][] = ['key' => '_wc_order_attribution_utm_campaign', 'value' => $mediacode];
$input['meta_data'][] = ['key' => '_wc_order_attribution_utm_source', 'value' => 'SalesPanel'];
$order = $woocommerce->post('orders', $input);
$mollie = new MollieApiClient();
$mollie->setApiKey($_ENV['MOLLIE_KEY']);
$is_sub = (stripos(json_encode($order->line_items), 'abonnement') !== false);
$payment = $mollie->payments->create([
"amount" => ["currency" => "EUR", "value" => ($gw['m'] === 'ideal' && $is_sub) ? "0.01" : number_format((float)$order->total, 2, '.', '')],
"description" => "Order #{$order->id} [$mediacode]",
"redirectUrl" => $_ENV['WC_URL'] . "/checkout/order-received/{$order->id}/?key={$order->order_key}&order_id={$order->id}&filter_flag=onMollieReturn",
"webhookUrl" => $_ENV['WC_URL'] . "/wc-api/mollie_wc_gateway_ideal?order_id={$order->id}&key={$order->order_key}&filter_flag=1",
"method" => $gw['m'],
"metadata" => ["order_id" => (string)$order->id]
]);
$woocommerce->put("orders/{$order->id}", ['meta_data' => [['key' => '_mollie_payment_id', 'value' => $payment->id], ['key' => '_transaction_id', 'value' => $payment->id]]]);
$woocommerce->post("orders/{$order->id}/notes", ['note' => "Betaallink: " . $payment->getCheckoutUrl(), 'customer_note' => true]);
writeLog('ORDER_CREATED', "Order #{$order->id} voor {$input['billing']['email']}");
echo json_encode(['payment_url' => $payment->getCheckoutUrl()]);
} catch (Exception $e) {
writeLog('ERROR', $e->getMessage());
http_response_code(422); echo json_encode(['error' => $e->getMessage()]);
}
exit;
}
if ($action === 'logout') { session_destroy(); echo json_encode(['success' => true]); exit; }

View File

@ -2,68 +2,65 @@
<html lang="nl">
<head>
<meta charset="UTF-8">
<title>Telvero Sales</title>
<title>Telvero Sales Panel</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/alpinejs" defer></script>
<style>[x-cloak] { display: none !important; }</style>
</head>
<body class="bg-slate-100 min-h-screen" x-data="salesApp()" x-init="checkAuth()">
<body class="bg-slate-100 min-h-screen font-sans" x-data="salesApp()">
<template x-if="!isLoggedIn">
<div class="fixed inset-0 bg-slate-900 flex items-center justify-center p-4 z-50">
<div class="bg-white p-10 rounded-[2.5rem] shadow-2xl w-full max-w-md text-center">
<h2 class="text-3xl font-black mb-8 italic">TELVERO <span class="text-blue-600">LOGIN</span></h2>
<div class="bg-white p-10 rounded-[2.5rem] shadow-2xl w-full max-w-md text-center border-t-8 border-blue-600">
<h2 class="text-3xl font-black mb-8 italic">TELVERO LOGIN</h2>
<div class="space-y-4">
<input type="text" x-model="loginForm.username" placeholder="Gebruikersnaam" class="w-full border-2 border-slate-100 p-4 rounded-2xl outline-none focus:border-blue-500 transition-all">
<input type="password" x-model="loginForm.password" @keyup.enter="doLogin()" placeholder="Wachtwoord" class="w-full border-2 border-slate-100 p-4 rounded-2xl outline-none focus:border-blue-500 transition-all">
<button @click="doLogin()" class="w-full bg-blue-600 text-white p-5 rounded-2xl font-black shadow-lg hover:bg-blue-700 transition active:scale-95">INLOGGEN</button>
<input type="text" x-model="loginForm.username" placeholder="Gebruikersnaam" class="w-full border p-4 rounded-2xl outline-none focus:border-blue-500 bg-slate-50">
<input type="password" x-model="loginForm.password" @keyup.enter="doLogin()" placeholder="Wachtwoord" class="w-full border p-4 rounded-2xl outline-none focus:border-blue-500 bg-slate-50">
<button @click="doLogin()" class="w-full bg-blue-600 text-white p-5 rounded-2xl font-black shadow-lg hover:bg-blue-700 transition uppercase tracking-widest text-sm">Inloggen</button>
</div>
</div>
</div>
</template>
<div x-show="isLoggedIn" x-cloak class="max-w-[1400px] mx-auto p-6">
<div x-show="isLoggedIn" x-cloak class="max-w-[1440px] mx-auto p-6">
<header class="flex justify-between items-center mb-8 bg-white p-6 rounded-3xl shadow-sm border-b-4 border-blue-600">
<h1 class="text-2xl font-black italic text-slate-800">TELVERO <span class="text-blue-600">PANEL</span></h1>
<div class="flex items-center gap-6">
<span class="font-bold text-slate-400 text-sm" x-text="'Agent: ' + currentUser"></span>
<button @click="doLogout()" class="text-xs font-black text-red-500 underline uppercase tracking-tighter">Uitloggen</button>
<h1 class="text-2xl font-black italic tracking-tighter">TELVERO <span class="text-blue-600">PANEL</span></h1>
<div class="flex items-center gap-6 text-sm font-bold text-slate-400">
<span x-text="'Agent: ' + currentUser"></span>
<button @click="doLogout()" class="text-red-500 underline uppercase text-xs font-black">Uitloggen</button>
</div>
</header>
<div class="grid grid-cols-12 gap-6">
<div class="grid grid-cols-12 gap-8">
<div class="col-span-12 lg:col-span-4 bg-white p-8 rounded-[2rem] shadow-sm border border-slate-200">
<div class="mb-8">
<label class="block text-[10px] font-black text-blue-600 uppercase tracking-widest mb-3">Bron / Mediacode</label>
<select x-model="meta.mediacode" class="w-full border-2 border-blue-500 p-4 rounded-2xl font-bold text-blue-800 bg-blue-50 outline-none shadow-sm">
<option value="">-- SELECTEER MEDIACODE --</option>
<div class="mb-8 p-6 bg-blue-50 rounded-2xl border-2 border-blue-100 shadow-inner">
<label class="block text-[10px] font-black text-blue-600 uppercase tracking-widest mb-3 italic">Mediacode</label>
<select x-model="meta.mediacode" class="w-full border-2 border-white p-4 rounded-xl font-bold text-blue-800 shadow-sm outline-none focus:border-blue-300">
<option value="">-- KIES MEDIACODE --</option>
<option value="TELVERO-NET5">TELVERO-NET5</option>
<option value="TELVERO-SBS6">TELVERO-SBS6</option>
</select>
</div>
<h2 class="font-bold mb-6 text-slate-400 uppercase text-[10px] tracking-widest border-b pb-2 italic">Klantgegevens</h2>
<div class="space-y-4">
<div class="grid grid-cols-2 gap-3">
<input type="text" x-model="form.initials" @blur="formatInitials()" placeholder="Voorletters" class="border p-3 rounded-xl w-full bg-slate-50">
<input type="text" x-model="form.lastname" @blur="formatLastname()" placeholder="Achternaam" class="border p-3 rounded-xl w-full bg-slate-50">
</div>
<div class="grid grid-cols-3 gap-2">
<input type="text" x-model="form.postcode" placeholder="Postcode" class="border p-3 rounded-xl w-full uppercase">
<input type="text" x-model="form.postcode" placeholder="Postcode" class="border p-3 rounded-xl w-full uppercase font-mono">
<input type="text" x-model="form.houseno" @blur="lookupAddress()" placeholder="Nr." class="border p-3 rounded-xl w-full">
<input type="text" x-model="form.suffix" placeholder="Toev." class="border p-3 rounded-xl w-full">
</div>
<input type="text" x-model="form.street" placeholder="Straat" class="w-full border p-3 rounded-xl bg-slate-100 font-bold text-xs" readonly>
<input type="text" x-model="form.city" placeholder="Stad" class="w-full border p-3 rounded-xl bg-slate-100 font-bold text-xs" readonly>
<input type="tel" x-model="form.phone" placeholder="Telefoonnummer (06...)" class="border-2 border-slate-100 p-3 rounded-xl w-full focus:border-blue-500 outline-none">
<input type="email" x-model="form.email" placeholder="E-mail (Verplicht)" class="border-2 border-amber-300 p-3 rounded-xl w-full outline-none focus:border-amber-400 transition-all">
<input type="text" x-model="form.dob" @blur="formatDOB()" placeholder="Geboortedatum (DDMMYYYY)" class="border p-3 rounded-xl w-full">
<input type="text" x-model="form.street" placeholder="Straat" class="w-full border p-3 rounded-xl bg-slate-100 font-bold text-xs shadow-inner" readonly>
<input type="text" x-model="form.city" placeholder="Stad" class="w-full border p-3 rounded-xl bg-slate-100 font-bold text-xs shadow-inner" readonly>
<input type="tel" x-model="form.phone" placeholder="Telefoon (06...)" class="border p-3 rounded-xl w-full focus:border-blue-500 outline-none">
<input type="email" x-model="form.email" placeholder="E-mail (Verplicht)" class="border-2 border-amber-300 p-3 rounded-xl w-full outline-none focus:border-amber-500">
</div>
</div>
<div class="col-span-12 lg:col-span-5 bg-white p-8 rounded-[2rem] shadow-sm border border-slate-200">
<h2 class="font-bold mb-6 text-slate-400 uppercase text-[10px] tracking-widest border-b pb-2 italic">Productselectie</h2>
<select x-model="selectedProductId" @change="selectProduct()" class="w-full border-2 border-slate-100 p-5 rounded-2xl font-black text-slate-700 mb-6 outline-none focus:border-blue-500 bg-slate-50">
<h2 class="font-bold mb-6 text-slate-400 uppercase text-[10px] tracking-widest border-b pb-2 text-center italic">Producten</h2>
<select x-model="selectedProductId" @change="selectProduct()" class="w-full border-2 border-slate-100 p-5 rounded-2xl font-black text-slate-700 mb-6 bg-slate-50 outline-none focus:border-blue-500 shadow-sm">
<option value="">-- Kies Hoofdproduct --</option>
<template x-for="p in products" :key="p.id">
<option :value="p.id" x-text="p.name"></option>
@ -71,9 +68,8 @@
</select>
<div x-show="variations.length > 0" x-cloak class="mb-8 p-6 bg-blue-50 rounded-3xl border border-blue-100 shadow-inner">
<label class="block text-[10px] font-black text-blue-600 uppercase mb-3 tracking-widest">Kies Optie</label>
<select x-model="selectedVariationId" @change="selectVariation()" class="w-full border-2 border-white p-4 rounded-2xl font-bold bg-white text-slate-700 shadow-sm">
<option value="">-- Maak een keuze --</option>
<option value="">-- Kies Optie --</option>
<template x-for="v in variations" :key="v.id">
<option :value="v.id" x-text="getVarName(v) + ' (€' + v.price + ')'"></option>
</template>
@ -81,11 +77,11 @@
</div>
<div x-show="upsellOptions.length > 0" x-cloak class="space-y-3">
<p class="text-[10px] font-black text-red-500 uppercase tracking-widest italic px-2">Aanbevolen Extra's</p>
<p class="text-[10px] font-black text-red-500 uppercase tracking-widest italic px-2">Aanbevolen extra's</p>
<template x-for="u in upsellOptions" :key="u.id">
<div class="flex items-center justify-between p-4 border rounded-2xl bg-slate-50 hover:bg-white transition-all shadow-sm">
<div class="flex items-center justify-between p-4 border rounded-2xl bg-slate-50 hover:bg-white transition-all shadow-sm border-slate-100">
<span class="text-xs font-bold text-slate-700" x-text="u.name + ' (€' + u.price + ')'"></span>
<button @click="toggleUpsell(u)" :class="isInCart(u.id) ? 'bg-red-500' : 'bg-green-600'" class="text-white px-6 py-2 rounded-xl text-[10px] font-black shadow-md uppercase transition active:scale-90" x-text="isInCart(u.id) ? 'Verwijder' : 'Voeg toe'"></button>
<button @click="toggleUpsell(u)" :class="isInCart(u.id) ? 'bg-red-500' : 'bg-green-600'" class="text-white px-6 py-2 rounded-xl text-[10px] font-black uppercase shadow-md transition active:scale-95" x-text="isInCart(u.id) ? 'Verwijder' : 'Voeg toe'"></button>
</div>
</template>
</div>
@ -93,32 +89,47 @@
<div class="col-span-12 lg:col-span-3">
<div class="bg-slate-900 text-white p-8 rounded-[2.5rem] shadow-2xl sticky top-6 border border-slate-800">
<h2 class="font-bold mb-6 border-b border-slate-800 pb-2 text-[10px] uppercase text-slate-500 tracking-widest italic">Overzicht</h2>
<div class="space-y-4 mb-8 min-h-[100px]">
<template x-for="item in cart" :key="item.id + '-' + (item.variation_id || 0)">
<div class="flex justify-between text-[11px] items-start">
<span x-text="item.name" class="opacity-80 leading-tight pr-4"></span>
<span x-text="'€' + item.price" class="font-bold text-blue-400 whitespace-nowrap"></span>
<h2 class="font-bold mb-6 border-b border-slate-800 pb-2 text-[10px] uppercase text-slate-500 tracking-widest italic text-center">Winkelmand</h2>
<div class="space-y-4 mb-8 min-h-[100px] max-h-[300px] overflow-y-auto pr-2 custom-scrollbar">
<template x-for="(item, index) in cart" :key="index">
<div class="flex justify-between items-center group">
<div class="flex flex-col flex-1 pr-2">
<span x-text="item.name" class="text-[11px] font-medium leading-tight text-slate-300"></span>
<span x-text="'€' + item.price" class="text-[11px] font-black text-blue-400"></span>
</div>
<button @click="removeFromCart(index)" class="text-slate-600 hover:text-red-500 transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</template>
</div>
<div class="mb-8 pt-4 border-t border-slate-800 space-y-2">
<button @click="payment_method = 'mollie_methods_ideal'" :class="payment_method === 'mollie_methods_ideal' ? 'bg-blue-600 border-blue-400' : 'bg-slate-800 border-slate-700'" class="w-full text-left p-4 rounded-2xl border text-[10px] font-bold transition-all shadow-inner">SEPA INCASSO (0.01)</button>
<button @click="payment_method = 'rve_riverty'" :class="payment_method === 'rve_riverty' ? 'bg-orange-600 border-orange-400' : 'bg-slate-800 border-slate-700'" class="w-full text-left p-4 rounded-2xl border text-[10px] font-bold uppercase transition-all shadow-inner">Riverty Achteraf</button>
<p class="text-[10px] text-slate-500 uppercase font-black mb-3 italic tracking-widest text-center">Betaling</p>
<div class="space-y-2 max-h-[200px] overflow-y-auto pr-2 custom-scrollbar">
<template x-for="method in paymentMethods" :key="method.id">
<button @click="payment_method = method.id"
:class="payment_method === method.id ? 'bg-blue-600 border-blue-400 ring-2 ring-blue-500/50' : 'bg-slate-800 border-slate-700 opacity-60'"
class="w-full text-left p-3 rounded-2xl border flex items-center gap-3 transition-all duration-200">
<img :src="method.image" class="w-7 h-7 rounded bg-white p-1 shadow-inner">
<span class="text-[10px] font-black uppercase text-white tracking-tighter" x-text="method.title"></span>
</button>
</template>
</div>
</div>
<div class="flex justify-between items-center mb-8 pt-4 border-t border-slate-800">
<span class="text-xs font-bold uppercase tracking-widest text-slate-500 italic">Totaal</span>
<span class="text-3xl font-black text-green-400" x-text="'€' + total"></span>
</div>
<button @click="submitOrder()"
:disabled="submitting || !form.email || !meta.mediacode || cart.length === 0"
class="w-full bg-blue-600 hover:bg-blue-500 p-6 rounded-2xl font-black text-lg shadow-xl disabled:opacity-20 transition active:scale-95 uppercase tracking-tighter">
class="w-full bg-blue-600 hover:bg-blue-500 p-6 rounded-2xl font-black text-lg shadow-xl disabled:opacity-20 uppercase tracking-tighter transition active:scale-95 shadow-blue-500/20">
<span x-text="submitting ? 'PROCESSING...' : 'ORDER VERSTUREN'"></span>
</button>
<p x-show="!meta.mediacode" class="text-[9px] text-red-400 mt-4 text-center font-bold italic animate-pulse">Selecteer eerst een Mediacode!</p>
<p x-show="!meta.mediacode" class="text-[9px] text-red-400 mt-4 text-center font-bold italic animate-pulse">Mediacode verplicht!</p>
</div>
</div>
</div>
@ -128,43 +139,48 @@
function salesApp() {
return {
isLoggedIn: false, currentUser: '', loginForm: { username: '', password: '' },
products: [], upsellOptions: [], cart: [], activeProduct: null,
selectedProductId: '', selectedVariationId: '', variations: [],
payment_method: 'mollie_methods_ideal', submitting: false,
products: [], paymentMethods: [], upsellOptions: [], cart: [], activeProduct: null,
selectedProductId: '', selectedVariationId: '', variations: [], payment_method: '',
submitting: false,
form: { initials: '', lastname: '', postcode: '', houseno: '', suffix: '', street: '', city: '', email: '', dob: '', phone: '' },
meta: { mediacode: '' },
async doLogin() {
const res = await fetch('api.php?action=login', { method: 'POST', body: JSON.stringify(this.loginForm) });
if(res.ok) {
const data = await res.json();
if(data.success) { this.isLoggedIn = true; this.currentUser = data.user; this.initData(); }
else { alert(data.error); }
this.isLoggedIn = true; this.currentUser = data.user;
await this.initData();
} else { alert("Login mislukt"); }
},
checkAuth() { if (document.cookie.includes('PHPSESSID')) { /* Optionele check */ } },
async initData() {
const res = await fetch('api.php?action=get_products');
this.products = await res.json();
},
async lookupAddress() {
if (this.form.postcode.length >= 6 && this.form.houseno) {
const res = await fetch(`api.php?action=postcode_check&postcode=${this.form.postcode}&number=${this.form.houseno}`);
const data = await res.json();
if (data.street) { this.form.street = data.street.toUpperCase(); this.form.city = data.city.toUpperCase(); }
const [pRes, mRes] = await Promise.all([
fetch('api.php?action=get_products'),
fetch('api.php?action=get_payment_methods')
]);
this.products = await pRes.json();
let methods = await mRes.json();
this.paymentMethods = methods.map(m => {
let iconKey = m.id.replace('mollie_wc_gateway_', '');
if (m.id.includes('riverty')) iconKey = 'riverty';
if (m.id.includes('klarna')) iconKey = 'klarna';
if (m.id.includes('in3')) iconKey = 'in3';
return { ...m, image: `https://www.mollie.com/external/icons/payment-methods/${iconKey}.svg` };
});
if(this.paymentMethods.length > 0) {
const ideal = this.paymentMethods.find(m => m.id.includes('ideal'));
this.payment_method = ideal ? ideal.id : this.paymentMethods[0].id;
}
},
selectProduct() {
const p = this.products.find(x => x.id == this.selectedProductId);
if(!p) return;
this.activeProduct = p;
this.variations = p.variation_details || [];
this.cart = [];
this.selectedVariationId = '';
this.activeProduct = p; this.variations = p.variation_details || [];
this.cart = []; this.selectedVariationId = '';
if (p.type !== 'variable') {
this.cart = [{ id: parseInt(p.id), name: p.name, price: p.price }];
this.cart.push({ id: parseInt(p.id), name: p.name, price: p.price });
this.loadUpsells(p);
}
},
@ -179,17 +195,25 @@
loadUpsells(product) {
this.upsellOptions = [];
if (product.upsell_ids && product.upsell_ids.length > 0) {
this.upsellOptions = this.products.filter(x => product.upsell_ids.includes(x.id));
const idsToFind = product.upsell_ids.map(id => parseInt(id));
this.upsellOptions = this.products.filter(p => idsToFind.includes(parseInt(p.id)));
}
},
getVarName(v) { return v.attributes.map(a => a.option).join(' '); },
toggleUpsell(u) {
const idx = this.cart.findIndex(i => i.id === u.id);
idx > -1 ? this.cart.splice(idx, 1) : this.cart.push({ id: parseInt(u.id), name: u.name, price: u.price });
removeFromCart(index) {
this.cart.splice(index, 1);
},
isInCart(id) { return this.cart.some(i => i.id === id); },
get total() { return this.cart.reduce((s, i) => s + parseFloat(i.price), 0).toFixed(2); },
getVarName(v) { return v.attributes.map(a => a.option).join(' '); },
toggleUpsell(u) {
const idx = this.cart.findIndex(i => parseInt(i.id) === parseInt(u.id));
if(idx > -1) { this.cart.splice(idx, 1); }
else { this.cart.push({ id: parseInt(u.id), name: u.name, price: u.price }); }
},
isInCart(id) { return this.cart.some(i => parseInt(i.id) === parseInt(id)); },
get total() { return this.cart.reduce((sum, item) => sum + parseFloat(item.price), 0).toFixed(2); },
formatInitials() { let v = this.form.initials.replace(/[^a-z]/gi, '').toUpperCase(); this.form.initials = v.split('').join('.') + (v ? '.' : ''); },
formatLastname() { this.form.lastname = this.form.lastname.charAt(0).toUpperCase() + this.form.lastname.slice(1); },
@ -199,18 +223,25 @@
this.submitting = true;
const payload = {
payment_method: this.payment_method, mediacode_internal: this.meta.mediacode,
billing: { first_name: this.form.initials, last_name: this.form.lastname, address_1: (this.form.street + ' ' + this.form.houseno).trim(), city: this.form.city, postcode: this.form.postcode, country: 'NL', email: this.form.email, phone: this.form.phone },
billing: { first_name: this.form.initials, last_name: this.form.lastname, address_1: (this.form.street + ' ' + this.form.houseno + ' ' + (this.form.suffix || '')).trim(), city: this.form.city, postcode: this.form.postcode, country: 'NL', email: this.form.email, phone: this.form.phone },
line_items: this.cart.map(i => ({ product_id: i.id, variation_id: i.variation_id || 0, quantity: 1 }))
};
try {
const res = await fetch('api.php?action=create_order', { method: 'POST', body: JSON.stringify(payload) });
const result = await res.json();
if(result.payment_url) { alert("SUCCES! De order is geplaatst."); window.location.reload(); }
if(result.payment_url) { alert("Succes! De order is aangemaakt."); this.cart = []; this.selectedProductId = ''; this.form = { initials: '', lastname: '', postcode: '', houseno: '', suffix: '', street: '', city: '', email: '', dob: '', phone: '' }; }
else { alert("Fout: " + result.error); }
} catch(e) { alert("Systeemfout"); }
this.submitting = false;
},
async doLogout() { await fetch('api.php?action=logout'); location.reload(); }
async doLogout() { await fetch('api.php?action=logout'); location.reload(); },
async lookupAddress() {
if (this.form.postcode.length >= 6 && this.form.houseno) {
const res = await fetch(`api.php?action=postcode_check&postcode=${this.form.postcode}&number=${this.form.houseno}`);
const data = await res.json();
if (data.street) { this.form.street = data.street.toUpperCase(); this.form.city = data.city.toUpperCase(); }
}
}
}
}
</script>