DEV Community

Rahul
Rahul

Posted on

Testcraft Studio frontend 37: src/seed.js

import { normalizeAccessModel } from './access.js';
const now = '2026-10-14T09:30:00+05:30';
export const categories = ['Technical', 'Functional / Bug Information', 'Business'];
export const defaultFields = ['Test ID', 'Title', 'Owner team', 'Category', 'Requirement', 'Objective', 'Preconditions', 'Test data', 'Steps', 'Expected result', 'Priority', 'Evidence', 'Review status'];
export const teamNames = { MCM: 'Membership and Collateral Management', RMS: 'Risk Management' };
export const canonicalTeamName = name => ['membership', 'mcm', 'membership and collateral management', 'membership & collateral management'].includes(name.trim().toLowerCase()) ? 'MCM' : name.trim();
const rule = (id, title, text, source) => ({ id, title, text, source });
const rules = [rule('VAL-001', 'Identifier format', 'Validate the identifier against the approved format.', 'd1'), rule('VAL-002', 'Required identifier', 'The member identifier is required in an incoming request.', 'd2'), rule('VAL-003', 'Identifier source', 'Validate the identifier using the approved source list.', 'd1')];
const document = (id, name, kind, category, excerpt, extra = {}) => ({ id, name, kind, category, excerpt, size: 'Sample', status: 'Ready', revision: 2, team: 'RMS', date: now, synthetic: true, ...extra });
function makeRmsSeed() {
  return structuredClone({
    schema: 1,
    session: { team: 'RMS', role: 'user', name: 'RMS User', authenticated: false },
    activeWorkspaceId: 'w1042',
    teams: ['RMS', 'Securities', 'Membership', 'Forex', 'Derivatives'],
    baselines: [
      { id: 'b1', ref: 'RMS-B1', team: 'RMS', version: '1.2', status: 'Approved', description: 'Reusable RMS message reception and member validation knowledge.', scope: 'Message reception', sourceIds: ['d1', 'd2', 'd5'], rules, incorporatedCRs: [], createdAt: now },
      { id: 'b2', ref: 'RMS-B2', team: 'RMS', version: '2.0', status: 'Approved', description: 'Approved RMS knowledge including explicit identifier rejection.', scope: 'Message reception', sourceIds: ['d1', 'd2', 'd3', 'd5'], rules: rules.map(r => r.id === 'VAL-002' ? { ...r, text: 'Reject a request with a missing required member identifier.', source: 'd3' } : r), incorporatedCRs: ['cr1042'], createdAt: now },
      { id: 'bs1', ref: 'SEC-B1', team: 'Securities', version: '1.0', status: 'Approved', description: 'Sample Securities-owned settlement knowledge.', scope: 'Settlement', sourceIds: [], rules: [], incorporatedCRs: [], createdAt: now },
    ],
    crs: [
      { id: 'cr1042', ref: 'CR-1042', team: 'RMS', name: 'Member identifier validation', revision: 2, requires: [], conflicts: ['cr1073'], changes: [{ ruleId: 'VAL-002', op: 'REPLACE', title: 'Required identifier', before: rules[1].text, after: 'Reject a request with a missing required member identifier.', source: 'd3' }] },
      { id: 'cr1051', ref: 'CR-1051', team: 'RMS', name: 'Settlement limit controls', revision: 1, requires: [], conflicts: [], changes: [{ ruleId: 'LIMIT-001', op: 'ADD', title: 'Settlement limit', before: '', after: 'Apply the approved participant settlement limit. Numeric limits remain symbolic sample fixtures.', source: 'd6' }] },
      { id: 'cr1068', ref: 'CR-1068', team: 'RMS', name: 'Participant status updates', revision: 1, requires: ['cr1051'], conflicts: [], changes: [{ ruleId: 'STATUS-001', op: 'ADD', title: 'Participant status', before: '', after: 'Validate the participant status before applying a settlement limit.', source: 'd6' }] },
      { id: 'cr1073', ref: 'CR-1073', team: 'RMS', name: 'Retire required identifier check', revision: 1, requires: [], conflicts: ['cr1042'], changes: [{ ruleId: 'VAL-002', op: 'REMOVE', title: 'Required identifier', before: rules[1].text, after: '', source: 'd3' }] },
    ],
    workspaces: [
      { id: 'w1042', ref: 'CR-1042', name: 'Member identifier validation', purpose: 'Review changes to member validation at the RMS message boundary.', team: 'RMS', baselineId: 'b1', crIds: ['cr1042'], version: 1, visibility: 'team', members: ['RMS'], updatedAt: now, requirementCount: 4, sharedContractIds: ['dshared'] },
      { id: 'w1051', ref: 'CR-1051', name: 'Settlement limit controls', purpose: 'Verify participant settlement controls.', team: 'RMS', baselineId: 'b2', crIds: ['cr1051'], version: 1, visibility: 'team', members: ['RMS'], updatedAt: now, requirementCount: 4, sharedContractIds: [] },
      { id: 'w1068', ref: 'CR-1068', name: 'Participant status updates', purpose: 'Review status and limit dependencies.', team: 'RMS', baselineId: 'b2', crIds: ['cr1051', 'cr1068'], version: 1, visibility: 'private', members: ['RMS'], updatedAt: now, requirementCount: 6, sharedContractIds: [] },
      { id: 'w1073', ref: 'CR-1073', name: 'Message acknowledgement', purpose: 'Collect evidence for message acknowledgement.', team: 'RMS', baselineId: 'b2', crIds: [], version: 1, visibility: 'team', members: ['RMS'], updatedAt: now, requirementCount: 3, sharedContractIds: [] },
    ],
    documents: [
      document('d1', 'RMS_Message_Processor.sql', 'SQL', 0, 'Synthetic example: member identifiers are checked against an approved format and source list. This is illustrative text, not actual Testcraft procedure logic.', { baselineId: 'b1', locator: 'Lines 18–32' }),
      document('d2', 'RMS_Receiving_BRD.pdf', 'PDF', 1, 'Synthetic requirement: the member identifier is required in an incoming request. The approved identifier validation rules continue to apply.', { baselineId: 'b1', locator: 'Page 7 · Section 4.2' }),
      document('d3', 'CR-1042_Requirements.docx', 'DOCX', 1, 'Synthetic change: reject a request when the required member identifier is absent. Timeout and retry behavior are not defined by this example.', { workspaceId: 'w1042', crId: 'cr1042', locator: 'Section 4.2' }),
      document('d4', 'Member_Validation_Screen.pdf', 'PDF', 0, 'Synthetic screen reference: the member identifier is a request field. No concrete error code or screen behavior is established here.', { workspaceId: 'w1042', locator: 'Page 2 · Fields' }),
      document('d5', 'Member_Lifecycle.md', 'MD', 2, 'Synthetic context: participants submit messages to RMS. This context explains terms and roles; expected behavior is established by functional requirements.', { baselineId: 'b1', locator: 'Participant roles' }),
      document('d6', 'Settlement_Controls.md', 'MD', 1, 'Synthetic requirement: apply the approved settlement limit for the participant. Use symbolic fixture APPROVED_LIMIT; this example does not establish numeric policy.', { workspaceId: 'w1051', crId: 'cr1051', locator: 'Section 2' }),
      document('dshared', 'Securities_Message_Contract.pdf', 'PDF', 0, 'Synthetic shared interface contract describes the request boundary. Timeout, retries, fallback, and duplicate handling are unspecified.', { team: 'Securities', sharedWith: ['RMS'], locator: 'v2.1 · Interface behavior', revision: '2.1' }),
    ],
    questions: [
      { id: 'q1', workspaceId: 'w1042', version: 1, requirement: 'REQ-RMS-03', title: 'What timeout should RMS apply?', why: 'The shared interface contract does not define the timeout for a delayed response.', requested: 'Provide the approved timeout rule, applicability, and source revision.', sourceId: 'dshared', status: 'open', answer: '' },
      { id: 'q2', workspaceId: 'w1042', version: 1, requirement: 'REQ-RMS-03', title: 'What is the approved retry and fallback behavior?', why: 'Retry, fallback, and duplicate-handling rules are absent from the selected evidence.', requested: 'Provide the retry limit, fallback rule, duplicate handling, and a source reference.', sourceId: 'dshared', status: 'open', answer: '' },
      { id: 'q3', workspaceId: 'w1068', version: 1, requirement: 'REQ-RMS-06', title: 'Which participant statuses can proceed?', why: 'The sample source does not enumerate approved statuses.', requested: 'Attach the approved status definition or provide a source-backed answer.', sourceId: 'd6', status: 'open', answer: '' },
    ],
    threads: {},
    templates: [{ id: 't1', name: 'Testcraft structured test case', team: 'RMS', version: 1, description: 'Evidence and requirement traceability with team review.', fields: defaultFields, visibility: 'team' }, { id: 't2', name: 'Compact regression checklist', team: 'RMS', version: 1, description: 'A concise checklist for focused regression reviews.', fields: ['Test ID', 'Title', 'Category', 'Steps', 'Expected result', 'Evidence', 'Review status'], visibility: 'team' }],
    suites: [{ id: 's1', name: 'Settlement controls · Review suite', workspaceId: 'w1051', version: 1, baselineId: 'b2', crIds: ['cr1051'], templateId: 't1', provisional: false, status: 'Ready for review', createdAt: now, gaps: [], tests: [{ id: 'TC-RMS-001', title: 'Accept a request within the approved limit', category: 'Positive', requirement: 'LIMIT-001', objective: 'Verify an eligible request follows the approved limit rule.', preconditions: 'Approved participant and limit fixture available.', data: 'ELIGIBLE_PARTICIPANT, APPROVED_LIMIT', steps: ['Prepare the approved participant fixture.', 'Submit a request within APPROVED_LIMIT.', 'Observe the outcome.'], expected: 'The request is accepted under the approved sample limit rule.', priority: 'High', rationale: 'Core participant limit behavior.', sourceIds: ['d6'], status: 'Generated', notes: '' }, { id: 'TC-RMS-002', title: 'Reject a request exceeding the approved limit', category: 'Negative', requirement: 'LIMIT-001', objective: 'Verify a request outside the approved limit is rejected.', preconditions: 'Approved limit fixture available.', data: 'EXCEEDS_APPROVED_LIMIT', steps: ['Prepare an above-limit request.', 'Submit the request.', 'Check the validation outcome.'], expected: 'The above-limit request is rejected under the sample rule.', priority: 'High', rationale: 'Prevents acceptance outside approved controls.', sourceIds: ['d6'], status: 'Generated', notes: '' }] }],
    candidates: [{ id: 'c1', ref: 'RMS-B3', team: 'RMS', parentId: 'b2', crIds: ['cr1051'], description: 'Incorporate settlement limit controls into reusable RMS knowledge.', status: 'Pending review', revision: 1, createdAt: now, decisions: [] }],
    jobs: [],
    shares: [{ id: 'share1', sourceId: 'dshared', owner: 'Securities', consumer: 'RMS', status: 'Active' }],
    settings: { reasoningModel: '', extractionModel: '', embeddingModel: '', gateway: '', retryLimit: 2 },
    audit: [{ id: 'a1', action: 'Sample knowledge initialized', actor: 'Demo fixture', at: now }],
  });
}

