diff --git a/memory-bank/activeContext.md b/memory-bank/activeContext.md index 6dc925c7..5c3d2ab1 100644 --- a/memory-bank/activeContext.md +++ b/memory-bank/activeContext.md @@ -3,11 +3,70 @@ ## Current development focus (from recent commits) - API contract consistency rollout (TASK22102), starting with helper-based response normalization in selected email/admin handlers. +- TASK22109 email API contract parity and phase21 contract coverage expansion. - Search/case navigation correctness, especially breadcrumb and back-link behavior. - My Portal "view all" and DNS application path handling. - Welsh/English email behavior for specific notification templates. - PDF output formatting and hyperlink behavior. +## TASK22109 completion status (2026-03-18) + +- Branch: `TASK22109-email-api-contracts` +- Commits: + - `6610e5c` — email API contract cleanup + initial phase21 email coverage + - `d17f3a1` — expanded email contract coverage and logging hygiene + - `e9cf1cf` — mini-slice tidy + notify negative-path tests +- Scope completed: + - email handler cleanup/hardening in: + - `pages/api/email/getevents.js` + - `pages/api/email/getdocuments.js` + - `pages/api/email/getall.js` + - `pages/api/email/getmailinglist.js` + - `pages/api/email/getcaseref.js` + - `pages/api/email/notify.js` + - expanded phase21 contract tests: + - `tests/phase21/email-handler-contract.test.cjs` + - `tests/phase21/api-contract-slice1.test.cjs` + - `tests/phase21/_shared.cjs` +- Validation snapshot: + - `node tests/phase21/api-contract-slice1.test.cjs` -> pass + - helper 4/4 + - file-handler 11/11 + - email-handler 12/12 + - `npm run lint` -> warnings only (pre-existing) + +## TASK22168 endpoint slice status (2026-03-19) + +- Branch: `TASK22168-endpoint-account-contract-consistency` +- Scope completed (next coherent low-risk `pages/api/endpoint/**` slice): + - `pages/api/endpoint/getaccounts_api.js` + - `pages/api/endpoint/getemailaccountcheck_api.js` + - `pages/api/endpoint/getpreferredlanguage_api.js` + - `tests/phase21/endpoint-handler-contract.test.cjs` + - `tests/phase21/api-contract-slice1.test.cjs` (runner extended) +- Pattern applied (aligned with TASK22109): + 1. removed dead/noisy code in selected handlers (unused imports + noisy/commented debug remnants), + 2. standardized structured negative-path envelopes for missing required input and catch/failure paths, + 3. preserved success response behavior (`data` pass-through), + 4. added focused phase21 endpoint contract tests: + - missing required input + - catch/failure path + - one success contract parity assertion. +- Validation snapshot: + - `node tests/phase21/api-contract-slice1.test.cjs` -> pass + - helper 4/4 + - file-handler 11/11 + - email-handler 12/12 + - endpoint-handler 7/7 + - `npm run lint` -> warnings only (pre-existing react-hooks warnings) + +## Suggested next work package + +- Continue API contract consistency in `pages/api/endpoint/**` with the same pattern used in TASK22109: + 1. remove noisy logging/commented dead traces in selected endpoints, + 2. add/standardize structured negative-path responses where contract drift exists, + 3. add focused phase21 endpoint contract tests for missing required input + catch-path failures. + ## Recently changed areas (high signal) - `components/breadcrumbs.js` diff --git a/memory-bank/change-log.md b/memory-bank/change-log.md index 7b86df07..d07613fc 100644 --- a/memory-bank/change-log.md +++ b/memory-bank/change-log.md @@ -1508,3 +1508,97 @@ Validation: Follow-ups: - Execute final Slice 7 for remaining complex handlers (`upload`, `getbloblist`, `downloadblob`, `generateappealpdf`) to complete the 2-slice finish plan. + +--- + +### CL-041: TASK22109 email API contract parity + phase21 expansion + +date: 2026-03-18 +author: Cline +scope: `pages/api/email/{getevents,getdocuments,getall,getmailinglist,getcaseref,notify}.js`, `tests/phase21/{api-contract-slice1,_shared,email-handler-contract}.test.cjs` +type: change +rationale: Extend standardized API response contract hardening into remaining email handlers and batch a larger in-scope test/cleanup slice so review is less fragmented while preserving runtime behavior. +impact: More consistent email API negative-path/error contracts, lower noisy logging in sensitive email flow, and stronger automated coverage for email handlers. +status: completed + +Summary: + +- Completed TASK22109 across three cohesive commits: + - `6610e5c` — email API contract cleanup + initial phase21 email coverage + - `d17f3a1` — expanded email contract coverage + logging hygiene + - `e9cf1cf` — final mini-slice tidy + notify negative-path tests +- Email handler cleanup/hardening updates: + - removed stale debug/commented logging and dead variables/imports in selected email handlers + - replaced noisy `console.log` usage in `notify.js` with structured `consoleLogger` redacted event log + - retained existing success payload behavior; no intended response-shape breaking changes +- Phase21 test expansion: + - added dedicated `email-handler-contract.test.cjs` + - combined runner now executes helper + file-handler + email-handler suites + - `_shared.cjs` loader improved to handle additional `export default async function` module forms + - email suite now covers: + - `getevents` (required input, missing linked record, catch path) + - `getdocuments` (required input, catch path) + - `getall` (top-level catch path) + - `getmailinglist` (success + failure) + - `getcaseref` (success + failure) + - `notify` (missing email + notify failure) + +Validation: + +- `node tests/phase21/api-contract-slice1.test.cjs` -> pass + - helper: 4/4 + - file-handler: 11/11 + - email-handler: 12/12 +- `npm run lint` -> warnings only (pre-existing `react-hooks/exhaustive-deps` warnings) + +Follow-ups: + +- Open/merge TASK22109 PR (if not already merged). +- Next candidate stream: apply same contract+coverage pattern to selected `pages/api/endpoint/**` handlers still carrying noisy logging or thin negative-path coverage. + +--- + +### CL-042: TASK22168 endpoint account contract consistency slice (phase21) + +date: 2026-03-19 +author: Cline +scope: `pages/api/endpoint/{getaccounts_api,getemailaccountcheck_api,getpreferredlanguage_api}.js`, `tests/phase21/{api-contract-slice1,endpoint-handler-contract}.test.cjs`, `memory-bank/*` +type: change +rationale: Continue the post-TASK22109 API contract consistency stream with a low-risk, reversible endpoint slice focused on account lookup handlers, removing noisy/dead patterns and standardizing negative-path error envelopes while preserving success contracts. +impact: Consistent structured 400 error responses for missing required input and catch/failure paths in selected endpoint handlers; no intended success payload contract changes. +status: completed + +Summary: + +- Created branch from `origin/SIPS-Development`: + - `TASK22168-endpoint-account-contract-consistency` +- Updated endpoint handlers: + - `getaccounts_api.js` + - `getemailaccountcheck_api.js` + - `getpreferredlanguage_api.js` +- Slice changes applied: + - removed unused imports/dead/commented debug remnants in touched handlers + - standardized missing `emailAddress` handling to structured 400 envelope: + - code: `EMAIL_ADDRESS_REQUIRED` + - standardized catch-path 400 envelopes: + - `ACCOUNTS_FETCH_FAILED` + - `EMAIL_ACCOUNT_CHECK_FAILED` + - `PREFERRED_LANGUAGE_FETCH_FAILED` + - kept success payload behavior stable by returning existing upstream `data` unchanged via `respondSuccess` +- Phase21 test expansion: + - added `tests/phase21/endpoint-handler-contract.test.cjs` + - extended `tests/phase21/api-contract-slice1.test.cjs` to include endpoint handler suite + - new endpoint tests cover missing required input + catch/failure paths, plus success-contract parity check for `getpreferredlanguage_api` + +Validation: + +- `node tests/phase21/api-contract-slice1.test.cjs` -> pass + - helper: 4/4 + - file-handler: 11/11 + - email-handler: 12/12 + - endpoint-handler: 7/7 +- `npm run lint` -> warnings only (pre-existing `react-hooks/exhaustive-deps` warnings; no new lint errors) + +Follow-ups: + +- Next coherent endpoint slice can target login-adjacent handler drift (`getlogin_api`) and/or another compact account endpoint group using the same phase21 contract pattern. diff --git a/memory-bank/progress.md b/memory-bank/progress.md index 4d330a1d..4d8f183e 100644 --- a/memory-bank/progress.md +++ b/memory-bank/progress.md @@ -753,6 +753,55 @@ - `node tests/phase16/service-behaviour.test.cjs` -> **pass** (4/4) - `npm run lint` -> **warnings only** (pre-existing `react-hooks/exhaustive-deps` warnings) +## Latest update (2026-03-19 — TASK22168 endpoint account contract consistency slice) + +- New branch created from `origin/SIPS-Development` with required work item prefix: + - `TASK22168-endpoint-account-contract-consistency` +- Delivered next coherent low-risk `pages/api/endpoint/**` slice after TASK22109 across: + - `pages/api/endpoint/getaccounts_api.js` + - `pages/api/endpoint/getemailaccountcheck_api.js` + - `pages/api/endpoint/getpreferredlanguage_api.js` +- Scope delivered: + - removed dead/noisy code in touched handlers (unused imports and commented debug remnants) + - standardized structured negative-path handling for: + - missing required `emailAddress` + - catch/failure paths + - preserved success response contracts by returning unchanged upstream `data` +- Added focused phase21 endpoint contract coverage: + - `tests/phase21/endpoint-handler-contract.test.cjs` + - extended `tests/phase21/api-contract-slice1.test.cjs` runner + +### Validation snapshot (TASK22168) + +- `node tests/phase21/api-contract-slice1.test.cjs` -> **pass** + - helper: 4/4 + - file-handler: 11/11 + - email-handler: 12/12 + - endpoint-handler: 7/7 +- `npm run lint` -> **warnings only** (pre-existing `react-hooks/exhaustive-deps` warnings) + +### Risks + mitigations (TASK22168) + +- Risk: endpoint contract drift in success payloads. + - Mitigation: success responses kept as upstream `data` payload via `respondSuccess`. +- Risk: over-broad behavior change in account/login adjacent APIs. + - Mitigation: scoped to 3 low-risk handlers only; no auth/session/security flow changes. +- Risk: regression in negative-path status/shape expectations. + - Mitigation: added explicit phase21 missing-input and catch-path assertions for each touched endpoint. + +### Rollback plan (TASK22168) + +1. Revert endpoint files: + - `pages/api/endpoint/getaccounts_api.js` + - `pages/api/endpoint/getemailaccountcheck_api.js` + - `pages/api/endpoint/getpreferredlanguage_api.js` +2. Revert phase21 test updates: + - `tests/phase21/endpoint-handler-contract.test.cjs` + - `tests/phase21/api-contract-slice1.test.cjs` +3. Re-run: + - `node tests/phase21/api-contract-slice1.test.cjs` + - `npm run lint` + ### Manual HTTP checks (Phase 16) - Dev server on `http://localhost:3002`. diff --git a/memory-bank/refactor-plan-actions-index.md b/memory-bank/refactor-plan-actions-index.md index babd2760..1a83e963 100644 --- a/memory-bank/refactor-plan-actions-index.md +++ b/memory-bank/refactor-plan-actions-index.md @@ -711,6 +711,41 @@ Status key: `[x] done`, `[ ] pending` - `tests/phase20/service-behaviour.test.cjs` - Re-run phase6–phase20 baseline tests and lint after rollback. +### Phase 21 endpoint contract slice snapshot (2026-03-19) + +Status key: `[x] done`, `[ ] pending` + +1. `[x]` Confirm work item + branch from `origin/SIPS-Development` + - work item: `TASK22168` + - branch: `TASK22168-endpoint-account-contract-consistency` +2. `[x]` Select next coherent low-risk endpoint contract slice after TASK22109 + - selected handlers: + - `getaccounts_api` + - `getemailaccountcheck_api` + - `getpreferredlanguage_api` +3. `[x]` Apply consistency pattern from TASK22109 + - remove dead/noisy code (unused imports/commented debug remnants) + - standardize structured negative-path responses (missing required input + catch path) + - preserve success payload behavior +4. `[x]` Add focused phase21 tests for endpoint slice + - added `tests/phase21/endpoint-handler-contract.test.cjs` + - extended `tests/phase21/api-contract-slice1.test.cjs` runner +5. `[x]` Execute required validation + - `node tests/phase21/api-contract-slice1.test.cjs` -> pass + - `npm run lint` -> warnings only (pre-existing) + +### Phase 21 rollback notes + +- Revert files: + - `pages/api/endpoint/getaccounts_api.js` + - `pages/api/endpoint/getemailaccountcheck_api.js` + - `pages/api/endpoint/getpreferredlanguage_api.js` + - `tests/phase21/endpoint-handler-contract.test.cjs` + - `tests/phase21/api-contract-slice1.test.cjs` +- Re-run: + - `node tests/phase21/api-contract-slice1.test.cjs` + - `npm run lint` + ## Safe execution mode for migration chunks (required) To reduce terminal hangs during bulk migration work, run refactor chunks in **safe stepwise mode** instead of long chained commands. diff --git a/pages/api/endpoint/getaccounts_api.js b/pages/api/endpoint/getaccounts_api.js index 681e5895..e48cb56c 100644 --- a/pages/api/endpoint/getaccounts_api.js +++ b/pages/api/endpoint/getaccounts_api.js @@ -16,49 +16,45 @@ * description: hello world */ import axios from "axios"; -import CryptoJS from "crypto-js"; -import _ from "lodash"; import { azureHeaders } from "../../../actions/core/headers"; import { consoleLogger } from "../../../actions/core/logger"; import { getToken } from "../../../actions/core/token"; import { hashAPIPath } from "../../../actions/core/hash"; +import { respondError, respondSuccess } from "../middleware/apiResponse"; const WEBAPI_URL = process.env.RELAY_ROOT || "https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/"; export default async function ApiProxy(req, res) { - var emailAddress = req.query.emailAddress; + const emailAddress = req.query.emailAddress; - if (typeof emailAddress === "undefined" || emailAddress.length === 0) { - return res.status(400).json(); + if (typeof emailAddress !== "string" || emailAddress.trim().length === 0) { + return respondError(res, { + status: 400, + code: "EMAIL_ADDRESS_REQUIRED", + message: "emailAddress is required" + }); } - var token = await getToken(); + try { + const token = await getToken(); + const queryUrl = + "contacts?$filter=emailaddress1 eq '" + + emailAddress + + "'&$count=true&$select=emailaddress1, contactid"; + const { data } = await axios.get( + WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), + azureHeaders(token.access_token) + ); - var queryUrl = - "contacts?$filter=emailaddress1 eq '" + - emailAddress + - "'&$count=true&$select=emailaddress1, contactid"; - - // var queryUrl = "contacts/?$count=true&$select=emailaddress1, contactid"; - - var apiResponse = _.isEmpty(req.query) - ? res.status(400).json() - : typeof emailAddress != "undefined" && emailAddress.length > 0 - ? axios - .get( - WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), - azureHeaders(token.access_token) - ) - .then(({ data }) => { - res.status(200).json(data); - }) - .catch((error) => { - consoleLogger(error); - res.status(400).json(error); - }) - : res.status(400).json(); - - return apiResponse; + return respondSuccess(res, data); + } catch (error) { + consoleLogger(error); + return respondError(res, { + status: 400, + code: "ACCOUNTS_FETCH_FAILED", + message: "Failed to fetch accounts" + }); + } } diff --git a/pages/api/endpoint/getemailaccountcheck_api.js b/pages/api/endpoint/getemailaccountcheck_api.js index 36111152..ce07f52f 100644 --- a/pages/api/endpoint/getemailaccountcheck_api.js +++ b/pages/api/endpoint/getemailaccountcheck_api.js @@ -16,42 +16,45 @@ * description: hello world */ import axios from "axios"; -import CryptoJS from "crypto-js"; -import _ from "lodash"; import { azureHeaders } from "../../../actions/core/headers"; import { consoleLogger } from "../../../actions/core/logger"; import { getToken } from "../../../actions/core/token"; import { hashAPIPath } from "../../../actions/core/hash"; +import { respondError, respondSuccess } from "../middleware/apiResponse"; const WEBAPI_URL = process.env.RELAY_ROOT || "https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/"; export default async function ApiProxy(req, res) { - var emailAddress = req.query.emailAddress; - var token = await getToken(); + const emailAddress = req.query.emailAddress; - var queryUrl = - "contacts?$filter=emailaddress1 eq '" + - emailAddress + - "'&$count=true&$select=emailaddress1, contactid"; + if (typeof emailAddress !== "string" || emailAddress.trim().length === 0) { + return respondError(res, { + status: 400, + code: "EMAIL_ADDRESS_REQUIRED", + message: "emailAddress is required" + }); + } - var apiResponse = _.isEmpty(req.query) - ? res.status(400).json() - : typeof emailAddress != "undefined" && emailAddress.length > 0 - ? axios - .get( - WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), - azureHeaders(token.access_token) - ) - .then(({ data }) => { - res.status(200).json(data); - }) - .catch((error) => { - consoleLogger(error); - res.status(400).json(error); - }) - : res.status(400).json(); + try { + const token = await getToken(); + const queryUrl = + "contacts?$filter=emailaddress1 eq '" + + emailAddress + + "'&$count=true&$select=emailaddress1, contactid"; + const { data } = await axios.get( + WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), + azureHeaders(token.access_token) + ); - return apiResponse; + return respondSuccess(res, data); + } catch (error) { + consoleLogger(error); + return respondError(res, { + status: 400, + code: "EMAIL_ACCOUNT_CHECK_FAILED", + message: "Failed to check email account" + }); + } } diff --git a/pages/api/endpoint/getpreferredlanguage_api.js b/pages/api/endpoint/getpreferredlanguage_api.js index 57bedf4e..ddc7ae4d 100644 --- a/pages/api/endpoint/getpreferredlanguage_api.js +++ b/pages/api/endpoint/getpreferredlanguage_api.js @@ -16,54 +16,51 @@ * description: hello world */ import axios from "axios"; -import CryptoJS from "crypto-js"; -import _ from "lodash"; import { azureHeaders } from "../../../actions/core/headers"; import { escapeODataString, isNonEmptyString, sanitizeString } from "../../../actions/core/guards"; -import { consoleLogger, redactSensitive } from "../../../actions/core/logger"; +import { consoleLogger } from "../../../actions/core/logger"; import { getToken } from "../../../actions/core/token"; import { hashAPIPath } from "../../../actions/core/hash"; +import { respondError, respondSuccess } from "../middleware/apiResponse"; const WEBAPI_URL = process.env.RELAY_ROOT || "https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/"; export default async function ApiProxy(req, res) { - var emailAddress = sanitizeString(req.query.emailAddress); - var token = await getToken(); + const emailAddress = sanitizeString(req.query.emailAddress); if (!isNonEmptyString(emailAddress)) { - return res.status(400).json({ error: "emailAddress is required" }); + return respondError(res, { + status: 400, + code: "EMAIL_ADDRESS_REQUIRED", + message: "emailAddress is required" + }); } - var queryUrl = - "contacts?$filter=emailaddress1 eq '" + - escapeODataString(emailAddress) + - "'&$count=true&$select=pinswg_preferredlanguage,contactid"; + try { + const token = await getToken(); + const queryUrl = + "contacts?$filter=emailaddress1 eq '" + + escapeODataString(emailAddress) + + "'&$count=true&$select=pinswg_preferredlanguage,contactid"; - console.log(redactSensitive(queryUrl)); - // var queryUrl = "contacts/?$count=true&$select=emailaddress1, contactid"; + const { data } = await axios.get( + WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), + azureHeaders(token.access_token) + ); - var apiResponse = _.isEmpty(req.query) - ? res.status(400).json() - : typeof emailAddress != "undefined" && emailAddress.length > 0 - ? axios - .get( - WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), - azureHeaders(token.access_token) - ) - .then(({ data }) => { - res.status(200).json(data); - }) - .catch((error) => { - consoleLogger(error); - res.status(400).json(error); - }) - : res.status(400).json(); - - return apiResponse; + return respondSuccess(res, data); + } catch (error) { + consoleLogger(error); + return respondError(res, { + status: 400, + code: "PREFERRED_LANGUAGE_FETCH_FAILED", + message: "Failed to fetch preferred language" + }); + } } diff --git a/tests/phase21/api-contract-slice1.test.cjs b/tests/phase21/api-contract-slice1.test.cjs index bc542f03..2f89aaf8 100644 --- a/tests/phase21/api-contract-slice1.test.cjs +++ b/tests/phase21/api-contract-slice1.test.cjs @@ -1,11 +1,13 @@ const runHelperTests = require("./api-response-helper.test.cjs"); const runHandlerTests = require("./file-handler-contract.test.cjs"); const runEmailHandlerTests = require("./email-handler-contract.test.cjs"); +const runEndpointHandlerTests = require("./endpoint-handler-contract.test.cjs"); const run = async () => { await runHelperTests(); await runHandlerTests(); await runEmailHandlerTests(); + await runEndpointHandlerTests(); console.log("Phase 21 combined suite passed."); }; diff --git a/tests/phase21/endpoint-handler-contract.test.cjs b/tests/phase21/endpoint-handler-contract.test.cjs new file mode 100644 index 00000000..927e7dd5 --- /dev/null +++ b/tests/phase21/endpoint-handler-contract.test.cjs @@ -0,0 +1,208 @@ +const assert = require("assert"); +const { + loadModule, + createRes, + respondSuccessMock, + respondErrorMock +} = require("./_shared.cjs"); + +const tests = []; +const test = (name, fn) => tests.push({ name, fn }); + +test("getaccounts returns EMAIL_ADDRESS_REQUIRED when emailAddress missing", async () => { + const mod = loadModule("pages/api/endpoint/getaccounts_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: () => "&hash=expected", + azureHeaders: () => ({}), + axios: { get: async () => ({ data: { value: [] } }) }, + consoleLogger: () => {} + }); + + const req = { query: {} }; + const res = createRes(); + await mod.default(req, res); + + assert.strictEqual(res.state.statusCode, 400); + assert.strictEqual(res.state.jsonBody.error.code, "EMAIL_ADDRESS_REQUIRED"); +}); + +test("getaccounts catch path returns ACCOUNTS_FETCH_FAILED", async () => { + const mod = loadModule("pages/api/endpoint/getaccounts_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: () => "&hash=expected", + azureHeaders: () => ({}), + axios: { + get: async () => { + throw new Error("relay failed"); + } + }, + consoleLogger: () => {} + }); + + const req = { query: { emailAddress: "user@test.local" } }; + const res = createRes(); + await mod.default(req, res); + + assert.strictEqual(res.state.statusCode, 400); + assert.strictEqual(res.state.jsonBody.error.code, "ACCOUNTS_FETCH_FAILED"); +}); + +test("getemailaccountcheck returns EMAIL_ADDRESS_REQUIRED when emailAddress missing", async () => { + const mod = loadModule("pages/api/endpoint/getemailaccountcheck_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: () => "&hash=expected", + azureHeaders: () => ({}), + axios: { get: async () => ({ data: { value: [] } }) }, + consoleLogger: () => {} + }); + + const req = { query: {} }; + const res = createRes(); + await mod.default(req, res); + + assert.strictEqual(res.state.statusCode, 400); + assert.strictEqual(res.state.jsonBody.error.code, "EMAIL_ADDRESS_REQUIRED"); +}); + +test("getemailaccountcheck catch path returns EMAIL_ACCOUNT_CHECK_FAILED", async () => { + const mod = loadModule("pages/api/endpoint/getemailaccountcheck_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: () => "&hash=expected", + azureHeaders: () => ({}), + axios: { + get: async () => { + throw new Error("relay failed"); + } + }, + consoleLogger: () => {} + }); + + const req = { query: { emailAddress: "user@test.local" } }; + const res = createRes(); + await mod.default(req, res); + + assert.strictEqual(res.state.statusCode, 400); + assert.strictEqual( + res.state.jsonBody.error.code, + "EMAIL_ACCOUNT_CHECK_FAILED" + ); +}); + +test("getpreferredlanguage returns EMAIL_ADDRESS_REQUIRED when emailAddress missing", async () => { + const mod = loadModule("pages/api/endpoint/getpreferredlanguage_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + sanitizeString: () => "", + isNonEmptyString: () => false, + escapeODataString: (value) => value, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: () => "&hash=expected", + azureHeaders: () => ({}), + axios: { get: async () => ({ data: { value: [] } }) }, + consoleLogger: () => {} + }); + + const req = { query: {} }; + const res = createRes(); + await mod.default(req, res); + + assert.strictEqual(res.state.statusCode, 400); + assert.strictEqual(res.state.jsonBody.error.code, "EMAIL_ADDRESS_REQUIRED"); +}); + +test("getpreferredlanguage catch path returns PREFERRED_LANGUAGE_FETCH_FAILED", async () => { + const mod = loadModule("pages/api/endpoint/getpreferredlanguage_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + sanitizeString: (value) => value, + isNonEmptyString: () => true, + escapeODataString: (value) => value, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: () => "&hash=expected", + azureHeaders: () => ({}), + axios: { + get: async () => { + throw new Error("relay failed"); + } + }, + consoleLogger: () => {} + }); + + const req = { query: { emailAddress: "user@test.local" } }; + const res = createRes(); + await mod.default(req, res); + + assert.strictEqual(res.state.statusCode, 400); + assert.strictEqual( + res.state.jsonBody.error.code, + "PREFERRED_LANGUAGE_FETCH_FAILED" + ); +}); + +test("getpreferredlanguage success returns existing data payload contract", async () => { + const mod = loadModule("pages/api/endpoint/getpreferredlanguage_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + sanitizeString: (value) => value, + isNonEmptyString: () => true, + escapeODataString: (value) => value, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: () => "&hash=expected", + azureHeaders: () => ({}), + axios: { + get: async () => ({ + data: { + value: [ + { + contactid: "c1", + pinswg_preferredlanguage: 807570001 + } + ] + } + }) + }, + consoleLogger: () => {} + }); + + const req = { query: { emailAddress: "user@test.local" } }; + const res = createRes(); + await mod.default(req, res); + + assert.strictEqual(res.state.statusCode, 200); + assert.deepStrictEqual(JSON.parse(JSON.stringify(res.state.jsonBody)), { + value: [ + { + contactid: "c1", + pinswg_preferredlanguage: 807570001 + } + ] + }); +}); + +const run = async () => { + let passed = 0; + for (const currentTest of tests) { + await currentTest.fn(); + passed += 1; + } + console.log( + `Phase 21 endpoint-handler contract tests passed (${passed}/${tests.length}).` + ); +}; + +module.exports = run; + +if (require.main === module) { + run().catch((error) => { + console.error(error); + process.exit(1); + }); +} \ No newline at end of file