Accept array payloads and add DB schema preflight for order import
This commit is contained in:
@@ -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
|
function find_or_create_party(PDO $pdo, array $data): int
|
||||||
{
|
{
|
||||||
$email = trim((string) ($data['EmailKunde'] ?? ''));
|
$email = trim((string) ($data['EmailKunde'] ?? ''));
|
||||||
@@ -316,6 +343,14 @@ if (!is_array($data)) {
|
|||||||
json_response(400, ['ok' => false, 'error' => 'JSON object expected']);
|
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'] ?? ''));
|
$externalRef = trim((string) ($data['BestellungNr'] ?? ''));
|
||||||
if ($externalRef === '') {
|
if ($externalRef === '') {
|
||||||
json_response(422, ['ok' => false, 'error' => 'BestellungNr is required']);
|
json_response(422, ['ok' => false, 'error' => 'BestellungNr is required']);
|
||||||
@@ -328,6 +363,7 @@ if (!is_array($lineItems)) {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
$pdo = connect_database($env);
|
$pdo = connect_database($env);
|
||||||
|
ensure_required_tables_exist($pdo);
|
||||||
$pdo->beginTransaction();
|
$pdo->beginTransaction();
|
||||||
|
|
||||||
$partyId = find_or_create_party($pdo, $data);
|
$partyId = find_or_create_party($pdo, $data);
|
||||||
|
|||||||
Reference in New Issue
Block a user