From de890e6b913988fcf3e79d10d62e26395e5e30e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mathias=20Gla=CC=88ser?= Date: Sun, 29 Mar 2026 20:47:03 +0200 Subject: [PATCH] Accept array payloads and add DB schema preflight for order import --- order-import.php | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/order-import.php b/order-import.php index ab02bc7..61075c3 100644 --- a/order-import.php +++ b/order-import.php @@ -200,6 +200,33 @@ function connect_database(array $localEnv): PDO ]); } +function ensure_required_tables_exist(PDO $pdo): void +{ + $required = [ + 'party', + 'address', + 'sales_order', + 'sales_order_line', + 'payment_method', + 'shipping_method', + ]; + + $stmt = $pdo->query( + "SELECT table_name + FROM information_schema.tables + WHERE table_schema = 'public'" + ); + $rows = $stmt->fetchAll(PDO::FETCH_COLUMN); + $existing = array_map('strval', $rows ?: []); + $missing = array_values(array_diff($required, $existing)); + + if ($missing !== []) { + throw new RuntimeException( + 'DB schema not initialized. Missing tables: ' . implode(', ', $missing) + ); + } +} + function find_or_create_party(PDO $pdo, array $data): int { $email = trim((string) ($data['EmailKunde'] ?? '')); @@ -316,6 +343,14 @@ if (!is_array($data)) { json_response(400, ['ok' => false, 'error' => 'JSON object expected']); } +// n8n can send either a JSON object or a single-item array with the order object. +if (array_is_list($data)) { + if (!isset($data[0]) || !is_array($data[0])) { + json_response(400, ['ok' => false, 'error' => 'Array payload must contain one order object']); + } + $data = $data[0]; +} + $externalRef = trim((string) ($data['BestellungNr'] ?? '')); if ($externalRef === '') { json_response(422, ['ok' => false, 'error' => 'BestellungNr is required']); @@ -328,6 +363,7 @@ if (!is_array($lineItems)) { try { $pdo = connect_database($env); + ensure_required_tables_exist($pdo); $pdo->beginTransaction(); $partyId = find_or_create_party($pdo, $data);