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);