simplify3x-connect 0.28.1 → 0.31.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +150 -55
- package/dist/adapters/http.d.ts.map +1 -1
- package/dist/adapters/http.js +3 -2
- package/dist/adapters/http.js.map +1 -1
- package/dist/adapters/simplifyqa/adapter.d.ts +464 -4
- package/dist/adapters/simplifyqa/adapter.d.ts.map +1 -1
- package/dist/adapters/simplifyqa/adapter.js +2474 -103
- package/dist/adapters/simplifyqa/adapter.js.map +1 -1
- package/dist/adapters/simplifyqa/executionFailures.d.ts +59 -1
- package/dist/adapters/simplifyqa/executionFailures.d.ts.map +1 -1
- package/dist/adapters/simplifyqa/executionFailures.js +429 -39
- package/dist/adapters/simplifyqa/executionFailures.js.map +1 -1
- package/dist/adapters/simplifyqa/failureAnalysis.d.ts +45 -0
- package/dist/adapters/simplifyqa/failureAnalysis.d.ts.map +1 -0
- package/dist/adapters/simplifyqa/failureAnalysis.js +373 -0
- package/dist/adapters/simplifyqa/failureAnalysis.js.map +1 -0
- package/dist/adapters/simplifyqa/failureAnalysisCard.d.ts +31 -0
- package/dist/adapters/simplifyqa/failureAnalysisCard.d.ts.map +1 -0
- package/dist/adapters/simplifyqa/failureAnalysisCard.js +371 -0
- package/dist/adapters/simplifyqa/failureAnalysisCard.js.map +1 -0
- package/dist/adapters/simplifyqa/failureAnalysisRun.d.ts +41 -0
- package/dist/adapters/simplifyqa/failureAnalysisRun.d.ts.map +1 -0
- package/dist/adapters/simplifyqa/failureAnalysisRun.js +138 -0
- package/dist/adapters/simplifyqa/failureAnalysisRun.js.map +1 -0
- package/dist/adapters/simplifyqa/failureAnalysisTypes.d.ts +84 -0
- package/dist/adapters/simplifyqa/failureAnalysisTypes.d.ts.map +1 -0
- package/dist/adapters/simplifyqa/failureAnalysisTypes.js +2 -0
- package/dist/adapters/simplifyqa/failureAnalysisTypes.js.map +1 -0
- package/dist/adapters/simplifyqa/failureHistory.d.ts +163 -0
- package/dist/adapters/simplifyqa/failureHistory.d.ts.map +1 -0
- package/dist/adapters/simplifyqa/failureHistory.js +174 -0
- package/dist/adapters/simplifyqa/failureHistory.js.map +1 -0
- package/dist/adapters/simplifyqa/failureImages.d.ts +13 -0
- package/dist/adapters/simplifyqa/failureImages.d.ts.map +1 -0
- package/dist/adapters/simplifyqa/failureImages.js +38 -0
- package/dist/adapters/simplifyqa/failureImages.js.map +1 -0
- package/dist/adapters/simplifyqa/failurePatterns.d.ts +54 -0
- package/dist/adapters/simplifyqa/failurePatterns.d.ts.map +1 -0
- package/dist/adapters/simplifyqa/failurePatterns.js +223 -0
- package/dist/adapters/simplifyqa/failurePatterns.js.map +1 -0
- package/dist/adapters/simplifyqa/failureReport.d.ts +35 -41
- package/dist/adapters/simplifyqa/failureReport.d.ts.map +1 -1
- package/dist/adapters/simplifyqa/failureReport.js +94 -249
- package/dist/adapters/simplifyqa/failureReport.js.map +1 -1
- package/dist/adapters/simplifyqa/failureReportModel.d.ts +73 -0
- package/dist/adapters/simplifyqa/failureReportModel.d.ts.map +1 -0
- package/dist/adapters/simplifyqa/failureReportModel.js +199 -0
- package/dist/adapters/simplifyqa/failureReportModel.js.map +1 -0
- package/dist/adapters/simplifyqa/failureReview.d.ts +36 -0
- package/dist/adapters/simplifyqa/failureReview.d.ts.map +1 -0
- package/dist/adapters/simplifyqa/failureReview.js +384 -0
- package/dist/adapters/simplifyqa/failureReview.js.map +1 -0
- package/dist/adapters/simplifyqa/failureSuggest.d.ts +13 -0
- package/dist/adapters/simplifyqa/failureSuggest.d.ts.map +1 -0
- package/dist/adapters/simplifyqa/failureSuggest.js +54 -0
- package/dist/adapters/simplifyqa/failureSuggest.js.map +1 -0
- package/dist/adapters/simplifyqa/failureTypes.d.ts +22 -1
- package/dist/adapters/simplifyqa/failureTypes.d.ts.map +1 -1
- package/dist/adapters/simplifyqa/loopConditions.d.ts +57 -0
- package/dist/adapters/simplifyqa/loopConditions.d.ts.map +1 -0
- package/dist/adapters/simplifyqa/loopConditions.js +145 -0
- package/dist/adapters/simplifyqa/loopConditions.js.map +1 -0
- package/dist/adapters/simplifyqa/mapper.d.ts.map +1 -1
- package/dist/adapters/simplifyqa/mapper.js +3 -1
- package/dist/adapters/simplifyqa/mapper.js.map +1 -1
- package/dist/adapters/simplifyqa/searchEngine.d.ts.map +1 -1
- package/dist/adapters/simplifyqa/searchEngine.js +6 -3
- package/dist/adapters/simplifyqa/searchEngine.js.map +1 -1
- package/dist/adapters/simplifyqa/searchRegistry.d.ts +7 -2
- package/dist/adapters/simplifyqa/searchRegistry.d.ts.map +1 -1
- package/dist/adapters/simplifyqa/searchRegistry.js +21 -2
- package/dist/adapters/simplifyqa/searchRegistry.js.map +1 -1
- package/dist/adapters/simplifyqa/spreadsheet.d.ts +15 -0
- package/dist/adapters/simplifyqa/spreadsheet.d.ts.map +1 -0
- package/dist/adapters/simplifyqa/spreadsheet.js +196 -0
- package/dist/adapters/simplifyqa/spreadsheet.js.map +1 -0
- package/dist/adapters/types.d.ts +24 -0
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/config.d.ts +0 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +15 -12
- package/dist/config.js.map +1 -1
- package/dist/connection.d.ts +4 -1
- package/dist/connection.d.ts.map +1 -1
- package/dist/connection.js +12 -5
- package/dist/connection.js.map +1 -1
- package/dist/defaults.d.ts +45 -0
- package/dist/defaults.d.ts.map +1 -0
- package/dist/defaults.js +50 -0
- package/dist/defaults.js.map +1 -0
- package/dist/domain/types.d.ts +40 -2
- package/dist/domain/types.d.ts.map +1 -1
- package/dist/domain/types.js.map +1 -1
- package/dist/drafts/store.d.ts +0 -1
- package/dist/drafts/store.d.ts.map +1 -1
- package/dist/drafts/store.js +8 -3
- package/dist/drafts/store.js.map +1 -1
- package/dist/export/json.d.ts +4 -0
- package/dist/export/json.d.ts.map +1 -0
- package/dist/export/json.js +5 -0
- package/dist/export/json.js.map +1 -0
- package/dist/export/layout.d.ts +119 -0
- package/dist/export/layout.d.ts.map +1 -0
- package/dist/export/layout.js +198 -0
- package/dist/export/layout.js.map +1 -0
- package/dist/export/pdf.d.ts +67 -0
- package/dist/export/pdf.d.ts.map +1 -0
- package/dist/export/pdf.js +279 -0
- package/dist/export/pdf.js.map +1 -0
- package/dist/export/xlsx.d.ts +52 -0
- package/dist/export/xlsx.d.ts.map +1 -0
- package/dist/export/xlsx.js +251 -0
- package/dist/export/xlsx.js.map +1 -0
- package/dist/gateway.d.ts.map +1 -1
- package/dist/gateway.js +13 -3
- package/dist/gateway.js.map +1 -1
- package/dist/httpMain.js +3 -2
- package/dist/httpMain.js.map +1 -1
- package/dist/initAgents.d.ts.map +1 -1
- package/dist/initAgents.js +13 -5
- package/dist/initAgents.js.map +1 -1
- package/dist/mcpResult.d.ts +4 -3
- package/dist/mcpResult.d.ts.map +1 -1
- package/dist/mcpResult.js +4 -2
- package/dist/mcpResult.js.map +1 -1
- package/dist/mount.d.ts +7 -1
- package/dist/mount.d.ts.map +1 -1
- package/dist/mount.js +14 -7
- package/dist/mount.js.map +1 -1
- package/dist/requestConnection.d.ts.map +1 -1
- package/dist/requestConnection.js +8 -3
- package/dist/requestConnection.js.map +1 -1
- package/dist/server.d.ts +9 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +53 -4
- package/dist/server.js.map +1 -1
- package/dist/tools/attachment.tools.d.ts.map +1 -1
- package/dist/tools/attachment.tools.js +54 -1
- package/dist/tools/attachment.tools.js.map +1 -1
- package/dist/tools/backlog.tools.d.ts.map +1 -1
- package/dist/tools/backlog.tools.js +41 -0
- package/dist/tools/backlog.tools.js.map +1 -1
- package/dist/tools/defectFromStep.tools.d.ts +16 -0
- package/dist/tools/defectFromStep.tools.d.ts.map +1 -0
- package/dist/tools/defectFromStep.tools.js +90 -0
- package/dist/tools/defectFromStep.tools.js.map +1 -0
- package/dist/tools/defectUpdate.tools.d.ts +15 -0
- package/dist/tools/defectUpdate.tools.d.ts.map +1 -0
- package/dist/tools/defectUpdate.tools.js +120 -0
- package/dist/tools/defectUpdate.tools.js.map +1 -0
- package/dist/tools/discovery.tools.d.ts +2 -0
- package/dist/tools/discovery.tools.d.ts.map +1 -1
- package/dist/tools/discovery.tools.js +8 -3
- package/dist/tools/discovery.tools.js.map +1 -1
- package/dist/tools/environment.tools.d.ts +18 -0
- package/dist/tools/environment.tools.d.ts.map +1 -0
- package/dist/tools/environment.tools.js +86 -0
- package/dist/tools/environment.tools.js.map +1 -0
- package/dist/tools/executionPlan.tools.d.ts.map +1 -1
- package/dist/tools/executionPlan.tools.js +37 -11
- package/dist/tools/executionPlan.tools.js.map +1 -1
- package/dist/tools/failure.tools.d.ts +12 -4
- package/dist/tools/failure.tools.d.ts.map +1 -1
- package/dist/tools/failure.tools.js +264 -33
- package/dist/tools/failure.tools.js.map +1 -1
- package/dist/tools/failureAnalysisStore.d.ts +30 -0
- package/dist/tools/failureAnalysisStore.d.ts.map +1 -0
- package/dist/tools/failureAnalysisStore.js +84 -0
- package/dist/tools/failureAnalysisStore.js.map +1 -0
- package/dist/tools/failureExport.tools.d.ts +26 -0
- package/dist/tools/failureExport.tools.d.ts.map +1 -0
- package/dist/tools/failureExport.tools.js +201 -0
- package/dist/tools/failureExport.tools.js.map +1 -0
- package/dist/tools/import.tools.d.ts +21 -0
- package/dist/tools/import.tools.d.ts.map +1 -0
- package/dist/tools/import.tools.js +187 -0
- package/dist/tools/import.tools.js.map +1 -0
- package/dist/tools/outDir.d.ts +9 -0
- package/dist/tools/outDir.d.ts.map +1 -0
- package/dist/tools/outDir.js +28 -0
- package/dist/tools/outDir.js.map +1 -0
- package/dist/tools/preference.tools.d.ts.map +1 -1
- package/dist/tools/preference.tools.js +29 -6
- package/dist/tools/preference.tools.js.map +1 -1
- package/dist/tools/query.tools.js +1 -1
- package/dist/tools/query.tools.js.map +1 -1
- package/dist/tools/releaseSprint.tools.d.ts +14 -0
- package/dist/tools/releaseSprint.tools.d.ts.map +1 -0
- package/dist/tools/releaseSprint.tools.js +130 -0
- package/dist/tools/releaseSprint.tools.js.map +1 -0
- package/dist/tools/report.tools.d.ts +2 -0
- package/dist/tools/report.tools.d.ts.map +1 -1
- package/dist/tools/report.tools.js +18 -4
- package/dist/tools/report.tools.js.map +1 -1
- package/dist/tools/run.tools.d.ts +7 -0
- package/dist/tools/run.tools.d.ts.map +1 -1
- package/dist/tools/run.tools.js +80 -18
- package/dist/tools/run.tools.js.map +1 -1
- package/dist/tools/schemas.d.ts +177 -0
- package/dist/tools/schemas.d.ts.map +1 -1
- package/dist/tools/schemas.js +4 -0
- package/dist/tools/schemas.js.map +1 -1
- package/dist/tools/suiteManage.tools.d.ts.map +1 -1
- package/dist/tools/suiteManage.tools.js +24 -2
- package/dist/tools/suiteManage.tools.js.map +1 -1
- package/dist/tools/tasks.tools.d.ts.map +1 -1
- package/dist/tools/tasks.tools.js +101 -0
- package/dist/tools/tasks.tools.js.map +1 -1
- package/dist/tools/testCaseLint.d.ts.map +1 -1
- package/dist/tools/testCaseLint.js +20 -0
- package/dist/tools/testCaseLint.js.map +1 -1
- package/dist/tools/testcase.tools.d.ts +4 -0
- package/dist/tools/testcase.tools.d.ts.map +1 -1
- package/dist/tools/testcase.tools.js +28 -0
- package/dist/tools/testcase.tools.js.map +1 -1
- package/dist/tools/testdata.tools.d.ts.map +1 -1
- package/dist/tools/testdata.tools.js +42 -1
- package/dist/tools/testdata.tools.js.map +1 -1
- package/dist/vendor/logger.d.ts +3 -5
- package/dist/vendor/logger.d.ts.map +1 -1
- package/dist/vendor/logger.js +13 -8
- package/dist/vendor/logger.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +8 -6
- package/dist/tools/xlsx.d.ts +0 -8
- package/dist/tools/xlsx.d.ts.map +0 -1
- package/dist/tools/xlsx.js +0 -113
- package/dist/tools/xlsx.js.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import os from 'node:os';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import { mkdir, writeFile } from 'node:fs/promises';
|
|
4
|
-
import { join } from 'node:path';
|
|
3
|
+
import { access, mkdir, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { join, parse as parsePath, resolve as resolvePath } from 'node:path';
|
|
5
5
|
import { ApiError, makeClient } from '../http.js';
|
|
6
6
|
import { RemoteMcpAdapter } from '../remoteMcp/adapter.js';
|
|
7
7
|
import { atLeast, findRuns, isPlainStep, pickNonOverlapping } from './functionMatch.js';
|
|
@@ -10,11 +10,12 @@ import { apiFailureReason } from './apiFailureReason.js';
|
|
|
10
10
|
import { buildDesktopConditionRows, seedDesktopConditionOperands } from './desktopConditions.js';
|
|
11
11
|
import { apiTransportFailure, dbFailureHint, emptyReadWarning, unresolvedPlaceholders } from './stepDiagnostics.js';
|
|
12
12
|
import { duplicateSteps } from '../../drafts/duplicate.js';
|
|
13
|
+
import { CONDITION_KINDS, buildConditionRows, normalizeLoopKinds, stepConditions } from './loopConditions.js';
|
|
13
14
|
import { mergeApiPatch } from '../../drafts/apiPatch.js';
|
|
14
15
|
import { matchStepNumbers } from '../../drafts/bulk.js';
|
|
15
16
|
import { resolveCollection } from './searchRegistry.js';
|
|
17
|
+
import { mapLimit } from './mapLimit.js';
|
|
16
18
|
import { ExecutionFailureAnalysis, fetchFailureImage } from './executionFailures.js';
|
|
17
|
-
import { failureImages, renderExecution } from './failureReport.js';
|
|
18
19
|
import { log } from '../../log.js';
|
|
19
20
|
import { applyHealPlan as applyHealPlanCore } from './heal/apply.js';
|
|
20
21
|
import { applyCollectionSteps, buildTestcasePayload, deriveTcType, extractApiParamNames, extractParamNames, extractValueParamNames, fromSqaStep, isApiRequestStep, runtimeSlotValue, looksSensitive, normalizeSuiteEntry, notDeleted, numericId, paramDefault, pickArray, str, SUITE_UPDATE_ALLOWED_KEYS, TECH_BY_STEPTYPE, toDefectSummary, toEpic, toEpicSummary, toFeature, toFeatureSummary, toFunction, toFunctionSummary, toModuleSaved, toModuleSummary, toObject, toImageUrl, toReleaseSummary, toSavedRef, toSprintSummary, toStory, toStorySummary, toSuite, toSuiteSummary, toTaskSummary, toTcSummary, toTestCase, toVersionEntries, withTotal, } from './mapper.js';
|
|
@@ -589,24 +590,95 @@ const SCHEDULE_UPDATE_KEYS = [
|
|
|
589
590
|
];
|
|
590
591
|
const RECURRENCE_KEYS = ['startDate', 'endDate', 'interval', 'daysOfWeek', 'dayOfMonth', 'occurencePosition'];
|
|
591
592
|
const WEEKDAYS = ['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'];
|
|
593
|
+
/** The recurrence settings a caller gave (only the ones present). */
|
|
594
|
+
function recurrenceExtras(o) {
|
|
595
|
+
const out = {};
|
|
596
|
+
if (o.interval !== undefined)
|
|
597
|
+
out.interval = o.interval;
|
|
598
|
+
if (o.daysOfWeek !== undefined)
|
|
599
|
+
out.daysOfWeek = o.daysOfWeek;
|
|
600
|
+
if (o.dayOfMonth !== undefined)
|
|
601
|
+
out.dayOfMonth = o.dayOfMonth;
|
|
602
|
+
if (o.occurrence !== undefined)
|
|
603
|
+
out.occurrence = o.occurrence;
|
|
604
|
+
return out;
|
|
605
|
+
}
|
|
606
|
+
/** MONDAY / Mon / monday → MONDAY. */
|
|
607
|
+
function sqaWeekday(v) {
|
|
608
|
+
const hit = WEEKDAYS.find((d) => d.slice(0, 3) === String(v).trim().toUpperCase().slice(0, 3));
|
|
609
|
+
if (!hit || String(v).trim().length < 3)
|
|
610
|
+
throw new Error(`"${v}" is not a weekday — use MONDAY … SUNDAY (or MON … SUN).`);
|
|
611
|
+
return hit;
|
|
612
|
+
}
|
|
613
|
+
/** The stored recurrence as the neutral cadence name. */
|
|
614
|
+
function neutralCadence(doc) {
|
|
615
|
+
const t = String(doc['recurrenceType'] ?? 'ONCE').toLowerCase();
|
|
616
|
+
return (['once', 'every_5_minutes', 'hourly', 'daily', 'weekly', 'monthly'].includes(t) ? t : 'once');
|
|
617
|
+
}
|
|
592
618
|
/** SimplifyQA recurrence for a neutral cadence, as the scheduler form builds it. Day of week / month are
|
|
593
|
-
* taken in `timeZone` (the user's), so "weekly" from a Tuesday morning in India is a Tuesday.
|
|
594
|
-
|
|
619
|
+
* taken in `timeZone` (the user's), so "weekly" from a Tuesday morning in India is a Tuesday. The form's
|
|
620
|
+
* "REPEAT EVERY N" is `interval`; weekly takes its days, monthly "ON DAY d" or "ON THE first/…/last <weekday>".
|
|
621
|
+
* Settings a cadence does not have are refused, never dropped. */
|
|
622
|
+
function sqaRecurrence(type, start, end, timeZone, extra = {}) {
|
|
595
623
|
const parts = new Intl.DateTimeFormat('en-US', { timeZone, weekday: 'long', day: 'numeric' }).formatToParts(new Date(start));
|
|
596
624
|
const weekday = (parts.find((p) => p.type === 'weekday')?.value ?? '').toUpperCase();
|
|
597
625
|
const day = Number(parts.find((p) => p.type === 'day')?.value);
|
|
598
626
|
const once = !type || type === 'once';
|
|
599
627
|
const recurrenceType = once ? 'ONCE' : type === 'weekdays' ? 'WEEKLY' : type.toUpperCase();
|
|
628
|
+
const given = Object.keys(extra);
|
|
629
|
+
if (given.length) {
|
|
630
|
+
if (once)
|
|
631
|
+
throw new Error(`A Once schedule has no recurrence settings (${given.join(', ')}) — pick hourly / daily / weekly / monthly.`);
|
|
632
|
+
if (type === 'every_5_minutes') {
|
|
633
|
+
throw new Error('Every 5 Minutes is fixed at 5 minutes — SimplifyQA has no other minute interval. For another cadence use hourly / daily / weekly / monthly with `interval` N (e.g. hourly, interval 2 = every 2 hours).');
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
let interval = 1;
|
|
637
|
+
if (extra.interval !== undefined) {
|
|
638
|
+
if (!Number.isInteger(extra.interval) || extra.interval < 1)
|
|
639
|
+
throw new Error('interval must be a whole number, 1 or more (repeat every N hours / days / weeks / months).');
|
|
640
|
+
interval = extra.interval;
|
|
641
|
+
}
|
|
642
|
+
if (extra.daysOfWeek !== undefined && type === 'weekdays')
|
|
643
|
+
throw new Error('weekdays already means Monday–Friday — use weekly with daysOfWeek for other days.');
|
|
644
|
+
if (extra.daysOfWeek !== undefined && type !== 'weekly' && !(type === 'monthly' && extra.occurrence !== undefined)) {
|
|
645
|
+
throw new Error('daysOfWeek applies to a weekly schedule (the days to run on) or a monthly one with `occurrence` (the weekday).');
|
|
646
|
+
}
|
|
647
|
+
if ((extra.dayOfMonth !== undefined || extra.occurrence !== undefined) && type !== 'monthly')
|
|
648
|
+
throw new Error('dayOfMonth / occurrence apply to a monthly schedule only.');
|
|
649
|
+
let daysOfWeek = type === 'weekdays' ? WEEKDAYS.slice(1, 6) : type === 'weekly' ? [weekday] : [];
|
|
650
|
+
let dayOfMonth = type === 'monthly' && Number.isFinite(day) ? day : null;
|
|
651
|
+
let occurencePosition = '';
|
|
652
|
+
if (extra.daysOfWeek !== undefined) {
|
|
653
|
+
daysOfWeek = [...new Set(extra.daysOfWeek.map(sqaWeekday))];
|
|
654
|
+
if (!daysOfWeek.length)
|
|
655
|
+
throw new Error('daysOfWeek needs at least one weekday.');
|
|
656
|
+
}
|
|
657
|
+
if (type === 'monthly') {
|
|
658
|
+
if (extra.occurrence !== undefined) {
|
|
659
|
+
if (extra.dayOfMonth !== undefined)
|
|
660
|
+
throw new Error('A monthly schedule is either "on day D" (dayOfMonth) or "on the first / second / third / last <weekday>" (occurrence) — not both.');
|
|
661
|
+
if (daysOfWeek.length !== 1)
|
|
662
|
+
throw new Error('"On the <first / second / third / last> …" needs exactly one weekday in daysOfWeek (e.g. ["MONDAY"]).');
|
|
663
|
+
occurencePosition = extra.occurrence.toUpperCase();
|
|
664
|
+
dayOfMonth = null;
|
|
665
|
+
}
|
|
666
|
+
else if (extra.dayOfMonth !== undefined) {
|
|
667
|
+
if (!Number.isInteger(extra.dayOfMonth) || extra.dayOfMonth < 1 || extra.dayOfMonth > 30)
|
|
668
|
+
throw new Error('dayOfMonth must be a whole number from 1 to 30 (the Scheduler form allows 30 at most).');
|
|
669
|
+
dayOfMonth = extra.dayOfMonth;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
600
672
|
return {
|
|
601
673
|
recurrenceType,
|
|
602
674
|
scheduleEndDate: once ? start : (end ?? null),
|
|
603
675
|
reccurenceData: {
|
|
604
676
|
startDate: start,
|
|
605
677
|
endDate: once ? null : (end ?? null),
|
|
606
|
-
interval
|
|
607
|
-
daysOfWeek
|
|
608
|
-
dayOfMonth
|
|
609
|
-
occurencePosition
|
|
678
|
+
interval,
|
|
679
|
+
daysOfWeek,
|
|
680
|
+
dayOfMonth,
|
|
681
|
+
occurencePosition,
|
|
610
682
|
},
|
|
611
683
|
};
|
|
612
684
|
}
|
|
@@ -1847,6 +1919,1096 @@ export class SimplifyQaAdapter {
|
|
|
1847
1919
|
const rows = pickArray(raw, 'data', 'content', 'tasks');
|
|
1848
1920
|
return withTotal(rows.map(toTaskSummary), raw);
|
|
1849
1921
|
}
|
|
1922
|
+
// ---------------------------------------------------------------------- Task update
|
|
1923
|
+
/** One task as the backend stores it (`GET /pm/task/:id`), or undefined when there is none. */
|
|
1924
|
+
async readTaskDoc(id) {
|
|
1925
|
+
const raw = await this.http.getJson(`/pm/task/${id}`).catch(() => undefined);
|
|
1926
|
+
let doc = raw?.data ?? raw;
|
|
1927
|
+
if (Array.isArray(doc))
|
|
1928
|
+
doc = doc[0];
|
|
1929
|
+
return doc && typeof doc === 'object' && doc.id !== undefined ? doc : undefined;
|
|
1930
|
+
}
|
|
1931
|
+
/** The project's configured values of a default field of Task (parent 4) — `key` is what the row stores. Empty when they
|
|
1932
|
+
* cannot be read; the caller then passes the given value through and lets the backend decide. */
|
|
1933
|
+
async taskFieldValues(key) {
|
|
1934
|
+
try {
|
|
1935
|
+
const raw = await this.http.getJson(`/pm/fields/4?projectId=${this.requireProjectId()}&fieldType=defaultFld`);
|
|
1936
|
+
const fields = Array.isArray(raw) ? raw : pickArray(raw, 'data', 'content', 'fields');
|
|
1937
|
+
const field = fields.find((f) => f?.key === key);
|
|
1938
|
+
return (Array.isArray(field?.values) ? field.values : [])
|
|
1939
|
+
.filter((v) => v?.archive !== true)
|
|
1940
|
+
.map((v) => ({ key: String(v?.key ?? v?.value ?? ''), value: String(v?.value ?? v?.key ?? ''), ...(v?.isDefault === true ? { isDefault: true } : {}) }))
|
|
1941
|
+
.filter((v) => v.key);
|
|
1942
|
+
}
|
|
1943
|
+
catch {
|
|
1944
|
+
return [];
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
/** Change a task the way the SimplifyQA editor does (a partial `PUT /pm/task/:id` carrying the project and the version it
|
|
1948
|
+
* read), then read it back and compare. The assignee may be a user id, email, name or "me"; `unassign` clears it. */
|
|
1949
|
+
async updateTask(ref, patch) {
|
|
1950
|
+
const projectId = this.requireProjectId();
|
|
1951
|
+
const canon = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
1952
|
+
const raw = String(ref ?? '').trim();
|
|
1953
|
+
if (!raw)
|
|
1954
|
+
throw new Error('task_update: say which task — its id, code (e.g. TA-3) or exact name.');
|
|
1955
|
+
// 1. which task
|
|
1956
|
+
let id;
|
|
1957
|
+
if (/^\d+$/.test(raw))
|
|
1958
|
+
id = Number.parseInt(raw, 10);
|
|
1959
|
+
else {
|
|
1960
|
+
const coded = /^[A-Za-z]{2,}[-_]\d+$/.test(raw);
|
|
1961
|
+
const escaped = raw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
1962
|
+
const rows = coded
|
|
1963
|
+
? await this.listTasks({ filters: [{ column: 'code', value: raw.toUpperCase().replace('_', '-') }], limit: 5 })
|
|
1964
|
+
: (await this.listTasks({ search: escaped, limit: 50 })).filter((r) => r.title.trim().toLowerCase() === raw.toLowerCase());
|
|
1965
|
+
const label = (r) => `${r.code ?? `#${r.id}`} "${r.title}"`;
|
|
1966
|
+
if (!rows.length)
|
|
1967
|
+
throw new Error(`No task "${raw}" in this project. Use task_list to find its id or code.`);
|
|
1968
|
+
if (rows.length > 1)
|
|
1969
|
+
throw new Error(`"${raw}" matches ${rows.length} tasks (${rows.map(label).join('; ')}). Pass the id or code.`);
|
|
1970
|
+
id = Number.parseInt(rows[0].id, 10);
|
|
1971
|
+
}
|
|
1972
|
+
const doc = id !== undefined && Number.isFinite(id) ? await this.readTaskDoc(id) : undefined;
|
|
1973
|
+
if (!doc || (doc['projectId'] != null && Number(doc['projectId']) !== projectId) || doc['deleted'] === true) {
|
|
1974
|
+
throw new Error(`No task "${raw}" in this project.`);
|
|
1975
|
+
}
|
|
1976
|
+
const taskId = Number(doc['id']);
|
|
1977
|
+
const code = String(doc['code'] ?? `#${taskId}`);
|
|
1978
|
+
// 2. what to change — only real differences, each checked before anything is sent
|
|
1979
|
+
const changes = {};
|
|
1980
|
+
const shown = [];
|
|
1981
|
+
const day = (v) => (v == null || v === '' ? '(none)' : String(v).slice(0, 10));
|
|
1982
|
+
const change = (field, key, to, from, toLabel) => {
|
|
1983
|
+
changes[key] = to;
|
|
1984
|
+
shown.push({ field, from, to: toLabel });
|
|
1985
|
+
};
|
|
1986
|
+
const pickValue = async (key, want) => {
|
|
1987
|
+
const values = await this.taskFieldValues(key);
|
|
1988
|
+
if (!values.length)
|
|
1989
|
+
return want;
|
|
1990
|
+
const hit = values.find((v) => canon(v.key) === canon(want) || canon(v.value) === canon(want));
|
|
1991
|
+
if (!hit)
|
|
1992
|
+
throw new Error(`"${want}" is not a task ${key} in this project. Valid: ${values.map((v) => v.key).join(', ')}.`);
|
|
1993
|
+
return hit.key;
|
|
1994
|
+
};
|
|
1995
|
+
if (patch.name !== undefined && patch.name.trim() !== String(doc['name'] ?? '')) {
|
|
1996
|
+
if (patch.name.trim().length < 3)
|
|
1997
|
+
throw new Error('A task name needs at least 3 characters.');
|
|
1998
|
+
change('name', 'name', patch.name.trim(), String(doc['name'] ?? ''), patch.name.trim());
|
|
1999
|
+
}
|
|
2000
|
+
if (patch.state !== undefined) {
|
|
2001
|
+
const s = await pickValue('state', patch.state);
|
|
2002
|
+
if (s !== doc['state'])
|
|
2003
|
+
change('state', 'state', s, String(doc['state'] ?? ''), s);
|
|
2004
|
+
}
|
|
2005
|
+
if (patch.priority !== undefined) {
|
|
2006
|
+
const p = await pickValue('priority', patch.priority);
|
|
2007
|
+
if (p !== doc['priority'])
|
|
2008
|
+
change('priority', 'priority', p, String(doc['priority'] ?? ''), p);
|
|
2009
|
+
}
|
|
2010
|
+
if (patch.description !== undefined && patch.description !== String(doc['description'] ?? '')) {
|
|
2011
|
+
change('description', 'description', patch.description, '(previous)', '(updated)');
|
|
2012
|
+
}
|
|
2013
|
+
if (patch.estimatedEffort !== undefined && patch.estimatedEffort !== doc['estimatedEffort']) {
|
|
2014
|
+
if (patch.estimatedEffort < 0 || patch.estimatedEffort > 9999)
|
|
2015
|
+
throw new Error('estimatedEffort must be between 0 and 9999.');
|
|
2016
|
+
change('estimated effort', 'estimatedEffort', patch.estimatedEffort, String(doc['estimatedEffort'] ?? ''), String(patch.estimatedEffort));
|
|
2017
|
+
}
|
|
2018
|
+
for (const [field, key] of [['actual effort', 'actualEffort'], ['remaining effort', 'remainingEffort']]) {
|
|
2019
|
+
const want = patch[key];
|
|
2020
|
+
if (want === undefined)
|
|
2021
|
+
continue;
|
|
2022
|
+
if (!Number.isFinite(want) || want < 0 || want > 9999)
|
|
2023
|
+
throw new Error(`${key} must be a number between 0 and 9999.`);
|
|
2024
|
+
if (want !== doc[key])
|
|
2025
|
+
change(field, key, want, String(doc[key] ?? ''), String(want));
|
|
2026
|
+
}
|
|
2027
|
+
// release / sprint / linked story: "none" clears; a sprint brings its release along
|
|
2028
|
+
if (patch.releaseId !== undefined || patch.sprintId !== undefined) {
|
|
2029
|
+
const plan = await this.resolveTaskPlanning(patch.releaseId, patch.sprintId);
|
|
2030
|
+
const was = (k) => String(doc[k] ?? '(none)');
|
|
2031
|
+
let iterationId = plan.iterationId;
|
|
2032
|
+
let sprintLabel = plan.sprintLabel;
|
|
2033
|
+
// moving to another release must not leave the old release's sprint behind
|
|
2034
|
+
if (patch.sprintId === undefined && plan.releaseId != null && plan.releaseId !== (doc['releaseId'] ?? null) && doc['iterationId'] != null) {
|
|
2035
|
+
iterationId = null;
|
|
2036
|
+
sprintLabel = 'none (it belonged to the old release)';
|
|
2037
|
+
}
|
|
2038
|
+
if (plan.releaseId !== undefined && plan.releaseId !== (doc['releaseId'] ?? null))
|
|
2039
|
+
change('release', 'releaseId', plan.releaseId, was('releaseId'), plan.releaseLabel ?? 'none');
|
|
2040
|
+
if (iterationId !== undefined && iterationId !== (doc['iterationId'] ?? null))
|
|
2041
|
+
change('sprint', 'iterationId', iterationId, was('iterationId'), sprintLabel ?? 'none');
|
|
2042
|
+
}
|
|
2043
|
+
if (patch.storyId !== undefined) {
|
|
2044
|
+
const clear = String(patch.storyId).trim().toLowerCase() === 'none';
|
|
2045
|
+
const sid = clear ? null : Number.parseInt(await this.resolveStoryNumericId(String(patch.storyId)), 10);
|
|
2046
|
+
if (sid !== (doc['userstoryId'] ?? null))
|
|
2047
|
+
change('linked story', 'userstoryId', sid, String(doc['userstoryId'] ?? '(none)'), clear ? 'none' : String(patch.storyId));
|
|
2048
|
+
}
|
|
2049
|
+
for (const [field, key] of [['planned start', 'plannedStartDate'], ['planned end', 'plannedEndDate']]) {
|
|
2050
|
+
const want = patch[key];
|
|
2051
|
+
if (want === undefined)
|
|
2052
|
+
continue;
|
|
2053
|
+
if (!/^\d{4}-\d{2}-\d{2}/.test(want) || Number.isNaN(new Date(want).getTime()))
|
|
2054
|
+
throw new Error(`${key} must be a date like 2026-11-17 (got "${want}").`);
|
|
2055
|
+
if (day(doc[key]) !== day(want))
|
|
2056
|
+
change(field, key, want, day(doc[key]), day(want));
|
|
2057
|
+
}
|
|
2058
|
+
const start = String(changes['plannedStartDate'] ?? doc['plannedStartDate'] ?? '');
|
|
2059
|
+
const end = String(changes['plannedEndDate'] ?? doc['plannedEndDate'] ?? '');
|
|
2060
|
+
if (start && end && new Date(end) < new Date(start) && ('plannedStartDate' in changes || 'plannedEndDate' in changes)) {
|
|
2061
|
+
throw new Error(`The planned start (${day(start)}) would be after the planned end (${day(end)}). Move the end date too (plannedEndDate), or pick an earlier start.`);
|
|
2062
|
+
}
|
|
2063
|
+
let owners;
|
|
2064
|
+
let ownerLabel = '';
|
|
2065
|
+
if (patch.unassign) {
|
|
2066
|
+
owners = [];
|
|
2067
|
+
ownerLabel = 'Unassigned';
|
|
2068
|
+
}
|
|
2069
|
+
else if (patch.assignee !== undefined && String(patch.assignee).trim()) {
|
|
2070
|
+
const who = String(patch.assignee).trim();
|
|
2071
|
+
if (who.toLowerCase() === 'me') {
|
|
2072
|
+
const me = await this.ensureUserId();
|
|
2073
|
+
if (!me)
|
|
2074
|
+
throw new Error('Could not identify your user from the token, so "me" cannot be used. Pass an email or a user id.');
|
|
2075
|
+
owners = [Number.parseInt(me, 10)];
|
|
2076
|
+
}
|
|
2077
|
+
else {
|
|
2078
|
+
owners = await this.resolveUserIds([who]); // id, email or name — refuses one that matches nobody
|
|
2079
|
+
}
|
|
2080
|
+
ownerLabel = who;
|
|
2081
|
+
}
|
|
2082
|
+
if (owners) {
|
|
2083
|
+
const current = (Array.isArray(doc['ownerId']) ? doc['ownerId'] : []).map(Number).sort((a, b) => a - b);
|
|
2084
|
+
const wanted = [...owners].sort((a, b) => a - b);
|
|
2085
|
+
if (JSON.stringify(current) !== JSON.stringify(wanted)) {
|
|
2086
|
+
change('assignee', 'ownerId', owners, current.length ? current.map((n) => `user ${n}`).join(', ') : 'Unassigned', ownerLabel || owners.join(', '));
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
const name = String(doc['name'] ?? '');
|
|
2090
|
+
if (!shown.length)
|
|
2091
|
+
return { id: String(taskId), code, name, changes: [], written: false };
|
|
2092
|
+
// 3. save (a stale version is retried once with the fresh one) and read it back
|
|
2093
|
+
const send = (d) => this.http.putJson(`/pm/task/${taskId}`, { projectId, updateVersion: typeof d['updateVersion'] === 'number' ? d['updateVersion'] : 0, ...changes });
|
|
2094
|
+
try {
|
|
2095
|
+
try {
|
|
2096
|
+
await send(doc);
|
|
2097
|
+
}
|
|
2098
|
+
catch (e) {
|
|
2099
|
+
if (!/CONCURRENCY/i.test(e instanceof Error ? e.message : String(e)))
|
|
2100
|
+
throw e;
|
|
2101
|
+
await send((await this.readTaskDoc(taskId)) ?? doc);
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
catch (e) {
|
|
2105
|
+
const m = e instanceof Error ? e.message : String(e);
|
|
2106
|
+
if (/INVALIDTOKEN|Don't Have Privileges|privilege/i.test(m)) {
|
|
2107
|
+
throw new Error(`Updating a task needs the "add_task" privilege in this project, and the connected user does not have it (${m}).`);
|
|
2108
|
+
}
|
|
2109
|
+
throw e;
|
|
2110
|
+
}
|
|
2111
|
+
const after = await this.readTaskDoc(taskId);
|
|
2112
|
+
if (!after)
|
|
2113
|
+
throw new Error(`${code} was updated but could not be read back.`);
|
|
2114
|
+
for (const k of Object.keys(changes)) {
|
|
2115
|
+
const want = changes[k];
|
|
2116
|
+
const got = after[k];
|
|
2117
|
+
const same = k === 'ownerId'
|
|
2118
|
+
? JSON.stringify([...(Array.isArray(got) ? got : [])].map(Number).sort()) === JSON.stringify([...want].sort())
|
|
2119
|
+
: k === 'plannedStartDate' || k === 'plannedEndDate'
|
|
2120
|
+
? day(got) === day(want)
|
|
2121
|
+
: String(got ?? '') === String(want ?? '');
|
|
2122
|
+
if (!same)
|
|
2123
|
+
throw new Error(`${code}: "${k}" was sent as ${JSON.stringify(want)} but reads back as ${JSON.stringify(got)}.`);
|
|
2124
|
+
}
|
|
2125
|
+
return { id: String(taskId), code, name: String(after['name'] ?? name), changes: shown, written: true };
|
|
2126
|
+
}
|
|
2127
|
+
/** A task's release / sprint from what the caller said: "none" clears, a sprint brings its own release along, and a sprint that
|
|
2128
|
+
* belongs to a different release than the one named is refused. `releaseId` / `iterationId` are what the task stores. */
|
|
2129
|
+
async resolveTaskPlanning(releaseRef, sprintRef) {
|
|
2130
|
+
const none = (v) => String(v ?? '').trim().toLowerCase() === 'none';
|
|
2131
|
+
const label = (r) => `${r.code ?? `#${r.id}`} "${r.name ?? ''}"`;
|
|
2132
|
+
const out = {};
|
|
2133
|
+
let release;
|
|
2134
|
+
if (releaseRef !== undefined) {
|
|
2135
|
+
if (none(releaseRef)) {
|
|
2136
|
+
out.releaseId = null;
|
|
2137
|
+
out.releaseLabel = 'none';
|
|
2138
|
+
if (sprintRef === undefined) {
|
|
2139
|
+
out.iterationId = null;
|
|
2140
|
+
out.sprintLabel = 'none';
|
|
2141
|
+
}
|
|
2142
|
+
}
|
|
2143
|
+
else {
|
|
2144
|
+
release = await this.findPm('release', releaseRef);
|
|
2145
|
+
out.releaseId = Number(release.id);
|
|
2146
|
+
out.releaseLabel = label(release);
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
if (sprintRef !== undefined) {
|
|
2150
|
+
if (none(sprintRef)) {
|
|
2151
|
+
out.iterationId = null;
|
|
2152
|
+
out.sprintLabel = 'none';
|
|
2153
|
+
}
|
|
2154
|
+
else {
|
|
2155
|
+
if (releaseRef !== undefined && none(releaseRef))
|
|
2156
|
+
throw new Error('A task cannot have a sprint without a release — clear the sprint too, or give the sprint\'s release.');
|
|
2157
|
+
const sprint = await this.findPm('sprint', sprintRef);
|
|
2158
|
+
if (release && String(sprint.releaseId) !== String(release.id)) {
|
|
2159
|
+
throw new Error(`Sprint ${label(sprint)} belongs to release ${sprint.releaseId}, not ${label(release)}. Pick a sprint of that release.`);
|
|
2160
|
+
}
|
|
2161
|
+
out.iterationId = Number(sprint.id);
|
|
2162
|
+
out.sprintLabel = label(sprint);
|
|
2163
|
+
if (!release && sprint.releaseId != null) {
|
|
2164
|
+
const own = (await this.pmRows('release')).find((r) => String(r.id) === String(sprint.releaseId));
|
|
2165
|
+
out.releaseId = Number(sprint.releaseId);
|
|
2166
|
+
out.releaseLabel = own ? label(own) : `#${sprint.releaseId}`;
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
return out;
|
|
2171
|
+
}
|
|
2172
|
+
/** Create a task the way Tasks → Create Task does (`POST /pm/task`), then read it back. The backend requires a name, an
|
|
2173
|
+
* estimate, a type and both planned dates, and refuses a duplicate name in the project — and answers any failure with a
|
|
2174
|
+
* bare "Error While Creating Task" — so everything is checked here first. What the caller did not give is defaulted
|
|
2175
|
+
* (type / state / priority from the project's own default values; dates from the sprint, else the release, else today)
|
|
2176
|
+
* and the result says so. */
|
|
2177
|
+
async createTask(input) {
|
|
2178
|
+
const projectId = this.requireProjectId();
|
|
2179
|
+
const canon = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
2180
|
+
const name = String(input.name ?? '').trim();
|
|
2181
|
+
if (name.length < 2 || name.length > 500)
|
|
2182
|
+
throw new Error('A task name needs 2–500 characters.');
|
|
2183
|
+
if (typeof input.estimatedEffort !== 'number' || !Number.isFinite(input.estimatedEffort) || input.estimatedEffort < 0 || input.estimatedEffort > 9999) {
|
|
2184
|
+
throw new Error('task_create needs estimatedEffort — a number of hours between 0 and 9999.');
|
|
2185
|
+
}
|
|
2186
|
+
const defaults = [];
|
|
2187
|
+
const warnings = [];
|
|
2188
|
+
const plan = await this.resolveTaskPlanning(input.releaseId, input.sprintId);
|
|
2189
|
+
// dates: given → used; else the sprint's, else the release's, else today
|
|
2190
|
+
const dayOf = (v) => String(v ?? '').slice(0, 10);
|
|
2191
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
2192
|
+
let fallbackStart = today;
|
|
2193
|
+
let fallbackEnd = today;
|
|
2194
|
+
let from = 'today';
|
|
2195
|
+
if (input.sprintId && plan.iterationId) {
|
|
2196
|
+
const s = (await this.pmRows('sprint')).find((r) => String(r.id) === String(plan.iterationId));
|
|
2197
|
+
if (s?.plannedStartDate && s?.plannedEndDate) {
|
|
2198
|
+
fallbackStart = dayOf(s.plannedStartDate);
|
|
2199
|
+
fallbackEnd = dayOf(s.plannedEndDate);
|
|
2200
|
+
from = `the sprint ${plan.sprintLabel}`;
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
else if (plan.releaseId) {
|
|
2204
|
+
const r = (await this.pmRows('release')).find((x) => String(x.id) === String(plan.releaseId));
|
|
2205
|
+
if (r?.plannedStartDate && r?.plannedEndDate) {
|
|
2206
|
+
fallbackStart = dayOf(r.plannedStartDate);
|
|
2207
|
+
fallbackEnd = dayOf(r.plannedEndDate);
|
|
2208
|
+
from = `the release ${plan.releaseLabel}`;
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
const start = input.plannedStartDate ?? fallbackStart;
|
|
2212
|
+
const end = input.plannedEndDate ?? (input.plannedStartDate && !input.plannedEndDate && fallbackEnd < input.plannedStartDate ? input.plannedStartDate : fallbackEnd);
|
|
2213
|
+
for (const [k, v] of [['plannedStartDate', start], ['plannedEndDate', end]]) {
|
|
2214
|
+
if (!/^\d{4}-\d{2}-\d{2}/.test(v) || Number.isNaN(new Date(v).getTime()))
|
|
2215
|
+
throw new Error(`${k} must be a date like 2026-11-17 (got "${v}").`);
|
|
2216
|
+
}
|
|
2217
|
+
if (new Date(end) < new Date(start))
|
|
2218
|
+
throw new Error(`plannedEndDate (${dayOf(end)}) must be on or after plannedStartDate (${dayOf(start)}).`);
|
|
2219
|
+
if (input.plannedStartDate === undefined || input.plannedEndDate === undefined) {
|
|
2220
|
+
defaults.push(`planned dates ${dayOf(start)} → ${dayOf(end)} (${from === 'today' ? 'today' : `taken from ${from}`})`);
|
|
2221
|
+
}
|
|
2222
|
+
// type (required by the backend), state, priority: the project's own values
|
|
2223
|
+
const pickValue = async (key, want, required) => {
|
|
2224
|
+
const values = await this.taskFieldValues(key);
|
|
2225
|
+
if (want !== undefined) {
|
|
2226
|
+
if (!values.length)
|
|
2227
|
+
return want;
|
|
2228
|
+
const hit = values.find((v) => canon(v.key) === canon(want) || canon(v.value) === canon(want));
|
|
2229
|
+
if (!hit)
|
|
2230
|
+
throw new Error(`"${want}" is not a task ${key} in this project. Valid: ${values.map((v) => v.key).join(', ')}.`);
|
|
2231
|
+
return hit.key;
|
|
2232
|
+
}
|
|
2233
|
+
const dflt = values.find((v) => v.isDefault) ?? values[0];
|
|
2234
|
+
if (dflt) {
|
|
2235
|
+
defaults.push(`${key} ${dflt.key}`);
|
|
2236
|
+
return dflt.key;
|
|
2237
|
+
}
|
|
2238
|
+
if (required)
|
|
2239
|
+
throw new Error(`The project's task ${key} values could not be read, and ${key} is required — pass \`${key}\`.`);
|
|
2240
|
+
return undefined;
|
|
2241
|
+
};
|
|
2242
|
+
const type = await pickValue('type', input.type, true);
|
|
2243
|
+
const state = await pickValue('state', input.state, false);
|
|
2244
|
+
const priority = await pickValue('priority', input.priority, false);
|
|
2245
|
+
let ownerId;
|
|
2246
|
+
if (input.assignee !== undefined && String(input.assignee).trim()) {
|
|
2247
|
+
const who = String(input.assignee).trim();
|
|
2248
|
+
if (who.toLowerCase() === 'me') {
|
|
2249
|
+
const me = await this.ensureUserId();
|
|
2250
|
+
if (!me)
|
|
2251
|
+
throw new Error('Could not identify your user from the token, so "me" cannot be used. Pass an email or a user id.');
|
|
2252
|
+
ownerId = [Number.parseInt(me, 10)];
|
|
2253
|
+
}
|
|
2254
|
+
else {
|
|
2255
|
+
ownerId = await this.resolveUserIds([who]);
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
let userstoryId;
|
|
2259
|
+
if (input.storyId !== undefined && String(input.storyId).trim())
|
|
2260
|
+
userstoryId = Number.parseInt(await this.resolveStoryNumericId(String(input.storyId)), 10);
|
|
2261
|
+
const clash = (await this.listTasks({ search: name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), limit: 50 })).find((t) => t.title.trim().toLowerCase() === name.toLowerCase());
|
|
2262
|
+
if (clash)
|
|
2263
|
+
throw new Error(`A task named "${name}" already exists in this project: ${clash.code ?? `#${clash.id}`}. Use task_update to change it, or pick another name.`);
|
|
2264
|
+
const body = {
|
|
2265
|
+
projectId, name, type, plannedStartDate: start, plannedEndDate: end, estimatedEffort: input.estimatedEffort,
|
|
2266
|
+
description: input.description ?? '',
|
|
2267
|
+
...(state ? { state } : {}), ...(priority ? { priority } : {}),
|
|
2268
|
+
...(ownerId ? { ownerId } : {}), ...(userstoryId !== undefined ? { userstoryId } : {}),
|
|
2269
|
+
...(plan.releaseId != null ? { releaseId: plan.releaseId } : {}), ...(plan.iterationId != null ? { iterationId: plan.iterationId } : {}),
|
|
2270
|
+
};
|
|
2271
|
+
let raw;
|
|
2272
|
+
try {
|
|
2273
|
+
raw = await this.http.postJson('/pm/task', body);
|
|
2274
|
+
}
|
|
2275
|
+
catch (e) {
|
|
2276
|
+
const m = e instanceof Error ? e.message : String(e);
|
|
2277
|
+
if (/INVALIDTOKEN|Don't Have Privileges|privilege/i.test(m)) {
|
|
2278
|
+
throw new Error(`Creating a task needs the "add_task" privilege in this project, and the connected user does not have it (${m}).`);
|
|
2279
|
+
}
|
|
2280
|
+
throw e;
|
|
2281
|
+
}
|
|
2282
|
+
const made = raw?.data && typeof raw.data === 'object' && !Array.isArray(raw.data) ? raw.data : raw;
|
|
2283
|
+
const madeId = Number(made?.id);
|
|
2284
|
+
const after = Number.isFinite(madeId) ? await this.readTaskDoc(madeId) : undefined;
|
|
2285
|
+
if (!after)
|
|
2286
|
+
throw new Error(`The task "${name}" was sent, but it could not be read back.`);
|
|
2287
|
+
if (String(after['name'] ?? '') !== name || Number(after['estimatedEffort']) !== input.estimatedEffort) {
|
|
2288
|
+
throw new Error(`${after['code'] ?? `#${madeId}`}: it reads back as "${String(after['name'] ?? '')}" / effort ${String(after['estimatedEffort'])}, not what was sent.`);
|
|
2289
|
+
}
|
|
2290
|
+
if (ownerId && JSON.stringify([...(Array.isArray(after['ownerId']) ? after['ownerId'] : [])].map(Number).sort()) !== JSON.stringify([...ownerId].sort())) {
|
|
2291
|
+
warnings.push(`The assignee did not read back as sent (${JSON.stringify(after['ownerId'])}).`);
|
|
2292
|
+
}
|
|
2293
|
+
return {
|
|
2294
|
+
id: String(madeId), code: String(after['code'] ?? `#${madeId}`), name, type: String(after['type'] ?? type ?? ''), state: String(after['state'] ?? state ?? ''),
|
|
2295
|
+
priority: String(after['priority'] ?? priority ?? ''), plannedStartDate: dayOf(start), plannedEndDate: dayOf(end), estimatedEffort: input.estimatedEffort,
|
|
2296
|
+
ownerIds: ownerId ?? [], ...(plan.releaseLabel && plan.releaseId != null ? { release: plan.releaseLabel } : {}),
|
|
2297
|
+
...(plan.sprintLabel && plan.iterationId != null ? { sprint: plan.sprintLabel } : {}), ...(userstoryId !== undefined ? { storyId: userstoryId } : {}),
|
|
2298
|
+
defaults, warnings,
|
|
2299
|
+
};
|
|
2300
|
+
}
|
|
2301
|
+
// ---------------------------------------------------------------------- Defect update
|
|
2302
|
+
/** The project's configured values of a default field of a backlog entity (parent 4 = Task, 9 = Defect) — `key` is what the row
|
|
2303
|
+
* stores. Empty when they cannot be read; the caller then passes the given value through. */
|
|
2304
|
+
async defaultFieldValues(parentId, key) {
|
|
2305
|
+
try {
|
|
2306
|
+
const raw = await this.http.getJson(`/pm/fields/${parentId}?projectId=${this.requireProjectId()}&fieldType=defaultFld`);
|
|
2307
|
+
const fields = Array.isArray(raw) ? raw : pickArray(raw, 'data', 'content', 'fields');
|
|
2308
|
+
const field = fields.find((f) => f?.key === key);
|
|
2309
|
+
return (Array.isArray(field?.values) ? field.values : [])
|
|
2310
|
+
.filter((v) => v?.archive !== true)
|
|
2311
|
+
.map((v) => ({ key: String(v?.key ?? v?.value ?? ''), value: String(v?.value ?? v?.key ?? ''), ...(v?.isDefault === true ? { isDefault: true } : {}) }))
|
|
2312
|
+
.filter((v) => v.key);
|
|
2313
|
+
}
|
|
2314
|
+
catch {
|
|
2315
|
+
return [];
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
/** A business code written with the other separator (US-25 / US_25) — tried second, since both appear in the product. */
|
|
2319
|
+
static codeVariants(ref) {
|
|
2320
|
+
const r = ref.trim();
|
|
2321
|
+
const swapped = r.includes('-') ? r.replace('-', '_') : r.replace('_', '-');
|
|
2322
|
+
return [...new Set([r, r.toUpperCase(), swapped, swapped.toUpperCase()])];
|
|
2323
|
+
}
|
|
2324
|
+
/** One defect of the active project as the backend stores it, by id, code (DE-61) or exact name. */
|
|
2325
|
+
async findDefectDoc(ref) {
|
|
2326
|
+
const projectId = this.requireProjectId();
|
|
2327
|
+
const raw = String(ref ?? '').trim();
|
|
2328
|
+
if (!raw)
|
|
2329
|
+
throw new Error('defect_update: say which defect — its id, code (e.g. DE-61) or exact name.');
|
|
2330
|
+
let id;
|
|
2331
|
+
if (/^\d+$/.test(raw))
|
|
2332
|
+
id = Number.parseInt(raw, 10);
|
|
2333
|
+
else if (/^[A-Za-z]{2,}[-_]\d+$/.test(raw)) {
|
|
2334
|
+
for (const code of SimplifyQaAdapter.codeVariants(raw)) {
|
|
2335
|
+
const rows = await this.listDefects({ filters: [{ column: 'code', value: code }], limit: 5 });
|
|
2336
|
+
if (rows.length) {
|
|
2337
|
+
id = Number.parseInt(rows[0].id, 10);
|
|
2338
|
+
break;
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
else {
|
|
2343
|
+
const escaped = raw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
2344
|
+
const rows = (await this.listDefects({ search: escaped, limit: 50 })).filter((r) => r.title.trim().toLowerCase() === raw.toLowerCase());
|
|
2345
|
+
if (rows.length > 1)
|
|
2346
|
+
throw new Error(`"${raw}" matches ${rows.length} defects (${rows.map((r) => `${r.code ?? `#${r.id}`}`).join(', ')}). Pass the id or code.`);
|
|
2347
|
+
if (rows.length)
|
|
2348
|
+
id = Number.parseInt(rows[0].id, 10);
|
|
2349
|
+
}
|
|
2350
|
+
const doc = id !== undefined && Number.isFinite(id) ? await this.readDefectDoc(id) : undefined;
|
|
2351
|
+
if (!doc || (doc['projectId'] != null && Number(doc['projectId']) !== projectId) || doc['deleted'] === true) {
|
|
2352
|
+
throw new Error(`No defect "${raw}" in this project. Use sqa_query (collection "defects") to find its id or code.`);
|
|
2353
|
+
}
|
|
2354
|
+
return doc;
|
|
2355
|
+
}
|
|
2356
|
+
async readDefectDoc(id) {
|
|
2357
|
+
const raw = await this.http.getJson(`/pm/defect/${id}`).catch(() => undefined);
|
|
2358
|
+
let doc = raw?.data ?? raw;
|
|
2359
|
+
if (Array.isArray(doc))
|
|
2360
|
+
doc = doc[0];
|
|
2361
|
+
return doc && typeof doc === 'object' && doc.id !== undefined ? doc : undefined;
|
|
2362
|
+
}
|
|
2363
|
+
/** A test case (id or code, optionally ":version" / "@version") as the defect form stores it in `selectedTestCase`. */
|
|
2364
|
+
async defectTestCaseEntry(ref) {
|
|
2365
|
+
const projectId = this.requireProjectId();
|
|
2366
|
+
const m = /^(.*?)[:@](.+)$/.exec(String(ref).trim());
|
|
2367
|
+
const tcRef = (m ? m[1] : String(ref)).trim();
|
|
2368
|
+
const wantVersion = m ? m[2].trim() : undefined;
|
|
2369
|
+
let tcId;
|
|
2370
|
+
if (/^\d+$/.test(tcRef))
|
|
2371
|
+
tcId = Number.parseInt(tcRef, 10);
|
|
2372
|
+
else {
|
|
2373
|
+
for (const code of SimplifyQaAdapter.codeVariants(tcRef)) {
|
|
2374
|
+
const body = this.searchBody([{ column: 'code', value: code }, { column: 'projectId', value: projectId }, { column: 'deleted', value: false }], { startIndex: 0, limit: 5, selectFields: ['id', 'code', 'name'] });
|
|
2375
|
+
const rows = pickArray(await this.http.postJson('/tm/testcase/search', body), 'data', 'content', 'testCases');
|
|
2376
|
+
const hit = rows.find((r) => String(r?.code ?? '').toLowerCase() === code.toLowerCase());
|
|
2377
|
+
if (hit) {
|
|
2378
|
+
tcId = Number.parseInt(str(hit, 'id', '_id') ?? '', 10);
|
|
2379
|
+
break;
|
|
2380
|
+
}
|
|
2381
|
+
}
|
|
2382
|
+
}
|
|
2383
|
+
const raw = tcId !== undefined && Number.isFinite(tcId) ? await this.fetchRawTestcase(String(tcId)) : undefined;
|
|
2384
|
+
if (!raw || raw['id'] === undefined || raw['deleted'] === true)
|
|
2385
|
+
throw new Error(`No test case "${tcRef}" in this project.`);
|
|
2386
|
+
const versions = (Array.isArray(raw['versions']) ? raw['versions'] : []).filter((v) => v?.deleted !== true);
|
|
2387
|
+
if (!versions.length)
|
|
2388
|
+
throw new Error(`Test case ${raw['code'] ?? tcRef} has no version to link.`);
|
|
2389
|
+
let version;
|
|
2390
|
+
let versionNote;
|
|
2391
|
+
if (wantVersion) {
|
|
2392
|
+
version = versions.find((v) => String(v?.name ?? '').trim().toLowerCase() === wantVersion.toLowerCase());
|
|
2393
|
+
if (!version)
|
|
2394
|
+
throw new Error(`Test case ${raw['code'] ?? tcRef} has no version "${wantVersion}". Versions: ${versions.map((v) => v.name).join(', ')}.`);
|
|
2395
|
+
}
|
|
2396
|
+
else {
|
|
2397
|
+
const currentId = str(raw, 'versionId', 'selectedVersionId');
|
|
2398
|
+
version = versions.find((v) => str(v, 'id', '_id') === currentId) ?? versions[versions.length - 1];
|
|
2399
|
+
if (versions.length > 1)
|
|
2400
|
+
versionNote = `${raw['code'] ?? tcRef}: no version given, used ${version.name} (the test case has ${versions.map((v) => v.name).join(', ')}).`;
|
|
2401
|
+
}
|
|
2402
|
+
const code = String(raw['code'] ?? `#${raw['id']}`);
|
|
2403
|
+
return {
|
|
2404
|
+
entry: {
|
|
2405
|
+
code, deleted: false, name: String(raw['name'] ?? ''), testcaseId: Number(raw['id']),
|
|
2406
|
+
testcaseVersion: [{ deleted: false, version: Number(str(version, 'id', '_id') ?? 0) || str(version, 'id', '_id'), versionName: String(version.name ?? '') }],
|
|
2407
|
+
},
|
|
2408
|
+
label: `${code} (${String(version.name ?? '')})`,
|
|
2409
|
+
tcId: Number(raw['id']),
|
|
2410
|
+
...(versionNote ? { versionNote } : {}),
|
|
2411
|
+
};
|
|
2412
|
+
}
|
|
2413
|
+
/** Change a defect the way the SimplifyQA defect form does (a partial `PUT /pm/defect/:id` carrying the project and the version it
|
|
2414
|
+
* read), then read it back. USER STORY is `userstoryId`; TEST CASE is `selectedTestCase` — entries with the test case's id, code,
|
|
2415
|
+
* name and chosen version — which the backend also writes onto the test case's own linked-defects list; that last step swallows its
|
|
2416
|
+
* failures, so it is checked here (and redone through the same endpoint when missing). */
|
|
2417
|
+
async updateDefect(ref, patch) {
|
|
2418
|
+
const projectId = this.requireProjectId();
|
|
2419
|
+
const canon = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
2420
|
+
const doc = await this.findDefectDoc(ref);
|
|
2421
|
+
const defectId = Number(doc['id']);
|
|
2422
|
+
const code = String(doc['code'] ?? `#${defectId}`);
|
|
2423
|
+
const name = String(doc['name'] ?? '');
|
|
2424
|
+
const changes = {};
|
|
2425
|
+
const shown = [];
|
|
2426
|
+
const warnings = [];
|
|
2427
|
+
const change = (field, key, to, from, toLabel) => {
|
|
2428
|
+
changes[key] = to;
|
|
2429
|
+
shown.push({ field, from, to: toLabel });
|
|
2430
|
+
};
|
|
2431
|
+
// plain fields: the project's own values
|
|
2432
|
+
for (const key of ['state', 'priority', 'severity']) {
|
|
2433
|
+
const want = patch[key];
|
|
2434
|
+
if (want === undefined)
|
|
2435
|
+
continue;
|
|
2436
|
+
const values = await this.defaultFieldValues(9, key);
|
|
2437
|
+
let v = want;
|
|
2438
|
+
if (values.length) {
|
|
2439
|
+
const hit = values.find((x) => canon(x.key) === canon(want) || canon(x.value) === canon(want));
|
|
2440
|
+
if (!hit)
|
|
2441
|
+
throw new Error(`"${want}" is not a defect ${key} in this project. Valid: ${values.map((x) => x.key).join(', ')}.`);
|
|
2442
|
+
v = hit.key;
|
|
2443
|
+
}
|
|
2444
|
+
if (v !== doc[key])
|
|
2445
|
+
change(key, key, v, String(doc[key] ?? '(none)'), v);
|
|
2446
|
+
}
|
|
2447
|
+
if (patch.name !== undefined && patch.name.trim() !== name) {
|
|
2448
|
+
if (patch.name.trim().length < 3)
|
|
2449
|
+
throw new Error('A defect name needs at least 3 characters.');
|
|
2450
|
+
change('name', 'name', patch.name.trim(), name, patch.name.trim());
|
|
2451
|
+
}
|
|
2452
|
+
if (patch.description !== undefined && patch.description !== String(doc['description'] ?? ''))
|
|
2453
|
+
change('description', 'description', patch.description, '(previous)', '(updated)');
|
|
2454
|
+
// release / sprint
|
|
2455
|
+
if (patch.releaseId !== undefined || patch.sprintId !== undefined) {
|
|
2456
|
+
const plan = await this.resolveTaskPlanning(patch.releaseId, patch.sprintId);
|
|
2457
|
+
let iterationId = plan.iterationId;
|
|
2458
|
+
let sprintLabel = plan.sprintLabel;
|
|
2459
|
+
if (patch.sprintId === undefined && plan.releaseId != null && plan.releaseId !== (doc['releaseId'] ?? null) && doc['iterationId'] != null) {
|
|
2460
|
+
iterationId = null;
|
|
2461
|
+
sprintLabel = 'none (it belonged to the old release)';
|
|
2462
|
+
}
|
|
2463
|
+
if (plan.releaseId !== undefined && plan.releaseId !== (doc['releaseId'] ?? null))
|
|
2464
|
+
change('release', 'releaseId', plan.releaseId, String(doc['releaseId'] ?? '(none)'), plan.releaseLabel ?? 'none');
|
|
2465
|
+
if (iterationId !== undefined && iterationId !== (doc['iterationId'] ?? null))
|
|
2466
|
+
change('sprint', 'iterationId', iterationId, String(doc['iterationId'] ?? '(none)'), sprintLabel ?? 'none');
|
|
2467
|
+
}
|
|
2468
|
+
// assignee
|
|
2469
|
+
let owners;
|
|
2470
|
+
let ownerLabel = '';
|
|
2471
|
+
if (patch.unassign) {
|
|
2472
|
+
owners = [];
|
|
2473
|
+
ownerLabel = 'Unassigned';
|
|
2474
|
+
}
|
|
2475
|
+
else if (patch.assignee !== undefined && String(patch.assignee).trim()) {
|
|
2476
|
+
const who = String(patch.assignee).trim();
|
|
2477
|
+
if (who.toLowerCase() === 'me') {
|
|
2478
|
+
const me = await this.ensureUserId();
|
|
2479
|
+
if (!me)
|
|
2480
|
+
throw new Error('Could not identify your user from the token, so "me" cannot be used. Pass an email or a user id.');
|
|
2481
|
+
owners = [Number.parseInt(me, 10)];
|
|
2482
|
+
}
|
|
2483
|
+
else {
|
|
2484
|
+
owners = await this.resolveUserIds([who]);
|
|
2485
|
+
}
|
|
2486
|
+
ownerLabel = who;
|
|
2487
|
+
}
|
|
2488
|
+
if (owners) {
|
|
2489
|
+
const current = (Array.isArray(doc['ownerId']) ? doc['ownerId'] : []).map(Number).sort((a, b) => a - b);
|
|
2490
|
+
if (JSON.stringify(current) !== JSON.stringify([...owners].sort((a, b) => a - b))) {
|
|
2491
|
+
change('assignee', 'ownerId', owners, current.length ? current.map((n) => `user ${n}`).join(', ') : 'Unassigned', ownerLabel || owners.join(', '));
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
// USER STORY field
|
|
2495
|
+
if (patch.storyId !== undefined) {
|
|
2496
|
+
const clear = String(patch.storyId).trim().toLowerCase() === 'none';
|
|
2497
|
+
let sid = null;
|
|
2498
|
+
if (!clear) {
|
|
2499
|
+
let lastErr;
|
|
2500
|
+
for (const v of SimplifyQaAdapter.codeVariants(String(patch.storyId))) {
|
|
2501
|
+
try {
|
|
2502
|
+
sid = Number.parseInt(await this.resolveStoryNumericId(v), 10);
|
|
2503
|
+
break;
|
|
2504
|
+
}
|
|
2505
|
+
catch (e) {
|
|
2506
|
+
lastErr = e;
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
if (sid === null || !Number.isFinite(sid))
|
|
2510
|
+
throw new Error(`No user story "${patch.storyId}" (${lastErr instanceof Error ? lastErr.message : 'not found'}). Pass its id or business key.`);
|
|
2511
|
+
}
|
|
2512
|
+
if (sid !== (doc['userstoryId'] ?? null))
|
|
2513
|
+
change('user story', 'userstoryId', sid, String(doc['userstoryId'] ?? '(none)'), clear ? 'none' : String(patch.storyId));
|
|
2514
|
+
}
|
|
2515
|
+
// TEST CASE field (selectedTestCase): add / replace per test case, remove, or clear
|
|
2516
|
+
const label = (e) => {
|
|
2517
|
+
const v = Array.isArray(e?.testcaseVersion) ? e.testcaseVersion[0]?.versionName : undefined;
|
|
2518
|
+
return `${e?.code ?? `#${e?.testcaseId ?? e}`}${v ? ` (${v})` : ''}`;
|
|
2519
|
+
};
|
|
2520
|
+
const currentTcs = Array.isArray(doc['selectedTestCase']) ? doc['selectedTestCase'] : [];
|
|
2521
|
+
let nextTcs = [...currentTcs];
|
|
2522
|
+
const added = [];
|
|
2523
|
+
if (patch.clearTestCases)
|
|
2524
|
+
nextTcs = [];
|
|
2525
|
+
for (const r of patch.removeTestCases ?? []) {
|
|
2526
|
+
const tcRef = String(r).split(/[:@]/)[0].trim();
|
|
2527
|
+
const before = nextTcs.length;
|
|
2528
|
+
nextTcs = nextTcs.filter((e) => ![String(e?.testcaseId), String(e?.code ?? '').toLowerCase()].some((k) => k === tcRef.toLowerCase() || k === tcRef));
|
|
2529
|
+
if (nextTcs.length === before)
|
|
2530
|
+
warnings.push(`${tcRef} was not among this defect's test cases.`);
|
|
2531
|
+
}
|
|
2532
|
+
for (const r of patch.testCases ?? []) {
|
|
2533
|
+
const e = await this.defectTestCaseEntry(r);
|
|
2534
|
+
if (e.versionNote)
|
|
2535
|
+
warnings.push(e.versionNote);
|
|
2536
|
+
const at = nextTcs.findIndex((x) => Number(x?.testcaseId) === e.tcId);
|
|
2537
|
+
if (at >= 0)
|
|
2538
|
+
nextTcs[at] = e.entry;
|
|
2539
|
+
else
|
|
2540
|
+
nextTcs.push(e.entry);
|
|
2541
|
+
added.push({ tcId: e.tcId, label: e.label });
|
|
2542
|
+
}
|
|
2543
|
+
const sig = (xs) => JSON.stringify(xs.map((x) => [Number(x?.testcaseId), Number(x?.testcaseVersion?.[0]?.version ?? 0)]).sort());
|
|
2544
|
+
if (sig(nextTcs) !== sig(currentTcs)) {
|
|
2545
|
+
change('test case', 'selectedTestCase', nextTcs, currentTcs.length ? currentTcs.map(label).join(', ') : '(none)', nextTcs.length ? nextTcs.map(label).join(', ') : '(none)');
|
|
2546
|
+
if ((patch.removeTestCases?.length || patch.clearTestCases) && !added.length) {
|
|
2547
|
+
warnings.push('SimplifyQA does not remove the defect from the removed test case\'s own linked-defects list when it is unlinked here.');
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
if (!shown.length)
|
|
2551
|
+
return { id: String(defectId), code, name, changes: [], written: false, warnings };
|
|
2552
|
+
// save (a stale version is retried once with the fresh one)
|
|
2553
|
+
const send = (d) => this.http.putJson(`/pm/defect/${defectId}`, { projectId, updateVersion: typeof d['updateVersion'] === 'number' ? d['updateVersion'] : 0, ...changes });
|
|
2554
|
+
try {
|
|
2555
|
+
try {
|
|
2556
|
+
await send(doc);
|
|
2557
|
+
}
|
|
2558
|
+
catch (e) {
|
|
2559
|
+
if (!/CONCURRENCY/i.test(e instanceof Error ? e.message : String(e)))
|
|
2560
|
+
throw e;
|
|
2561
|
+
await send((await this.readDefectDoc(defectId)) ?? doc);
|
|
2562
|
+
}
|
|
2563
|
+
}
|
|
2564
|
+
catch (e) {
|
|
2565
|
+
const m = e instanceof Error ? e.message : String(e);
|
|
2566
|
+
if (/INVALIDTOKEN|Don't Have Privileges|privilege/i.test(m)) {
|
|
2567
|
+
throw new Error(`Updating a defect needs the "add_defect" privilege in this project, and the connected user does not have it (${m}).`);
|
|
2568
|
+
}
|
|
2569
|
+
throw e;
|
|
2570
|
+
}
|
|
2571
|
+
// read the defect back and compare
|
|
2572
|
+
const after = await this.readDefectDoc(defectId);
|
|
2573
|
+
if (!after)
|
|
2574
|
+
throw new Error(`${code} was updated but could not be read back.`);
|
|
2575
|
+
for (const k of Object.keys(changes)) {
|
|
2576
|
+
const want = changes[k];
|
|
2577
|
+
const got = after[k];
|
|
2578
|
+
const same = k === 'ownerId'
|
|
2579
|
+
? JSON.stringify([...(Array.isArray(got) ? got : [])].map(Number).sort()) === JSON.stringify([...want].sort())
|
|
2580
|
+
: k === 'selectedTestCase'
|
|
2581
|
+
? sig(Array.isArray(got) ? got : []) === sig(want)
|
|
2582
|
+
: String(got ?? '') === String(want ?? '');
|
|
2583
|
+
if (!same)
|
|
2584
|
+
throw new Error(`${code}: "${k}" was sent as ${JSON.stringify(want).slice(0, 200)} but reads back as ${JSON.stringify(got).slice(0, 200)}.`);
|
|
2585
|
+
}
|
|
2586
|
+
// the test case's own linked-defects list is written by the backend with its failures swallowed — check it, repair it, re-check
|
|
2587
|
+
for (const t of added) {
|
|
2588
|
+
const hasIt = async () => {
|
|
2589
|
+
const raw = await this.fetchRawTestcase(String(t.tcId));
|
|
2590
|
+
const ids = (Array.isArray(raw['defectId']) ? raw['defectId'] : []).map(Number);
|
|
2591
|
+
return { ok: ids.includes(defectId), ids };
|
|
2592
|
+
};
|
|
2593
|
+
let state = await hasIt();
|
|
2594
|
+
if (!state.ok) {
|
|
2595
|
+
await this.http.putJson(`/tm/testcase/bulkupdate/${t.tcId}`, { projectId, defectId: [...state.ids, defectId] }).catch(() => undefined);
|
|
2596
|
+
state = await hasIt();
|
|
2597
|
+
}
|
|
2598
|
+
if (!state.ok)
|
|
2599
|
+
warnings.push(`${t.label}: the defect is saved with the test case, but the test case's own linked-defects list does not show ${code}.`);
|
|
2600
|
+
}
|
|
2601
|
+
return { id: String(defectId), code, name: String(after['name'] ?? name), changes: shown, written: true, warnings };
|
|
2602
|
+
}
|
|
2603
|
+
// ---------------------------------------------------------------------- Defect create
|
|
2604
|
+
/** Log a defect the way Defect Management → Create Defect does (`POST /pm/defect`), then read it back. The backend requires a name,
|
|
2605
|
+
* state and priority — defaulted here from the project's own defaults when not given — refuses a duplicate name, and (for a defect not
|
|
2606
|
+
* logged from an execution) enforces the project's mandatory custom fields, which it reports in its own words. The User Story and
|
|
2607
|
+
* Test Case fields are set as the form stores them, and each test case is checked to list the defect. */
|
|
2608
|
+
async createDefect(input) {
|
|
2609
|
+
const projectId = this.requireProjectId();
|
|
2610
|
+
const canon = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
2611
|
+
const name = String(input.name ?? '').trim();
|
|
2612
|
+
if (name.length < 3 || name.length > 500)
|
|
2613
|
+
throw new Error('A defect name needs 3–500 characters.');
|
|
2614
|
+
const warnings = [];
|
|
2615
|
+
const defaults = [];
|
|
2616
|
+
const clash = (await this.listDefects({ search: name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), limit: 50 })).find((d) => d.title.trim().toLowerCase() === name.toLowerCase());
|
|
2617
|
+
if (clash)
|
|
2618
|
+
throw new Error(`A defect named "${name}" already exists in this project: ${clash.code ?? `#${clash.id}`}. Use defect_update to change it, or pick another name.`);
|
|
2619
|
+
const pick = async (key, want, required) => {
|
|
2620
|
+
const values = await this.defaultFieldValues(9, key);
|
|
2621
|
+
if (want !== undefined) {
|
|
2622
|
+
if (!values.length)
|
|
2623
|
+
return want;
|
|
2624
|
+
const hit = values.find((v) => canon(v.key) === canon(want) || canon(v.value) === canon(want));
|
|
2625
|
+
if (!hit)
|
|
2626
|
+
throw new Error(`"${want}" is not a defect ${key} in this project. Valid: ${values.map((v) => v.key).join(', ')}.`);
|
|
2627
|
+
return hit.key;
|
|
2628
|
+
}
|
|
2629
|
+
const dflt = values.find((v) => v.isDefault) ?? (required ? values[0] : undefined);
|
|
2630
|
+
if (!dflt && required)
|
|
2631
|
+
throw new Error(`The project's defect ${key} values could not be read, and ${key} is required — pass \`${key}\`.`);
|
|
2632
|
+
if (dflt && required)
|
|
2633
|
+
defaults.push(`${key} ${dflt.key}`);
|
|
2634
|
+
return dflt?.key;
|
|
2635
|
+
};
|
|
2636
|
+
const state = await pick('state', input.state, true);
|
|
2637
|
+
const priority = await pick('priority', input.priority, true);
|
|
2638
|
+
const severity = await pick('severity', input.severity, false);
|
|
2639
|
+
const category = await pick('category', input.category, false);
|
|
2640
|
+
const plan = input.releaseId !== undefined || input.sprintId !== undefined ? await this.resolveTaskPlanning(input.releaseId, input.sprintId) : {};
|
|
2641
|
+
let ownerId;
|
|
2642
|
+
if (input.assignee !== undefined && String(input.assignee).trim()) {
|
|
2643
|
+
const who = String(input.assignee).trim();
|
|
2644
|
+
if (who.toLowerCase() === 'me') {
|
|
2645
|
+
const me = await this.ensureUserId();
|
|
2646
|
+
if (!me)
|
|
2647
|
+
throw new Error('Could not identify your user from the token, so "me" cannot be used. Pass an email or a user id.');
|
|
2648
|
+
ownerId = [Number.parseInt(me, 10)];
|
|
2649
|
+
}
|
|
2650
|
+
else {
|
|
2651
|
+
ownerId = await this.resolveUserIds([who]);
|
|
2652
|
+
}
|
|
2653
|
+
if (ownerId.length !== 1)
|
|
2654
|
+
throw new Error('A defect has exactly one assignee when it is created.');
|
|
2655
|
+
}
|
|
2656
|
+
let userstoryId;
|
|
2657
|
+
if (input.storyId !== undefined && String(input.storyId).trim()) {
|
|
2658
|
+
let lastErr;
|
|
2659
|
+
for (const v of SimplifyQaAdapter.codeVariants(String(input.storyId))) {
|
|
2660
|
+
try {
|
|
2661
|
+
userstoryId = Number.parseInt(await this.resolveStoryNumericId(v), 10);
|
|
2662
|
+
break;
|
|
2663
|
+
}
|
|
2664
|
+
catch (e) {
|
|
2665
|
+
lastErr = e;
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
if (userstoryId === undefined || !Number.isFinite(userstoryId))
|
|
2669
|
+
throw new Error(`No user story "${input.storyId}" (${lastErr instanceof Error ? lastErr.message : 'not found'}). Pass its id or business key.`);
|
|
2670
|
+
}
|
|
2671
|
+
const tcEntries = [];
|
|
2672
|
+
for (const r of input.testCases ?? []) {
|
|
2673
|
+
const e = await this.defectTestCaseEntry(r);
|
|
2674
|
+
if (e.versionNote)
|
|
2675
|
+
warnings.push(e.versionNote);
|
|
2676
|
+
if (!tcEntries.some((x) => x.tcId === e.tcId))
|
|
2677
|
+
tcEntries.push(e);
|
|
2678
|
+
}
|
|
2679
|
+
// the module: the caller's, else the project's "Default module" when it has one (the form's own default)
|
|
2680
|
+
let moduleId;
|
|
2681
|
+
if (input.module !== undefined && String(input.module).trim())
|
|
2682
|
+
moduleId = await this.resolveModuleId(input.module);
|
|
2683
|
+
else
|
|
2684
|
+
moduleId = await this.resolveModuleId('Default module').catch(() => undefined);
|
|
2685
|
+
if (moduleId !== undefined && !Number.isFinite(moduleId))
|
|
2686
|
+
moduleId = undefined;
|
|
2687
|
+
const body = {
|
|
2688
|
+
projectId, name, state, priority, description: input.description ?? '',
|
|
2689
|
+
...(severity ? { severity } : {}), ...(category ? { category } : {}),
|
|
2690
|
+
...(ownerId ? { ownerId } : {}),
|
|
2691
|
+
...(plan.releaseId != null ? { releaseId: plan.releaseId } : {}), ...(plan.iterationId != null ? { iterationId: plan.iterationId } : {}),
|
|
2692
|
+
...(userstoryId !== undefined ? { userstoryId } : {}),
|
|
2693
|
+
...(tcEntries.length ? { selectedTestCase: tcEntries.map((t) => t.entry) } : {}),
|
|
2694
|
+
...(moduleId ? { moduleId } : {}),
|
|
2695
|
+
...(input.estimatedEffort !== undefined ? { estimatedEffort: input.estimatedEffort } : {}),
|
|
2696
|
+
customFields: input.customFields ?? {},
|
|
2697
|
+
};
|
|
2698
|
+
let raw;
|
|
2699
|
+
try {
|
|
2700
|
+
raw = await this.http.postJson('/pm/defect', body);
|
|
2701
|
+
}
|
|
2702
|
+
catch (e) {
|
|
2703
|
+
const m = e instanceof Error ? e.message : String(e);
|
|
2704
|
+
if (/INVALIDTOKEN|Don't Have Privileges|privilege/i.test(m)) {
|
|
2705
|
+
throw new Error(`Logging a defect needs the "add_defect" privilege in this project, and the connected user does not have it (${m}).`);
|
|
2706
|
+
}
|
|
2707
|
+
if (/mandatory|required.*custom|custom.*required/i.test(m)) {
|
|
2708
|
+
throw new Error(`This project requires custom fields on a defect: ${m} Pass them as \`customFields\` ({ "<field key>": value }).`);
|
|
2709
|
+
}
|
|
2710
|
+
throw e;
|
|
2711
|
+
}
|
|
2712
|
+
const made = raw?.data && typeof raw.data === 'object' && !Array.isArray(raw.data) ? raw.data : raw;
|
|
2713
|
+
const defectId = Number(made?.id);
|
|
2714
|
+
const doc = Number.isFinite(defectId) ? await this.readDefectDoc(defectId) : undefined;
|
|
2715
|
+
if (!doc)
|
|
2716
|
+
throw new Error(`The defect "${name}" was sent, but it could not be read back.`);
|
|
2717
|
+
const defectCode = String(doc['code'] ?? `#${defectId}`);
|
|
2718
|
+
if (String(doc['name'] ?? '') !== name)
|
|
2719
|
+
throw new Error(`${defectCode} reads back as "${String(doc['name'] ?? '')}", not "${name}".`);
|
|
2720
|
+
if (userstoryId !== undefined && Number(doc['userstoryId']) !== userstoryId)
|
|
2721
|
+
warnings.push(`${defectCode}: the user story did not read back as sent (${String(doc['userstoryId'] ?? 'empty')}).`);
|
|
2722
|
+
for (const t of tcEntries) {
|
|
2723
|
+
if (!(await this.ensureTestCaseListsDefect(t.tcId, defectId).catch(() => false))) {
|
|
2724
|
+
warnings.push(`${t.label}: the defect is saved with the test case, but the test case's own linked-defects list does not show ${defectCode}.`);
|
|
2725
|
+
}
|
|
2726
|
+
}
|
|
2727
|
+
return {
|
|
2728
|
+
defectId: String(defectId), defectCode, name, state: String(doc['state'] ?? state ?? ''), priority: String(doc['priority'] ?? priority ?? ''),
|
|
2729
|
+
...(severity ? { severity: String(doc['severity'] ?? severity) } : {}), testCases: tcEntries.map((t) => t.label),
|
|
2730
|
+
...(userstoryId !== undefined ? { storyId: userstoryId } : {}), defaults, warnings,
|
|
2731
|
+
};
|
|
2732
|
+
}
|
|
2733
|
+
// ---------------------------------------------------------------------- Defects from a failed step
|
|
2734
|
+
/** Make sure a test case's own linked-defects list shows the defect. The backend writes it when a defect is saved with the test case,
|
|
2735
|
+
* but swallows any failure — so check it, redo it through the same endpoint when missing, check again. */
|
|
2736
|
+
async ensureTestCaseListsDefect(tcId, defectId) {
|
|
2737
|
+
const projectId = this.requireProjectId();
|
|
2738
|
+
const read = async () => {
|
|
2739
|
+
const raw = await this.fetchRawTestcase(String(tcId));
|
|
2740
|
+
const ids = (Array.isArray(raw['defectId']) ? raw['defectId'] : []).map(Number);
|
|
2741
|
+
return { ok: ids.includes(defectId), ids };
|
|
2742
|
+
};
|
|
2743
|
+
let state = await read();
|
|
2744
|
+
if (!state.ok) {
|
|
2745
|
+
await this.http.putJson(`/tm/testcase/bulkupdate/${tcId}`, { projectId, defectId: [...state.ids, defectId] }).catch(() => undefined);
|
|
2746
|
+
state = await read();
|
|
2747
|
+
}
|
|
2748
|
+
return state.ok;
|
|
2749
|
+
}
|
|
2750
|
+
/** The failed step an execution report shows — with its run, test case and version — found by execution id (EX-170), step number
|
|
2751
|
+
* and, for an execution of several test cases, the test case. Only a FAILED step can be logged / linked, as in the report. */
|
|
2752
|
+
async resolveFailedStep(executionRef, step, tcRef) {
|
|
2753
|
+
const projectId = this.requireProjectId();
|
|
2754
|
+
const execId = Number.parseInt(numericId(String(executionRef ?? '')), 10);
|
|
2755
|
+
if (!Number.isFinite(execId))
|
|
2756
|
+
throw new Error(`"${executionRef}" is not an execution id (e.g. EX-170 or 170).`);
|
|
2757
|
+
if (!Number.isInteger(step) || step < 1)
|
|
2758
|
+
throw new Error('step must be the step number shown in the report (1, 2, 3 …).');
|
|
2759
|
+
const execDoc = await this.fetchExecDoc(execId, projectId);
|
|
2760
|
+
if (!execDoc)
|
|
2761
|
+
throw new Error(`No execution ${executionRef} in this project.`);
|
|
2762
|
+
const execCode = String(execDoc.code ?? `EX-${execId}`);
|
|
2763
|
+
const rawRuns = await this.http.getJson(`/exec/report/${execId}/${projectId}`);
|
|
2764
|
+
let runs = (Array.isArray(rawRuns) ? notDeleted(rawRuns) : []);
|
|
2765
|
+
if (!runs.length)
|
|
2766
|
+
throw new Error(`${execCode} has no results yet — it may not have run.`);
|
|
2767
|
+
const tcOf = (r) => Number(str(r, 'testcaseId') ?? r?.executionItemId ?? execDoc.executionTypeId);
|
|
2768
|
+
if (tcRef) {
|
|
2769
|
+
let want = /^\d+$/.test(tcRef.trim()) ? Number.parseInt(tcRef.trim(), 10) : undefined;
|
|
2770
|
+
if (want === undefined) {
|
|
2771
|
+
for (const code of SimplifyQaAdapter.codeVariants(tcRef)) {
|
|
2772
|
+
const body = this.searchBody([{ column: 'code', value: code }, { column: 'projectId', value: projectId }, { column: 'deleted', value: false }], { startIndex: 0, limit: 5, selectFields: ['id', 'code'] });
|
|
2773
|
+
const hit = pickArray(await this.http.postJson('/tm/testcase/search', body), 'data', 'content', 'testCases')
|
|
2774
|
+
.find((r) => String(r?.code ?? '').toLowerCase() === code.toLowerCase());
|
|
2775
|
+
if (hit) {
|
|
2776
|
+
want = Number.parseInt(str(hit, 'id', '_id') ?? '', 10);
|
|
2777
|
+
break;
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
}
|
|
2781
|
+
runs = runs.filter((r) => tcOf(r) === want);
|
|
2782
|
+
if (!runs.length)
|
|
2783
|
+
throw new Error(`${execCode} has no run of test case "${tcRef}".`);
|
|
2784
|
+
}
|
|
2785
|
+
if (runs.length > 1) {
|
|
2786
|
+
throw new Error(`${execCode} ran ${runs.length} test cases (ids ${runs.map(tcOf).join(', ')}). Say which one with \`tc\`.`);
|
|
2787
|
+
}
|
|
2788
|
+
const run = runs[0];
|
|
2789
|
+
const runId = str(run, 'id', '_id') ?? '';
|
|
2790
|
+
const parentId = Number(run?.executionItemId ?? 0);
|
|
2791
|
+
const resp = await this.http.postJson('/reports/execution/getstepResult', { executionId: execId, executionRunId: runId, parentId, projectId });
|
|
2792
|
+
const rows = Array.isArray(resp?.data) ? notDeleted(resp.data) : [];
|
|
2793
|
+
const noise = new Set(['FUNCTION', 'FUNCTION_ITERATION_START', 'FUNCTION_ITERATION_END', 'FUNCTION_END', 'INFO']);
|
|
2794
|
+
const candidates = rows.filter((r) => Number(r?.seq) === step && !noise.has(String(r?.stepType ?? '').toUpperCase()));
|
|
2795
|
+
if (!candidates.length) {
|
|
2796
|
+
const known = rows.filter((r) => !noise.has(String(r?.stepType ?? '').toUpperCase())).map((r) => `${r.seq}:${String(r.status ?? '').toLowerCase()}`).join(', ');
|
|
2797
|
+
throw new Error(`${execCode} has no step ${step}. Steps: ${known || '(none)'}.`);
|
|
2798
|
+
}
|
|
2799
|
+
const row = candidates.find((r) => String(r?.status ?? '').toUpperCase() === 'FAILED');
|
|
2800
|
+
if (!row) {
|
|
2801
|
+
throw new Error(`Step ${step} of ${execCode} is ${String(candidates[0]?.status ?? 'not executed').toLowerCase()}, not failed — only a failed step can be logged or linked, as in the report.`);
|
|
2802
|
+
}
|
|
2803
|
+
const tcId = tcOf(run);
|
|
2804
|
+
const tcRaw = await this.fetchRawTestcase(String(tcId));
|
|
2805
|
+
if (!tcRaw || tcRaw['id'] === undefined)
|
|
2806
|
+
throw new Error(`The test case of ${execCode} (id ${tcId}) could not be read.`);
|
|
2807
|
+
const versions = Array.isArray(tcRaw['versions']) ? tcRaw['versions'] : [];
|
|
2808
|
+
const versionId = String(row.versionId ?? str(run, 'versionId') ?? '');
|
|
2809
|
+
const version = versions.find((v) => str(v, 'id', '_id') === versionId);
|
|
2810
|
+
const versionName = String(version?.name ?? versions[0]?.name ?? '');
|
|
2811
|
+
const tcLabel = `${tcRaw['code'] ?? `#${tcId}`}${versionName ? ` (${versionName})` : ''}`;
|
|
2812
|
+
// the report's own wording of why it failed (exception / ERROR log lines / API assertion), for the defect text
|
|
2813
|
+
const mapped = await this.fetchStepResults(execId, runId, parentId, projectId).catch(() => []);
|
|
2814
|
+
const error = mapped.find((m) => m.n === step && m.status === 'failed')?.error;
|
|
2815
|
+
return { execId, execCode, execDoc, run, rows, row, error, tcId, tcRaw, tcLabel, versionId, versionName };
|
|
2816
|
+
}
|
|
2817
|
+
/** Add defect ids to a step result — the way the report's "link defect" does (`POST /exec/stepResult?from=reports` with the stored
|
|
2818
|
+
* step result). That save overwrites status, testdata, actualResult, screenShots and defectIds with what it is sent, so the stored
|
|
2819
|
+
* values go back unchanged, and the step is read again to prove nothing else moved. */
|
|
2820
|
+
async addDefectsToStep(execId, runId, parentId, row, defectIds) {
|
|
2821
|
+
const projectId = this.requireProjectId();
|
|
2822
|
+
const merged = [...new Set([...(Array.isArray(row['defectIds']) ? row['defectIds'] : []).map(Number), ...defectIds])];
|
|
2823
|
+
// what must still be true afterwards — copied BEFORE the write, so a later change to the same objects cannot hide a difference
|
|
2824
|
+
const before = JSON.parse(JSON.stringify({ status: row['status'] ?? null, testdata: row['testdata'] ?? null, actualResult: row['actualResult'] ?? null, screenShots: row['screenShots'] ?? null }));
|
|
2825
|
+
const doc = { ...row, defectIds: merged };
|
|
2826
|
+
for (const k of ['_id', 'executionId', 'updatedAt', 'customerId', 'deleted', 'projectId', 'margin', 'attachments', 'children', 'createdAt',
|
|
2827
|
+
'lineCount', 'technologyType', 'copiedBaseLinepath', 'copiedThumbnailpath', 'tempSubSteps', 'conditions'])
|
|
2828
|
+
delete doc[k];
|
|
2829
|
+
await this.http.postJson(`/exec/stepResult?executionId=${execId}&projectId=${projectId}&from=reports`, [doc]);
|
|
2830
|
+
const resp = await this.http.postJson('/reports/execution/getstepResult', { executionId: execId, executionRunId: runId, parentId, projectId });
|
|
2831
|
+
const after = (Array.isArray(resp?.data) ? notDeleted(resp.data) : []).find((r) => r?.id === row['id']);
|
|
2832
|
+
if (!after)
|
|
2833
|
+
throw new Error('The step result could not be read back after linking the defect.');
|
|
2834
|
+
const got = (Array.isArray(after['defectIds']) ? after['defectIds'] : []).map(Number);
|
|
2835
|
+
if (!defectIds.every((d) => got.includes(d)))
|
|
2836
|
+
throw new Error(`The step result reads back with defects ${JSON.stringify(got)}, not ${JSON.stringify(merged)}.`);
|
|
2837
|
+
for (const k of ['status', 'testdata', 'actualResult', 'screenShots']) {
|
|
2838
|
+
if (JSON.stringify(after[k] ?? null) !== JSON.stringify(before[k] ?? null)) {
|
|
2839
|
+
throw new Error(`Linking the defect changed the step's ${k} — it does not read back as it was. Check the report before relying on it.`);
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2842
|
+
}
|
|
2843
|
+
/** "Log Defect" on a failed step of an execution report: create the defect pre-filled with the test case + version, the steps to
|
|
2844
|
+
* replicate up to the failure, the execution, environment, browser, expected / actual and error, and the step's screenshots, then
|
|
2845
|
+
* link it to the step. */
|
|
2846
|
+
async logDefectFromStep(input) {
|
|
2847
|
+
const projectId = this.requireProjectId();
|
|
2848
|
+
const canon = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
2849
|
+
const f = await this.resolveFailedStep(input.executionId, input.step, input.tc);
|
|
2850
|
+
const warnings = [];
|
|
2851
|
+
const esc = (v) => String(v ?? '').replace(/<[^>]*>/g, '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').trim();
|
|
2852
|
+
const stepText = esc(f.row['description']) || `step ${input.step}`;
|
|
2853
|
+
const name = (input.name ?? `${f.tcRaw['code'] ?? `TC-${f.tcId}`} step ${input.step} failed: ${stepText.slice(0, 80)} (${f.execCode})`).trim();
|
|
2854
|
+
if (name.length < 3 || name.length > 500)
|
|
2855
|
+
throw new Error('A defect name needs 3–500 characters.');
|
|
2856
|
+
const clash = (await this.listDefects({ search: name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), limit: 50 })).find((d) => d.title.trim().toLowerCase() === name.toLowerCase());
|
|
2857
|
+
if (clash) {
|
|
2858
|
+
throw new Error(`A defect named "${name}" already exists: ${clash.code ?? `#${clash.id}`}. If it is the same failure, link it with defect_link_step; otherwise pass a different \`name\`.`);
|
|
2859
|
+
}
|
|
2860
|
+
const already = (Array.isArray(f.row['defectIds']) ? f.row['defectIds'] : []).length;
|
|
2861
|
+
if (already)
|
|
2862
|
+
warnings.push(`Step ${input.step} already has ${already} defect(s) linked; this one is added to them.`);
|
|
2863
|
+
const pick = async (key, want, required) => {
|
|
2864
|
+
const values = await this.defaultFieldValues(9, key);
|
|
2865
|
+
if (want !== undefined) {
|
|
2866
|
+
if (!values.length)
|
|
2867
|
+
return want;
|
|
2868
|
+
const hit = values.find((v) => canon(v.key) === canon(want) || canon(v.value) === canon(want));
|
|
2869
|
+
if (!hit)
|
|
2870
|
+
throw new Error(`"${want}" is not a defect ${key} in this project. Valid: ${values.map((v) => v.key).join(', ')}.`);
|
|
2871
|
+
return hit.key;
|
|
2872
|
+
}
|
|
2873
|
+
const dflt = values.find((v) => v.isDefault) ?? (required ? values[0] : undefined);
|
|
2874
|
+
if (!dflt && required)
|
|
2875
|
+
throw new Error(`The project's defect ${key} values could not be read, and ${key} is required — pass \`${key}\`.`);
|
|
2876
|
+
return dflt?.key;
|
|
2877
|
+
};
|
|
2878
|
+
const state = await pick('state', input.state, true);
|
|
2879
|
+
const priority = await pick('priority', input.priority, true);
|
|
2880
|
+
const severity = await pick('severity', input.severity, false);
|
|
2881
|
+
let ownerId;
|
|
2882
|
+
if (input.assignee !== undefined && String(input.assignee).trim()) {
|
|
2883
|
+
const who = String(input.assignee).trim();
|
|
2884
|
+
if (who.toLowerCase() === 'me') {
|
|
2885
|
+
const me = await this.ensureUserId();
|
|
2886
|
+
if (!me)
|
|
2887
|
+
throw new Error('Could not identify your user from the token, so "me" cannot be used. Pass an email or a user id.');
|
|
2888
|
+
ownerId = [Number.parseInt(me, 10)];
|
|
2889
|
+
}
|
|
2890
|
+
else {
|
|
2891
|
+
ownerId = await this.resolveUserIds([who]);
|
|
2892
|
+
}
|
|
2893
|
+
if (ownerId.length !== 1)
|
|
2894
|
+
throw new Error('A defect has exactly one assignee when it is created.');
|
|
2895
|
+
}
|
|
2896
|
+
// description: what the report writes (steps to replicate, up to the failed step) under a header with the evidence
|
|
2897
|
+
const noise = new Set(['FUNCTION', 'FUNCTION_ITERATION_START', 'FUNCTION_ITERATION_END', 'FUNCTION_END', 'INFO']);
|
|
2898
|
+
const usable = f.rows.filter((r) => !noise.has(String(r?.stepType ?? '').toUpperCase()));
|
|
2899
|
+
const upTo = [];
|
|
2900
|
+
for (const r of usable) {
|
|
2901
|
+
upTo.push(r);
|
|
2902
|
+
if (r.stepId === f.row['stepId'] && String(r.status).toUpperCase() === 'FAILED')
|
|
2903
|
+
break;
|
|
2904
|
+
}
|
|
2905
|
+
const platform = Array.isArray(f.row['platform']) ? f.row['platform'][0] : undefined;
|
|
2906
|
+
const browser = String(platform?.name ?? '').trim();
|
|
2907
|
+
const environment = String(f.execDoc.environment ?? '').trim();
|
|
2908
|
+
const expected = esc(f.row['expectedResult']);
|
|
2909
|
+
const actual = esc(f.row['actualResult']);
|
|
2910
|
+
const why = esc(f.error ?? f.row['exception']);
|
|
2911
|
+
let html = `<strong>Logged from execution ${esc(f.execCode)}</strong><br>` +
|
|
2912
|
+
`Test case: ${esc(f.tcLabel)} ${esc(f.tcRaw['name'])}<br>` +
|
|
2913
|
+
`Failed step ${input.step}: ${stepText}<br>` +
|
|
2914
|
+
(environment ? `Environment: ${esc(environment)}<br>` : '') + (browser ? `Browser: ${esc(browser)}<br>` : '') +
|
|
2915
|
+
(expected ? `<strong>Expected:</strong> ${expected}<br>` : '') + (actual ? `<strong>Actual:</strong> ${actual}<br>` : '') +
|
|
2916
|
+
(why ? `<strong>Error:</strong> ${why}<br>` : '') +
|
|
2917
|
+
(input.description ? `<br>${esc(input.description)}<br>` : '') + '<br><strong>Steps to replicate:</strong><br>';
|
|
2918
|
+
let j = 1;
|
|
2919
|
+
for (const r of upTo) {
|
|
2920
|
+
const status = String(r.status).toUpperCase();
|
|
2921
|
+
const text = esc(r.description);
|
|
2922
|
+
if ((status === 'PASSED' || status === 'FAILED') && text) {
|
|
2923
|
+
html += `<span style="color:${status === 'PASSED' ? 'rgb(124,252,0)' : 'rgb(255,0,0)'};">[${status === 'PASSED' ? 'PASS' : 'FAIL'}]</span> ${j}. ${text}<br>`;
|
|
2924
|
+
for (const td of Array.isArray(r.testdata) ? r.testdata : [])
|
|
2925
|
+
html += `<span style="color:rgb(0,0,0);">[TESTDATA]</span> : ${esc(td?.paramName)} = ${esc(td?.value)}<br>`;
|
|
2926
|
+
j++;
|
|
2927
|
+
}
|
|
2928
|
+
}
|
|
2929
|
+
const attachments = [
|
|
2930
|
+
...(Array.isArray(f.row['attachments']) ? f.row['attachments'] : []),
|
|
2931
|
+
...(Array.isArray(f.row['screenShots']) ? f.row['screenShots'] : []),
|
|
2932
|
+
];
|
|
2933
|
+
if (!attachments.length)
|
|
2934
|
+
warnings.push('The failed step has no screenshot, so none is attached.');
|
|
2935
|
+
const releaseId = Number(f.execDoc.releaseId) || undefined;
|
|
2936
|
+
const iterationId = Number(f.execDoc.iterationId) || undefined;
|
|
2937
|
+
const body = {
|
|
2938
|
+
projectId, name, state, priority, description: html,
|
|
2939
|
+
...(severity ? { severity } : {}),
|
|
2940
|
+
...(ownerId ? { ownerId } : {}),
|
|
2941
|
+
...(releaseId ? { releaseId } : {}), ...(iterationId ? { iterationId } : {}),
|
|
2942
|
+
...(f.tcRaw['moduleId'] ? { moduleId: Number(f.tcRaw['moduleId']) } : {}),
|
|
2943
|
+
attachments,
|
|
2944
|
+
networkLogs: Array.isArray(f.row['networkLogs']) ? f.row['networkLogs'] : [],
|
|
2945
|
+
selectedTestCase: [{
|
|
2946
|
+
code: String(f.tcRaw['code'] ?? ''), deleted: false, name: String(f.tcRaw['name'] ?? ''), testcaseId: f.tcId,
|
|
2947
|
+
testcaseVersion: [{ deleted: false, version: Number(f.versionId) || f.versionId, versionName: f.versionName }],
|
|
2948
|
+
}],
|
|
2949
|
+
fromExecution: true,
|
|
2950
|
+
};
|
|
2951
|
+
let raw;
|
|
2952
|
+
try {
|
|
2953
|
+
raw = await this.http.postJson('/pm/defect', body);
|
|
2954
|
+
}
|
|
2955
|
+
catch (e) {
|
|
2956
|
+
const m = e instanceof Error ? e.message : String(e);
|
|
2957
|
+
if (/INVALIDTOKEN|Don't Have Privileges|privilege/i.test(m)) {
|
|
2958
|
+
throw new Error(`Logging a defect needs the "add_defect" privilege in this project, and the connected user does not have it (${m}).`);
|
|
2959
|
+
}
|
|
2960
|
+
throw e;
|
|
2961
|
+
}
|
|
2962
|
+
const made = raw?.data && typeof raw.data === 'object' && !Array.isArray(raw.data) ? raw.data : raw;
|
|
2963
|
+
const defectId = Number(made?.id);
|
|
2964
|
+
const doc = Number.isFinite(defectId) ? await this.readDefectDoc(defectId) : undefined;
|
|
2965
|
+
if (!doc)
|
|
2966
|
+
throw new Error(`The defect "${name}" was sent, but it could not be read back.`);
|
|
2967
|
+
const defectCode = String(doc['code'] ?? `#${defectId}`);
|
|
2968
|
+
// link it to the failed step, then make sure the test case lists it
|
|
2969
|
+
const runId = str(f.run, 'id', '_id') ?? '';
|
|
2970
|
+
let linkedToStep = false;
|
|
2971
|
+
try {
|
|
2972
|
+
await this.addDefectsToStep(f.execId, runId, Number(f.run?.executionItemId ?? 0), f.row, [defectId]);
|
|
2973
|
+
linkedToStep = true;
|
|
2974
|
+
}
|
|
2975
|
+
catch (e) {
|
|
2976
|
+
warnings.push(`${defectCode} was created, but linking it to step ${input.step} failed: ${(e instanceof Error ? e.message : String(e)).replace(/\.$/, '')}. Use defect_link_step to retry.`);
|
|
2977
|
+
}
|
|
2978
|
+
if (!(await this.ensureTestCaseListsDefect(f.tcId, defectId).catch(() => false))) {
|
|
2979
|
+
warnings.push(`${f.tcLabel}: the defect is saved with the test case, but the test case's own linked-defects list does not show ${defectCode}.`);
|
|
2980
|
+
}
|
|
2981
|
+
return {
|
|
2982
|
+
defectId: String(defectId), defectCode, name, execution: f.execCode, testCase: f.tcLabel, step: input.step, attachments: attachments.length,
|
|
2983
|
+
linkedToStep, state: String(doc['state'] ?? state ?? ''), priority: String(doc['priority'] ?? priority ?? ''), warnings,
|
|
2984
|
+
};
|
|
2985
|
+
}
|
|
2986
|
+
/** Link a failed step to an EXISTING defect (DE-60): the defect id goes onto the step result (what the report shows), and the step's
|
|
2987
|
+
* test case + version is added to the defect's TEST CASE field so the link also shows from the defect and the test case. */
|
|
2988
|
+
async linkDefectToStep(input) {
|
|
2989
|
+
const f = await this.resolveFailedStep(input.executionId, input.step, input.tc);
|
|
2990
|
+
const defect = await this.findDefectDoc(input.defectId);
|
|
2991
|
+
const defectId = Number(defect['id']);
|
|
2992
|
+
const defectCode = String(defect['code'] ?? `#${defectId}`);
|
|
2993
|
+
const warnings = [];
|
|
2994
|
+
const have = (Array.isArray(f.row['defectIds']) ? f.row['defectIds'] : []).map(Number);
|
|
2995
|
+
let stepLinked = false;
|
|
2996
|
+
if (!have.includes(defectId)) {
|
|
2997
|
+
await this.addDefectsToStep(f.execId, str(f.run, 'id', '_id') ?? '', Number(f.run?.executionItemId ?? 0), f.row, [defectId]);
|
|
2998
|
+
stepLinked = true;
|
|
2999
|
+
}
|
|
3000
|
+
const onDefect = (Array.isArray(defect['selectedTestCase']) ? defect['selectedTestCase'] : []).some((e) => Number(e?.testcaseId) === f.tcId);
|
|
3001
|
+
let testCaseLinked = false;
|
|
3002
|
+
if (!onDefect) {
|
|
3003
|
+
const r = await this.updateDefect(String(defectId), { testCases: [f.versionName ? `${f.tcId}:${f.versionName}` : String(f.tcId)] });
|
|
3004
|
+
warnings.push(...r.warnings);
|
|
3005
|
+
testCaseLinked = r.written;
|
|
3006
|
+
}
|
|
3007
|
+
else if (!(await this.ensureTestCaseListsDefect(f.tcId, defectId).catch(() => false))) {
|
|
3008
|
+
warnings.push(`${f.tcLabel}: the test case's own linked-defects list does not show ${defectCode}.`);
|
|
3009
|
+
}
|
|
3010
|
+
return { defectCode, defectName: String(defect['name'] ?? ''), execution: f.execCode, testCase: f.tcLabel, step: input.step, stepLinked, testCaseLinked, warnings };
|
|
3011
|
+
}
|
|
1850
3012
|
// ---------------------------------------------------------------------- Backlog defaults
|
|
1851
3013
|
/** Fetch the project's default `state` and `priority` for a backlog entity.
|
|
1852
3014
|
* parentId: 1 = Epic, 2 = Feature, 3 = User Story. Two-source resolution, in order:
|
|
@@ -2002,6 +3164,90 @@ export class SimplifyQaAdapter {
|
|
|
2002
3164
|
const rows = Array.isArray(raw) ? raw : pickArray(raw, 'data', 'content', 'attachments');
|
|
2003
3165
|
return Array.isArray(rows) ? rows.filter((a) => a?.['deleted'] !== true) : [];
|
|
2004
3166
|
}
|
|
3167
|
+
/** Download attachments of an epic / feature / user story from SimplifyQA into a local folder. The file is fetched from the attachment's
|
|
3168
|
+
* `/download/…` URL through the SAME authenticated client the rest of the MCP uses (the user's token goes with the request — and only to the
|
|
3169
|
+
* connected SimplifyQA host). With one attachment and no choice it downloads it; with several and no choice it lists them instead
|
|
3170
|
+
* (`needsChoice`) so the caller can ask. Each saved file is compared with the size SimplifyQA reports, and a web page standing in for the file
|
|
3171
|
+
* (an expired login) is refused rather than saved as a "download". Never overwrites: a name that exists gets " (1)". */
|
|
3172
|
+
async downloadAttachments(input) {
|
|
3173
|
+
if (!this.http.getBinary)
|
|
3174
|
+
throw new Error('This connection cannot download files.');
|
|
3175
|
+
const base = (this.cfg.baseUrl ?? '').replace(/\/+$/, '');
|
|
3176
|
+
const rows = await this.entityAttachments(input.entityType, input.itemId);
|
|
3177
|
+
const nameOf = (a) => String(a['original_name'] ?? a['name'] ?? '').trim();
|
|
3178
|
+
const sizeOf = (a) => {
|
|
3179
|
+
const n = typeof a['size'] === 'number' ? a['size'] : Number(a['size'] ?? a['fileSize']);
|
|
3180
|
+
return Number.isFinite(n) && n > 0 ? n : undefined;
|
|
3181
|
+
};
|
|
3182
|
+
const available = rows.map((a) => ({ id: String(a['id'] ?? ''), name: nameOf(a), ...(sizeOf(a) !== undefined ? { bytes: sizeOf(a) } : {}) }));
|
|
3183
|
+
if (!rows.length)
|
|
3184
|
+
throw new Error(`${input.entityType} ${input.itemId} has no attachments.`);
|
|
3185
|
+
let chosen;
|
|
3186
|
+
if (input.all)
|
|
3187
|
+
chosen = rows;
|
|
3188
|
+
else if (input.attachments?.length) {
|
|
3189
|
+
chosen = [];
|
|
3190
|
+
for (const ref of input.attachments) {
|
|
3191
|
+
const want = String(ref).trim().toLowerCase();
|
|
3192
|
+
const hits = rows.filter((a) => String(a['id'] ?? '').toLowerCase() === want || String(a['name'] ?? '').toLowerCase() === want || nameOf(a).toLowerCase() === want);
|
|
3193
|
+
if (!hits.length)
|
|
3194
|
+
throw new Error(`${input.entityType} ${input.itemId} has no attachment "${ref}". It has: ${available.map((a) => a.name).join(', ')}.`);
|
|
3195
|
+
if (hits.length > 1)
|
|
3196
|
+
throw new Error(`"${ref}" matches ${hits.length} attachments (ids ${hits.map((h) => String(h['id'])).join(', ')}) — pass the id.`);
|
|
3197
|
+
if (!chosen.includes(hits[0]))
|
|
3198
|
+
chosen.push(hits[0]);
|
|
3199
|
+
}
|
|
3200
|
+
}
|
|
3201
|
+
else if (rows.length === 1)
|
|
3202
|
+
chosen = rows;
|
|
3203
|
+
else
|
|
3204
|
+
return { files: [], available, needsChoice: true, warnings: [] };
|
|
3205
|
+
const dir = resolvePath(input.outDir);
|
|
3206
|
+
await mkdir(dir, { recursive: true });
|
|
3207
|
+
const files = [];
|
|
3208
|
+
const warnings = [];
|
|
3209
|
+
for (const a of chosen) {
|
|
3210
|
+
const name = nameOf(a) || String(a['name'] ?? 'attachment');
|
|
3211
|
+
const url = String(a['url'] ?? '').trim();
|
|
3212
|
+
if (!url)
|
|
3213
|
+
throw new Error(`"${name}" has no download URL in SimplifyQA.`);
|
|
3214
|
+
let path;
|
|
3215
|
+
if (/^https?:\/\//i.test(url)) {
|
|
3216
|
+
if (!base || !url.startsWith(`${base}/`))
|
|
3217
|
+
throw new Error(`"${name}" points outside the connected SimplifyQA host (${url}) — not sending your token there.`);
|
|
3218
|
+
path = url.slice(base.length);
|
|
3219
|
+
}
|
|
3220
|
+
else
|
|
3221
|
+
path = url.startsWith('/') ? url : `/${url}`;
|
|
3222
|
+
path = path.split('/').map((seg) => (/%[0-9A-Fa-f]{2}/.test(seg) ? seg : encodeURIComponent(seg))).join('/');
|
|
3223
|
+
let res;
|
|
3224
|
+
try {
|
|
3225
|
+
res = await this.http.getBinary(path);
|
|
3226
|
+
}
|
|
3227
|
+
catch (e) {
|
|
3228
|
+
throw new Error(`Could not download "${name}": ${e instanceof Error ? e.message : String(e)}`);
|
|
3229
|
+
}
|
|
3230
|
+
const head = Buffer.from(res.data.subarray(0, 200)).toString('utf8').trimStart().toLowerCase();
|
|
3231
|
+
const looksHtml = /text\/html/i.test(res.contentType) || head.startsWith('<!doctype html') || head.startsWith('<html');
|
|
3232
|
+
if (looksHtml && !/\.(html?|svg)$/i.test(name)) {
|
|
3233
|
+
throw new Error(`Downloading "${name}" returned a web page, not the file — the login may have expired. Reconnect (qa_connect) and try again.`);
|
|
3234
|
+
}
|
|
3235
|
+
if (res.data.byteLength === 0)
|
|
3236
|
+
throw new Error(`"${name}" downloaded empty (0 bytes) — nothing was saved.`);
|
|
3237
|
+
const safeName = name.replace(/[\\/:*?"<>|\u0000-\u001f]+/g, '_').replace(/^\.+/, '').trim() || 'attachment';
|
|
3238
|
+
const { name: stem, ext } = parsePath(safeName);
|
|
3239
|
+
let target = join(dir, safeName);
|
|
3240
|
+
for (let i = 1; await access(target).then(() => true, () => false); i++)
|
|
3241
|
+
target = join(dir, `${stem} (${i})${ext}`);
|
|
3242
|
+
await writeFile(target, res.data);
|
|
3243
|
+
const reported = sizeOf(a);
|
|
3244
|
+
const sizeMatches = reported === undefined ? null : reported === res.data.byteLength;
|
|
3245
|
+
if (sizeMatches === false)
|
|
3246
|
+
warnings.push(`"${name}": downloaded ${res.data.byteLength} bytes, but SimplifyQA reports ${reported} — the file may be incomplete or changed.`);
|
|
3247
|
+
files.push({ id: String(a['id'] ?? ''), name, path: target, bytes: res.data.byteLength, ...(reported !== undefined ? { reportedBytes: reported } : {}), sizeMatches });
|
|
3248
|
+
}
|
|
3249
|
+
return { files, available, warnings };
|
|
3250
|
+
}
|
|
2005
3251
|
/** Remove one attachment (by id or stored/original name) from an epic / feature / user story.
|
|
2006
3252
|
* Mirrors the UI: mark the row `deleted:true` and re-save the item (multipart, no file part). */
|
|
2007
3253
|
async removeAttachment(input) {
|
|
@@ -2545,21 +3791,277 @@ export class SimplifyQaAdapter {
|
|
|
2545
3791
|
name: input.versionName,
|
|
2546
3792
|
isDelete,
|
|
2547
3793
|
};
|
|
2548
|
-
const raw = await this.http.putJson('/tm/tcfnversion/delete', body);
|
|
2549
|
-
const data = raw?.data ?? raw;
|
|
2550
|
-
// Distinguish "dep array" from "delete result": the service returns an ARRAY of dep rows for
|
|
2551
|
-
// the dry-run + refused-delete branches, and a single mongo doc (findOneAndUpdate result) for
|
|
2552
|
-
// the successful delete branch. Array → parse deps; single doc → deleted.
|
|
2553
|
-
if (Array.isArray(data)) {
|
|
2554
|
-
const dependencies = data
|
|
2555
|
-
.filter((r) => r && typeof r === 'object')
|
|
2556
|
-
.map((r) => normalizeVersionDep(r, parentType));
|
|
2557
|
-
const hasBlockers = dependencies.some((d) => !versionDepIsEmpty(d));
|
|
2558
|
-
return { dryRun: !isDelete, deleted: false, dependencies, hasBlockers };
|
|
3794
|
+
const raw = await this.http.putJson('/tm/tcfnversion/delete', body);
|
|
3795
|
+
const data = raw?.data ?? raw;
|
|
3796
|
+
// Distinguish "dep array" from "delete result": the service returns an ARRAY of dep rows for
|
|
3797
|
+
// the dry-run + refused-delete branches, and a single mongo doc (findOneAndUpdate result) for
|
|
3798
|
+
// the successful delete branch. Array → parse deps; single doc → deleted.
|
|
3799
|
+
if (Array.isArray(data)) {
|
|
3800
|
+
const dependencies = data
|
|
3801
|
+
.filter((r) => r && typeof r === 'object')
|
|
3802
|
+
.map((r) => normalizeVersionDep(r, parentType));
|
|
3803
|
+
const hasBlockers = dependencies.some((d) => !versionDepIsEmpty(d));
|
|
3804
|
+
return { dryRun: !isDelete, deleted: false, dependencies, hasBlockers };
|
|
3805
|
+
}
|
|
3806
|
+
// Single doc → successful delete (or upsert-echo when nothing matched, but the service only
|
|
3807
|
+
// reaches that branch after emptyIds.push).
|
|
3808
|
+
return { dryRun: false, deleted: true, dependencies: [], hasBlockers: false };
|
|
3809
|
+
}
|
|
3810
|
+
/** Every live release (of the active project) or sprint (of its releases) as the backend stores it. */
|
|
3811
|
+
async pmRows(kind) {
|
|
3812
|
+
const projectId = this.requireProjectId();
|
|
3813
|
+
const fields = [{ column: 'deleted', value: false }];
|
|
3814
|
+
if (kind === 'release')
|
|
3815
|
+
fields.push({ column: 'projectIds', value: projectId });
|
|
3816
|
+
const rows = [];
|
|
3817
|
+
for (let startIndex = 0; startIndex < 2000; startIndex += 100) {
|
|
3818
|
+
const raw = await this.http.postJson(`/pm/${kind}/search`, this.searchBody(fields, { startIndex, limit: 100 }));
|
|
3819
|
+
const page = pickArray(raw, 'data', 'content', kind === 'release' ? 'releases' : 'sprints');
|
|
3820
|
+
rows.push(...page);
|
|
3821
|
+
if (page.length < 100)
|
|
3822
|
+
break;
|
|
3823
|
+
}
|
|
3824
|
+
if (kind === 'release')
|
|
3825
|
+
return rows;
|
|
3826
|
+
// a sprint row carries only its release — keep the ones of this project's releases
|
|
3827
|
+
const mine = new Set((await this.pmRows('release')).map((r) => String(r?.id)));
|
|
3828
|
+
return rows.filter((r) => r?.releaseId == null || mine.has(String(r.releaseId)));
|
|
3829
|
+
}
|
|
3830
|
+
/** One release / sprint by id, business code (RE-44) or exact name — never a guess when a name matches several. */
|
|
3831
|
+
async findPm(kind, ref) {
|
|
3832
|
+
const raw = String(ref ?? '').trim();
|
|
3833
|
+
if (!raw)
|
|
3834
|
+
throw new Error(`${kind}: say which one — its id, code (e.g. ${kind === 'release' ? 'RE-44' : 'SP-3'}) or name.`);
|
|
3835
|
+
const rows = await this.pmRows(kind);
|
|
3836
|
+
const lower = raw.toLowerCase();
|
|
3837
|
+
const byId = /^\d+$/.test(raw) ? rows.filter((r) => String(r.id) === raw) : [];
|
|
3838
|
+
const byCode = rows.filter((r) => String(r.code ?? '').toLowerCase() === lower);
|
|
3839
|
+
const byName = rows.filter((r) => String(r.name ?? '').trim().toLowerCase() === lower);
|
|
3840
|
+
const hits = byId.length ? byId : byCode.length ? byCode : byName;
|
|
3841
|
+
const label = (r) => `${r.code ?? `#${r.id}`} "${r.name ?? ''}" [${r.state ?? ''}]`;
|
|
3842
|
+
if (!hits.length) {
|
|
3843
|
+
throw new Error(`No ${kind} "${raw}" in this project. ${rows.length ? `Known: ${rows.slice(0, 12).map(label).join('; ')}${rows.length > 12 ? '; …' : ''}.` : `The project has no ${kind}s.`}`);
|
|
3844
|
+
}
|
|
3845
|
+
if (hits.length > 1)
|
|
3846
|
+
throw new Error(`"${raw}" matches ${hits.length} ${kind}s (${hits.map(label).join('; ')}). Pass the id or code.`);
|
|
3847
|
+
return hits[0];
|
|
3848
|
+
}
|
|
3849
|
+
/** The project's configured `state` values for releases (fields 11) or sprints (12): `key` is what the row stores. Empty when
|
|
3850
|
+
* they cannot be read — the caller then passes the given state through and lets the backend decide. */
|
|
3851
|
+
async pmStates(kind) {
|
|
3852
|
+
try {
|
|
3853
|
+
const raw = await this.http.getJson(`/pm/fields/${kind === 'release' ? 11 : 12}?projectId=${this.requireProjectId()}&fieldType=defaultFld`);
|
|
3854
|
+
const fields = Array.isArray(raw) ? raw : pickArray(raw, 'data', 'content', 'fields');
|
|
3855
|
+
const state = fields.find((f) => f?.key === 'state');
|
|
3856
|
+
return (Array.isArray(state?.values) ? state.values : [])
|
|
3857
|
+
.filter((v) => v?.archive !== true)
|
|
3858
|
+
.map((v) => ({ key: String(v?.key ?? v?.value ?? ''), value: String(v?.value ?? v?.key ?? '') }))
|
|
3859
|
+
.filter((v) => v.key);
|
|
3860
|
+
}
|
|
3861
|
+
catch {
|
|
3862
|
+
return [];
|
|
3863
|
+
}
|
|
3864
|
+
}
|
|
3865
|
+
/** Update a release or a sprint the way the SimplifyQA editor does (read it, change what was asked, PUT the whole record),
|
|
3866
|
+
* then read it back to confirm. `close` sets the project's completed-type state and the actual end date. */
|
|
3867
|
+
async updateReleaseOrSprint(kind, ref, patch) {
|
|
3868
|
+
const canon = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
3869
|
+
const row = await this.findPm(kind, ref);
|
|
3870
|
+
const states = await this.pmStates(kind);
|
|
3871
|
+
const listing = states.map((s) => s.key).join(', ');
|
|
3872
|
+
const pickState = (want) => {
|
|
3873
|
+
if (!states.length)
|
|
3874
|
+
return want;
|
|
3875
|
+
const hit = states.find((s) => canon(s.key) === canon(want) || canon(s.value) === canon(want));
|
|
3876
|
+
if (!hit)
|
|
3877
|
+
throw new Error(`"${want}" is not a ${kind} state in this project. Valid states: ${listing}.`);
|
|
3878
|
+
return hit.key;
|
|
3879
|
+
};
|
|
3880
|
+
const closedState = (k) => {
|
|
3881
|
+
const order = k === 'release' ? ['completed', 'released', 'closed', 'done'] : ['completed', 'closed', 'done'];
|
|
3882
|
+
for (const c of order) {
|
|
3883
|
+
const hit = states.find((s) => canon(s.key) === c || canon(s.value) === c);
|
|
3884
|
+
if (hit)
|
|
3885
|
+
return hit.key;
|
|
3886
|
+
}
|
|
3887
|
+
return undefined;
|
|
3888
|
+
};
|
|
3889
|
+
let newState;
|
|
3890
|
+
if (patch.close) {
|
|
3891
|
+
newState = closedState(kind) ?? (states.length ? undefined : 'Completed');
|
|
3892
|
+
if (!newState)
|
|
3893
|
+
throw new Error(`This project's ${kind} states (${listing}) have no completed / closed one. Pass the state to use.`);
|
|
3894
|
+
}
|
|
3895
|
+
else if (patch.state !== undefined) {
|
|
3896
|
+
newState = pickState(patch.state);
|
|
3897
|
+
}
|
|
3898
|
+
const body = {};
|
|
3899
|
+
for (const k of SimplifyQaAdapter.PM_FIELDS[kind])
|
|
3900
|
+
if (row[k] !== undefined)
|
|
3901
|
+
body[k] = row[k];
|
|
3902
|
+
// fields the validator takes only as a string / number: a stored null would be refused
|
|
3903
|
+
if (body['description'] == null)
|
|
3904
|
+
body['description'] = '';
|
|
3905
|
+
for (const k of ['azureSprintPath', 'azureSprintId'])
|
|
3906
|
+
if (typeof body[k] !== 'string')
|
|
3907
|
+
delete body[k];
|
|
3908
|
+
body['updateVersion'] = typeof row.updateVersion === 'number' ? row.updateVersion : 0;
|
|
3909
|
+
const changes = [];
|
|
3910
|
+
const set = (k, v) => { if (v !== undefined && JSON.stringify(body[k]) !== JSON.stringify(v)) {
|
|
3911
|
+
body[k] = v;
|
|
3912
|
+
changes.push(k);
|
|
3913
|
+
} };
|
|
3914
|
+
if (newState !== undefined)
|
|
3915
|
+
set('state', newState);
|
|
3916
|
+
set('name', patch.name);
|
|
3917
|
+
set('plannedStartDate', patch.plannedStartDate);
|
|
3918
|
+
set('plannedEndDate', patch.plannedEndDate);
|
|
3919
|
+
set('actualStartDate', patch.actualStartDate);
|
|
3920
|
+
set('actualEndDate', patch.actualEndDate);
|
|
3921
|
+
set('description', patch.description);
|
|
3922
|
+
set('estimatedEffort', patch.estimatedEffort);
|
|
3923
|
+
set('ownerIds', patch.ownerIds);
|
|
3924
|
+
if (patch.close && !body['actualEndDate']) {
|
|
3925
|
+
body['actualEndDate'] = new Date().toISOString();
|
|
3926
|
+
changes.push('actualEndDate');
|
|
3927
|
+
}
|
|
3928
|
+
if (body['plannedStartDate'] && body['plannedEndDate'] && new Date(String(body['plannedEndDate'])) < new Date(String(body['plannedStartDate']))) {
|
|
3929
|
+
throw new Error('plannedEndDate must be on or after plannedStartDate.');
|
|
3930
|
+
}
|
|
3931
|
+
const stateBefore = String(row.state ?? '');
|
|
3932
|
+
const id = String(row.id);
|
|
3933
|
+
const code = String(row.code ?? `#${id}`);
|
|
3934
|
+
const warnings = [];
|
|
3935
|
+
if (patch.close && kind === 'release') {
|
|
3936
|
+
const done = closedState('sprint');
|
|
3937
|
+
const open = (await this.pmRows('sprint').catch(() => []))
|
|
3938
|
+
.filter((s) => String(s?.releaseId) === id && done && canon(String(s?.state ?? '')) !== canon(done));
|
|
3939
|
+
if (open.length)
|
|
3940
|
+
warnings.push(`${open.length} sprint(s) of this release are not completed: ${open.map((s) => `${s.code ?? `#${s.id}`} [${s.state}]`).join(', ')}.`);
|
|
3941
|
+
}
|
|
3942
|
+
if (patch.close && kind === 'sprint') {
|
|
3943
|
+
warnings.push('SimplifyQA\'s editor refuses to complete a sprint that still has new / pending stories, tasks or defects; this was not checked here.');
|
|
3944
|
+
}
|
|
3945
|
+
if (!changes.length) {
|
|
3946
|
+
return { id, code, name: String(row.name ?? ''), stateBefore, stateAfter: stateBefore, changed: [], warnings, written: false };
|
|
3947
|
+
}
|
|
3948
|
+
try {
|
|
3949
|
+
await this.http.putJson(`/pm/${kind}/${id}`, body);
|
|
3950
|
+
}
|
|
3951
|
+
catch (e) {
|
|
3952
|
+
const m = e instanceof Error ? e.message : String(e);
|
|
3953
|
+
if (/INVALIDUSERTYPE|admin privileges|not.*authori[sz]ed|forbidden|\b40[13]\b/i.test(m)) {
|
|
3954
|
+
throw new Error(`Updating a ${kind} needs an admin user in SimplifyQA, and the connected user is not one (${m}).`);
|
|
3955
|
+
}
|
|
3956
|
+
throw e;
|
|
3957
|
+
}
|
|
3958
|
+
// Read it back — the update only counts when the stored record shows it.
|
|
3959
|
+
const after = (await this.pmRows(kind)).find((r) => String(r.id) === id);
|
|
3960
|
+
if (!after)
|
|
3961
|
+
throw new Error(`${code} was updated but could not be read back.`);
|
|
3962
|
+
if (newState !== undefined && canon(String(after.state ?? '')) !== canon(newState)) {
|
|
3963
|
+
throw new Error(`${code} was sent state "${newState}" but reads back "${String(after.state ?? '')}".`);
|
|
3964
|
+
}
|
|
3965
|
+
return { id, code, name: String(after.name ?? row.name ?? ''), stateBefore, stateAfter: String(after.state ?? ''), changed: changes, warnings, written: true };
|
|
3966
|
+
}
|
|
3967
|
+
/** Create a release or a sprint the way Releases → Create does (`POST /pm/release` / `/pm/sprint`), then read it back.
|
|
3968
|
+
* The backend requires a state and at least one owner, so the state defaults to the project's first one (New) and the owner to
|
|
3969
|
+
* the connected user. A sprint needs an existing release of this project. */
|
|
3970
|
+
async createReleaseOrSprint(kind, input) {
|
|
3971
|
+
const projectId = this.requireProjectId();
|
|
3972
|
+
const canon = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
3973
|
+
const name = String(input.name ?? '').trim();
|
|
3974
|
+
if (name.length < 3 || name.length > 500)
|
|
3975
|
+
throw new Error(`A ${kind} name needs 3–500 characters.`);
|
|
3976
|
+
for (const k of ['plannedStartDate', 'plannedEndDate']) {
|
|
3977
|
+
const v = input[k];
|
|
3978
|
+
if (!v)
|
|
3979
|
+
throw new Error(`${kind}_create needs ${k} (YYYY-MM-DD).`);
|
|
3980
|
+
if (!/^\d{4}-\d{2}-\d{2}/.test(v) || Number.isNaN(new Date(v).getTime()))
|
|
3981
|
+
throw new Error(`${k} must be a date like 2026-11-16 (got "${v}").`);
|
|
3982
|
+
}
|
|
3983
|
+
if (new Date(input.plannedEndDate) < new Date(input.plannedStartDate))
|
|
3984
|
+
throw new Error('plannedEndDate must be on or after plannedStartDate.');
|
|
3985
|
+
if (typeof input.estimatedEffort !== 'number' || !Number.isFinite(input.estimatedEffort) || input.estimatedEffort < 0) {
|
|
3986
|
+
throw new Error(`${kind}_create needs estimatedEffort — a number of hours, 0 or more.`);
|
|
3987
|
+
}
|
|
3988
|
+
let release;
|
|
3989
|
+
if (kind === 'sprint') {
|
|
3990
|
+
if (!input.releaseId)
|
|
3991
|
+
throw new Error('sprint_create needs releaseId — the release it belongs to (id, code like RE-44, or exact name).');
|
|
3992
|
+
release = await this.findPm('release', input.releaseId);
|
|
3993
|
+
}
|
|
3994
|
+
const dup = (await this.pmRows(kind)).find((r) => String(r.name ?? '').trim().toLowerCase() === name.toLowerCase()
|
|
3995
|
+
&& (kind === 'release' || String(r.releaseId) === String(release.id)));
|
|
3996
|
+
if (dup) {
|
|
3997
|
+
throw new Error(`A ${kind} named "${name}" already exists${kind === 'sprint' ? ' in that release' : ''}: ${dup.code ?? `#${dup.id}`} [${dup.state ?? ''}]. ` +
|
|
3998
|
+
`Use ${kind}_update to change it, or pick another name.`);
|
|
3999
|
+
}
|
|
4000
|
+
const states = await this.pmStates(kind);
|
|
4001
|
+
let state;
|
|
4002
|
+
if (input.state) {
|
|
4003
|
+
const hit = states.find((s) => canon(s.key) === canon(input.state) || canon(s.value) === canon(input.state));
|
|
4004
|
+
if (states.length && !hit)
|
|
4005
|
+
throw new Error(`"${input.state}" is not a ${kind} state in this project. Valid states: ${states.map((s) => s.key).join(', ')}.`);
|
|
4006
|
+
state = hit?.key ?? input.state;
|
|
4007
|
+
}
|
|
4008
|
+
else {
|
|
4009
|
+
state = states.find((s) => canon(s.key) === 'new')?.key ?? states[0]?.key ?? 'New';
|
|
4010
|
+
}
|
|
4011
|
+
const me = await this.ensureUserId();
|
|
4012
|
+
const refs = input.owners?.length ? input.owners : ['me'];
|
|
4013
|
+
const ownerIds = [];
|
|
4014
|
+
for (const ref of refs) {
|
|
4015
|
+
if (String(ref).trim().toLowerCase() === 'me') {
|
|
4016
|
+
if (!me)
|
|
4017
|
+
throw new Error('Could not identify your user from the token, so "me" cannot be the owner. Pass owners (an email, name or user id).');
|
|
4018
|
+
ownerIds.push(Number.parseInt(me, 10));
|
|
4019
|
+
}
|
|
4020
|
+
else {
|
|
4021
|
+
ownerIds.push(...await this.resolveUserIds([ref]));
|
|
4022
|
+
}
|
|
4023
|
+
}
|
|
4024
|
+
const owners = [...new Set(ownerIds)];
|
|
4025
|
+
const body = {
|
|
4026
|
+
name, state, ownerIds: owners, description: input.description ?? '',
|
|
4027
|
+
plannedStartDate: input.plannedStartDate, plannedEndDate: input.plannedEndDate, estimatedEffort: input.estimatedEffort,
|
|
4028
|
+
...(kind === 'release' ? { projectIds: [projectId] } : { releaseId: Number(release.id) }),
|
|
4029
|
+
};
|
|
4030
|
+
let raw;
|
|
4031
|
+
try {
|
|
4032
|
+
raw = await this.http.postJson(`/pm/${kind}`, body);
|
|
2559
4033
|
}
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
4034
|
+
catch (e) {
|
|
4035
|
+
const m = e instanceof Error ? e.message : String(e);
|
|
4036
|
+
if (/INVALIDUSERTYPE|admin privileges|not.*authori[sz]ed|forbidden|\b40[13]\b/i.test(m)) {
|
|
4037
|
+
throw new Error(`Creating a ${kind} needs an admin user in SimplifyQA, and the connected user is not one (${m}).`);
|
|
4038
|
+
}
|
|
4039
|
+
throw e;
|
|
4040
|
+
}
|
|
4041
|
+
const made = raw?.data && typeof raw.data === 'object' && !Array.isArray(raw.data) ? raw.data : raw;
|
|
4042
|
+
// Read it back — it only counts when the stored record shows it.
|
|
4043
|
+
const rows = await this.pmRows(kind);
|
|
4044
|
+
const after = rows.find((r) => made?.id !== undefined && String(r.id) === String(made.id))
|
|
4045
|
+
?? rows.filter((r) => String(r.name ?? '').trim().toLowerCase() === name.toLowerCase()).pop();
|
|
4046
|
+
if (!after)
|
|
4047
|
+
throw new Error(`The ${kind} "${name}" was sent, but it was not found when read back.`);
|
|
4048
|
+
if (after.estimatedEffort !== undefined && Number(after.estimatedEffort) !== input.estimatedEffort) {
|
|
4049
|
+
throw new Error(`${after.code ?? `#${after.id}`}: estimatedEffort was sent as ${input.estimatedEffort} but reads back as ${after.estimatedEffort}.`);
|
|
4050
|
+
}
|
|
4051
|
+
const warnings = [];
|
|
4052
|
+
if (kind === 'sprint') {
|
|
4053
|
+
const d = (v) => String(v ?? '').slice(0, 10);
|
|
4054
|
+
if (release.plannedStartDate && d(input.plannedStartDate) < d(release.plannedStartDate))
|
|
4055
|
+
warnings.push(`The sprint starts (${d(input.plannedStartDate)}) before its release does (${d(release.plannedStartDate)}).`);
|
|
4056
|
+
if (release.plannedEndDate && d(input.plannedEndDate) > d(release.plannedEndDate))
|
|
4057
|
+
warnings.push(`The sprint ends (${d(input.plannedEndDate)}) after its release does (${d(release.plannedEndDate)}).`);
|
|
4058
|
+
}
|
|
4059
|
+
return {
|
|
4060
|
+
id: String(after.id), code: String(after.code ?? `#${after.id}`), name: String(after.name ?? name), state: String(after.state ?? state),
|
|
4061
|
+
plannedStartDate: String(input.plannedStartDate).slice(0, 10), plannedEndDate: String(input.plannedEndDate).slice(0, 10),
|
|
4062
|
+
estimatedEffort: input.estimatedEffort, ownerIds: owners,
|
|
4063
|
+
...(kind === 'sprint' ? { release: String(release.code ?? `#${release.id}`) } : {}), warnings,
|
|
4064
|
+
};
|
|
2563
4065
|
}
|
|
2564
4066
|
/** `list_releases` has no limit/offset of its own — it always wants the WHOLE visible set — so
|
|
2565
4067
|
* page internally past `searchBody`'s default 100 instead of silently truncating (same fix as
|
|
@@ -2822,6 +4324,108 @@ export class SimplifyQaAdapter {
|
|
|
2822
4324
|
}
|
|
2823
4325
|
return { linkTypeKey: chosen.key, ...(dest.code ? { destinationCode: dest.code } : {}), linkedIssues: links };
|
|
2824
4326
|
}
|
|
4327
|
+
/** Remove a link between two backlog items — the UI's Linkages delete. The link is a row stored on the SOURCE item and mirrored on the
|
|
4328
|
+
* destination under the SAME id; the backend removes it when the source is saved with that row marked `deleted:true`, which drops both sides.
|
|
4329
|
+
* The row is the stored one (it must carry its destination code, or the backend errors), the removal is read back from /pm/linkages, and the
|
|
4330
|
+
* other side is checked too. With several links to the same item, `linkType` says which one. */
|
|
4331
|
+
async unlinkBacklogItem(input) {
|
|
4332
|
+
const specs = {
|
|
4333
|
+
epic: { path: '/pm/epic', search: '/pm/epic/search', parentType: 'EP' },
|
|
4334
|
+
feature: { path: '/pm/feature', search: '/pm/feature/search', parentType: 'FT' },
|
|
4335
|
+
userstory: { path: '/pm/userstory', search: '/pm/userstory/search', parentType: 'US' },
|
|
4336
|
+
defect: { path: '/pm/defect', search: '/pm/defect/search', parentType: 'DE' },
|
|
4337
|
+
task: { path: '/pm/task', search: '/pm/task/search', parentType: 'TA' },
|
|
4338
|
+
};
|
|
4339
|
+
const projectId = this.requireProjectId();
|
|
4340
|
+
const asDoc = (raw) => (Array.isArray(raw) ? (raw[0] ?? {}) : (raw?.data && typeof raw.data === 'object' && !Array.isArray(raw.data) ? raw.data : raw)) ?? {};
|
|
4341
|
+
const refOf = async (type, ref) => {
|
|
4342
|
+
const spec = specs[type];
|
|
4343
|
+
const bare = numericId(ref);
|
|
4344
|
+
if (/^\d+$/.test(String(bare))) {
|
|
4345
|
+
try {
|
|
4346
|
+
const doc = asDoc(await this.http.getJson(`${spec.path}/${bare}`));
|
|
4347
|
+
const id = Number.parseInt(str(doc, 'id', '_id') ?? String(bare), 10);
|
|
4348
|
+
if (Number.isFinite(id))
|
|
4349
|
+
return { id, ...(str(doc, 'code') ? { code: str(doc, 'code') } : {}), ...(str(doc, 'name') ? { name: str(doc, 'name') } : {}) };
|
|
4350
|
+
}
|
|
4351
|
+
catch { /* fall through to search */ }
|
|
4352
|
+
}
|
|
4353
|
+
for (const column of ['code', 'name']) {
|
|
4354
|
+
const raw = await this.http.postJson(spec.search, this.searchBody([{ column, value: ref }], { startIndex: 0, limit: 20, selectFields: ['id', 'code', 'name'] }));
|
|
4355
|
+
const hit = pickArray(raw, 'data', 'content').find((r) => String(str(r, column) ?? '').trim().toLowerCase() === ref.trim().toLowerCase());
|
|
4356
|
+
const id = hit ? Number.parseInt(str(hit, 'id', '_id') ?? '', 10) : NaN;
|
|
4357
|
+
if (Number.isFinite(id))
|
|
4358
|
+
return { id, ...(str(hit, 'code') ? { code: str(hit, 'code') } : {}), ...(str(hit, 'name') ? { name: str(hit, 'name') } : {}) };
|
|
4359
|
+
}
|
|
4360
|
+
throw new Error(`${type} "${ref}" was not found in this project.`);
|
|
4361
|
+
};
|
|
4362
|
+
const readLinks = async (id, parentType) => {
|
|
4363
|
+
const raw = await this.http.getJson(`/pm/linkages/${id}/${parentType}?projectId=${projectId}`);
|
|
4364
|
+
return (Array.isArray(raw) ? raw : pickArray(raw, 'data', 'content', 'linkages'));
|
|
4365
|
+
};
|
|
4366
|
+
const label = (l) => `${l['destinationCode'] ?? l['destinationId']} (${l['linkTypeKey']})`;
|
|
4367
|
+
const source = await refOf(input.sourceType, input.sourceId);
|
|
4368
|
+
const dest = await refOf(input.destType, input.destId);
|
|
4369
|
+
const sourceName = source.code ?? input.sourceId;
|
|
4370
|
+
const destName = dest.code ?? input.destId;
|
|
4371
|
+
const links = await readLinks(source.id, specs[input.sourceType].parentType);
|
|
4372
|
+
// which link(s): to that item, and — when asked — of that type (by its key, or by the name the UI shows)
|
|
4373
|
+
let matches = links.filter((l) => Number(l['destinationId']) === dest.id);
|
|
4374
|
+
const want = input.linkType?.trim().toLowerCase();
|
|
4375
|
+
if (want) {
|
|
4376
|
+
let narrowed = matches.filter((l) => String(l['linkTypeKey']).toLowerCase() === want);
|
|
4377
|
+
if (!narrowed.length && matches.length) {
|
|
4378
|
+
// the name the dropdown shows → its key, from the same catalogue backlog_link reads
|
|
4379
|
+
const rawTypes = await this.http.getJson(`/pm/fields/10?projectId=${projectId}&fieldType=linkages`).catch(() => undefined);
|
|
4380
|
+
const keys = new Set();
|
|
4381
|
+
const typeRows = new Set(); // the catalogue row either of whose names was given — both sides are the same link type
|
|
4382
|
+
for (const row of (Array.isArray(rawTypes) ? rawTypes : pickArray(rawTypes, 'data', 'content', 'fields'))) {
|
|
4383
|
+
for (const side of ['inwardType', 'outwardType']) {
|
|
4384
|
+
const t = row?.[side];
|
|
4385
|
+
if (t && typeof t === 'object' && [str(t, 'value'), str(t, 'label'), str(t, 'name')].some((v) => (v ?? '').trim().toLowerCase() === want)) {
|
|
4386
|
+
keys.add((str(t, 'key') ?? '').toLowerCase());
|
|
4387
|
+
if (row?.id !== undefined)
|
|
4388
|
+
typeRows.add(String(row.id));
|
|
4389
|
+
}
|
|
4390
|
+
}
|
|
4391
|
+
}
|
|
4392
|
+
narrowed = matches.filter((l) => keys.has(String(l['linkTypeKey']).toLowerCase()) || typeRows.has(String(l['linkId'])));
|
|
4393
|
+
}
|
|
4394
|
+
matches = narrowed;
|
|
4395
|
+
}
|
|
4396
|
+
if (!matches.length) {
|
|
4397
|
+
throw new Error(`${sourceName} has no link to ${destName}${input.linkType ? ` of type "${input.linkType}"` : ''}. Its links: ${links.map(label).join(', ') || '(none)'}.`);
|
|
4398
|
+
}
|
|
4399
|
+
const types = [...new Set(matches.map((l) => String(l['linkTypeKey'])))];
|
|
4400
|
+
if (!want && types.length > 1) {
|
|
4401
|
+
throw new Error(`${sourceName} has ${matches.length} links to ${destName} (${types.join(', ')}) — say which one to remove with \`linkType\`.`);
|
|
4402
|
+
}
|
|
4403
|
+
// save the source with each stored row marked deleted (the backend skips rows without `deleted`, and needs their destinationCode)
|
|
4404
|
+
const entries = matches.map((m) => ({ ...m, deleted: true }));
|
|
4405
|
+
const ids = new Set(matches.map((m) => String(m['id'])));
|
|
4406
|
+
const sourceDoc = asDoc(await this.http.getJson(`${specs[input.sourceType].path}/${source.id}`));
|
|
4407
|
+
const version = typeof sourceDoc['updateVersion'] === 'number' ? sourceDoc['updateVersion'] : 0;
|
|
4408
|
+
if (input.sourceType === 'epic')
|
|
4409
|
+
await this.updateEpic(String(source.id), { linkedIssues: entries, updateVersion: version });
|
|
4410
|
+
else if (input.sourceType === 'feature')
|
|
4411
|
+
await this.updateFeature(String(source.id), { linkedIssues: entries, updateVersion: version });
|
|
4412
|
+
else if (input.sourceType === 'userstory')
|
|
4413
|
+
await this.updateStory(String(source.id), { linkedIssues: entries });
|
|
4414
|
+
else
|
|
4415
|
+
await this.http.putJson(`${specs[input.sourceType].path}/${source.id}`, { projectId, linkedIssues: entries, updateVersion: version });
|
|
4416
|
+
// read it back — from the source, and from the other side
|
|
4417
|
+
const after = await readLinks(source.id, specs[input.sourceType].parentType);
|
|
4418
|
+
if (after.some((l) => ids.has(String(l['id'])))) {
|
|
4419
|
+
throw new Error(`Asked to remove the link ${sourceName} → ${destName}, but the Linkages still show it. Links now: ${after.map(label).join(', ') || '(none)'}`);
|
|
4420
|
+
}
|
|
4421
|
+
const warnings = [];
|
|
4422
|
+
const destParent = (dest.code ?? '').split('-')[0] || specs[input.destType].parentType;
|
|
4423
|
+
const mirror = await readLinks(dest.id, destParent).catch(() => undefined);
|
|
4424
|
+
if (mirror?.some((l) => ids.has(String(l['id'])))) {
|
|
4425
|
+
warnings.push(`${destName}'s own Linkages still show the link back to ${sourceName} — the other side did not clear.`);
|
|
4426
|
+
}
|
|
4427
|
+
return { sourceCode: sourceName, destinationCode: destName, removed: matches.map(label), remaining: after.map(label), warnings };
|
|
4428
|
+
}
|
|
2825
4429
|
/** Create a PROJECT (`POST /pm/project`). The UI's new-project form sends a name, description and
|
|
2826
4430
|
* the member `users` plus a defaults block; the backend accepts the minimal shape, so start there
|
|
2827
4431
|
* and let the backend fill its own defaults. */
|
|
@@ -4439,6 +6043,18 @@ export class SimplifyQaAdapter {
|
|
|
4439
6043
|
st.runtimeParameters = names;
|
|
4440
6044
|
}
|
|
4441
6045
|
const allRuntimeNames = new Set([...slotNamesByStep.values()].flat());
|
|
6046
|
+
// Every parameter this save has to bind is collected first (same precedence order as before —
|
|
6047
|
+
// first occurrence wins) and then resolved with bounded concurrency. A recording save used to
|
|
6048
|
+
// spend one round-trip per token (search + maybe create), one AFTER another: with 10+ steps that
|
|
6049
|
+
// was the bulk of the post-recording wait in the client. Different names are independent.
|
|
6050
|
+
const pendingParams = [];
|
|
6051
|
+
const queuedParams = new Set();
|
|
6052
|
+
const queueParam = (name, value, access) => {
|
|
6053
|
+
if (paramIdByName.has(name) || queuedParams.has(name))
|
|
6054
|
+
return;
|
|
6055
|
+
queuedParams.add(name);
|
|
6056
|
+
pendingParams.push({ name, value, access });
|
|
6057
|
+
};
|
|
4442
6058
|
for (const s of steps) {
|
|
4443
6059
|
// Replace-a-parameter edits: the NEW parameter is get-or-create; the OLD one must already exist (a name or an id) —
|
|
4444
6060
|
// never create a parameter just to remove it, and never guess.
|
|
@@ -4466,20 +6082,19 @@ export class SimplifyQaAdapter {
|
|
|
4466
6082
|
}
|
|
4467
6083
|
}
|
|
4468
6084
|
for (const name of extractParamNames(s.description)) {
|
|
4469
|
-
if (paramIdByName.has(name))
|
|
6085
|
+
if (paramIdByName.has(name) || queuedParams.has(name))
|
|
4470
6086
|
continue;
|
|
4471
6087
|
// `${7001}` is an already-bound parameter id, not a name to get-or-create.
|
|
4472
6088
|
if (/^\d+$/.test(name))
|
|
4473
6089
|
continue;
|
|
4474
6090
|
const isSlot = allRuntimeNames.has(name);
|
|
4475
6091
|
const defaultValue = isSlot ? runtimeSlotValue(paramDefault(name, tc.data, s.value)) : paramDefault(name, tc.data, s.value);
|
|
4476
|
-
|
|
4477
|
-
paramIdByName.set(name, id);
|
|
6092
|
+
queueParam(name, defaultValue, isSlot ? 'Runtime' : 'Local');
|
|
4478
6093
|
}
|
|
4479
6094
|
if (s.recordedParam) {
|
|
4480
6095
|
const runtimeNames = new Set(slotNamesByStep.get(s) ?? []);
|
|
4481
6096
|
for (const [name, value] of Object.entries(s.recordedParam)) {
|
|
4482
|
-
if (paramIdByName.has(name))
|
|
6097
|
+
if (paramIdByName.has(name) || queuedParams.has(name))
|
|
4483
6098
|
continue;
|
|
4484
6099
|
// An all-digit key is an EXISTING parameter id, not a name — map it to itself and never
|
|
4485
6100
|
// create a parameter named "7001" (that junk row is exactly what a copied step bound to).
|
|
@@ -4492,21 +6107,19 @@ export class SimplifyQaAdapter {
|
|
|
4492
6107
|
// A store slot ("Runtime Parameter") must be a Runtime param so the agent hands the plugin a
|
|
4493
6108
|
// writable argument; everything else stays Local.
|
|
4494
6109
|
const isSlot = runtimeNames.has(name);
|
|
4495
|
-
|
|
4496
|
-
paramIdByName.set(name, id);
|
|
6110
|
+
queueParam(name, isSlot ? runtimeSlotValue(String(value ?? '')) : String(value ?? ''), isSlot ? 'Runtime' : 'Local');
|
|
4497
6111
|
}
|
|
4498
6112
|
// DATABASE steps: parameters referenced inside an argument value (`${suffix}` / `{{suffix}}` in a filter) must
|
|
4499
6113
|
// exist so the mapper can bind them (parameterizedParamIds).
|
|
4500
6114
|
if (s.stepType === 'database') {
|
|
4501
6115
|
for (const [argName, value] of Object.entries(s.recordedParam)) {
|
|
4502
6116
|
for (const name of extractValueParamNames(value)) {
|
|
4503
|
-
if (name === argName
|
|
6117
|
+
if (name === argName)
|
|
4504
6118
|
continue;
|
|
4505
6119
|
// `{{7001}}` is already a bound id — never a parameter name.
|
|
4506
6120
|
if (/^\d+$/.test(name))
|
|
4507
6121
|
continue;
|
|
4508
|
-
|
|
4509
|
-
paramIdByName.set(name, id);
|
|
6122
|
+
queueParam(name, paramDefault(name, tc.data, undefined), allRuntimeNames.has(name) ? 'Runtime' : 'Local');
|
|
4510
6123
|
}
|
|
4511
6124
|
}
|
|
4512
6125
|
}
|
|
@@ -4521,13 +6134,16 @@ export class SimplifyQaAdapter {
|
|
|
4521
6134
|
// backend), not a parameter name — never create a parameter for it.
|
|
4522
6135
|
if (/^\d+$/.test(name))
|
|
4523
6136
|
continue;
|
|
4524
|
-
|
|
4525
|
-
continue;
|
|
4526
|
-
const id = await this.getOrCreateParameter(projectId, moduleId, name, paramDefault(name, tc.data, undefined));
|
|
4527
|
-
paramIdByName.set(name, id);
|
|
6137
|
+
queueParam(name, paramDefault(name, tc.data, undefined), 'Local');
|
|
4528
6138
|
}
|
|
4529
6139
|
}
|
|
4530
6140
|
}
|
|
6141
|
+
// Resolve every collected token with bounded concurrency. getOrCreateParameter is idempotent per
|
|
6142
|
+
// name (it recovers a race-lost duplicate by re-reading), so distinct names are safe in parallel.
|
|
6143
|
+
await mapLimit(pendingParams, 6, async (p) => {
|
|
6144
|
+
const id = await this.getOrCreateParameter(projectId, moduleId, p.name, p.value, p.access);
|
|
6145
|
+
paramIdByName.set(p.name, id);
|
|
6146
|
+
});
|
|
4531
6147
|
if (accessById) {
|
|
4532
6148
|
// The catalog's access type is what the executor keys on for RUNTIME substitution. Copy only the
|
|
4533
6149
|
// ids this save will bind (plus every round-tripped sourceParameterId so an untouched step is
|
|
@@ -4559,6 +6175,52 @@ export class SimplifyQaAdapter {
|
|
|
4559
6175
|
catch { /* best-effort: never block a save over the parameter catalog */ }
|
|
4560
6176
|
return out;
|
|
4561
6177
|
}
|
|
6178
|
+
/** Targeted `POST /tm/action/search` for ONE action by id, name or display name. The cached catalog can
|
|
6179
|
+
* miss a project's newer custom actions (type CUSTOM), and `GET /tm/action/:id` is not an option for
|
|
6180
|
+
* them (the backend reads the id as a project id → "Project not found"). Returns undefined on no hit. */
|
|
6181
|
+
async findActionLive(key) {
|
|
6182
|
+
const projectId = this.requireProjectId();
|
|
6183
|
+
const numeric = /^\d+$/.test(key.trim());
|
|
6184
|
+
const columns = numeric ? ['id'] : ['name', 'disname'];
|
|
6185
|
+
for (const column of columns) {
|
|
6186
|
+
let raw;
|
|
6187
|
+
try {
|
|
6188
|
+
raw = await this.http.postJson('/tm/action/search', {
|
|
6189
|
+
searchFields: [
|
|
6190
|
+
{ column: 'deleted', value: false },
|
|
6191
|
+
{ column: 'projectId', value: { $in: [0, projectId] } },
|
|
6192
|
+
{ column, value: numeric ? Number.parseInt(key, 10) : key.trim() },
|
|
6193
|
+
],
|
|
6194
|
+
startIndex: 0,
|
|
6195
|
+
limit: 10,
|
|
6196
|
+
selectFields: ['id', 'name', 'objectTemplate', 'objectRequired', 'uniqueId', 'disname', 'projectId'],
|
|
6197
|
+
});
|
|
6198
|
+
}
|
|
6199
|
+
catch {
|
|
6200
|
+
continue;
|
|
6201
|
+
}
|
|
6202
|
+
const rows = pickArray(raw, 'data', 'content', 'actions');
|
|
6203
|
+
const want = key.trim().toLowerCase();
|
|
6204
|
+
const row = rows.find((r) => numeric ? str(r, 'id', '_id', 'actionId') === String(Number.parseInt(key, 10))
|
|
6205
|
+
: [str(r, 'name'), str(r, 'disname', 'displayName')].some(v => v?.toLowerCase() === want));
|
|
6206
|
+
const idStr = row ? str(row, 'id', '_id', 'actionId') : undefined;
|
|
6207
|
+
if (!row || !idStr)
|
|
6208
|
+
continue;
|
|
6209
|
+
const otRaw = row?.objectTemplate;
|
|
6210
|
+
const objectTemplate = typeof otRaw === 'number' ? otRaw
|
|
6211
|
+
: typeof otRaw === 'string' && /^\d+$/.test(otRaw) ? Number.parseInt(otRaw, 10) : undefined;
|
|
6212
|
+
const name = str(row, 'name');
|
|
6213
|
+
const displayName = str(row, 'disname', 'displayName') ?? undefined;
|
|
6214
|
+
return {
|
|
6215
|
+
id: Number.parseInt(idStr, 10),
|
|
6216
|
+
objectRequired: row?.objectRequired === true,
|
|
6217
|
+
...(objectTemplate !== undefined ? { objectTemplate } : {}),
|
|
6218
|
+
...(displayName ? { displayName } : {}),
|
|
6219
|
+
...(name ? { name } : {}),
|
|
6220
|
+
};
|
|
6221
|
+
}
|
|
6222
|
+
return undefined;
|
|
6223
|
+
}
|
|
4562
6224
|
actionCatalog() {
|
|
4563
6225
|
if (this.actionCatalogCache)
|
|
4564
6226
|
return this.actionCatalogCache;
|
|
@@ -4815,12 +6477,26 @@ export class SimplifyQaAdapter {
|
|
|
4815
6477
|
async resolveAutomationSteps(projectId, moduleId, tc) {
|
|
4816
6478
|
const catalog = await this.actionCatalog();
|
|
4817
6479
|
const steps = Array.isArray(tc.steps) ? tc.steps : [];
|
|
6480
|
+
// "while" / "end_while" / "do_while" … become the markers SimplifyQA reads (WHILE_START / WHILE_END / DO / the closing WHILE)
|
|
6481
|
+
normalizeLoopKinds(steps);
|
|
4818
6482
|
// ponytail: objectId can be `undefined` here to mean "don't emit — preserve the backend value".
|
|
4819
6483
|
// Used when an existing step (sourceId set) has no round-trip objectRef.id, e.g. because it was
|
|
4820
6484
|
// recorded before objectRequired was flipped on the action. Emitting null would $set-clobber the DB.
|
|
4821
6485
|
// actionId also nullable for control-flow / function / switch / function_end — those steps don't
|
|
4822
6486
|
// have an action; buildAutomationPayload omits action/object emit when actionId is null.
|
|
4823
6487
|
const out = [];
|
|
6488
|
+
// One lookup per object NAME per save: a recording often touches the same element several times
|
|
6489
|
+
// ("Type ..." then "Wait until ..."), and each repeat used to be another round-trip.
|
|
6490
|
+
const objectIdByName = new Map();
|
|
6491
|
+
const lookupObjectByName = (projId, name) => {
|
|
6492
|
+
const key = name.trim().toLowerCase();
|
|
6493
|
+
let hit = objectIdByName.get(key);
|
|
6494
|
+
if (!hit) {
|
|
6495
|
+
hit = this.findObjectIdByName(projId, name);
|
|
6496
|
+
objectIdByName.set(key, hit);
|
|
6497
|
+
}
|
|
6498
|
+
return hit;
|
|
6499
|
+
};
|
|
4824
6500
|
for (let i = 0; i < steps.length; i++) {
|
|
4825
6501
|
const s = steps[i];
|
|
4826
6502
|
// ponytail: control-flow / function / switch / function_end steps have no action to resolve.
|
|
@@ -4850,6 +6526,43 @@ export class SimplifyQaAdapter {
|
|
|
4850
6526
|
}),
|
|
4851
6527
|
};
|
|
4852
6528
|
}
|
|
6529
|
+
// WHILE / DO-WHILE / IF with a real condition: write the condition rows + readable text (not just a label)
|
|
6530
|
+
if (s.stepType === 'control_flow' && !s.desktopConditions?.length) {
|
|
6531
|
+
const specs = stepConditions(s);
|
|
6532
|
+
const wire = String(s.sourceRaw?.['stepType'] ?? s.controlFlow?.kind ?? '').toUpperCase();
|
|
6533
|
+
if (specs.length && !CONDITION_KINDS.has(wire)) {
|
|
6534
|
+
throw new Error(`Step ${i + 1}: ${wire} takes no condition. The condition of a WHILE is on WHILE_START ("while"), of a DO-WHILE on its closing WHILE ("end_do_while").`);
|
|
6535
|
+
}
|
|
6536
|
+
if (specs.length) {
|
|
6537
|
+
const tech = (deriveTcType(tc) || 'WEB').toUpperCase();
|
|
6538
|
+
s.sourceRaw = {
|
|
6539
|
+
...(s.sourceRaw ?? {}),
|
|
6540
|
+
conditions: await buildConditionRows(wire, specs, {
|
|
6541
|
+
projectId, technology: tech,
|
|
6542
|
+
action: (names, uid) => {
|
|
6543
|
+
const hit = (uid ? (catalog.get(`uniq::${uid}`) ?? catalog.get(`dis::${uid.toLowerCase()}`)) : undefined)
|
|
6544
|
+
?? names.map((n) => catalog.get(`${tech}::${n}`) ?? catalog.get(n)).find(Boolean);
|
|
6545
|
+
return hit ? { id: hit.id, displayName: hit.displayName, name: hit.name, objectRequired: hit.objectRequired } : undefined;
|
|
6546
|
+
},
|
|
6547
|
+
object: async (ref) => {
|
|
6548
|
+
if (ref.objectId) {
|
|
6549
|
+
const id = Number.parseInt(numericId(ref.objectId), 10);
|
|
6550
|
+
if (!Number.isFinite(id))
|
|
6551
|
+
throw new Error(`Step ${i + 1}: object "${ref.objectId}" is not an object id.`);
|
|
6552
|
+
const o = await this.getObject(String(id)).catch(() => undefined);
|
|
6553
|
+
if (!o?.name)
|
|
6554
|
+
throw new Error(`Step ${i + 1}: object ${ref.objectId} was not found in this project.`);
|
|
6555
|
+
return { id, name: o.name };
|
|
6556
|
+
}
|
|
6557
|
+
const id = await lookupObjectByName(projectId, ref.objectName ?? '');
|
|
6558
|
+
if (id == null)
|
|
6559
|
+
throw new Error(`Step ${i + 1}: no object named "${ref.objectName}" in this project — give its objectId.`);
|
|
6560
|
+
return { id, name: ref.objectName ?? '' };
|
|
6561
|
+
},
|
|
6562
|
+
}),
|
|
6563
|
+
};
|
|
6564
|
+
}
|
|
6565
|
+
}
|
|
4853
6566
|
out.push({ actionId: null, objectId: null });
|
|
4854
6567
|
continue;
|
|
4855
6568
|
}
|
|
@@ -4908,39 +6621,26 @@ export class SimplifyQaAdapter {
|
|
|
4908
6621
|
// Fallback: if the by-id scan misses (action created in a different project and thus not in
|
|
4909
6622
|
// the UI's projectId-filtered catalog), fetch it directly via GET /tm/action/:id. Only tries
|
|
4910
6623
|
// for numeric-id lookups — model-authored name lookups have no id to fetch.
|
|
6624
|
+
// The catalog can miss a project's newer custom actions, so look the id / name / display name up
|
|
6625
|
+
// directly with a targeted search (never GET /tm/action/:id — that route reads the id as a project id).
|
|
4911
6626
|
let fallbackDiag = '';
|
|
4912
|
-
if (!meta
|
|
6627
|
+
if (!meta) {
|
|
4913
6628
|
try {
|
|
4914
|
-
|
|
4915
|
-
const row = raw?.data && typeof raw.data === 'object' ? raw.data
|
|
4916
|
-
: Array.isArray(raw?.data) ? raw.data[0]
|
|
4917
|
-
: Array.isArray(raw) ? raw[0]
|
|
4918
|
-
: raw;
|
|
4919
|
-
const idStr = str(row, 'id', '_id', 'actionId');
|
|
4920
|
-
// ponytail: no `technology` gate. Catalog builder proved action rows have no top-level
|
|
4921
|
-
// technology field (see comment at ~line 2357); requiring it here made the fallback
|
|
4922
|
-
// never succeed — every cross-project action id threw "no SQA action named X".
|
|
4923
|
-
if (idStr) {
|
|
4924
|
-
const otRaw = row?.objectTemplate;
|
|
4925
|
-
const objectTemplate = typeof otRaw === 'number' ? otRaw
|
|
4926
|
-
: typeof otRaw === 'string' && /^\d+$/.test(otRaw) ? Number.parseInt(otRaw, 10)
|
|
4927
|
-
: undefined;
|
|
4928
|
-
meta = {
|
|
4929
|
-
id: Number.parseInt(idStr, 10),
|
|
4930
|
-
objectRequired: row?.objectRequired === true,
|
|
4931
|
-
...(objectTemplate !== undefined ? { objectTemplate } : {}),
|
|
4932
|
-
};
|
|
4933
|
-
}
|
|
4934
|
-
else {
|
|
4935
|
-
fallbackDiag = ` [GET /tm/action/${name} returned no usable row (idStr=null). Raw keys: ${row && typeof row === 'object' ? Object.keys(row).join(',') : typeof row}]`;
|
|
4936
|
-
}
|
|
6629
|
+
meta = await this.findActionLive(name);
|
|
4937
6630
|
}
|
|
4938
6631
|
catch (e) {
|
|
4939
|
-
fallbackDiag = ` [
|
|
6632
|
+
fallbackDiag = ` [action search failed: ${e.message}]`;
|
|
6633
|
+
}
|
|
6634
|
+
if (meta) {
|
|
6635
|
+
catalog.set(`id::${meta.id}`, meta);
|
|
6636
|
+
if (meta.name)
|
|
6637
|
+
catalog.set(meta.name.toLowerCase(), meta);
|
|
6638
|
+
if (meta.displayName)
|
|
6639
|
+
catalog.set(`dis::${meta.displayName.toLowerCase()}`, meta);
|
|
4940
6640
|
}
|
|
4941
6641
|
}
|
|
4942
6642
|
if (!meta) {
|
|
4943
|
-
throw new Error(`Automation step ${i + 1}:
|
|
6643
|
+
throw new Error(`Automation step ${i + 1}: the action "${name}" was not found in the action list for technology ${tech} (project ${projectId}). Check the action id, method name or display name.${fallbackDiag} [catalog: ${this.actionCatalogFetchDiag}]`);
|
|
4944
6644
|
}
|
|
4945
6645
|
let objectId = null;
|
|
4946
6646
|
if (meta.objectRequired) {
|
|
@@ -4960,7 +6660,7 @@ export class SimplifyQaAdapter {
|
|
|
4960
6660
|
const idIsSaved = !Number.isFinite(roundTripId) || String(roundTripId) === s.sourceObjectId;
|
|
4961
6661
|
const nameDiffers = !!refName && !!s.sourceObjectName && refName.toLowerCase() !== s.sourceObjectName.trim().toLowerCase();
|
|
4962
6662
|
if (refName && !(s.objectRef?.locators?.length) && s.sourceId && idIsSaved && (!Number.isFinite(roundTripId) || nameDiffers)) {
|
|
4963
|
-
const found = await
|
|
6663
|
+
const found = await lookupObjectByName(projectId, refName);
|
|
4964
6664
|
if (found == null) {
|
|
4965
6665
|
throw new Error(`Automation step ${i + 1} ("${name}"): no object named "${refName}" found in this project. Pass objectRef.id, or objectRef.locators to create one.`);
|
|
4966
6666
|
}
|
|
@@ -4973,7 +6673,7 @@ export class SimplifyQaAdapter {
|
|
|
4973
6673
|
objectId = undefined;
|
|
4974
6674
|
}
|
|
4975
6675
|
else if (s.objectRef?.name && !(s.objectRef.locators?.length)) {
|
|
4976
|
-
const found = await
|
|
6676
|
+
const found = await lookupObjectByName(projectId, s.objectRef.name);
|
|
4977
6677
|
if (found != null) {
|
|
4978
6678
|
objectId = found;
|
|
4979
6679
|
}
|
|
@@ -5031,15 +6731,20 @@ export class SimplifyQaAdapter {
|
|
|
5031
6731
|
* unless the step still uses them (a recorded value). Leaves a step alone when the object did not change or an
|
|
5032
6732
|
* object cannot be read — it never makes things worse than before. */
|
|
5033
6733
|
async reconcileObjectParams(steps, resolutions) {
|
|
6734
|
+
// Changed objects are independent per step — fetch their old/new parameter data in parallel.
|
|
6735
|
+
const changed = [];
|
|
5034
6736
|
for (let i = 0; i < steps.length; i++) {
|
|
5035
6737
|
const s = steps[i];
|
|
5036
6738
|
const newId = resolutions[i]?.objectId;
|
|
5037
6739
|
const oldId = s.sourceObjectId ? Number.parseInt(s.sourceObjectId, 10) : NaN;
|
|
5038
6740
|
if (typeof newId !== 'number' || !Number.isFinite(oldId) || oldId === newId)
|
|
5039
6741
|
continue;
|
|
5040
|
-
|
|
6742
|
+
changed.push({ s, oldId, newId });
|
|
6743
|
+
}
|
|
6744
|
+
await mapLimit(changed, 6, async ({ s, oldId, newId }) => {
|
|
6745
|
+
const [oldObj, newObj] = await Promise.all([this.fetchObjectParams(oldId), this.fetchObjectParams(newId)]);
|
|
5041
6746
|
if (!newObj)
|
|
5042
|
-
|
|
6747
|
+
return;
|
|
5043
6748
|
const keep = new Set(newObj.parameterId);
|
|
5044
6749
|
const rec = { ...(s.sourceRecordedParam ?? {}) };
|
|
5045
6750
|
const drop = new Set((oldObj?.parameterId ?? []).filter((id) => !keep.has(id) && String(rec[String(id)] ?? '').trim() === ''));
|
|
@@ -5056,7 +6761,7 @@ export class SimplifyQaAdapter {
|
|
|
5056
6761
|
else
|
|
5057
6762
|
delete s.sourceRecordedParam;
|
|
5058
6763
|
s.sourceObjectId = String(newId); // idempotent: a draft saved twice does not re-derive
|
|
5059
|
-
}
|
|
6764
|
+
});
|
|
5060
6765
|
}
|
|
5061
6766
|
/** Case-insensitive project-scoped exact-name lookup. Backend duplicate-name check uses Mongo
|
|
5062
6767
|
* collation strength:2, so a case-sensitive search here misses params stored under different
|
|
@@ -5551,10 +7256,93 @@ export class SimplifyQaAdapter {
|
|
|
5551
7256
|
* (`type:'EXECUTIONPLAN'`, `childExecution`, `parentExecutionId`) whose items are the assigned,
|
|
5552
7257
|
* non-blocked AUTOMATION entries matched to the shell's items. Every refusal happens before the
|
|
5553
7258
|
* first write. `POST /tm/execplantestcases/execute` (dead code) is never used. */
|
|
7259
|
+
/** The plan's saved STACK canvas (`/tm/executionFlow/EP/<id>/STACK`) or null. */
|
|
7260
|
+
async getPlanStacks(planId) {
|
|
7261
|
+
const plan = await this.readOwnPlan(planId);
|
|
7262
|
+
const raw = await this.http
|
|
7263
|
+
.getJson(`/tm/executionFlow/EP/${plan['id']}/STACK`)
|
|
7264
|
+
.catch(() => undefined);
|
|
7265
|
+
const doc = raw?.data ?? raw;
|
|
7266
|
+
return doc && typeof doc === 'object' && doc.id !== undefined ? doc : null;
|
|
7267
|
+
}
|
|
7268
|
+
/** Configure the plan's STACK canvas with N stacks and distribute its automation test cases across
|
|
7269
|
+
* them — the same document the UI's Stack Setup saves (`POST/PUT /tm/executionFlow`, flowType
|
|
7270
|
+
* 'STACK'). Round-robin by default; the backend divides the saved stacks at run time. */
|
|
7271
|
+
async configurePlanStacks(planId, opts) {
|
|
7272
|
+
const count = Math.trunc(opts.count);
|
|
7273
|
+
if (!Number.isFinite(count) || count < 1)
|
|
7274
|
+
throw new Error('stacks must be at least 1.');
|
|
7275
|
+
const plan = await this.readOwnPlan(planId, { writable: true });
|
|
7276
|
+
const projectId = this.requireProjectId();
|
|
7277
|
+
const mode = (opts.mode ?? 'CLOUD').toUpperCase();
|
|
7278
|
+
const entries = (await this.listPlanEntries(Number(plan['id'])))
|
|
7279
|
+
.filter((e) => String(e.executionType ?? '').toUpperCase() === 'AUTOMATION' && String(e.status ?? '').toUpperCase() !== 'BLOCKED');
|
|
7280
|
+
if (!entries.length)
|
|
7281
|
+
throw new Error(`${plan['code'] ?? planId} has no AUTOMATION test cases to distribute.`);
|
|
7282
|
+
const browserKey = (opts.browser ?? 'chrome').toLowerCase();
|
|
7283
|
+
const browser = { name: browserKey.charAt(0).toUpperCase() + browserKey.slice(1), key: browserKey, type: 'NONE' };
|
|
7284
|
+
const existing = await this.getPlanStacks(planId);
|
|
7285
|
+
const stackDefs = Array.from({ length: count }, (_, i) => ({
|
|
7286
|
+
id: randomUUID(), name: `Stack ${i + 1}`, position: null,
|
|
7287
|
+
mode, agentId: null,
|
|
7288
|
+
executionPlatform: { LOCAL: {}, REMOTE: {}, CLOUD: mode === 'CLOUD' ? { browser } : {} },
|
|
7289
|
+
items: [],
|
|
7290
|
+
}));
|
|
7291
|
+
entries.forEach((e, i) => {
|
|
7292
|
+
const stack = stackDefs[i % count];
|
|
7293
|
+
const tech = String(e.tcType ?? 'WEB').toUpperCase();
|
|
7294
|
+
const p = e.executionPlatform ?? {};
|
|
7295
|
+
const platform = PLAN_SPECIAL_TECH.includes(tech)
|
|
7296
|
+
? [{ name: tech, id: tech, technologyType: tech, type: 'NONE' }]
|
|
7297
|
+
: tech === 'WEB'
|
|
7298
|
+
? [{ name: browser.name, id: browser.key, technologyType: 'WEB', type: 'NONE' }]
|
|
7299
|
+
: [{ name: p.name, id: p.id, technologyType: p.technologyType ?? tech, type: p.type ?? 'NONE',
|
|
7300
|
+
...(p.cloudDeviceType ? { cloudDeviceType: p.cloudDeviceType } : {}), ...(p.osVersion ? { osVersion: p.osVersion } : {}) }];
|
|
7301
|
+
const item = {
|
|
7302
|
+
id: e.testcaseId, versionId: e.tcVersionId, stepId: e.stepId, type: e.type ?? 'TC',
|
|
7303
|
+
technologyType: tech, name: e.tcName ?? '', description: '', versionName: e.versionName ?? '',
|
|
7304
|
+
seq: e.seq ?? 0, stepCount: -1, code: e.code ?? '', prerequisite: '',
|
|
7305
|
+
projectId, projectName: '', moduleId: e.moduleId ?? null, moduleName: '',
|
|
7306
|
+
userstoryId: e.userstoryId ?? null, userstoryName: '',
|
|
7307
|
+
sourceType: e.sourceType ?? null, sourceId: e.sourceId ?? null,
|
|
7308
|
+
assignTo: e.expAssignedTo ?? null, assignDate: e.expAssignedDate ?? null, assigneeName: '',
|
|
7309
|
+
createdByName: '', createdBy: null,
|
|
7310
|
+
executionType: 'AUTOMATION', status: 'NOTEXECUTED', executionId: null, executionOS: null,
|
|
7311
|
+
iterationsSelected: [], platform,
|
|
7312
|
+
};
|
|
7313
|
+
stack.items.push(item);
|
|
7314
|
+
});
|
|
7315
|
+
const payload = {
|
|
7316
|
+
...(existing?.['id'] ? { id: existing['id'] } : {}),
|
|
7317
|
+
parentId: Number(plan['id']), parentType: 'EP', flowType: 'STACK', projectId,
|
|
7318
|
+
viewMode: false, stacks: stackDefs.map((s) => ({ ...s, position: s.position ?? null })),
|
|
7319
|
+
connections: [], canvasConfig: { startNodePosition: { x: 0, y: 0 } },
|
|
7320
|
+
};
|
|
7321
|
+
if (existing?.['id'])
|
|
7322
|
+
await this.http.putJson('/tm/executionFlow', payload);
|
|
7323
|
+
else
|
|
7324
|
+
await this.http.postJson('/tm/executionFlow', payload);
|
|
7325
|
+
// Read it back — the canvas shows the saved document, and a run divides by it.
|
|
7326
|
+
const after = await this.getPlanStacks(planId);
|
|
7327
|
+
const savedStacks = Array.isArray(after?.['stacks']) ? after['stacks'] : [];
|
|
7328
|
+
if (savedStacks.length !== count) {
|
|
7329
|
+
throw new Error(`Saved ${count} stack(s) but the plan's STACK drawing reads back ${savedStacks.length}.`);
|
|
7330
|
+
}
|
|
7331
|
+
const cloudAvailable = mode === 'CLOUD' ? (await this.listCloudRunners().catch(() => [])).some((r) => r.online) : undefined;
|
|
7332
|
+
return {
|
|
7333
|
+
created: !existing,
|
|
7334
|
+
...(cloudAvailable !== undefined ? { cloudAvailable } : {}),
|
|
7335
|
+
stacks: savedStacks.map((s, i) => ({
|
|
7336
|
+
id: String(s.id ?? ''), name: String(s.name ?? `Stack ${i + 1}`), mode: String(s.mode ?? mode),
|
|
7337
|
+
codes: (Array.isArray(s.items) ? s.items : []).map((it) => String(it.code ?? `TC-${it.id}`)),
|
|
7338
|
+
})),
|
|
7339
|
+
};
|
|
7340
|
+
}
|
|
5554
7341
|
async startExecutionPlanRun(planId, opts) {
|
|
5555
7342
|
const plan = await this.readOwnPlan(planId);
|
|
5556
7343
|
const code = String(plan['code'] ?? `PL-${plan['id']}`);
|
|
5557
7344
|
const projectId = this.requireProjectId();
|
|
7345
|
+
const runMode = opts.mode ?? 'local';
|
|
5558
7346
|
const reasons = [];
|
|
5559
7347
|
const runnable = [];
|
|
5560
7348
|
for (const e of await this.listPlanEntries(Number(plan['id']))) {
|
|
@@ -5574,12 +7362,62 @@ export class SimplifyQaAdapter {
|
|
|
5574
7362
|
const noPlatform = runnable.filter((e) => !PLAN_SPECIAL_TECH.includes(String(e.tcType)) && !e.executionPlatform?.id);
|
|
5575
7363
|
if (noPlatform.length)
|
|
5576
7364
|
throw new Error(`Set an execution platform first for: ${noPlatform.map((e) => str(e, 'code')).join(', ')}.`);
|
|
5577
|
-
|
|
5578
|
-
|
|
5579
|
-
|
|
5580
|
-
|
|
7365
|
+
// LOCAL uses this machine's agent; REMOTE the other machine's agent the caller names; CLOUD the project's configured
|
|
7366
|
+
// cloud machine; STACK is the canvas-saved stack drawing (auto-distributed), divided server-side. Like the UI's
|
|
7367
|
+
// Execute dialog, a STACK run sends the live local agent (for its LOCAL stacks) and the project's cloud type
|
|
7368
|
+
// (NONE when cloud isn't set up) — it is NOT gated on a cloud machine unless a stack really is CLOUD.
|
|
7369
|
+
let agentId;
|
|
7370
|
+
let cloudType = 'NONE';
|
|
7371
|
+
const requireLocalAgent = async () => {
|
|
7372
|
+
const probe = await this.probeLocalAgentDetailed();
|
|
7373
|
+
if (!probe.up) {
|
|
7374
|
+
throw new Error(`Can't run ${code} locally: the SimplifyQA desktop agent at ${probe.url ?? '(no URL)'} is not reachable` +
|
|
7375
|
+
`${probe.reason ? ` (${probe.reason})` : ''}. Start it, then try again.`);
|
|
7376
|
+
}
|
|
7377
|
+
return this.resolveLocalAgentId(opts.agentId);
|
|
7378
|
+
};
|
|
7379
|
+
const onlineCloud = async () => (await this.listCloudRunners().catch(() => [])).filter((r) => r.online);
|
|
7380
|
+
if (runMode === 'local') {
|
|
7381
|
+
agentId = await requireLocalAgent();
|
|
7382
|
+
}
|
|
7383
|
+
else if (runMode === 'remote') {
|
|
7384
|
+
if (!opts.agentId)
|
|
7385
|
+
throw new Error(`Running ${code} on a remote machine needs agentId — the other machine's agent (see remote_agents).`);
|
|
7386
|
+
agentId = opts.agentId;
|
|
7387
|
+
}
|
|
7388
|
+
else if (runMode === 'cloud') {
|
|
7389
|
+
const online = await onlineCloud();
|
|
7390
|
+
if (!online.length) {
|
|
7391
|
+
throw new Error(`No cloud machine is configured for this project, so ${code} cannot run on the cloud. ` +
|
|
7392
|
+
'Add/assign a cloud machine (VM / Azure / Kubernetes) in the project settings, or run the plan locally.');
|
|
7393
|
+
}
|
|
7394
|
+
cloudType = online[0]?.cloudType ?? 'VM';
|
|
7395
|
+
}
|
|
7396
|
+
else {
|
|
7397
|
+
const flow = await this.getPlanStacks(planId);
|
|
7398
|
+
const stacks = Array.isArray(flow?.['stacks']) ? flow['stacks'] : [];
|
|
7399
|
+
if (!stacks.length)
|
|
7400
|
+
throw new Error(`${code} has no saved stack setup — configure it first (action:"stack_setup").`);
|
|
7401
|
+
// The backend runs only the stacks holding a test case assigned to the user who starts the run, and silently does
|
|
7402
|
+
// nothing for anyone else — refuse that here instead of reporting a run that executes nothing.
|
|
7403
|
+
const me = await this.ensureUserId();
|
|
7404
|
+
const mine = stacks.filter((s) => (Array.isArray(s?.items) ? s.items : []).some((i) => me != null && String(i?.assignTo) === String(me)));
|
|
7405
|
+
if (!mine.length) {
|
|
7406
|
+
throw new Error(`None of ${code}'s stack test cases are assigned to you, so a stack run started by you would execute nothing. ` +
|
|
7407
|
+
'Run it as the assignee, or assign the test cases to yourself.');
|
|
7408
|
+
}
|
|
7409
|
+
const cloudStacks = mine.filter((s) => String(s?.mode).toUpperCase() === 'CLOUD');
|
|
7410
|
+
if (cloudStacks.length) {
|
|
7411
|
+
const online = await onlineCloud();
|
|
7412
|
+
if (!online.length) {
|
|
7413
|
+
throw new Error(`${code} has CLOUD stack(s) (${cloudStacks.map((s) => s?.name ?? s?.id).join(', ')}) but this project has no cloud machine configured. ` +
|
|
7414
|
+
'Add/assign a cloud machine (VM / Azure / Kubernetes) in the project settings, or re-run stack_setup with stackMode:"local".');
|
|
7415
|
+
}
|
|
7416
|
+
cloudType = online[0]?.cloudType ?? 'VM';
|
|
7417
|
+
}
|
|
7418
|
+
if (mine.some((s) => String(s?.mode).toUpperCase() === 'LOCAL'))
|
|
7419
|
+
agentId = await requireLocalAgent();
|
|
5581
7420
|
}
|
|
5582
|
-
const agentId = await this.resolveLocalAgentId(opts.agentId);
|
|
5583
7421
|
const shellRaw = await this.http.postJson('/exec/execution/search', {
|
|
5584
7422
|
searchFields: [
|
|
5585
7423
|
{ column: 'id', sort: 'dsc' }, { column: 'executionTypeId', value: Number(plan['id']) },
|
|
@@ -5620,14 +7458,16 @@ export class SimplifyQaAdapter {
|
|
|
5620
7458
|
delete body[k];
|
|
5621
7459
|
Object.assign(body, {
|
|
5622
7460
|
type: 'EXECUTIONPLAN', isRecordingEnabled: false, executionOS: this.detectExecutionOS(), status: 'INPROGRESS',
|
|
5623
|
-
executionType: 'AUTOMATION',
|
|
7461
|
+
executionType: 'AUTOMATION',
|
|
7462
|
+
mode: runMode === 'local' ? 'LOCAL' : runMode === 'remote' ? 'REMOTE' : runMode === 'cloud' ? 'CLOUD' : 'STACK',
|
|
7463
|
+
executionStyle: 'SERIAL', agentId: agentId ?? null, cloudType,
|
|
5624
7464
|
releaseId: plan['releaseId'] ?? null, iterationId: plan['iterationId'] ?? null,
|
|
5625
7465
|
childExecution: true, parentExecutionId: Number(shell.id),
|
|
5626
7466
|
globalConfiguration: {
|
|
5627
7467
|
TERMINATE_ON_FAIL: plan['terminateOnFailure'] ?? false, NEW_BROWSER_SESSION: plan['newBrowserSession'] ?? false,
|
|
5628
7468
|
RE_EXECUTION_COUNT: plan['autoReExecCount'] ?? 0, RE_EXECUTION_TYPE: plan['autoReExecTriggerOn'] ?? 'AFTER_TESTCASE',
|
|
5629
7469
|
},
|
|
5630
|
-
executionItems: items,
|
|
7470
|
+
executionItems: runMode === 'stack' ? [] : items,
|
|
5631
7471
|
});
|
|
5632
7472
|
let created;
|
|
5633
7473
|
try {
|
|
@@ -5684,6 +7524,132 @@ export class SimplifyQaAdapter {
|
|
|
5684
7524
|
throw new Error(`Unknown environment "${requested}". Available: ${envs.map((e) => e.name).join(', ')}.`);
|
|
5685
7525
|
return hit.key;
|
|
5686
7526
|
}
|
|
7527
|
+
/** The suite's saved STACK canvas (`/tm/executionFlow/SU/<id>/STACK`) or null. */
|
|
7528
|
+
async getSuiteStacks(suiteId) {
|
|
7529
|
+
const suite = await this.readOwnSuite(suiteId);
|
|
7530
|
+
const raw = await this.http
|
|
7531
|
+
.getJson(`/tm/executionFlow/SU/${suite['id']}/STACK`)
|
|
7532
|
+
.catch(() => undefined);
|
|
7533
|
+
const doc = raw?.data ?? raw;
|
|
7534
|
+
return doc && typeof doc === 'object' && doc.id !== undefined ? doc : null;
|
|
7535
|
+
}
|
|
7536
|
+
/** Configure the suite's STACK canvas with N stacks and spread its test cases across them — the same
|
|
7537
|
+
* document the suite's Stack canvas saves (`POST/PUT /tm/executionFlow`, parentType 'SU', flowType
|
|
7538
|
+
* 'STACK'). Round-robin; the backend divides the saved stacks at run time. */
|
|
7539
|
+
async configureSuiteStacks(suiteId, opts) {
|
|
7540
|
+
const count = Math.trunc(opts.count);
|
|
7541
|
+
if (!Number.isFinite(count) || count < 1)
|
|
7542
|
+
throw new Error('stacks must be at least 1.');
|
|
7543
|
+
const suite = await this.readOwnSuite(suiteId);
|
|
7544
|
+
const label = String(suite['code'] ?? `SU-${suite['id']}`);
|
|
7545
|
+
if (String(suite['suiteType'] ?? 'AUTOMATION').toUpperCase() === 'MANUAL') {
|
|
7546
|
+
throw new Error(`${label} is a manual suite — Stack execution is for automation suites.`);
|
|
7547
|
+
}
|
|
7548
|
+
const projectId = this.requireProjectId();
|
|
7549
|
+
const mode = (opts.mode ?? 'CLOUD').toUpperCase();
|
|
7550
|
+
const rows = (Array.isArray(suite['testCases']) ? suite['testCases'] : []).filter((r) => r?.deleted !== true && r?.stepId);
|
|
7551
|
+
if (!rows.length)
|
|
7552
|
+
throw new Error(`${label} has no saved test cases to distribute.`);
|
|
7553
|
+
const browserKey = (opts.browser ?? 'chrome').toLowerCase();
|
|
7554
|
+
const browser = { name: browserKey.charAt(0).toUpperCase() + browserKey.slice(1), key: browserKey, type: 'NONE' };
|
|
7555
|
+
const existing = await this.getSuiteStacks(suiteId);
|
|
7556
|
+
const stackDefs = Array.from({ length: count }, (_, i) => ({
|
|
7557
|
+
id: randomUUID(), name: `Stack ${i + 1}`, position: null,
|
|
7558
|
+
mode, agentId: null,
|
|
7559
|
+
executionPlatform: { LOCAL: {}, REMOTE: {}, CLOUD: mode === 'CLOUD' ? { browser } : {} },
|
|
7560
|
+
items: [],
|
|
7561
|
+
}));
|
|
7562
|
+
let i = 0;
|
|
7563
|
+
for (const row of rows) {
|
|
7564
|
+
const rawTc = await this.fetchRawTestcase(String(row.testcaseId)).catch(() => undefined);
|
|
7565
|
+
if (!rawTc || !Object.keys(rawTc).length)
|
|
7566
|
+
continue;
|
|
7567
|
+
const tech = String(str(rawTc, 'tcType') ?? 'WEB').toUpperCase();
|
|
7568
|
+
const versions = Array.isArray(rawTc?.versions) ? rawTc.versions : [];
|
|
7569
|
+
const ver = versions.find((v) => str(v, 'id', '_id') === String(row.versionId));
|
|
7570
|
+
const p = row?.executionPlatform?.[mode] ?? {};
|
|
7571
|
+
const platform = PLAN_SPECIAL_TECH.includes(tech)
|
|
7572
|
+
? [{ name: tech, id: tech, technologyType: tech, type: 'NONE' }]
|
|
7573
|
+
: tech === 'WEB'
|
|
7574
|
+
? [{ name: browser.name, id: browser.key, technologyType: 'WEB', type: 'NONE' }]
|
|
7575
|
+
: [{ name: p.name, id: p.id, technologyType: p.technologyType ?? tech, type: p.type ?? 'NONE',
|
|
7576
|
+
...(p.cloudDeviceType ? { cloudDeviceType: p.cloudDeviceType } : {}), ...(p.osVersion ? { osVersion: p.osVersion } : {}) }];
|
|
7577
|
+
stackDefs[i % count].items.push({
|
|
7578
|
+
id: Number(rawTc.id ?? row.testcaseId), versionId: row.versionId, stepId: row.stepId, type: 'TC',
|
|
7579
|
+
technologyType: tech, name: str(rawTc, 'name', 'title') ?? '', description: '', versionName: str(ver, 'name') ?? '',
|
|
7580
|
+
seq: row.seq ?? i + 1, stepCount: -1, code: str(rawTc, 'code') ?? '', prerequisite: '',
|
|
7581
|
+
projectId, projectName: '', moduleId: rawTc.moduleId ?? null, moduleName: '',
|
|
7582
|
+
userstoryId: rawTc.userstoryId ?? null, userstoryName: '',
|
|
7583
|
+
sourceType: null, sourceId: null, assignTo: null, assignDate: null, assigneeName: '',
|
|
7584
|
+
createdByName: '', createdBy: null,
|
|
7585
|
+
executionType: 'AUTOMATION', status: 'NOTEXECUTED', executionId: null, executionOS: null,
|
|
7586
|
+
iterationsSelected: [], platform,
|
|
7587
|
+
});
|
|
7588
|
+
i++;
|
|
7589
|
+
}
|
|
7590
|
+
if (!i)
|
|
7591
|
+
throw new Error(`None of ${label}'s test cases could be read, so there is nothing to distribute.`);
|
|
7592
|
+
if (count > i)
|
|
7593
|
+
throw new Error(`${label} has ${i} test case(s) — it cannot fill ${count} stacks (every stack needs at least one).`);
|
|
7594
|
+
const payload = {
|
|
7595
|
+
...(existing?.['id'] ? { id: existing['id'] } : {}),
|
|
7596
|
+
parentId: Number(suite['id']), parentType: 'SU', flowType: 'STACK', projectId,
|
|
7597
|
+
viewMode: false, stacks: stackDefs,
|
|
7598
|
+
connections: [], canvasConfig: { startNodePosition: { x: 0, y: 0 } },
|
|
7599
|
+
};
|
|
7600
|
+
if (existing?.['id'])
|
|
7601
|
+
await this.http.putJson('/tm/executionFlow', payload);
|
|
7602
|
+
else
|
|
7603
|
+
await this.http.postJson('/tm/executionFlow', payload);
|
|
7604
|
+
const after = await this.getSuiteStacks(suiteId);
|
|
7605
|
+
const saved = Array.isArray(after?.['stacks']) ? after['stacks'] : [];
|
|
7606
|
+
if (saved.length !== count)
|
|
7607
|
+
throw new Error(`Saved ${count} stack(s) but ${label}'s STACK drawing reads back ${saved.length}.`);
|
|
7608
|
+
const cloudAvailable = mode === 'CLOUD' ? (await this.listCloudRunners().catch(() => [])).some((r) => r.online) : undefined;
|
|
7609
|
+
return {
|
|
7610
|
+
created: !existing,
|
|
7611
|
+
...(cloudAvailable !== undefined ? { cloudAvailable } : {}),
|
|
7612
|
+
stacks: saved.map((s, n) => ({
|
|
7613
|
+
id: String(s.id ?? ''), name: String(s.name ?? `Stack ${n + 1}`), mode: String(s.mode ?? mode),
|
|
7614
|
+
codes: (Array.isArray(s.items) ? s.items : []).map((it) => String(it.code ?? `TC-${it.id}`)),
|
|
7615
|
+
})),
|
|
7616
|
+
};
|
|
7617
|
+
}
|
|
7618
|
+
/** What a suite STACK run needs, checked before anything is created: a saved canvas with no empty stack,
|
|
7619
|
+
* a cloud machine only when a stack is CLOUD, and this machine's agent only when a stack is LOCAL. */
|
|
7620
|
+
async suiteStackRunPlan(rawSuite, opts) {
|
|
7621
|
+
const label = String(rawSuite['code'] ?? `SU-${rawSuite['id']}`);
|
|
7622
|
+
if (String(rawSuite['suiteType'] ?? 'AUTOMATION').toUpperCase() === 'MANUAL') {
|
|
7623
|
+
throw new Error(`${label} is a manual suite — Stack execution is for automation suites.`);
|
|
7624
|
+
}
|
|
7625
|
+
const flow = await this.getSuiteStacks(String(rawSuite['id']));
|
|
7626
|
+
const stacks = Array.isArray(flow?.['stacks']) ? flow['stacks'] : [];
|
|
7627
|
+
if (!stacks.length)
|
|
7628
|
+
throw new Error(`${label} has no saved stack setup — configure it first (suite_manage action:"stack_setup").`);
|
|
7629
|
+
const empty = stacks.filter((s) => !(Array.isArray(s?.items) && s.items.length));
|
|
7630
|
+
if (empty.length)
|
|
7631
|
+
throw new Error(`Every stack needs at least one test case — empty: ${empty.map((s) => s?.name ?? s?.id).join(', ')}.`);
|
|
7632
|
+
let cloudType = 'NONE';
|
|
7633
|
+
const cloudStacks = stacks.filter((s) => String(s?.mode).toUpperCase() === 'CLOUD');
|
|
7634
|
+
if (cloudStacks.length) {
|
|
7635
|
+
const online = (await this.listCloudRunners().catch(() => [])).filter((r) => r.online);
|
|
7636
|
+
if (!online.length) {
|
|
7637
|
+
throw new Error(`${label} has CLOUD stack(s) (${cloudStacks.map((s) => s?.name ?? s?.id).join(', ')}) but this project has no cloud machine configured. ` +
|
|
7638
|
+
'Add/assign a cloud machine in the project settings, or re-run stack_setup with stackMode:"local".');
|
|
7639
|
+
}
|
|
7640
|
+
cloudType = online[0]?.cloudType ?? 'VM';
|
|
7641
|
+
}
|
|
7642
|
+
let agentId = null;
|
|
7643
|
+
if (stacks.some((s) => (String(s?.mode ?? 'LOCAL')).toUpperCase() === 'LOCAL')) {
|
|
7644
|
+
const probe = await this.probeLocalAgentDetailed();
|
|
7645
|
+
if (!probe.up) {
|
|
7646
|
+
throw new Error(`Can't run ${label} with local stacks: the SimplifyQA desktop agent at ${probe.url ?? '(no URL)'} is not reachable` +
|
|
7647
|
+
`${probe.reason ? ` (${probe.reason})` : ''}. Start it, then try again.`);
|
|
7648
|
+
}
|
|
7649
|
+
agentId = await this.resolveLocalAgentId(opts.agentId);
|
|
7650
|
+
}
|
|
7651
|
+
return { agentId, cloudType };
|
|
7652
|
+
}
|
|
5687
7653
|
/** A live suite of the ACTIVE project, or a clear refusal — checked before every suite write. */
|
|
5688
7654
|
async readOwnSuite(id) {
|
|
5689
7655
|
const raw = await this.fetchRawSuite(id);
|
|
@@ -5717,6 +7683,38 @@ export class SimplifyQaAdapter {
|
|
|
5717
7683
|
throw e;
|
|
5718
7684
|
}
|
|
5719
7685
|
// ---------------------------------------------------------------------- Scheduler
|
|
7686
|
+
/** The names schedules already have in the active project (lower-case → id / code) — the Scheduler refuses a second one. */
|
|
7687
|
+
async scheduleNames() {
|
|
7688
|
+
const out = new Map();
|
|
7689
|
+
// best effort: a failed lookup must not block scheduling — the Scheduler's own duplicate answer is still translated (scheduleNameError)
|
|
7690
|
+
const raw = await this.http.postJson('/sh/scheduler/search', this.searchBody([{ column: 'projectId', value: this.requireProjectId() }], { limit: 500, rawOffset: true })).catch(() => undefined);
|
|
7691
|
+
for (const r of raw ? pickArray(raw, 'data', 'content') : []) {
|
|
7692
|
+
if (r?.deleted === true || typeof r?.name !== 'string')
|
|
7693
|
+
continue;
|
|
7694
|
+
out.set(r.name.trim().toLowerCase(), { id: String(r.id), ...(r.code ? { code: String(r.code) } : {}) });
|
|
7695
|
+
}
|
|
7696
|
+
return out;
|
|
7697
|
+
}
|
|
7698
|
+
/** The Scheduler form's rule for a name: 3–501 characters, unique in the project. `selfId` is the schedule being renamed. */
|
|
7699
|
+
checkScheduleName(name, taken, selfId) {
|
|
7700
|
+
const n = String(name ?? '').trim();
|
|
7701
|
+
if (n.length < 3)
|
|
7702
|
+
throw new Error('A schedule name needs at least 3 characters.');
|
|
7703
|
+
if (n.length > 501)
|
|
7704
|
+
throw new Error('A schedule name can be at most 501 characters.');
|
|
7705
|
+
const clash = taken.get(n.toLowerCase());
|
|
7706
|
+
if (clash && clash.id !== selfId) {
|
|
7707
|
+
throw new Error(`A schedule named "${n}" already exists in this project (${clash.code ?? `#${clash.id}`}). Pick another name — the Scheduler needs each schedule name to be unique.`);
|
|
7708
|
+
}
|
|
7709
|
+
return n;
|
|
7710
|
+
}
|
|
7711
|
+
/** The Scheduler's own duplicate answer (HTTP 409 / DUPLICATENAME), said in words. */
|
|
7712
|
+
scheduleNameError(e, name) {
|
|
7713
|
+
const text = e instanceof ApiError ? `${e.body} ${e.message}` : (e instanceof Error ? e.message : String(e));
|
|
7714
|
+
return /DUPLICATENAME|Duplicate Name|\b409\b/i.test(text)
|
|
7715
|
+
? new Error(`A schedule named "${name}" already exists in this project — the Scheduler needs each schedule name to be unique. Pick another name.`)
|
|
7716
|
+
: undefined;
|
|
7717
|
+
}
|
|
5720
7718
|
/** A schedule — the scheduler form's body (scheduler-form.component.ts:363-388, +tz on create). TC:
|
|
5721
7719
|
* the browser as its platform; SU: one platform per technology in the suite (suitePlatform). An execution
|
|
5722
7720
|
* plan is refused: the Scheduler UI offers only test case and suite (its EP option is commented out). */
|
|
@@ -5749,10 +7747,21 @@ export class SimplifyQaAdapter {
|
|
|
5749
7747
|
throw new Error('Nothing to schedule: give a test case or a suite.');
|
|
5750
7748
|
}
|
|
5751
7749
|
const timeZone = opts.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
5752
|
-
const rec = sqaRecurrence(opts.scheduleType, opts.scheduledFor, opts.endDate, timeZone);
|
|
7750
|
+
const rec = sqaRecurrence(opts.scheduleType, opts.scheduledFor, opts.endDate, timeZone, recurrenceExtras(opts));
|
|
5753
7751
|
const code = String(parent['code'] ?? parent['id']);
|
|
7752
|
+
// the caller's name; or "<TC-22> schedule", numbered when taken — a second schedule of the same target used to fail with HTTP 409
|
|
7753
|
+
const taken = await this.scheduleNames();
|
|
7754
|
+
let scheduleName;
|
|
7755
|
+
if (opts.name !== undefined)
|
|
7756
|
+
scheduleName = this.checkScheduleName(opts.name, taken);
|
|
7757
|
+
else {
|
|
7758
|
+
const base = `${code} schedule`;
|
|
7759
|
+
scheduleName = base;
|
|
7760
|
+
for (let i = 2; taken.has(scheduleName.toLowerCase()); i++)
|
|
7761
|
+
scheduleName = `${base} ${i}`;
|
|
7762
|
+
}
|
|
5754
7763
|
const body = {
|
|
5755
|
-
projectId, name:
|
|
7764
|
+
projectId, name: scheduleName, schedulerType, parentId: Number(parent['id']),
|
|
5756
7765
|
...(parentVersionId ? { parentVersionId } : {}),
|
|
5757
7766
|
platForm,
|
|
5758
7767
|
environment: opts.environmentId ? await this.environmentKey(opts.environmentId) : 'general',
|
|
@@ -5766,10 +7775,17 @@ export class SimplifyQaAdapter {
|
|
|
5766
7775
|
offset: new Date().getTimezoneOffset(), tz: timeZone,
|
|
5767
7776
|
retryConfig: { retryEnabled: false, retryCount: 1, retryIntervalMinutes: 5 },
|
|
5768
7777
|
};
|
|
5769
|
-
|
|
7778
|
+
let raw;
|
|
7779
|
+
try {
|
|
7780
|
+
raw = await this.http.postJson('/sh/scheduler', body);
|
|
7781
|
+
}
|
|
7782
|
+
catch (e) {
|
|
7783
|
+
throw this.scheduleNameError(e, scheduleName) ?? e;
|
|
7784
|
+
}
|
|
5770
7785
|
const doc = raw?.data ?? raw;
|
|
5771
7786
|
return {
|
|
5772
7787
|
id: String(doc?.id ?? ''),
|
|
7788
|
+
name: String(doc?.name ?? scheduleName),
|
|
5773
7789
|
...(doc?.status ? { status: String(doc.status) } : {}),
|
|
5774
7790
|
...(doc?.nextRecurrenceTime ? { nextRunAt: String(doc.nextRecurrenceTime) } : {}),
|
|
5775
7791
|
};
|
|
@@ -5778,6 +7794,7 @@ export class SimplifyQaAdapter {
|
|
|
5778
7794
|
const raw = await this.http.postJson('/sh/scheduler/search', this.searchBody([{ column: 'projectId', value: this.requireProjectId() }], { limit: 500, rawOffset: true }));
|
|
5779
7795
|
return pickArray(raw, 'data', 'content').map((r) => ({
|
|
5780
7796
|
id: String(r.id),
|
|
7797
|
+
...(typeof r.name === 'string' && r.name ? { name: r.name } : {}),
|
|
5781
7798
|
target: `${r.schedulerType ?? ''} ${r.parentId ?? ''} — ${r.name ?? r.code ?? ''}`.trim(),
|
|
5782
7799
|
scheduleType: String(r.recurrenceType ?? ''),
|
|
5783
7800
|
status: String(r.status ?? ''),
|
|
@@ -5816,6 +7833,9 @@ export class SimplifyQaAdapter {
|
|
|
5816
7833
|
}
|
|
5817
7834
|
body['reccurenceData'] = rec;
|
|
5818
7835
|
Object.assign(body, changes, { nextRecurrenceTime: null, updateVersion: doc['updateVersion'] ?? 0 });
|
|
7836
|
+
for (const k of Object.keys(changes))
|
|
7837
|
+
if (changes[k] === undefined)
|
|
7838
|
+
delete body[k];
|
|
5819
7839
|
const raw = await this.http.putJson(`/sh/scheduler/${doc['id']}`, body).catch((e) => this.rethrowWrite(e, doc));
|
|
5820
7840
|
const out = raw?.data ?? raw;
|
|
5821
7841
|
return { id: String(doc['id']), ...(out?.status ? { status: String(out.status) } : {}) };
|
|
@@ -5823,16 +7843,19 @@ export class SimplifyQaAdapter {
|
|
|
5823
7843
|
async updateSchedule(scheduleId, changes) {
|
|
5824
7844
|
const doc = await this.readOwnSchedule(scheduleId);
|
|
5825
7845
|
const patch = {};
|
|
5826
|
-
|
|
7846
|
+
const extras = recurrenceExtras(changes);
|
|
7847
|
+
// a change to N / days / day-of-month rebuilds the cadence the schedule already has
|
|
7848
|
+
const cadence = changes.scheduleType ?? (Object.keys(extras).length ? neutralCadence(doc) : undefined);
|
|
7849
|
+
if (changes.scheduledFor || changes.scheduleType || changes.endDate !== undefined || cadence) {
|
|
5827
7850
|
const start = changes.scheduledFor ?? String(doc['scheduleStartDate']);
|
|
5828
7851
|
const storedOnce = String(doc['recurrenceType'] ?? 'ONCE').toUpperCase() === 'ONCE';
|
|
5829
|
-
if (
|
|
7852
|
+
if (cadence) {
|
|
5830
7853
|
// A new cadence: rebuilt like a new schedule. Its end date is the one given, or the stored
|
|
5831
7854
|
// one only when the schedule already recurred (a ONCE schedule's end is just its start).
|
|
5832
7855
|
const end = realEndDate(changes.endDate) ?? (storedOnce ? undefined : realEndDate(doc['scheduleEndDate']));
|
|
5833
|
-
if (
|
|
7856
|
+
if (cadence !== 'once' && !end)
|
|
5834
7857
|
throw new Error(NEEDS_END_DATE);
|
|
5835
|
-
const rec = sqaRecurrence(
|
|
7858
|
+
const rec = sqaRecurrence(cadence, start, end, changes.timezone ?? doc['tz'] ?? Intl.DateTimeFormat().resolvedOptions().timeZone, extras);
|
|
5836
7859
|
Object.assign(patch, {
|
|
5837
7860
|
scheduleStartDate: start, scheduleEndDate: rec.scheduleEndDate,
|
|
5838
7861
|
recurrenceType: rec.recurrenceType, reccurenceData: rec.reccurenceData,
|
|
@@ -5856,7 +7879,62 @@ export class SimplifyQaAdapter {
|
|
|
5856
7879
|
if (changes.scheduledFor && doc['cancelled'] === true)
|
|
5857
7880
|
Object.assign(patch, { cancelled: false, status: 'NOT STARTED' });
|
|
5858
7881
|
}
|
|
5859
|
-
|
|
7882
|
+
// WHAT it runs: a test case or a suite — the same schedule, re-pointed (the Scheduler form's type + target), with the platform and
|
|
7883
|
+
// version that kind of schedule carries, as createSchedule builds them.
|
|
7884
|
+
const notes = [];
|
|
7885
|
+
let target;
|
|
7886
|
+
if (changes.tcId !== undefined || changes.suiteId !== undefined) {
|
|
7887
|
+
if (changes.tcId !== undefined && changes.suiteId !== undefined)
|
|
7888
|
+
throw new Error('Give either a test case (tcId) or a suite (suiteId) to run, not both.');
|
|
7889
|
+
const projectId = this.requireProjectId();
|
|
7890
|
+
const wasType = String(doc['schedulerType'] ?? '');
|
|
7891
|
+
if (changes.suiteId !== undefined) {
|
|
7892
|
+
const suite = await this.readOwnSuite(changes.suiteId);
|
|
7893
|
+
const platForm = suitePlatform(suite, changes.browser, 'schedule it');
|
|
7894
|
+
Object.assign(patch, { schedulerType: 'SU', parentId: Number(suite['id']), platForm, parentVersionId: undefined });
|
|
7895
|
+
target = { type: 'SU', id: Number(suite['id']), code: String(suite['code'] ?? `SU-${suite['id']}`) };
|
|
7896
|
+
}
|
|
7897
|
+
else {
|
|
7898
|
+
const tc = await this.fetchRawTestcase(changes.tcId);
|
|
7899
|
+
if (!Object.keys(tc).length || tc['deleted'] === true)
|
|
7900
|
+
throw new Error(`Test case ${changes.tcId} not found.`);
|
|
7901
|
+
if (Number(tc['projectId']) !== projectId)
|
|
7902
|
+
throw new Error(`${tc['code'] ?? `TC-${tc['id']}`} is not in project ${projectId}.`);
|
|
7903
|
+
// keep the browser the schedule already runs WEB in (a suite schedule has one per technology) unless a new one is given
|
|
7904
|
+
const webEntry = (Array.isArray(doc['platForm']) ? doc['platForm'] : []).find((p) => String(p?.technologyType ?? '').toUpperCase() === 'WEB');
|
|
7905
|
+
const keepBrowser = changes.browser ?? (webEntry?.id ? String(webEntry.id) : undefined);
|
|
7906
|
+
Object.assign(patch, {
|
|
7907
|
+
schedulerType: 'TC', parentId: Number(tc['id']), platForm: tcPlatform(tc, keepBrowser),
|
|
7908
|
+
parentVersionId: testcaseVersion(tc, true).versionId || undefined,
|
|
7909
|
+
});
|
|
7910
|
+
target = { type: 'TC', id: Number(tc['id']), code: String(tc['code'] ?? `TC-${tc['id']}`) };
|
|
7911
|
+
}
|
|
7912
|
+
if (wasType === target.type && Number(doc['parentId']) === target.id) {
|
|
7913
|
+
target = undefined;
|
|
7914
|
+
for (const k of ['schedulerType', 'parentId', 'platForm', 'parentVersionId'])
|
|
7915
|
+
delete patch[k];
|
|
7916
|
+
}
|
|
7917
|
+
else if (wasType !== target.type)
|
|
7918
|
+
notes.push(`This schedule was a ${wasType === 'SU' ? 'Suite' : 'Test Case'} schedule; it is now a ${target.type === 'SU' ? 'Suite' : 'Test Case'} schedule (same id).`);
|
|
7919
|
+
const stored = String(doc['name'] ?? '');
|
|
7920
|
+
if (target && changes.name === undefined && /schedule(?: \d+)?$/i.test(stored) && /^[A-Z]{2,}[-_]\d+ schedule/i.test(stored)) {
|
|
7921
|
+
notes.push(`Its name is still "${stored}" — pass \`name\` to rename it for ${target.code}.`);
|
|
7922
|
+
}
|
|
7923
|
+
}
|
|
7924
|
+
// release / sprint (a suite schedule needs a release)
|
|
7925
|
+
if (changes.releaseId !== undefined || changes.sprintId !== undefined) {
|
|
7926
|
+
const plan = await this.resolveTaskPlanning(changes.releaseId, changes.sprintId);
|
|
7927
|
+
if (plan.releaseId !== undefined)
|
|
7928
|
+
patch['releaseId'] = plan.releaseId;
|
|
7929
|
+
if (plan.iterationId !== undefined)
|
|
7930
|
+
patch['iterationId'] = plan.iterationId;
|
|
7931
|
+
}
|
|
7932
|
+
const finalType = String(patch['schedulerType'] ?? doc['schedulerType'] ?? '');
|
|
7933
|
+
const finalRelease = 'releaseId' in patch ? patch['releaseId'] : doc['releaseId'];
|
|
7934
|
+
if (target?.type === 'SU' && (finalRelease === null || finalRelease === undefined || finalRelease === 0)) {
|
|
7935
|
+
throw new Error('A suite schedule needs a release (the Scheduler marks Release as required for a suite) — pass releaseId (id, code or name).');
|
|
7936
|
+
}
|
|
7937
|
+
if (changes.browser && doc['schedulerType'] === 'TC' && finalType === 'TC' && !('platForm' in patch)) {
|
|
5860
7938
|
const b = sqaBrowser(changes.browser);
|
|
5861
7939
|
patch['platForm'] = [{ id: b, name: b, type: 'NONE', technologyType: 'WEB' }];
|
|
5862
7940
|
}
|
|
@@ -5866,7 +7944,29 @@ export class SimplifyQaAdapter {
|
|
|
5866
7944
|
patch['agentId'] = [changes.agentId];
|
|
5867
7945
|
if (changes.mode)
|
|
5868
7946
|
patch['executionMode'] = changes.mode;
|
|
5869
|
-
|
|
7947
|
+
let newName;
|
|
7948
|
+
if (changes.name !== undefined) {
|
|
7949
|
+
newName = this.checkScheduleName(changes.name, await this.scheduleNames(), String(doc['id']));
|
|
7950
|
+
if (newName !== String(doc['name'] ?? ''))
|
|
7951
|
+
patch['name'] = newName;
|
|
7952
|
+
else
|
|
7953
|
+
newName = undefined;
|
|
7954
|
+
}
|
|
7955
|
+
let ref;
|
|
7956
|
+
try {
|
|
7957
|
+
ref = await this.putSchedule(doc, patch);
|
|
7958
|
+
}
|
|
7959
|
+
catch (e) {
|
|
7960
|
+
throw (newName ? this.scheduleNameError(e, newName) : undefined) ?? e;
|
|
7961
|
+
}
|
|
7962
|
+
const after = newName !== undefined || target ? await this.readOwnSchedule(String(doc['id'])) : undefined;
|
|
7963
|
+
if (after && newName !== undefined && String(after['name'] ?? '') !== newName) {
|
|
7964
|
+
throw new Error(`The schedule was sent the name "${newName}" but reads back as "${String(after['name'] ?? '')}".`);
|
|
7965
|
+
}
|
|
7966
|
+
if (after && target && (String(after['schedulerType'] ?? '') !== target.type || Number(after['parentId']) !== target.id)) {
|
|
7967
|
+
throw new Error(`The schedule was pointed at ${target.type} ${target.id} (${target.code}) but reads back as ${String(after['schedulerType'] ?? '')} ${String(after['parentId'] ?? '')}.`);
|
|
7968
|
+
}
|
|
7969
|
+
return { ...ref, ...(newName !== undefined ? { name: newName } : {}), ...(notes.length ? { notes } : {}) };
|
|
5870
7970
|
}
|
|
5871
7971
|
async controlSchedule(scheduleId, action) {
|
|
5872
7972
|
if (action === 'pause')
|
|
@@ -6974,7 +9074,7 @@ export class SimplifyQaAdapter {
|
|
|
6974
9074
|
throw new Error(`No iteration "${w}" on ${q.entityType} ${q.id}. Rows: ${rows.iterations.map((r) => r.name || r.id).join(', ') || '(none)'}.`);
|
|
6975
9075
|
}
|
|
6976
9076
|
if (rows.defaultIterationId && String(row.id) === String(rows.defaultIterationId)) {
|
|
6977
|
-
throw new Error(`"${row.name || row.id}" is the DEFAULT iteration and cannot be deleted.`);
|
|
9077
|
+
throw new Error(`"${row.name || row.id}" is the DEFAULT iteration and cannot be deleted. Make another iteration the default first (testdata_set_default_iteration), then delete it.`);
|
|
6978
9078
|
}
|
|
6979
9079
|
if (!targets.includes(String(row.id)))
|
|
6980
9080
|
targets.push(String(row.id));
|
|
@@ -6992,6 +9092,64 @@ export class SimplifyQaAdapter {
|
|
|
6992
9092
|
const after = await this.testdataRowsFor(td, q.entityType, q.id, q.environmentType);
|
|
6993
9093
|
return { deleted: targets, rows: after };
|
|
6994
9094
|
}
|
|
9095
|
+
/** Make one iteration row the DEFAULT of an environment — the row a run executes — for a test case, function or suite. The default is not a flag
|
|
9096
|
+
* on the row: it is `defaultIteration` on the test data DEFINITION, a map of environment → iteration id, saved through the same update the test data page
|
|
9097
|
+
* uses (`PUT /tm/testdata/update`, which also records the change). That update takes at least one row (the backend reads the project from it) and
|
|
9098
|
+
* the definition's NUMERIC id, so the chosen row goes back unchanged. Other environments' defaults are kept, a stale version is retried once, and the
|
|
9099
|
+
* test data is read again to confirm the new default. */
|
|
9100
|
+
async setDefaultTestdataIteration(q) {
|
|
9101
|
+
const projectId = this.requireProjectId();
|
|
9102
|
+
const key = String(q.iteration ?? '').trim();
|
|
9103
|
+
if (!key)
|
|
9104
|
+
throw new Error('iteration is required — the iteration name (e.g. "ITR-2") or id to make the default.');
|
|
9105
|
+
let td = await this.testdataDefinitionRow(q.entityType, q.id);
|
|
9106
|
+
let rows = await this.testdataRowsFor(td, q.entityType, q.id, q.environmentType);
|
|
9107
|
+
const row = rows.iterations.find((r) => r.name === key)
|
|
9108
|
+
?? rows.iterations.find((r) => r.name.trim().toLowerCase() === key.toLowerCase())
|
|
9109
|
+
?? rows.iterations.find((r) => String(r.id) === key);
|
|
9110
|
+
if (!row) {
|
|
9111
|
+
throw new Error(`No iteration "${key}" on ${q.entityType} ${q.id} in environment "${rows.environmentType}". Rows: ${rows.iterations.map((r) => r.name || r.id).join(', ') || '(none)'}.`);
|
|
9112
|
+
}
|
|
9113
|
+
const previousRow = rows.defaultIterationId ? rows.iterations.find((r) => String(r.id) === String(rows.defaultIterationId)) : undefined;
|
|
9114
|
+
const previous = previousRow ? (previousRow.name || previousRow.id) : undefined;
|
|
9115
|
+
if (String(row.id) === String(rows.defaultIterationId ?? '')) {
|
|
9116
|
+
return { iteration: row.name || row.id, ...(previous ? { previous } : {}), changed: false, rows };
|
|
9117
|
+
}
|
|
9118
|
+
const env = rows.environmentType;
|
|
9119
|
+
const stripped = JSON.parse(JSON.stringify(row));
|
|
9120
|
+
for (const k of ['_id', '__v', 'customerId', 'deleted', 'createdAt', 'createdBy', 'updatedAt', 'updatedBy', 'fnMap', 'isEdit', 'newIteration', 'showEditMode'])
|
|
9121
|
+
delete stripped[k];
|
|
9122
|
+
stripped['projectId'] = stripped['projectId'] ?? td['projectId'] ?? projectId;
|
|
9123
|
+
const send = (d) => {
|
|
9124
|
+
const current = d['defaultIteration'];
|
|
9125
|
+
const map = current && typeof current === 'object' && !Array.isArray(current) ? { ...current } : {};
|
|
9126
|
+
map[env] = String(row.id);
|
|
9127
|
+
const idText = String(d['id']);
|
|
9128
|
+
return this.http.putJson('/tm/testdata/update', {
|
|
9129
|
+
payload: [stripped],
|
|
9130
|
+
testdata: {
|
|
9131
|
+
id: /^\d+$/.test(idText) ? Number(idText) : d['id'], defaultIteration: map,
|
|
9132
|
+
projectId: Number(d['projectId'] ?? projectId), updateVersion: d['updateVersion'] ?? 0,
|
|
9133
|
+
},
|
|
9134
|
+
});
|
|
9135
|
+
};
|
|
9136
|
+
try {
|
|
9137
|
+
await send(td);
|
|
9138
|
+
}
|
|
9139
|
+
catch (e) {
|
|
9140
|
+
if (!/CONCURRENCY|Concurrency Error/i.test(e instanceof Error ? e.message : String(e)))
|
|
9141
|
+
throw e;
|
|
9142
|
+
td = await this.testdataDefinitionRow(q.entityType, q.id);
|
|
9143
|
+
await send(td);
|
|
9144
|
+
}
|
|
9145
|
+
const after = await this.testdataDefinitionRow(q.entityType, q.id);
|
|
9146
|
+
rows = await this.testdataRowsFor(after, q.entityType, q.id, q.environmentType);
|
|
9147
|
+
if (String(rows.defaultIterationId ?? '') !== String(row.id)) {
|
|
9148
|
+
const now = rows.defaultIterationId ? rows.iterations.find((r) => String(r.id) === String(rows.defaultIterationId)) : undefined;
|
|
9149
|
+
throw new Error(`Sent "${row.name || row.id}" as the default of ${q.entityType} ${q.id} (env ${env}), but SimplifyQA still shows "${now ? (now.name || now.id) : '(none)'}" as the default.`);
|
|
9150
|
+
}
|
|
9151
|
+
return { iteration: row.name || row.id, ...(previous ? { previous } : {}), changed: true, rows };
|
|
9152
|
+
}
|
|
6995
9153
|
/** Copy the default-iteration values of one TC onto another, matching parameters BY NAME. * Used by tc_automate: a manual TC converted to automated must carry the manual TC's testdata,
|
|
6996
9154
|
* not the values that happened to be typed during the recording. Protected source values are read
|
|
6997
9155
|
* unmasked internally so they can be copied — they are never returned to the model.
|
|
@@ -7114,8 +9272,12 @@ export class SimplifyQaAdapter {
|
|
|
7114
9272
|
data[idx] = next;
|
|
7115
9273
|
}
|
|
7116
9274
|
else {
|
|
9275
|
+
// `type:'OB'` is what the backend writes on every parameter cell; a cell without it makes the
|
|
9276
|
+
// test-data screen throw "Cannot read properties of undefined (reading 'type')" and the run
|
|
9277
|
+
// end as Not Executed.
|
|
7117
9278
|
data.push({
|
|
7118
9279
|
paramId,
|
|
9280
|
+
type: 'OB',
|
|
7119
9281
|
value: cell.value ?? '',
|
|
7120
9282
|
...(cell.formulaValue ? { formulaValue: cell.formulaValue } : {}),
|
|
7121
9283
|
});
|
|
@@ -7133,6 +9295,75 @@ export class SimplifyQaAdapter {
|
|
|
7133
9295
|
});
|
|
7134
9296
|
return { patched, skipped };
|
|
7135
9297
|
}
|
|
9298
|
+
/** Find and repair test-data cells that have no `type` in EVERY version of a test case.
|
|
9299
|
+
* The recorder window's save of a new version adds cells (`{paramId, value}`) to the first test-data
|
|
9300
|
+
* header it finds for the test case without filtering by version, so either version can end up with
|
|
9301
|
+
* typeless cells. Such a version cannot load its test data and its runs end Not Executed with no steps.
|
|
9302
|
+
* Each such cell gets `type:'OB'` plus the stepId / stepSeq of the step that uses the parameter in that
|
|
9303
|
+
* version; nothing is deleted and no value is touched. */
|
|
9304
|
+
async repairTestdataCells(tcId) {
|
|
9305
|
+
const projectId = this.requireProjectId();
|
|
9306
|
+
const tcNum = Number.parseInt(numericId(tcId), 10);
|
|
9307
|
+
const rawTc = await this.fetchRawTestcase(tcId);
|
|
9308
|
+
const versions = [];
|
|
9309
|
+
for (const v of Array.isArray(rawTc?.versions) ? rawTc.versions : []) {
|
|
9310
|
+
const id = str(v, 'id', '_id');
|
|
9311
|
+
if (id)
|
|
9312
|
+
versions.push({ id, name: str(v, 'name') ?? id });
|
|
9313
|
+
}
|
|
9314
|
+
const fixed = [];
|
|
9315
|
+
let checked = 0;
|
|
9316
|
+
let repaired = 0;
|
|
9317
|
+
for (const ver of versions) {
|
|
9318
|
+
const search = await this.http.postJson('/tm/testdata/searchItr', {
|
|
9319
|
+
searchFields: [
|
|
9320
|
+
{ column: 'testcaseId', value: tcNum, regEx: false },
|
|
9321
|
+
{ column: 'versionId', value: ver.id, regEx: false },
|
|
9322
|
+
{ column: 'deleted', value: false, regEx: false },
|
|
9323
|
+
],
|
|
9324
|
+
startIndex: 0,
|
|
9325
|
+
limit: 1000,
|
|
9326
|
+
});
|
|
9327
|
+
const rows = pickArray(search, 'data', 'content', 'iterations');
|
|
9328
|
+
const broken = rows.filter((r) => Array.isArray(r?.data)
|
|
9329
|
+
&& r.data.some((c) => c && typeof c === 'object' && typeof c.type !== 'string'));
|
|
9330
|
+
checked += rows.length;
|
|
9331
|
+
if (!broken.length)
|
|
9332
|
+
continue;
|
|
9333
|
+
const stepOfParam = new Map();
|
|
9334
|
+
for (const s of await this.fetchStepsCollection(tcId, rawTc, ver.id)) {
|
|
9335
|
+
if (s?.deleted)
|
|
9336
|
+
continue;
|
|
9337
|
+
for (const pid of [...(s?.objectParameterIds ?? []), ...(s?.parameterIds ?? []), ...(s?.parameterizedParamIds ?? [])]) {
|
|
9338
|
+
if (!stepOfParam.has(Number(pid)))
|
|
9339
|
+
stepOfParam.set(Number(pid), { stepId: s.id, stepSeq: s.seq });
|
|
9340
|
+
}
|
|
9341
|
+
}
|
|
9342
|
+
for (const row of broken) {
|
|
9343
|
+
const customerId = Number(row?.customerId ?? rawTc?.customerId);
|
|
9344
|
+
if (!Number.isFinite(customerId))
|
|
9345
|
+
continue;
|
|
9346
|
+
const data = row.data.map((c) => {
|
|
9347
|
+
if (!c || typeof c !== 'object' || typeof c.type === 'string')
|
|
9348
|
+
return c;
|
|
9349
|
+
const at = stepOfParam.get(Number(c.paramId));
|
|
9350
|
+
return {
|
|
9351
|
+
...c,
|
|
9352
|
+
type: 'OB',
|
|
9353
|
+
...(c.stepId === undefined && at?.stepId !== undefined ? { stepId: at.stepId } : {}),
|
|
9354
|
+
...(c.stepSeq === undefined && at?.stepSeq !== undefined ? { stepSeq: at.stepSeq } : {}),
|
|
9355
|
+
};
|
|
9356
|
+
});
|
|
9357
|
+
await this.http.postJson('/tm/testdata/updateItr', {
|
|
9358
|
+
parentId: row.parentId, id: row.id, customerId, projectId, data,
|
|
9359
|
+
});
|
|
9360
|
+
repaired += data.filter((c, i) => c !== row.data[i]).length;
|
|
9361
|
+
if (!fixed.includes(ver.name))
|
|
9362
|
+
fixed.push(ver.name);
|
|
9363
|
+
}
|
|
9364
|
+
}
|
|
9365
|
+
return { checked, repaired, versions: fixed };
|
|
9366
|
+
}
|
|
7136
9367
|
/** Environment key: caller wins; else fetch the project's configured envs and pick the first;
|
|
7137
9368
|
* else 'general' (matches the SQA UI fallback). */
|
|
7138
9369
|
async resolveEnvironment(projectId, requested) {
|
|
@@ -7639,30 +9870,40 @@ export class SimplifyQaAdapter {
|
|
|
7639
9870
|
reportUrl: `${base}/user/reports/reports-page?type=SUITE&parentId=${suiteNum}&id=${runIdNum}&projectId=${projectId}`,
|
|
7640
9871
|
};
|
|
7641
9872
|
}
|
|
7642
|
-
/**
|
|
7643
|
-
|
|
7644
|
-
async getExecutionFailures(input) {
|
|
9873
|
+
/** The failure-analysis engine (executionFailures.ts) bound to this connection. */
|
|
9874
|
+
failureAnalyzer() {
|
|
7645
9875
|
return new ExecutionFailureAnalysis({
|
|
7646
9876
|
http: this.http,
|
|
7647
9877
|
projectId: this.requireProjectId(),
|
|
7648
9878
|
baseUrl: this.baseUrl(),
|
|
7649
9879
|
fetchExecDoc: (id, projectId) => this.fetchExecDoc(id, projectId),
|
|
7650
9880
|
latestExecutionOf: (kind, id) => this.getLatestRunFor(kind, id),
|
|
7651
|
-
})
|
|
9881
|
+
});
|
|
9882
|
+
}
|
|
9883
|
+
/** Whole-execution failure analysis (executionFailures.ts) for TC-123 / SU-123 / PL-123 or one
|
|
9884
|
+
* named execution. */
|
|
9885
|
+
async getExecutionFailures(input) {
|
|
9886
|
+
return this.failureAnalyzer().analyse(input);
|
|
9887
|
+
}
|
|
9888
|
+
/** Level-1 history of each failed test case in `ctx`, searched across every execution of the test
|
|
9889
|
+
* case before it — standalone, any suite, any plan (failureHistory.ts). Keyed by
|
|
9890
|
+
* `executionItemId`; status `unknown` when its run search failed. `cache` (one per analysis)
|
|
9891
|
+
* makes a test case failing in several executions one search. "Edited since pass" carries
|
|
9892
|
+
* version names. */
|
|
9893
|
+
async getFailureHistory(ctx, cache) {
|
|
9894
|
+
const analyzer = this.failureAnalyzer();
|
|
9895
|
+
const history = await analyzer.failureHistory(ctx, cache);
|
|
9896
|
+
await analyzer.nameHistoryVersions(history);
|
|
9897
|
+
return history;
|
|
9898
|
+
}
|
|
9899
|
+
/** Level-2: the failing step of `it` as it ran in the last passed run (failureHistory.ts). */
|
|
9900
|
+
async compareWithLastPass(it, history, executionItemId, rows) {
|
|
9901
|
+
return this.failureAnalyzer().compareWithLastPass(it, history, executionItemId, rows);
|
|
7652
9902
|
}
|
|
7653
9903
|
/** A failure screenshot as base64 (see executionFailures.fetchFailureImage). */
|
|
7654
9904
|
async fetchFailureImage(absoluteUrl, maxBytes) {
|
|
7655
9905
|
return fetchFailureImage(this.http, this.baseUrl(), absoluteUrl, maxBytes);
|
|
7656
9906
|
}
|
|
7657
|
-
/** The failure-analysis card + evidence text and the top causes' screenshots (failureReport.ts). */
|
|
7658
|
-
async getFailureReport(input) {
|
|
7659
|
-
const { includeImages, ...analysisInput } = input;
|
|
7660
|
-
const ctx = await this.getExecutionFailures(analysisInput);
|
|
7661
|
-
const images = includeImages === false || input.includeScreenshots === false
|
|
7662
|
-
? []
|
|
7663
|
-
: await failureImages(ctx, (url, maxBytes) => this.fetchFailureImage(url, maxBytes));
|
|
7664
|
-
return { text: renderExecution(ctx), images };
|
|
7665
|
-
}
|
|
7666
9907
|
baseUrl() {
|
|
7667
9908
|
return (this.cfg.baseUrl ?? '').replace(/\/+$/, '');
|
|
7668
9909
|
}
|
|
@@ -8103,7 +10344,10 @@ export class SimplifyQaAdapter {
|
|
|
8103
10344
|
// and breaks the agent's iteration join. Missing platform for a row is not an error here (UI
|
|
8104
10345
|
// sends `[]`) — the agent tolerates it for MANUAL suites; AUTOMATION suites without a saved
|
|
8105
10346
|
// platform were misconfigured upstream and would fail regardless.
|
|
8106
|
-
|
|
10347
|
+
// STACK: the backend runs the SAVED stack canvas, so the run carries no items (the UI's Execute dialog
|
|
10348
|
+
// sends `executionItems: []`, SERIAL, the live local agent and the project's cloud type).
|
|
10349
|
+
const stackRun = mode === 'STACK' ? await this.suiteStackRunPlan(rawSuite, opts) : undefined;
|
|
10350
|
+
const members = !stackRun && Array.isArray(rawSuite.testCases) ? rawSuite.testCases : [];
|
|
8107
10351
|
const executionItems = [];
|
|
8108
10352
|
let seqCounter = 0;
|
|
8109
10353
|
for (const row of members) {
|
|
@@ -8185,7 +10429,7 @@ export class SimplifyQaAdapter {
|
|
|
8185
10429
|
userstoryName: '',
|
|
8186
10430
|
});
|
|
8187
10431
|
}
|
|
8188
|
-
if (executionItems.length === 0) {
|
|
10432
|
+
if (!stackRun && executionItems.length === 0) {
|
|
8189
10433
|
throw new Error(`startRun: suite ${suiteId} has no runnable test cases (all members were deleted, ` +
|
|
8190
10434
|
`unreadable, or filtered out).`);
|
|
8191
10435
|
}
|
|
@@ -8193,7 +10437,10 @@ export class SimplifyQaAdapter {
|
|
|
8193
10437
|
// pin the suite doc's saved `agentId` (or null when the suite wasn't pinned). CLOUD_AGENT
|
|
8194
10438
|
// fallback (:771-774) promotes `cloudType` to 'SQA'.
|
|
8195
10439
|
let agentId;
|
|
8196
|
-
if (
|
|
10440
|
+
if (stackRun) {
|
|
10441
|
+
agentId = stackRun.agentId;
|
|
10442
|
+
}
|
|
10443
|
+
else if (mode === 'LOCAL') {
|
|
8197
10444
|
agentId = await this.resolveLocalAgentId(opts.agentId);
|
|
8198
10445
|
}
|
|
8199
10446
|
else if (mode === 'REMOTE') {
|
|
@@ -8203,15 +10450,16 @@ export class SimplifyQaAdapter {
|
|
|
8203
10450
|
else {
|
|
8204
10451
|
agentId = typeof rawSuite.agentId === 'string' && rawSuite.agentId.length > 0 ? rawSuite.agentId : null;
|
|
8205
10452
|
}
|
|
8206
|
-
let cloudType = mode === 'CLOUD' ? normalizeCloudType(opts.cloudType)
|
|
8207
|
-
|
|
10453
|
+
let cloudType = mode === 'CLOUD' ? normalizeCloudType(opts.cloudType)
|
|
10454
|
+
: stackRun && stackRun.cloudType !== 'NONE' ? normalizeCloudType(stackRun.cloudType) : 'NONE';
|
|
10455
|
+
if (!stackRun && !agentId && typeof rawSuite.cloudAgentId === 'string' && rawSuite.cloudAgentId.length > 0) {
|
|
8208
10456
|
agentId = rawSuite.cloudAgentId;
|
|
8209
10457
|
cloudType = 'SQA';
|
|
8210
10458
|
}
|
|
8211
10459
|
const body = {
|
|
8212
10460
|
projectId,
|
|
8213
10461
|
environmentType: env,
|
|
8214
|
-
executionStyle: (opts.strategy ?? 'serial').toUpperCase(),
|
|
10462
|
+
executionStyle: stackRun ? 'SERIAL' : (opts.strategy ?? 'serial').toUpperCase(),
|
|
8215
10463
|
executionOS: this.detectExecutionOS(),
|
|
8216
10464
|
executionTypeId: suiteNum,
|
|
8217
10465
|
executionTypeName: str(rawSuite, 'name') ?? '',
|
|
@@ -8691,6 +10939,118 @@ export class SimplifyQaAdapter {
|
|
|
8691
10939
|
}
|
|
8692
10940
|
return out;
|
|
8693
10941
|
}
|
|
10942
|
+
/** Raw environment rows of the active project (the rows `/pm/fields/savefields` round-trips). */
|
|
10943
|
+
async fetchEnvironmentRows() {
|
|
10944
|
+
const projectId = this.requireProjectId();
|
|
10945
|
+
const raw = await this.http.getJson(`/pm/fields/8?projectId=${projectId}&fieldType=environment`);
|
|
10946
|
+
const arr = Array.isArray(raw) ? raw : Array.isArray(raw?.data) ? raw.data : [];
|
|
10947
|
+
return arr.filter((e) => e && typeof e === 'object');
|
|
10948
|
+
}
|
|
10949
|
+
/** Persist the project's WHOLE environment list — byte-for-byte what the UI's Environment editor
|
|
10950
|
+
* posts: `POST /pm/fields/savefields { environment: [...], customlevel: false }`. A new row has an
|
|
10951
|
+
* empty id; an existing one is edited in place; a deleted one is sent back with `deleted: true`.
|
|
10952
|
+
* The backend then provisions that environment's test-data rows itself (the UI calls it
|
|
10953
|
+
* "Test Data environment creation has been initiated"). */
|
|
10954
|
+
async saveEnvironmentRows(rows) {
|
|
10955
|
+
await this.http.postJson('/pm/fields/savefields', {
|
|
10956
|
+
environment: rows, customlevel: false,
|
|
10957
|
+
});
|
|
10958
|
+
}
|
|
10959
|
+
/** The logged-in user's id, as the UI stamps createdBy/updatedBy (0 when it cannot be resolved). */
|
|
10960
|
+
async environmentActor() {
|
|
10961
|
+
const id = await this.fetchUserIdFromMe();
|
|
10962
|
+
const n = Number.parseInt(id ?? '', 10);
|
|
10963
|
+
return Number.isFinite(n) ? n : 0;
|
|
10964
|
+
}
|
|
10965
|
+
/** The project's customerId — the UI puts it inside the generated environment key. */
|
|
10966
|
+
async projectCustomerId(projectId) {
|
|
10967
|
+
try {
|
|
10968
|
+
const n = Number((await this.getProjectById(String(projectId)))['customerId']);
|
|
10969
|
+
return Number.isFinite(n) ? n : undefined;
|
|
10970
|
+
}
|
|
10971
|
+
catch {
|
|
10972
|
+
return undefined;
|
|
10973
|
+
}
|
|
10974
|
+
}
|
|
10975
|
+
/** Key the UI would generate (`CUSTFIELD_<customerId><name>_<name.length>_<rand5>`). */
|
|
10976
|
+
newEnvironmentKey(name, customerId) {
|
|
10977
|
+
const rand = Math.random().toString(26).slice(4, 9);
|
|
10978
|
+
return `CUSTFIELD_${customerId ?? ''}${name}_${name.length}_${rand}`;
|
|
10979
|
+
}
|
|
10980
|
+
/** Create an ENVIRONMENT (project configuration > Environments) and return it as saved. */
|
|
10981
|
+
async createEnvironment(input) {
|
|
10982
|
+
const projectId = this.requireProjectId();
|
|
10983
|
+
const name = (input.name ?? '').trim();
|
|
10984
|
+
if (!name)
|
|
10985
|
+
throw new Error('createEnvironment: name is required.');
|
|
10986
|
+
const rows = await this.fetchEnvironmentRows();
|
|
10987
|
+
if (rows.some((r) => String(r['name'] ?? '').trim().toLowerCase() === name.toLowerCase())) {
|
|
10988
|
+
throw new Error(`An environment named "${name}" already exists in this project. Use action:"update" to change it.`);
|
|
10989
|
+
}
|
|
10990
|
+
const key = (input.key ?? '').trim() || this.newEnvironmentKey(name, await this.projectCustomerId(projectId));
|
|
10991
|
+
if (rows.some((r) => String(r['key'] ?? '').trim() === key)) {
|
|
10992
|
+
throw new Error(`Environment key "${key}" is already used in this project — pass a different key.`);
|
|
10993
|
+
}
|
|
10994
|
+
// Same row the UI's "Add environment" form produces (createdBy/updatedBy = the logged-in user).
|
|
10995
|
+
const actor = await this.environmentActor();
|
|
10996
|
+
const row = {
|
|
10997
|
+
id: '', name, key, parentId: 8, deleted: false, fieldType: 'environment', projectId,
|
|
10998
|
+
createdBy: actor, updatedBy: actor,
|
|
10999
|
+
};
|
|
11000
|
+
await this.saveEnvironmentRows([...rows, row]);
|
|
11001
|
+
// Prove it: read the list back (the save answer alone is not enough — the UI re-reads too).
|
|
11002
|
+
const saved = (await this.listEnvironments()).find((e) => e.key === key || e.name.toLowerCase() === name.toLowerCase());
|
|
11003
|
+
if (!saved)
|
|
11004
|
+
throw new Error(`Saved environment "${name}" but it is not in the project's environment list on read-back.`);
|
|
11005
|
+
return { id: saved.id, key: saved.key ?? key, name: saved.name };
|
|
11006
|
+
}
|
|
11007
|
+
/** Rename / re-key an EXISTING environment. `ref` is its name or key. */
|
|
11008
|
+
async updateEnvironment(ref, patch) {
|
|
11009
|
+
const want = (ref ?? '').trim().toLowerCase();
|
|
11010
|
+
if (!want)
|
|
11011
|
+
throw new Error('updateEnvironment: the environment name or key is required.');
|
|
11012
|
+
const rows = await this.fetchEnvironmentRows();
|
|
11013
|
+
const row = rows.find((r) => String(r['name'] ?? '').trim().toLowerCase() === want || String(r['key'] ?? '').trim().toLowerCase() === want);
|
|
11014
|
+
if (!row)
|
|
11015
|
+
throw new Error(`No environment named or keyed "${ref}" in this project.`);
|
|
11016
|
+
const nextName = (patch.name ?? String(row['name'] ?? '')).trim();
|
|
11017
|
+
if (!nextName)
|
|
11018
|
+
throw new Error('updateEnvironment: name cannot be empty.');
|
|
11019
|
+
if (rows.some((r) => r !== row && String(r['name'] ?? '').trim().toLowerCase() === nextName.toLowerCase())) {
|
|
11020
|
+
throw new Error(`Another environment is already named "${nextName}".`);
|
|
11021
|
+
}
|
|
11022
|
+
const nextKey = (patch.key ?? String(row['key'] ?? '')).trim() || this.newEnvironmentKey(nextName);
|
|
11023
|
+
if (rows.some((r) => r !== row && String(r['key'] ?? '').trim() === nextKey)) {
|
|
11024
|
+
throw new Error(`Another environment already uses the key "${nextKey}".`);
|
|
11025
|
+
}
|
|
11026
|
+
const updated = { ...row, name: nextName, key: nextKey, updatedBy: await this.environmentActor() };
|
|
11027
|
+
await this.saveEnvironmentRows(rows.map((r) => (r === row ? updated : r)));
|
|
11028
|
+
const saved = (await this.listEnvironments()).find((e) => e.key === nextKey || e.name.toLowerCase() === nextName.toLowerCase());
|
|
11029
|
+
if (!saved)
|
|
11030
|
+
throw new Error(`Saved environment "${nextName}" but it is not in the project's environment list on read-back.`);
|
|
11031
|
+
return { id: saved.id, key: saved.key ?? nextKey, name: saved.name };
|
|
11032
|
+
}
|
|
11033
|
+
/** Delete an environment the way the UI does: mark the row `deleted:true` and send the list back.
|
|
11034
|
+
* The default `general` environment is refused. */
|
|
11035
|
+
async deleteEnvironment(ref) {
|
|
11036
|
+
const want = (ref ?? '').trim().toLowerCase();
|
|
11037
|
+
if (!want)
|
|
11038
|
+
throw new Error('deleteEnvironment: the environment name or key is required.');
|
|
11039
|
+
const rows = await this.fetchEnvironmentRows();
|
|
11040
|
+
const row = rows.find((r) => String(r['name'] ?? '').trim().toLowerCase() === want || String(r['key'] ?? '').trim().toLowerCase() === want);
|
|
11041
|
+
if (!row)
|
|
11042
|
+
throw new Error(`No environment named or keyed "${ref}" in this project.`);
|
|
11043
|
+
const key = String(row['key'] ?? '');
|
|
11044
|
+
const name = String(row['name'] ?? '');
|
|
11045
|
+
if (key === 'general')
|
|
11046
|
+
throw new Error('The default "General" environment cannot be deleted.');
|
|
11047
|
+
const gone = { ...row, deleted: true, updatedBy: await this.environmentActor() };
|
|
11048
|
+
await this.saveEnvironmentRows([...rows.filter((r) => r !== row), gone]);
|
|
11049
|
+
const still = (await this.listEnvironments()).some((e) => e.id === String(row['id']) || e.name.toLowerCase() === name.toLowerCase());
|
|
11050
|
+
if (still)
|
|
11051
|
+
throw new Error(`SimplifyQA answered OK but "${name}" is still in the environment list — nothing was deleted.`);
|
|
11052
|
+
return { id: String(row['id']), name, key };
|
|
11053
|
+
}
|
|
8694
11054
|
async listDatasets(tcId) {
|
|
8695
11055
|
const h = this.hop();
|
|
8696
11056
|
return h?.listDatasets ? h.listDatasets(tcId) : [];
|
|
@@ -8804,6 +11164,8 @@ export class SimplifyQaAdapter {
|
|
|
8804
11164
|
steps[i] = {
|
|
8805
11165
|
...cur, ...patch,
|
|
8806
11166
|
...(patch.flags ? { flags: { ...cur.flags, ...patch.flags } } : {}),
|
|
11167
|
+
// a controlFlow patch (e.g. just a new condition) keeps the saved kind / block id
|
|
11168
|
+
...(patch.controlFlow ? { controlFlow: { ...cur.controlFlow, ...patch.controlFlow } } : {}),
|
|
8807
11169
|
// api edits (assertions, URL, headers, body) change the saved request in place instead of replacing it
|
|
8808
11170
|
...(patch.api ? { api: mergeApiPatch(cur, patch) } : {}),
|
|
8809
11171
|
// A patch that names an object but gives no id means "use THAT object": keeping the saved id (as a plain merge does)
|
|
@@ -9123,4 +11485,13 @@ export class SimplifyQaAdapter {
|
|
|
9123
11485
|
}
|
|
9124
11486
|
SimplifyQaAdapter.ADMIN_TTL_MS = 60000;
|
|
9125
11487
|
SimplifyQaAdapter.PRIVILEGES_TTL_MS = 5 * 60000;
|
|
11488
|
+
// ---------------------------------------------------------------------- Release / sprint update
|
|
11489
|
+
/** The keys the backend's release / sprint validators accept (project-management releaseValidation.js / sprintValidation.js).
|
|
11490
|
+
* The PUT validates the WHOLE body and refuses any other key (id, code, customerId, createdAt …), so only these are sent. */
|
|
11491
|
+
SimplifyQaAdapter.PM_FIELDS = {
|
|
11492
|
+
release: ['name', 'plannedStartDate', 'state', 'plannedEndDate', 'estimatedEffort', 'projectIds', 'ownerIds', 'description',
|
|
11493
|
+
'actualStartDate', 'actualEndDate', 'remainingEffort', 'actualEffort', 'customFields', 'azureReleaseId', 'jiraReleaseId'],
|
|
11494
|
+
sprint: ['name', 'plannedStartDate', 'plannedEndDate', 'estimatedEffort', 'releaseId', 'state', 'ownerIds', 'description',
|
|
11495
|
+
'actualStartDate', 'actualEndDate', 'actualEffort', 'remainingEffort', 'customFields', 'azureSprintPath', 'azureSprintId', 'jiraSprintId'],
|
|
11496
|
+
};
|
|
9126
11497
|
//# sourceMappingURL=adapter.js.map
|