From 0ba7c072875aa6529d93420549457d26c009e28e Mon Sep 17 00:00:00 2001 From: Remo Zaros Date: Wed, 10 Jun 2026 09:11:28 +0200 Subject: [PATCH] rewrite API call --- session_dialog.php | 286 ++++++++++++++++++++++++++++----------------- 1 file changed, 178 insertions(+), 108 deletions(-) diff --git a/session_dialog.php b/session_dialog.php index 0bb3abf..8e74fcf 100644 --- a/session_dialog.php +++ b/session_dialog.php @@ -24,6 +24,8 @@ function modal_styles() wp_enqueue_style( "prijs-per-postcode", plugins_url("/assets/postcode_modal.css", __FILE__), + [], // Voeg een lege dependencies array toe (verplicht) + filemtime(plugin_dir_path(__FILE__) . "assets/postcode_modal.css"), // Voeg versie toe ); } @@ -48,72 +50,92 @@ function send_postcode_data() const sndBtnTxt = sndBtn.querySelector(".btn_text"); const errorMsg = document.querySelector("#error_message_modal_postcode"); + // 1. Validatie bij blur (client-side checks) modalForm.querySelectorAll("input").forEach(input => { - input.addEventListener("blur", ev => { - errorMsg.innerHTML = "" - if(!ev.target.validity.valid && ev.target.value !== "") { - errorMsg.innerHTML = ev.target.title; - } - }) - }) + input.addEventListener("blur", ev => { + errorMsg.innerHTML = ""; + if (!ev.target.validity.valid && ev.target.value !== "") { + errorMsg.innerHTML = ev.target.title; + } + }); + }); + // 2. Submit Handler modalForm.addEventListener('submit', async (e) => { e.preventDefault(); errorMsg.innerHTML = ""; + + // UI: Laadstatus sndBtn.disabled = true; sndBtnLdr.style.opacity = "1"; sndBtnTxt.style.opacity = "0"; + const formData = new FormData(e.target); - const data = Object.fromEntries(formData.entries()); - const json = JSON.stringify(data); + const payload = Object.fromEntries(formData.entries()); try { - const resp = await fetch('', { - method: 'POST', - credentials: 'same-origin', - headers: { - 'Content-Type': 'application/json', - 'X-WP-Nonce': '' - }, - body: json - }); + const resp = await fetch('', { + method: 'POST', + credentials: 'same-origin', + headers: { + 'Content-Type': 'application/json', + 'X-WP-Nonce': '' + }, + body: JSON.stringify(payload) + }); - if(!resp.ok){ - throw new Error(`HTTP Error! status: ${resp.status}` ); - } - sndBtn.disabled = false; - sndBtnLdr.style.opacity = "0"; - sndBtnTxt.style.opacity = "1"; - const data = await resp.json(); - console.log("Data returnd", data); + // Parse altijd eerst de JSON, zelfs bij HTTP fouten + const data = await resp.json(); - if (data.status === "error"){ - const err = data.code; - let errmsg + // UI: Reset knop + sndBtn.disabled = false; + sndBtnLdr.style.opacity = "0"; + sndBtnTxt.style.opacity = "1"; - switch (err) { - case "HUISNUMMER_NOT_FOUND": - errmsg = "Adres is niet gevonden."; - break; - case "HUISNUMMER_AMBIGUOUS": - errmsg = "Huisnummertovoeging mist."; - break; - default: - errmsg = "Gegevens zijn niet correct."; - } - errorMsg.innerHTML = errmsg; - } + if (data.status === "error") { + const errorCode = data.code; // Komt nu correct door vanuit PHP + const apiMessage = data.message; - if (data.status === "success"){ - postcodeModal.close(); - //location.reload(); - } - }catch(err){ - console.error("Fetch Failed:", err); - throw err; + let userErrorMessage = "Gegevens zijn niet correct."; + + // Specifieke foutafhandeling + if (errorCode === "HUISNUMMER_NOT_FOUND" || apiMessage.includes("not found")) { + userErrorMessage = "Adres is niet gevonden."; + } + else if (errorCode === "HUISNUMMER_AMBIGUOUS") { + // Deze komt ALLEEN nog hier als PHP géén 'platte' match kon vinden. + // Dat betekent dat de gebruiker verplicht een toevoeging moet geven (bijv. alleen 15A bestaat). + const suggestions = data.suggestions || []; + if (suggestions.length > 0) { + userErrorMessage = `Meerdere opties: ${suggestions.join(", ")}. Voeg een toevoeging toe.`; + } else { + userErrorMessage = "Huisnummertoevoeging is verplicht."; + } + } + else if (errorCode === "CURL_ERROR" || errorCode === "JSON_ERROR") { + userErrorMessage = "Serverfout. Probeer het later opnieuw."; + } + + errorMsg.innerHTML = userErrorMessage; + } + + if (data.status === "success") { + // Succes: Modal sluiten en eventueel reload of update + postcodeModal.close(); + // Optioneel: location.reload(); of update de pagina content + } + + } catch (err) { + console.error("Fetch Failed:", err); + sndBtn.disabled = false; + sndBtnLdr.style.opacity = "0"; + sndBtnTxt.style.opacity = "1"; + errorMsg.innerHTML = "Er ging iets mis bij het verbinden."; } }); @@ -180,56 +202,99 @@ function handle_postcode_modal($data) $params = $data->get_params(); $nonce = $data->get_header("X-WP-Nonce"); - if (wp_verify_nonce($nonce, "wp_rest")) { - if (!verify_postcode($params["postcode"])) { - $resp = [ - "status" => "error", - "message" => "postcode", - ]; - echo json_encode($resp); - exit(); - } - - if (!verify_huisnummer($params["huisnummer"])) { - $resp = [ - "status" => "error", - "message" => "huisnummer", - ]; - echo json_encode($resp); - exit(); - } - - $result = getStraatnaam($params["postcode"], $params["huisnummer"]); - if (isset($result["error"])) { - $resp = [ - "status" => "error", - "message" => $result["error"], - "apirequest" => "openpostcode.nl", - ]; - echo json_encode($resp); - exit(); - } - - $_SESSION["postcode"] = $params["postcode"]; - $_SESSION["huisnummer"] = $params["huisnummer"]; - $_SESSION["straatnaam"] = $result["straatnaam"]; - $_SESSION["woonplaats"] = $result["woonplaats"]; - - $_SESSION["postcode_is_local"] = postcode_in_range($params["postcode"]); - - $resp = [ - "status" => "success", - "message" => "all good", - "straatnaam" => $result["straatnaam"], - "lokaal_trarief" => postcode_in_range($params["postcode"]), - ]; - } else { - $resp = [ - "status" => "error", - "message" => "nononce", - ]; + // 1. Security + if (!wp_verify_nonce($nonce, "wp_rest")) { + echo json_encode(["status" => "error", "message" => "nononce"]); + exit(); } - echo json_encode($resp); + + // 2. Basis Validatie + if (!verify_postcode($params["postcode"])) { + echo json_encode(["status" => "error", "message" => "postcode"]); + exit(); + } + if (!verify_huisnummer($params["huisnummer"])) { + echo json_encode(["status" => "error", "message" => "huisnummer"]); + exit(); + } + + // 3. API Call (Ruwe data) + $result = getStraatnaam($params["postcode"], $params["huisnummer"]); + + // 4. Validatie & Logic + $hasError = isset($result["error"]); + $errorCode = null; + $errorMessage = null; + $candidates = []; + $straatnaam = null; + $woonplaats = null; + + if ($hasError) { + $errorCode = $result["error"]["code"] ?? "UNKNOWN_ERROR"; + $errorMessage = $result["error"]["message"] ?? "Onbekende fout"; + $candidates = $result["error"]["details"]["candidates"] ?? []; + + // SPECIAL CASE: HUISNUMMER_AMBIGUOUS + if ($errorCode === "HUISNUMMER_AMBIGUOUS" && !empty($candidates)) { + $plainMatch = null; + + // Zoek naar candidate ZONDER toevoeging + foreach ($candidates as $candidate) { + if ( + empty($candidate["huisletter"]) && + empty($candidate["huisnummertoevoeging"]) + ) { + $plainMatch = $candidate; + break; + } + } + + // Als we een 'platte' match hebben (bijv. 15), dan is het SUCCES + if ($plainMatch) { + $hasError = false; // Negeer de error + $straatnaam = $plainMatch["straat"]; + $woonplaats = $plainMatch["woonplaats"]; + } + } + } else { + // Normaal succes (geen error in response) + if (!empty($result["results"])) { + $straatnaam = $result["results"][0]["straat"]; + $woonplaats = $result["results"][0]["woonplaats"]; + } else { + // Edge case: geen error veld, maar ook geen results + $hasError = true; + $errorCode = "NO_RESULTS"; + $errorMessage = "Adres niet gevonden"; + } + } + + // 5. Response sturen + if ($hasError) { + echo json_encode([ + "status" => "error", + "code" => $errorCode, + "message" => $errorMessage, + "suggestions" => $result["error"]["details"]["suggestions"] ?? [], + "apirequest" => "openpostcode.nl", + ]); + exit(); + } + + // 6. Succes: Sessie opslaan & response + $_SESSION["postcode"] = $params["postcode"]; + $_SESSION["huisnummer"] = $params["huisnummer"]; + $_SESSION["straatnaam"] = $straatnaam; + $_SESSION["woonplaats"] = $woonplaats; + $_SESSION["postcode_is_local"] = postcode_in_range($params["postcode"]); + + echo json_encode([ + "status" => "success", + "message" => "all good", + "straatnaam" => $straatnaam, + "woonplaats" => $woonplaats, + "lokaal_tarief" => postcode_in_range($params["postcode"]), + ]); exit(); } @@ -272,27 +337,32 @@ function getStraatnaam($postcode, $huisnummer) curl_setopt($ch, CURLOPT_USERAGENT, "PHP/OpenPostcodeClient"); $response = curl_exec($ch); + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (curl_error($ch)) { curl_close($ch); - return ["error" => "cURL error: " . curl_error($ch)]; + return [ + "error" => ["code" => "CURL_ERROR", "message" => curl_error($ch)], + ]; } curl_close($ch); + // Decodeer als associatieve array (true) $data = json_decode($response, true); - if (isset($data["error"])) { + // Als JSON decode faalt + if (json_last_error() !== JSON_ERROR_NONE) { return [ - "error" => $data["error"]["message"], - "code" => $data["error"]["code"], + "error" => [ + "code" => "JSON_ERROR", + "message" => "Invalid JSON response", + ], ]; } - return [ - "straatnaam" => $data["results"][0]["straat"], - "woonplaats" => $data["results"][0]["woonplaats"], - ]; + // Geef de RUWE response terug (inclusief meta, error, results, etc.) + return $data; } function postcode_in_range($postcode)