General source code refactoring

This commit is contained in:
2026-09-17 12:07:01 -03:00
parent 4421b28efe
commit ac817a69d4
92 changed files with 18211 additions and 19394 deletions

View File

@@ -12,25 +12,21 @@
</head>
<body>
<div id="opportunities-extension-modal" class="opportunities-extension-modal" data-theme="light"></div>
<script src="/fixture-runtime.js"></script>
<script>
window.chrome = { runtime: { onMessage: { addListener() {} } } };
async function initialize() {
const source = await fetch("/src/content.js").then((response) => response.text());
const marker = /\r?\n if \(insertTile\(\)\) \{/;
const exposure = `
window.__trendHarness = {
ensureStyles: ensureExtensionStyles,
createAccountPlanDetails,
createConsumptionTrendSection,
renderConsumptionTrendChart
};
return;
`;
const testableSource = source
.replace(" if (!isAllowedPage()) {", " if (false) {")
.replace(marker, `${exposure}\n if (insertTile()) {`);
window.eval(testableSource);
const app = window.createFixtureApplication({
fetch: () => Promise.reject(new Error("Network disabled in fixture")),
browser: undefined,
chrome: undefined
});
const harness = {
ensureStyles: app.contentStyles.ensureExtensionStyles,
createAccountPlanDetails: app.consumptionPlansView.createAccountPlanDetails,
createConsumptionTrendSection: app.consumptionTrendController.createConsumptionTrendSection,
renderConsumptionTrendChart: app.consumptionChart.renderConsumptionTrendChart
};
const plan = {
subPlanNum: "11276098",
@@ -63,7 +59,7 @@
return rows;
});
window.__trendHarness.ensureStyles();
harness.ensureStyles();
const overlay = document.getElementById("opportunities-extension-modal");
overlay.dataset.theme = new URLSearchParams(window.location.search).get("theme") === "dark"
? "dark"
@@ -82,13 +78,13 @@
tabs.innerHTML = '<button class="opportunities-extension-account-plan-tab" aria-selected="true"><span class="opportunities-extension-account-plan-status-indicator" data-active="true"></span>Universal Credits 11276098</button>';
const panel = document.createElement("section");
panel.className = "opportunities-extension-account-plan-panel";
const trend = window.__trendHarness.createConsumptionTrendSection(plan);
panel.append(window.__trendHarness.createAccountPlanDetails(plan), trend);
const trend = harness.createConsumptionTrendSection(plan);
panel.append(harness.createAccountPlanDetails(plan), trend);
content.append(tabs, panel);
dialog.append(header, content);
modal.append(dialog);
overlay.append(modal);
window.__trendHarness.renderConsumptionTrendChart(
harness.renderConsumptionTrendChart(
trend,
trend.querySelector(".opportunities-extension-consumption-chart"),
items,

13
tests/fixtures/extension.html vendored Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Extension Synthetic Integration Fixture</title>
</head>
<body>
<button id="open" type="button">Open Opportunities</button>
<script src="/fixture-runtime.js"></script>
<script src="/extension.js"></script>
</body>
</html>

77
tests/fixtures/extension.js vendored Normal file
View File

@@ -0,0 +1,77 @@
(() => {
const listeners = [];
const storage = new Map();
const opportunities = Array.from({ length: 25 }, (_, index) => ({
OptyNumber: `TEST${index + 1}`,
Name: `Synthetic opportunity ${index + 1} - Database migration`,
CustomerAccount: { PartyUniqueName: "Example public sector customer (Example City, BR)", PartyId: "test-party", PartyNumber: "test-account" },
Owner: { PersonFirstName: "Example", PersonLastName: "Owner" },
PrimaryRevenue: { RevnAmountCurcyCode: "USD", RevnAmount: "25000", WinProb: 60 },
EffectiveDate: "2026-11-15T00:00:00Z",
LastUpdateDate: "2026-09-15T17:00:00Z",
ForecastGroup_c: ["SQL", "PIPELINE", "UPSIDE", "FORECAST", "WON"][index % 5],
StatusCode: ["OPEN", "CLOSED", "LOST", "WON", "WON_PENDING"][index % 5]
}));
const products = [{ ProdGroupName: "Migrate databases to cloud", WorkloadName_c: "Example workload", RevnAmountCurcyCode: "USD", RevnAmount: "25000", TypeCode: "NEWCOMMIT", StatusCode: "OPEN", WinProb: 60, EffectiveDate: "2026-11-15", ConsumptionStartDate_c: "2026-11-15", RampMonths_c: 3 }];
const trend = Array.from({ length: 30 }, (_, index) => ({
fyDate: `2026-09-${String((index % 28) + 1).padStart(2, "0")}`,
fiscalTime: [`${String((index % 28) + 1).padStart(2, "0")}-Sep-26`],
fiscalQtr: "FY27-Q2", currencyCode: "USD", arrCd: 0,
usageCategory: index % 4 ? "Funded Allocation" : "OVERAGE",
usedAmount: 1000 + index * 100
}));
const authorizations = {
accountSummary: { label: "Account-Ti-Authorization", value: "synthetic-accp" },
accountPlans: { label: "G2m-Authorization", value: "synthetic-ocicons" }
};
const runtime = {
onMessage: { addListener: listener => listeners.push(listener) },
async sendMessage(message) {
const operation = message.type.split(".").at(-1);
if (operation === "getXsrfToken") return { ok: true, token: "synthetic-xsrf", cookieName: "XSRF-TOKEN-TEST" };
if (operation === "requestConsumerTokenService") return { ok: true, authorizations, debugRequests: [] };
if (operation === "requestOpptyProducts") {
message.optyNumbers.forEach((optyNumber, index) => listeners.forEach(listener => listener({
type: "opportunitiesExtension.opptyProductsProgress", requestId: message.requestId,
optyNumber, items: products, cachedAt: Date.now(), completed: index + 1,
total: message.optyNumbers.length, state: index + 1 === message.optyNumbers.length ? "complete" : "running"
})));
return { ok: true, requestId: message.requestId };
}
if (operation === "requestAccountPlans") return {
ok: true, debugRequests: [], plans: ["ACTIVE", "EXPIRED"].map((hdrStatusCode, index) => ({
subPlanNum: `PLAN${index + 1}`, planType: "Universal Credits", hdrStatusCode,
bookingCustomer: "Example Customer", soldToPartyName: "Example Sold To",
contractId: "synthetic-contract", startDate: "2026-06-01", endDate: "2027-05-31"
}))
};
if (operation === "requestConsumptionTrend") return { ok: true, items: trend, debugRequests: [] };
throw new Error(`Unexpected synthetic message: ${operation}`);
}
};
const application = window.createFixtureApplication({
browser: { runtime: {
onMessage: runtime.onMessage,
sendMessage(message, callback) {
const result = runtime.sendMessage(message);
if (callback) result.then(callback);
return result;
}
} }, chrome: undefined,
localStorage: { getItem: key => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, value) },
async fetch(input, options) {
const url = new URL(input);
let body;
if (url.pathname === "/fscmRestApi/tokenrelay") body = { access_token: "synthetic-fusion-token", expires_in: 3600 };
else if (url.pathname.endsWith("custom-actions/queries")) {
const { offset, limit } = JSON.parse(options.body);
body = { items: opportunities.slice(offset, offset + limit), totalResults: opportunities.length, count: Math.min(limit, opportunities.length - offset), hasMore: offset + limit < opportunities.length, offset, limit };
} else if (url.pathname.endsWith("summarizations/generate")) body = { summaryText: "Synthetic AI summary.\nText is displayed safely: <script>never executed</script>." };
else throw new Error(`Unexpected synthetic fetch: ${url.pathname}`);
return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } });
}
});
application.productsContentJobs.ensureProductsBackgroundMessageHandler();
document.getElementById("open").addEventListener("click", () => application.contentModal.openOpportunitiesModal());
application.contentModal.openOpportunitiesModal();
})();