README + add tests cases

This commit is contained in:
2026-04-29 03:25:57 -03:00
parent 8662a153fe
commit 728d56bb5b
8 changed files with 876 additions and 9 deletions

View File

@@ -1530,11 +1530,18 @@ const VIEW_DEFS = {
},
],
fields: OPPORTUNITIES_CLOSE_WINDOW_COLUMNS.map((column) => column.name),
buildSql: ({ fromDateSql, toDateSql, statuses, cluster = null }) =>
buildSql: ({ fromDateSql, toDateSql, statuses, cluster = null, ownerEmail = null, ownerManagerEmail = null }) =>
buildSelectQuery({
columns: PRIMARY_OPPORTUNITY_WINDOW_COLUMNS,
fromClause: `FROM ${SA_ATTACH_OPPORTUNITIES_DATASET}`,
whereClauses: buildPrimaryOpportunityWhereClauses({ fromDateSql, toDateSql, statuses, cluster }),
whereClauses: buildPrimaryOpportunityWhereClauses({
fromDateSql,
toDateSql,
statuses,
cluster,
ownerEmail,
ownerManagerEmail,
}),
groupBy: [
xsaColumn(SA_ATTACH_OPPORTUNITIES_DATASET, "Opportunity ID"),
xsaColumn(SA_ATTACH_OPPORTUNITIES_DATASET, "Opportunity Name"),
@@ -1687,6 +1694,66 @@ function workloadClusterParameter() {
};
}
function closeWindowDateParameters() {
return [
{
name: "fromDate",
cli: "--from-date",
required: false,
default: "today",
description: "Start of the close-date window. Accepts YYYY-MM-DD, today, +7d, -3d, or today+7d.",
},
{
name: "toDate",
cli: "--to-date",
required: false,
default: "+7d",
description: "End of the close-date window. Accepts YYYY-MM-DD, today, +7d, -3d, or today+7d.",
},
{
name: "date",
cli: "--date",
required: false,
description: "Exact close date. Shortcut for a one-day window.",
},
{
name: "month",
cli: "--month",
required: false,
description: "Calendar month in YYYY-MM format. Shortcut for a full-month window.",
},
{
name: "quarter",
cli: "--quarter",
required: false,
description: "Fiscal quarter in FY26-Q4 or Q4 FY26 format. Shortcut for a full fiscal-quarter window.",
},
{
name: "week",
cli: "--week",
required: false,
description: "Annual week shortcut anchored on June 1. Accepts 1..53, w1..w53, or week 1..week 53.",
},
{
name: "weekYear",
cli: "--week-year",
required: false,
default: "current June-cycle start year",
description: "Cycle start year used with --week. For example, 2025 means the 2025-06-01 through 2026-05-31 cycle.",
},
];
}
function limitParameter(description = "Optional row limit for the extract.") {
return {
name: "limit",
cli: "--limit",
required: false,
default: "5000",
description,
};
}
const INTENT_CATALOG = {
"opportunities-default": {
description: "Default opportunity path using the traced commercial pipeline defaults on Knowledge DV - Opportunities - V2.",
@@ -1781,6 +1848,81 @@ const INTENT_CATALOG = {
`node "${path.resolve(process.argv[1] || "fetch-sales-intelligence.mjs")}" --intent workloads-by-owner-manager-current --owner-manager-email territory.manager@oracle.com --forecast-type Forecast`,
],
},
"workloads-by-owner-close-window": {
description: "List org-wide workload revenue lines in a close-date window for one explicit territory owner.",
view: "sa-attach-pipeline-details",
parameters: [
{
name: "ownerEmail",
cli: "--owner-email",
required: true,
description: "Territory-owner email to match on the direct owner of the workload row.",
},
...closeWindowDateParameters(),
{
name: "forecastType",
cli: "--forecast-type",
required: false,
default: "all forecast types",
description: "Optional forecast-type filter such as Forecast, Upside, or Won.",
},
workloadClusterParameter(),
limitParameter("Optional row limit for the workload extract."),
],
examples: [
`node "${path.resolve(process.argv[1] || "fetch-sales-intelligence.mjs")}" --intent workloads-by-owner-close-window --owner-email territory.owner@oracle.com --month 2026-05`,
],
},
"workloads-by-owner-manager-close-window": {
description: "List org-wide workload revenue lines in a close-date window for territory owners under one explicit owner manager.",
view: "sa-attach-pipeline-details",
parameters: [
{
name: "ownerManagerEmail",
cli: "--owner-manager-email",
required: true,
description: "Upper territory-owner manager email to match in the workload owner hierarchy.",
},
...closeWindowDateParameters(),
{
name: "forecastType",
cli: "--forecast-type",
required: false,
default: "all forecast types",
description: "Optional forecast-type filter such as Forecast, Upside, or Won.",
},
workloadClusterParameter(),
limitParameter("Optional row limit for the workload extract."),
],
examples: [
`node "${path.resolve(process.argv[1] || "fetch-sales-intelligence.mjs")}" --intent workloads-by-owner-manager-close-window --owner-manager-email territory.manager@oracle.com --week w43`,
],
},
"workloads-by-resource-close-window": {
description: "List org-wide workload revenue lines in a close-date window for opportunities where one explicit resource appears in Presales Involvement Aux coverage.",
view: "sa-attach-pipeline-details",
parameters: [
{
name: "resource",
cli: "--resource",
required: true,
description: "Oracle user identifier. Accepts resource.member or resource.member@oracle.com.",
},
...closeWindowDateParameters(),
{
name: "forecastType",
cli: "--forecast-type",
required: false,
default: "all forecast types",
description: "Optional forecast-type filter such as Forecast, Upside, or Won.",
},
workloadClusterParameter(),
limitParameter("Optional row limit for the org-wide workload revenue-line extract before coverage intersection."),
],
examples: [
`node "${path.resolve(process.argv[1] || "fetch-sales-intelligence.mjs")}" --intent workloads-by-resource-close-window --resource resource.member --week w43`,
],
},
"workloads-by-manager-resource-close-window": {
description:
"List org-wide workload revenue lines closing inside a date window, keeping only opportunities that have allocated presales resources under one or more explicit managers from Knowledge DV - Presales Involvement Aux - V1. This default intent is involvement/allocation only and does not fetch SR details from DV - SE Team.",
@@ -1929,6 +2071,56 @@ const INTENT_CATALOG = {
`node "${path.resolve(process.argv[1] || "fetch-sales-intelligence.mjs")}" --intent opportunities-close-quarter --quarter current-quarter`,
],
},
"opportunities-by-owner-close-window": {
description: "List org-wide commercial opportunities/workloads in a close-date window for one explicit territory owner.",
view: "opportunities-close-window",
parameters: [
{
name: "ownerEmail",
cli: "--owner-email",
required: true,
description: "Territory-owner email to match on the direct owner of the opportunity row.",
},
...closeWindowDateParameters(),
{
name: "optyStatus",
cli: "--opty-status",
required: false,
default: "all statuses",
description: "Optional comma-separated opportunity statuses such as Open,Won,Closed.",
},
closeWindowClusterParameter(),
limitParameter("Optional row limit for the opportunity window."),
],
examples: [
`node "${path.resolve(process.argv[1] || "fetch-sales-intelligence.mjs")}" --intent opportunities-by-owner-close-window --owner-email territory.owner@oracle.com --week w43`,
],
},
"opportunities-by-owner-manager-close-window": {
description: "List org-wide commercial opportunities/workloads in a close-date window for territory owners under one explicit owner manager.",
view: "opportunities-close-window",
parameters: [
{
name: "ownerManagerEmail",
cli: "--owner-manager-email",
required: true,
description: "Upper territory-owner manager email to match in the opportunity owner hierarchy.",
},
...closeWindowDateParameters(),
{
name: "optyStatus",
cli: "--opty-status",
required: false,
default: "all statuses",
description: "Optional comma-separated opportunity statuses such as Open,Won,Closed.",
},
closeWindowClusterParameter(),
limitParameter("Optional row limit for the opportunity window."),
],
examples: [
`node "${path.resolve(process.argv[1] || "fetch-sales-intelligence.mjs")}" --intent opportunities-by-owner-manager-close-window --owner-manager-email territory.manager@oracle.com --month 2026-05`,
],
},
"opportunities-current-team-close-window": {
description:
"List commercial opportunities/workloads in a close-date window and enrich them with current-team presales/SR coverage for the executing user when present. Org-wide opportunity rows are preserved even when no current-team resource matches.",
@@ -4203,6 +4395,15 @@ function applyCurrentWorkloadIntentDefaults(args) {
return nextArgs;
}
function applyCloseWindowIntentDefaults(args) {
const nextArgs = { ...args };
if (!hasAnyDateWindowArgs(nextArgs)) {
nextArgs["from-date"] = "today";
nextArgs["to-date"] = "+7d";
}
return nextArgs;
}
function resolveSaAttachFilters(args, definition) {
const statuses = splitCsv(args["revenue-line-status"], definition.defaultStatuses || SA_ATTACH_DEFAULT_ALL_STATUSES);
const cluster = String(args.cluster || SA_ATTACH_DEFAULT_CLUSTER).trim();
@@ -4416,7 +4617,14 @@ function resolveCoverageLimit(limit) {
return Math.min(10000, Math.max(5000, Number(limit) * 8));
}
function buildManagerResourceWorkloadSql({ fromDateSql, toDateSql, cluster = SA_ATTACH_DEFAULT_CLUSTER }) {
function buildWorkloadCloseWindowSql({
fromDateSql,
toDateSql,
cluster = SA_ATTACH_DEFAULT_CLUSTER,
ownerEmail = null,
ownerManagerEmail = null,
forecastTypes = [],
}) {
return buildDenseQuery({
columns: WORKLOAD_MANAGER_RESOURCE_PIPELINE_COLUMNS,
fromClause: `FROM ${SA_ATTACH_OPPORTUNITIES_DATASET}`,
@@ -4433,7 +4641,9 @@ function buildManagerResourceWorkloadSql({ fromDateSql, toDateSql, cluster = SA_
revenueTypeGroups: ["WORKLOAD"],
salesCreditType: SA_ATTACH_DEFAULT_SALES_CREDIT_TYPE,
minOpportunityProbability: SA_ATTACH_DEFAULT_MIN_OPPORTUNITY_PROBABILITY,
forecastTypes: [],
ownerEmail,
ownerManagerEmail,
forecastTypes,
}),
orderBy: `${xsaColumn(SA_ATTACH_OPPORTUNITIES_DATASET, "Revenue Line Close Date")}, ${xsaColumn(
SA_ATTACH_OPPORTUNITIES_DATASET,
@@ -4442,6 +4652,10 @@ function buildManagerResourceWorkloadSql({ fromDateSql, toDateSql, cluster = SA_
});
}
function buildManagerResourceWorkloadSql({ fromDateSql, toDateSql, cluster = SA_ATTACH_DEFAULT_CLUSTER }) {
return buildWorkloadCloseWindowSql({ fromDateSql, toDateSql, cluster });
}
function buildRevenueTeamFilter() {
return buildXsaTeamFilter(SA_ATTACH_REVENUE_LINES_DATASET);
}
@@ -4528,6 +4742,8 @@ function buildPrimaryOpportunityWhereClauses({
toDateSql = null,
fiscalYear = null,
cluster = null,
ownerEmail = null,
ownerManagerEmail = null,
}) {
const clauses = [];
const closeDateExpr = xsaColumn(SA_ATTACH_OPPORTUNITIES_DATASET, "Revenue Line Close Date");
@@ -4551,6 +4767,20 @@ function buildPrimaryOpportunityWhereClauses({
if (statuses.length > 0) {
clauses.push(`${xsaColumn(SA_ATTACH_OPPORTUNITIES_DATASET, "Opportunity Status")} IN (${toSqlList(statuses)})`);
}
const normalizedOwnerEmail = String(ownerEmail || "").trim().toLowerCase();
if (normalizedOwnerEmail) {
clauses.push(`${xsaColumn(SA_ATTACH_OPPORTUNITIES_DATASET, "Level 7 Territory Owner E-mail")} = ${quoteLiteral(normalizedOwnerEmail)}`);
}
const normalizedOwnerManagerEmail = String(ownerManagerEmail || "").trim().toLowerCase();
if (normalizedOwnerManagerEmail) {
clauses.push(`(
${xsaColumn(SA_ATTACH_OPPORTUNITIES_DATASET, "Level 2 Territory Owner E-mail")} = ${quoteLiteral(normalizedOwnerManagerEmail)}
OR ${xsaColumn(SA_ATTACH_OPPORTUNITIES_DATASET, "Level 3 Territory Owner E-mail")} = ${quoteLiteral(normalizedOwnerManagerEmail)}
OR ${xsaColumn(SA_ATTACH_OPPORTUNITIES_DATASET, "Level 4 Territory Owner E-mail")} = ${quoteLiteral(normalizedOwnerManagerEmail)}
OR ${xsaColumn(SA_ATTACH_OPPORTUNITIES_DATASET, "Level 5 Territory Owner E-mail")} = ${quoteLiteral(normalizedOwnerManagerEmail)}
OR ${xsaColumn(SA_ATTACH_OPPORTUNITIES_DATASET, "Level 6 Territory Owner E-mail")} = ${quoteLiteral(normalizedOwnerManagerEmail)}
)`);
}
return clauses;
}
@@ -5655,6 +5885,169 @@ async function executeWorkloadManagerResourceIntent({
};
}
async function executeWorkloadResourceIntent({
args,
intent,
limit,
state,
meta,
baseUrl,
statePath,
metaPath,
useCache,
}) {
const effectiveArgs = applyCloseWindowIntentDefaults(args);
const dateWindow = resolveDateWindow(effectiveArgs, { from: "today", to: "+7d" });
const resourceFilter = resolveResourceFilter(effectiveArgs);
const cluster = resolveCommercialClusterFilter(effectiveArgs);
const forecastTypes = splitCsv(effectiveArgs["forecast-type"], []);
const workloadSql = buildWorkloadCloseWindowSql({
fromDateSql: dateWindow.fromDateSql,
toDateSql: dateWindow.toDateSql,
cluster,
forecastTypes,
});
const coverageLimit = resolveCoverageLimit(limit);
const [workloadResult] = await executeSqlQueries({
state,
meta,
baseUrl,
statePath,
metaPath,
useCache,
queries: [{ sql: workloadSql, limit }],
});
const workloadRecords = mapRows(
WORKLOAD_MANAGER_RESOURCE_PIPELINE_COLUMNS.map((column) => column.name),
workloadResult?.aResults || []
);
const opportunityIds = Array.from(new Set(workloadRecords.map((record) => record.opportunityId).filter(Boolean)));
let coverageSql = null;
let coverageResult = null;
let coverageRecords = [];
if (opportunityIds.length > 0) {
coverageSql = buildExplicitCoverageSqlForOpportunityIds(opportunityIds, resourceFilter.resourceEmailSql);
[coverageResult] = await executeSqlQueries({
state,
meta,
baseUrl,
statePath,
metaPath,
useCache,
queries: [{ sql: coverageSql, limit: coverageLimit }],
});
coverageRecords = mapRows(
SA_ATTACH_PRESALES_AUX_COLUMNS.map((column) => column.name),
coverageResult?.aResults || []
);
}
const coverageSummary = summarizeOrgWideRevenueLineCoverage(workloadRecords, coverageRecords);
coverageSummary.summary.resourcesRequested = 1;
return {
generatedAt: new Date().toISOString(),
scope: buildScopeDescriptor({
scopeMode: SCOPE_ORG_WIDE,
baseScope: SCOPE_ORG_WIDE,
baseLabel: "Opportunities/workloads",
baseSource: SOURCE_OPPORTUNITIES,
enrichmentScope: SCOPE_ORG_WIDE,
enrichmentLabel: "Manager/resource allocation",
enrichmentSource: SOURCE_PRESALES_AUX,
customDisclosureLines: [
"Opportunities/workloads: org-wide.",
"Manager/resource allocation: org-wide from Knowledge DV - Presales Involvement Aux - V1.",
],
components: [
buildScopeComponent({
name: "commercialRows",
label: "Opportunities/workloads",
source: SOURCE_OPPORTUNITIES,
scope: SCOPE_ORG_WIDE,
}),
buildScopeComponent({
name: "managerResourceAllocation",
label: "Manager/resource allocation",
source: SOURCE_PRESALES_AUX,
scope: SCOPE_ORG_WIDE,
}),
],
}),
apiMetrics: buildApiMetrics([
{ label: "workloadRevenueLines", result: workloadResult, source: SOURCE_OPPORTUNITIES },
...(coverageResult ? [{ label: "resourceCoverage", result: coverageResult, source: SOURCE_PRESALES_AUX }] : []),
]),
request: {
mode: "intent",
intent,
view: "sa-attach-pipeline-details",
secondaryView: "sa-attach-presales-coverage",
endpoint: new URL(SQL_ENDPOINT, baseUrl).toString(),
statePath,
metaPath,
scopeMode: SCOPE_ORG_WIDE,
matchStrategy:
"Filter org-wide workload revenue lines by Revenue Line Close Date, then keep only opportunities where the requested resource appears in Presales Involvement Aux coverage.",
resourceInput: resourceFilter.resourceInput,
resourceEmail: resourceFilter.resourceEmail,
cluster,
forecastTypes,
datePreset: dateWindow.preset,
fromDate: dateWindow.fromDate,
fromDateInput: dateWindow.fromDateInput,
toDate: dateWindow.toDate,
toDateInput: dateWindow.toDateInput,
...(dateWindow.fiscalQuarter
? {
fiscalYear: dateWindow.fiscalYear,
fiscalQuarter: dateWindow.fiscalQuarter,
}
: {}),
...(dateWindow.week
? {
week: dateWindow.week,
weekLabel: dateWindow.weekLabel,
weekYear: dateWindow.weekYear,
}
: {}),
limit,
coverageLimit,
useCache,
dataSource: SOURCE_OPPORTUNITIES,
coverageSource: SOURCE_PRESALES_AUX,
sql: {
workloadRevenueLines: workloadSql,
resourceCoverage: coverageSql,
},
},
columns: WORKLOAD_MANAGER_RESOURCE_CLOSE_WINDOW_COLUMNS,
records: coverageSummary.records,
summary: coverageSummary.summary,
warnings: [
...buildWarnings({
requestedLimit: limit,
recordsCount: workloadResult?.aResults?.length || 0,
customSql: false,
}),
...(coverageResult
? buildWarnings({
requestedLimit: coverageLimit,
recordsCount: coverageResult?.aResults?.length || 0,
customSql: false,
})
: []),
"Workload rows stay org-wide and do not fall back to DV - SE Team.",
"Resource linkage is taken only from Knowledge DV - Presales Involvement Aux - V1.",
],
raw: {
workloadRevenueLines: workloadResult,
resourceCoverage: coverageResult,
},
};
}
async function executeOpportunityCoverageIntent({
args,
intent,
@@ -6527,6 +6920,55 @@ async function main() {
effectiveArgs = applyCurrentWorkloadIntentDefaults(args);
}
if (intent === "opportunities-by-owner-close-window") {
const ownerFilter = resolveOwnerEmailFilter(
args,
"owner-email",
"Pass --owner-email when using opportunities-by-owner-close-window."
);
effectiveArgs = { ...effectiveArgs, ownerEmail: ownerFilter.ownerEmail };
}
if (intent === "opportunities-by-owner-manager-close-window") {
const ownerFilter = resolveOwnerEmailFilter(
args,
"owner-manager-email",
"Pass --owner-manager-email when using opportunities-by-owner-manager-close-window."
);
effectiveArgs = { ...effectiveArgs, ownerManagerEmail: ownerFilter.ownerEmail };
}
if (intent === "workloads-by-owner-close-window") {
resolveOwnerEmailFilter(args, "owner-email", "Pass --owner-email when using workloads-by-owner-close-window.");
effectiveArgs = applyCloseWindowIntentDefaults(args);
}
if (intent === "workloads-by-owner-manager-close-window") {
resolveOwnerEmailFilter(
args,
"owner-manager-email",
"Pass --owner-manager-email when using workloads-by-owner-manager-close-window."
);
effectiveArgs = applyCloseWindowIntentDefaults(args);
}
if (intent === "workloads-by-resource-close-window") {
const payload = await executeWorkloadResourceIntent({
args: effectiveArgs,
intent,
limit,
state,
meta,
baseUrl,
statePath,
metaPath,
useCache,
});
const json = await emitJson(effectiveArgs, payload, runtimeHome);
console.log(json);
return;
}
if (intent === "workloads-by-manager-resource-close-window") {
const payload = await executeWorkloadManagerResourceIntent({
args: effectiveArgs,
@@ -6760,6 +7202,8 @@ async function main() {
...dateWindow,
...resourceFilter,
...(explicitCluster ? { cluster: explicitCluster } : {}),
...(effectiveArgs.ownerEmail ? { ownerEmail: effectiveArgs.ownerEmail } : {}),
...(effectiveArgs.ownerManagerEmail ? { ownerManagerEmail: effectiveArgs.ownerManagerEmail } : {}),
...(saAttachFilters ? { saAttachFilters } : {}),
});
const fallbackSql = allowFallbackForRequest(definition, { intent, view: resolvedView })
@@ -6887,10 +7331,12 @@ async function main() {
}
export {
applyCloseWindowIntentDefaults,
applyCurrentWorkloadIntentDefaults,
buildManagerResourceWorkloadSql,
buildPrimaryOpportunityWhereClauses,
buildSaAttachOpportunityWhereClauses,
buildWorkloadCloseWindowSql,
buildApiMetrics,
buildIntentScopeDescriptor,
buildScopeDescriptor,
@@ -6899,6 +7345,7 @@ export {
renderViewSql,
resolveDateWindow,
resolveCoverageLimit,
resolveManagerEmailListFilter,
resolveQuarterInput,
resolveSaAttachFilters,
summarizeOrgWideRevenueLineCoverage,