From 26b889d182f25ef7b7c10e316d4f1869c8b92abe Mon Sep 17 00:00:00 2001 From: robbond Date: Thu, 19 Mar 2026 12:27:17 +0000 Subject: [PATCH] TASK22168 bundle C endpoint login/account consistency extension --- memory-bank/activeContext.md | 5 + memory-bank/change-log.md | 49 ++++ memory-bank/progress.md | 48 ++++ memory-bank/refactor-plan-actions-index.md | 33 +++ pages/api/endpoint/getlogin_api.js | 71 ++--- pages/api/endpoint/getpersonalaccount_api.js | 53 ++-- pages/api/endpoint/getportallogin_api.js | 65 +++-- pages/api/endpoint/getportalloginproxy_api.js | 56 ++-- .../endpoint-handler-contract.test.cjs | 257 +++++++++++++++++- 9 files changed, 525 insertions(+), 112 deletions(-) diff --git a/memory-bank/activeContext.md b/memory-bank/activeContext.md index 5c3d2ab1..189531a1 100644 --- a/memory-bank/activeContext.md +++ b/memory-bank/activeContext.md @@ -60,6 +60,11 @@ - endpoint-handler 7/7 - `npm run lint` -> warnings only (pre-existing react-hooks warnings) +- Risk/rollback snapshot: + - risk: broader endpoint touch in one bundle could drift contracts + - mitigation: success payloads preserved as upstream `data`; phase21 endpoint tests expanded to 18/18 + - rollback: revert `getlogin_api`, `getportallogin_api`, `getportalloginproxy_api`, `getpersonalaccount_api`, and phase21 endpoint test updates, then rerun phase21 + lint + ## Suggested next work package - Continue API contract consistency in `pages/api/endpoint/**` with the same pattern used in TASK22109: diff --git a/memory-bank/change-log.md b/memory-bank/change-log.md index d07613fc..46e0fdf7 100644 --- a/memory-bank/change-log.md +++ b/memory-bank/change-log.md @@ -1602,3 +1602,52 @@ Validation: 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. + +--- + +### CL-043: TASK22168 Bundle C extension — login/portal/account adjacency sweep (phase21) + +date: 2026-03-19 +author: Cline +scope: `pages/api/endpoint/{getlogin_api,getportallogin_api,getportalloginproxy_api,getpersonalaccount_api}.js`, `tests/phase21/endpoint-handler-contract.test.cjs` +type: change +rationale: User requested a larger same-branch bundle while preserving low-risk contract-consistency scope in endpoint account/login adjacency handlers. +impact: Structured 400 negative-path envelopes and cleanup consistency across additional login/account handlers with success payload contract stability preserved. +status: completed + +Summary: + +- Continued on branch: `TASK22168-endpoint-account-contract-consistency`. +- Extended endpoint contract-consistency pattern to additional handlers: + - `getlogin_api.js` + - removed dead imports/noisy logging + - standardized required input errors (`EMAIL_ADDRESS_REQUIRED`, `PASSWORD_REQUIRED`) + - standardized catch path (`LOGIN_FETCH_FAILED`) + - `getportallogin_api.js` + - removed dead imports + - standardized missing hash and invalid hash paths (`HASH_REQUIRED`, `INVALID_HASH`) + - standardized catch path (`PORTAL_LOGIN_FETCH_FAILED`) + - `getportalloginproxy_api.js` + - removed dead imports/legacy conditional noise + - standardized required input error (`EMAIL_ADDRESS_REQUIRED`) + - standardized catch path (`PORTAL_LOGIN_PROXY_FETCH_FAILED`) + - `getpersonalaccount_api.js` + - removed dead imports/noisy logging + - standardized required input error (`CONTACT_ID_REQUIRED`) + - standardized catch path (`PERSONAL_ACCOUNT_FETCH_FAILED`) +- Phase21 endpoint suite expansion: + - `tests/phase21/endpoint-handler-contract.test.cjs` + - expanded from 7 to 18 tests to cover Bundle C handlers and success-parity checks for adjacent account endpoints. + +Validation: + +- `node tests/phase21/api-contract-slice1.test.cjs` -> pass + - helper: 4/4 + - file-handler: 11/11 + - email-handler: 12/12 + - endpoint-handler: 18/18 +- `npm run lint` -> warnings only (pre-existing `react-hooks/exhaustive-deps` warnings) + +Follow-ups: + +- Next slice can target additional endpoint proxy groups only if needed, but current account/login consistency scope is now a meaningful bundle on TASK22168. diff --git a/memory-bank/progress.md b/memory-bank/progress.md index 4d8f183e..75847f97 100644 --- a/memory-bank/progress.md +++ b/memory-bank/progress.md @@ -802,6 +802,54 @@ - `node tests/phase21/api-contract-slice1.test.cjs` - `npm run lint` +## Latest update (2026-03-19 — TASK22168 Bundle C extension on same branch) + +- Continued same branch with user-approved larger bundle: + - `TASK22168-endpoint-account-contract-consistency` +- Added contract-consistency coverage for login/portal/account-adjacent endpoints: + - `pages/api/endpoint/getlogin_api.js` + - `pages/api/endpoint/getportallogin_api.js` + - `pages/api/endpoint/getportalloginproxy_api.js` + - `pages/api/endpoint/getpersonalaccount_api.js` +- Scope delivered: + - removed dead imports/commented debug/noisy logging remnants + - standardized structured 400 errors for required-input negative paths and catch/failure paths + - preserved success payload contracts via `respondSuccess` pass-through +- Phase21 endpoint suite expanded in: + - `tests/phase21/endpoint-handler-contract.test.cjs` + - test count grew from 7 to 18 for endpoint handler coverage + +### Validation snapshot (TASK22168 Bundle C) + +- `node tests/phase21/api-contract-slice1.test.cjs` -> **pass** + - helper: 4/4 + - file-handler: 11/11 + - email-handler: 12/12 + - endpoint-handler: 18/18 +- `npm run lint` -> **warnings only** (pre-existing `react-hooks/exhaustive-deps` warnings) + +### Risks + mitigations (TASK22168 Bundle C) + +- Risk: contract drift from broad endpoint touch surface. + - Mitigation: constrained to login/account adjacency group only and preserved success pass-through behavior. +- Risk: hash-path behavior regression in `getportallogin_api`. + - Mitigation: explicit tests for missing hash, invalid hash, and catch path. +- Risk: inconsistent required-input behavior across adjacent handlers. + - Mitigation: standardized explicit required-input envelopes in all four newly touched handlers. + +### Rollback plan (TASK22168 Bundle C) + +1. Revert endpoint files: + - `pages/api/endpoint/getlogin_api.js` + - `pages/api/endpoint/getportallogin_api.js` + - `pages/api/endpoint/getportalloginproxy_api.js` + - `pages/api/endpoint/getpersonalaccount_api.js` +2. Revert endpoint contract test updates: + - `tests/phase21/endpoint-handler-contract.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 1a83e963..604735f0 100644 --- a/memory-bank/refactor-plan-actions-index.md +++ b/memory-bank/refactor-plan-actions-index.md @@ -746,6 +746,39 @@ Status key: `[x] done`, `[ ] pending` - `node tests/phase21/api-contract-slice1.test.cjs` - `npm run lint` +### Phase 21 Bundle C extension snapshot (2026-03-19) + +Status key: `[x] done`, `[ ] pending` + +1. `[x]` Confirm user preference for larger same-branch bundle + - selected: Bundle C +2. `[x]` Extend endpoint consistency in login/portal/account adjacency handlers + - `getlogin_api` + - `getportallogin_api` + - `getportalloginproxy_api` + - `getpersonalaccount_api` +3. `[x]` Apply consistency pattern + - remove dead/noisy imports/logging remnants + - standardize structured negative-path responses (required input + catch/failure) + - preserve success contracts +4. `[x]` Expand phase21 endpoint tests + - `tests/phase21/endpoint-handler-contract.test.cjs` expanded to 18 tests +5. `[x]` Execute required validation + - `node tests/phase21/api-contract-slice1.test.cjs` -> pass + - `npm run lint` -> warnings only (pre-existing) + +### Phase 21 Bundle C rollback notes + +- Revert files: + - `pages/api/endpoint/getlogin_api.js` + - `pages/api/endpoint/getportallogin_api.js` + - `pages/api/endpoint/getportalloginproxy_api.js` + - `pages/api/endpoint/getpersonalaccount_api.js` + - `tests/phase21/endpoint-handler-contract.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/getlogin_api.js b/pages/api/endpoint/getlogin_api.js index c7185de8..bac72976 100644 --- a/pages/api/endpoint/getlogin_api.js +++ b/pages/api/endpoint/getlogin_api.js @@ -22,51 +22,56 @@ */ import axios from "axios"; -import CryptoJS from "crypto-js"; -import _ from "lodash"; import { azureHeadersPaged } 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 pwd = req.query.pwd; - var token = await getToken(); + const emailAddress = req.query.emailAddress; + const pwd = req.query.pwd; - var queryUrl = - "contacts?$filter=emailaddress1 eq '" + - emailAddress + - "' and pinswg_custom_password eq '" + - pwd + - "'&$count=true&$select=emailaddress1,contactid,pinswg_custom_password,yomifullname,firstname,lastname"; + if (typeof emailAddress !== "string" || emailAddress.trim().length === 0) { + return respondError(res, { + status: 400, + code: "EMAIL_ADDRESS_REQUIRED", + message: "emailAddress is required" + }); + } - //console.log(_.isEmpty(req.query)); + if (typeof pwd !== "string" || pwd.trim().length === 0) { + return respondError(res, { + status: 400, + code: "PASSWORD_REQUIRED", + message: "pwd is required" + }); + } - var apiResponse = _.isEmpty(req.query) - ? res.status(400).json() - : typeof emailAddress != "undefined" && - emailAddress.length > 0 && - typeof pwd != "undefined" && - pwd.length > 0 - ? axios - .get( - WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), - azureHeadersPaged(token.access_token) - ) - .then(({ data }) => { - console.log(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 + + "' and pinswg_custom_password eq '" + + pwd + + "'&$count=true&$select=emailaddress1,contactid,pinswg_custom_password,yomifullname,firstname,lastname"; + const { data } = await axios.get( + WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), + azureHeadersPaged(token.access_token) + ); - return apiResponse; + return respondSuccess(res, data); + } catch (error) { + consoleLogger(error); + return respondError(res, { + status: 400, + code: "LOGIN_FETCH_FAILED", + message: "Failed to fetch login details" + }); + } } diff --git a/pages/api/endpoint/getpersonalaccount_api.js b/pages/api/endpoint/getpersonalaccount_api.js index 5a2f3050..2aae367a 100644 --- a/pages/api/endpoint/getpersonalaccount_api.js +++ b/pages/api/endpoint/getpersonalaccount_api.js @@ -18,42 +18,45 @@ */ import axios from "axios"; -import CryptoJS from "crypto-js"; 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 contactid = req.query.contactid; - var token = await getToken(); + const contactid = req.query.contactid; - var queryUrl = - "contacts(" + - contactid + - ")?$select=firstname, lastname, emailaddress1, telephone1, company, address1_line1,address1_line2,address1_city, address1_county,address1_postalcode,pinswg_typeofinvolvement,pinswg_contact_associatedlpa,pinswg_preferredlanguage&$count=true"; + if (typeof contactid !== "string" || contactid.trim().length === 0) { + return respondError(res, { + status: 400, + code: "CONTACT_ID_REQUIRED", + message: "contactid is required" + }); + } - //console.log(WEBAPI_URL + queryUrl + hashAPIPath(queryUrl)); + try { + const token = await getToken(); + const queryUrl = + "contacts(" + + contactid + + ")?$select=firstname, lastname, emailaddress1, telephone1, company, address1_line1,address1_line2,address1_city, address1_county,address1_postalcode,pinswg_typeofinvolvement,pinswg_contact_associatedlpa,pinswg_preferredlanguage&$count=true"; + const { data } = await axios.get( + WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), + azureHeaders(token.access_token) + ); - var apiResponse = - contactid.length > 0 - ? axios - .get( - WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), - azureHeaders(token.access_token) - ) - .then(({ data }) => { - res.status(200).json(data); - }) - .catch((err) => { - console.log(consoleLogger(err)); - res.status(400).json(err); - }) - : res.status(400).json(); - - return apiResponse; + return respondSuccess(res, data); + } catch (error) { + consoleLogger(error); + return respondError(res, { + status: 400, + code: "PERSONAL_ACCOUNT_FETCH_FAILED", + message: "Failed to fetch personal account" + }); + } } diff --git a/pages/api/endpoint/getportallogin_api.js b/pages/api/endpoint/getportallogin_api.js index a3f5b7a0..e1adb714 100644 --- a/pages/api/endpoint/getportallogin_api.js +++ b/pages/api/endpoint/getportallogin_api.js @@ -17,50 +17,65 @@ */ import axios from "axios"; -import CryptoJS from "crypto-js"; import { azureHeadersPaged } 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 checkHash = req.query.hash; + const emailAddress = req.query.emailAddress; + const checkHash = req.query.hash; - 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 checkquerypath = + if (typeof checkHash !== "string" || checkHash.length === 0) { + return respondError(res, { + status: 400, + code: "HASH_REQUIRED", + message: "hash is required" + }); + } + + const checkquerypath = "/api/endpoint/getportallogin_api?emailAddress=" + emailAddress; if (hashAPIPath(checkquerypath) != "&hash=" + checkHash) { - return res.status(400).json(); + return respondError(res, { + status: 400, + code: "INVALID_HASH", + message: "Invalid hash" + }); } - var token = await getToken(); - - var queryUrl = - "contacts?$filter=emailaddress1 eq '" + - emailAddress + - "' and statuscode eq 1&$count=true&$select=emailaddress1,contactid,yomifullname,firstname,lastname"; - - var apiResponse = axios - .get( + try { + const token = await getToken(); + const queryUrl = + "contacts?$filter=emailaddress1 eq '" + + emailAddress + + "' and statuscode eq 1&$count=true&$select=emailaddress1,contactid,yomifullname,firstname,lastname"; + const { data } = await axios.get( WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), azureHeadersPaged(token.access_token) - ) - .then(({ data }) => { - res.status(200).json(data); - }) - .catch((error) => { - consoleLogger(error); - res.status(400).json(error); - }); + ); - return apiResponse; + return respondSuccess(res, data); + } catch (error) { + consoleLogger(error); + return respondError(res, { + status: 400, + code: "PORTAL_LOGIN_FETCH_FAILED", + message: "Failed to fetch portal login" + }); + } } diff --git a/pages/api/endpoint/getportalloginproxy_api.js b/pages/api/endpoint/getportalloginproxy_api.js index d0059910..0a1a3b61 100644 --- a/pages/api/endpoint/getportalloginproxy_api.js +++ b/pages/api/endpoint/getportalloginproxy_api.js @@ -17,45 +17,45 @@ */ import axios from "axios"; -import CryptoJS from "crypto-js"; -import _ from "lodash"; import { azureHeadersPaged } 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,yomifullname,firstname,lastname"; + if (typeof emailAddress !== "string" || emailAddress.trim().length === 0) { + return respondError(res, { + status: 400, + code: "EMAIL_ADDRESS_REQUIRED", + message: "emailAddress is required" + }); + } - //console.log(req.query); + try { + const token = await getToken(); + const queryUrl = + "contacts?$filter=emailaddress1 eq '" + + emailAddress + + "'&$count=true&$select=emailaddress1,contactid,yomifullname,firstname,lastname"; + const { data } = await axios.get( + WEBAPI_URL + queryUrl + hashAPIPath(queryUrl), + azureHeadersPaged(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), - azureHeadersPaged(token.access_token) - ) - .then(({ data }) => { - //console.log(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: "PORTAL_LOGIN_PROXY_FETCH_FAILED", + message: "Failed to fetch portal login proxy details" + }); + } } diff --git a/tests/phase21/endpoint-handler-contract.test.cjs b/tests/phase21/endpoint-handler-contract.test.cjs index 927e7dd5..2f8ccbed 100644 --- a/tests/phase21/endpoint-handler-contract.test.cjs +++ b/tests/phase21/endpoint-handler-contract.test.cjs @@ -187,6 +187,261 @@ test("getpreferredlanguage success returns existing data payload contract", asyn }); }); +test("getlogin returns EMAIL_ADDRESS_REQUIRED when emailAddress missing", async () => { + const mod = loadModule("pages/api/endpoint/getlogin_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: () => "&hash=expected", + azureHeadersPaged: () => ({}), + axios: { get: async () => ({ data: { value: [] } }) }, + consoleLogger: () => {} + }); + + const req = { query: { pwd: "abc123" } }; + 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("getlogin returns PASSWORD_REQUIRED when pwd missing", async () => { + const mod = loadModule("pages/api/endpoint/getlogin_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: () => "&hash=expected", + azureHeadersPaged: () => ({}), + axios: { get: async () => ({ data: { value: [] } }) }, + 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, "PASSWORD_REQUIRED"); +}); + +test("getlogin catch path returns LOGIN_FETCH_FAILED", async () => { + const mod = loadModule("pages/api/endpoint/getlogin_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: () => "&hash=expected", + azureHeadersPaged: () => ({}), + axios: { + get: async () => { + throw new Error("relay failed"); + } + }, + consoleLogger: () => {} + }); + + const req = { query: { emailAddress: "user@test.local", pwd: "abc123" } }; + const res = createRes(); + await mod.default(req, res); + + assert.strictEqual(res.state.statusCode, 400); + assert.strictEqual(res.state.jsonBody.error.code, "LOGIN_FETCH_FAILED"); +}); + +test("getportallogin returns HASH_REQUIRED when hash missing", async () => { + const mod = loadModule("pages/api/endpoint/getportallogin_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: (input) => + input && input.startsWith("/api/endpoint/getportallogin_api") + ? "&hash=expected" + : "&hash=relay", + azureHeadersPaged: () => ({}), + axios: { get: async () => ({ data: { value: [] } }) }, + 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, "HASH_REQUIRED"); +}); + +test("getportallogin returns INVALID_HASH when hash mismatch", async () => { + const mod = loadModule("pages/api/endpoint/getportallogin_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: (input) => + input && input.startsWith("/api/endpoint/getportallogin_api") + ? "&hash=expected" + : "&hash=relay", + azureHeadersPaged: () => ({}), + axios: { get: async () => ({ data: { value: [] } }) }, + consoleLogger: () => {} + }); + + const req = { query: { emailAddress: "user@test.local", hash: "wrong" } }; + const res = createRes(); + await mod.default(req, res); + + assert.strictEqual(res.state.statusCode, 400); + assert.strictEqual(res.state.jsonBody.error.code, "INVALID_HASH"); +}); + +test("getportallogin catch path returns PORTAL_LOGIN_FETCH_FAILED", async () => { + const mod = loadModule("pages/api/endpoint/getportallogin_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: (input) => + input && input.startsWith("/api/endpoint/getportallogin_api") + ? "&hash=expected" + : "&hash=relay", + azureHeadersPaged: () => ({}), + axios: { + get: async () => { + throw new Error("relay failed"); + } + }, + consoleLogger: () => {} + }); + + const req = { + query: { emailAddress: "user@test.local", hash: "expected" } + }; + const res = createRes(); + await mod.default(req, res); + + assert.strictEqual(res.state.statusCode, 400); + assert.strictEqual( + res.state.jsonBody.error.code, + "PORTAL_LOGIN_FETCH_FAILED" + ); +}); + +test("getportalloginproxy catch path returns PORTAL_LOGIN_PROXY_FETCH_FAILED", async () => { + const mod = loadModule("pages/api/endpoint/getportalloginproxy_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: () => "&hash=expected", + azureHeadersPaged: () => ({}), + 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, + "PORTAL_LOGIN_PROXY_FETCH_FAILED" + ); +}); + +test("getpersonalaccount returns CONTACT_ID_REQUIRED when contactid missing", async () => { + const mod = loadModule("pages/api/endpoint/getpersonalaccount_api.js", { + respondError: respondErrorMock, + respondSuccess: respondSuccessMock, + getToken: async () => ({ access_token: "token" }), + hashAPIPath: () => "&hash=expected", + azureHeaders: () => ({}), + axios: { get: async () => ({ data: { contactid: "c1" } }) }, + 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, "CONTACT_ID_REQUIRED"); +}); + +test("getpersonalaccount catch path returns PERSONAL_ACCOUNT_FETCH_FAILED", async () => { + const mod = loadModule("pages/api/endpoint/getpersonalaccount_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: { contactid: "c1" } }; + const res = createRes(); + await mod.default(req, res); + + assert.strictEqual(res.state.statusCode, 400); + assert.strictEqual( + res.state.jsonBody.error.code, + "PERSONAL_ACCOUNT_FETCH_FAILED" + ); +}); + +test("getaccounts success returns existing data payload contract", 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: [{ contactid: "c1" }] } }) + }, + 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" }] + }); +}); + +test("getemailaccountcheck success returns existing data payload contract", 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: [{ emailaddress1: "u@test" }] } + }) + }, + 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: [{ emailaddress1: "u@test" }] + }); +}); + const run = async () => { let passed = 0; for (const currentTest of tests) { @@ -205,4 +460,4 @@ if (require.main === module) { console.error(error); process.exit(1); }); -} \ No newline at end of file +}