const teamCollections = ['baselines', 'crs', 'workspaces', 'documents', 'questions', 'templates', 'suites', 'candidates', 'shares'];

function mcmSamples() {
  const source = makeRmsSeed();
  const workspaceIds = new Set(source.workspaces.filter(w => w.team === 'RMS').map(w => w.id));
  const records = Object.fromEntries(teamCollections.map(key => [key, source[key].filter(item =>
    item.team === 'RMS' || workspaceIds.has(item.workspaceId) || item.consumer === 'RMS'
  )]));
  const ids = new Map(Object.values(records).flat().map(item => [item.id, `mcm-${item.id}`]));
  // Remap every internal reference, while retaining the Securities-owned shared contract.
  const copy = value => {
    if (typeof value === 'string') return ids.get(value) || value.replaceAll('RMS', 'MCM');
    if (Array.isArray(value)) return value.map(copy);
    if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copy(item)]));
    return value;
  };
  return copy(records);
}

export function upgradeDemoState(state) {
  if (state.demoTeamVersion >= 2) return normalizeMembershipTeam(state);
  const samples = mcmSamples();
  for (const key of teamCollections) {
    const existing = new Set(state[key].map(item => item.id));
    state[key].push(...samples[key].filter(item => !existing.has(item.id)));
  }
  state.teams = ['MCM', ...state.teams.filter(team => team !== 'MCM')];
  const contract = state.documents.find(d => d.id === 'dshared');
  if (contract && !contract.sharedWith.includes('MCM')) contract.sharedWith.push('MCM');
  const role = state.session.role === 'administrator' ? 'administrator' : 'user';
  const label = role === 'administrator' ? 'Administrator' : 'User';
  state.session = { team: 'MCM', role, name: `MCM ${label}` };
  state.activeWorkspaceId = 'mcm-w1042';
  state.demoTeamVersion = 2;
  return normalizeMembershipTeam(state);
}

function normalizeMembershipTeam(state) {
  state.teams = ['MCM', ...new Set(state.teams.map(canonicalTeamName).filter(team => team !== 'MCM'))];
  for (const key of teamCollections) for (const item of state[key]) {
    for (const field of ['team', 'owner', 'consumer']) if (item[field]) item[field] = canonicalTeamName(item[field]);
    if (item.sharedWith) item.sharedWith = [...new Set(item.sharedWith.map(canonicalTeamName))];
    if (item.members) item.members = [...new Set(item.members.map(name => name.replace(/^Membership /, 'MCM ')))];
  }
  state.session.team = canonicalTeamName(state.session.team);
  state.session.name = state.session.name.replace(/^Membership /, 'MCM ');
  state.demoTeamVersion = 3;
  return normalizeAccessModel(state);
}

export function makeSeed() {
  return upgradeDemoState(makeRmsSeed());
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)