a↗agentbay.Get AgentBay
My account ▾
Menu
← Back to the walkthrough
WALKTHROUGH OUTPUT

The architecture

Download original ↓

CRM-142 architecture

Existing boundaries (unchanged)

src/contacts.js exports initialContacts, normalEmail(value), validContact(row), addContact(rows, row), searchContacts(rows, query=''). Reuse normalization/validation and addContact for final contact IDs and trimming. src/storage.js exports readContacts() and async saveContacts(rows, {fail=false}={}); it replaces only agentbay-crm-142-contacts after a 180ms delay. Leave both modules unchanged. src/app.js retains list rendering, search and Add contact integration.

Pure import module

Create src/import.js with exactly the public exports required by docs/import-contract.md:

  • previewCSV(text, existing) → {rows, counts: {ready, invalid, duplicate}}. Each row: {record, name, email, company, status, reason}; record is the 1-based nonblank data-record number, status is ready|invalid|duplicate, reason is empty for Ready. No DOM/storage access or persistence.
  • mergeReady(preview, existing) → {contacts, added, skipped}. Return a new array, preserve all existing objects/data, never mutate either input. Revalidate Ready row fields and normalized emails against the passed current contacts and earlier accepted rows; use addContact for new IDs. skipped equals preview.rows.length minus added, including newly conflicting Ready records.

Use a character scanner with field-start, unquoted, quoted and after-quote states; handle doubled quotes, delimiters and record separators only outside quotes. Reject stray quotes, text after a closing quote, unclosed quotes and too many fields before producing a preview. Strip initial BOM; support LF/CRLF, quoted commas and embedded newlines. Normalize header names by trim/lowercase, reject duplicates and missing name/email. Pad shorter rows, ignore distinct unknown header fields. Ignore parsed all-whitespace records. Enforce TextEncoder UTF-8 byteLength <=100000 and <=500 nonblank data records. Validate fields before reserving emails: invalid rows cannot make later valid rows duplicate. Seed normalized email set from existing contacts; first valid file occurrence wins.

UI state and write ordering

In src/app.js, retain rows as committed contacts. Add panel phase (closed|select|reading|review|saving), selected File, preview, read generation token, a synchronous global writeBusy flag and failNextSave boolean. renderImport() creates text nodes/cards, counts and disabled states. Increment generation on selection/cancel; ignore late file.text() results. Check File.size before reading and enforce bytes again in previewCSV.

All Add and Import writes use one app-owned persistContacts(makeNext) async coordinator: synchronously acquire writeBusy before any await; reject a second attempt, disable Add/Import mutation controls, then call makeNext with latest committed rows. Import's factory calls mergeReady(preview, rows); Add's factory wraps addContact(rows, input) as {contacts, added:1, skipped:0}, matching the coordinator result shape. This serializes writes in this page; it is not a cross-tab lock. Consume failNextSave only when calling saveContacts(next, {fail}); publish next to rows and render only after resolution. On rejection preserve committed rows, input/preview and retry controls; release busy in finally. Never clear/remove the storage key. Successful import closes preview, so queued/double clicks cannot reuse it. Zero additions after revalidation return to list with accurate zero-added/all-skipped summary without an unnecessary save.

Preview is transient. Revalidation uses latest successful in-page rows immediately before save, not a captured upload snapshot. This browser-only exercise provides no multi-tab transaction, remote database concurrency or delivery verification. localStorage is origin/browser-profile specific, may fail, and clearing browser data removes imported contacts. No network upload or new storage key.

Rendering and failure boundary

Use createElement/textContent/replaceChildren for CSV content, filenames, reasons and summaries, matching the existing safe list renderer. Do not use innerHTML interpolation. Keep existing #status live region. Structural/read errors discard importable preview only, never committed contacts. Save failure retains preview and only the adapter decides persistence success. UI details and focus rules are in docs/screen-design.md.

Original file & source details

output/docs/architecture.md.txt · SHA-256 69d6f9009c7611dac555bd970d0b58d9346461bb735a225f6b2aa7d80887b557

# CRM-142 architecture

## Existing boundaries (unchanged)
`src/contacts.js` exports initialContacts, normalEmail(value), validContact(row), addContact(rows, row), searchContacts(rows, query=''). Reuse normalization/validation and addContact for final contact IDs and trimming. `src/storage.js` exports readContacts() and async saveContacts(rows, {fail=false}={}); it replaces only `agentbay-crm-142-contacts` after a 180ms delay. Leave both modules unchanged. `src/app.js` retains list rendering, search and Add contact integration.

## Pure import module
Create `src/import.js` with exactly the public exports required by `docs/import-contract.md`:

- `previewCSV(text, existing)` → `{rows, counts: {ready, invalid, duplicate}}`. Each row: `{record, name, email, company, status, reason}`; record is the 1-based nonblank data-record number, status is `ready|invalid|duplicate`, reason is empty for Ready. No DOM/storage access or persistence.
- `mergeReady(preview, existing)` → `{contacts, added, skipped}`. Return a new array, preserve all existing objects/data, never mutate either input. Revalidate Ready row fields and normalized emails against the passed current contacts and earlier accepted rows; use addContact for new IDs. skipped equals preview.rows.length minus added, including newly conflicting Ready records.

Use a character scanner with field-start, unquoted, quoted and after-quote states; handle doubled quotes, delimiters and record separators only outside quotes. Reject stray quotes, text after a closing quote, unclosed quotes and too many fields before producing a preview. Strip initial BOM; support LF/CRLF, quoted commas and embedded newlines. Normalize header names by trim/lowercase, reject duplicates and missing name/email. Pad shorter rows, ignore distinct unknown header fields. Ignore parsed all-whitespace records. Enforce TextEncoder UTF-8 byteLength <=100000 and <=500 nonblank data records. Validate fields before reserving emails: invalid rows cannot make later valid rows duplicate. Seed normalized email set from existing contacts; first valid file occurrence wins.

## UI state and write ordering
In `src/app.js`, retain `rows` as committed contacts. Add panel phase (`closed|select|reading|review|saving`), selected File, preview, read generation token, a synchronous global writeBusy flag and failNextSave boolean. `renderImport()` creates text nodes/cards, counts and disabled states. Increment generation on selection/cancel; ignore late file.text() results. Check File.size before reading and enforce bytes again in previewCSV.

All Add and Import writes use one app-owned `persistContacts(makeNext)` async coordinator: synchronously acquire writeBusy before any await; reject a second attempt, disable Add/Import mutation controls, then call makeNext with latest committed rows. Import's factory calls mergeReady(preview, rows); Add's factory wraps addContact(rows, input) as {contacts, added:1, skipped:0}, matching the coordinator result shape. This serializes writes in this page; it is not a cross-tab lock. Consume failNextSave only when calling saveContacts(next, {fail}); publish next to rows and render only after resolution. On rejection preserve committed rows, input/preview and retry controls; release busy in finally. Never clear/remove the storage key. Successful import closes preview, so queued/double clicks cannot reuse it. Zero additions after revalidation return to list with accurate zero-added/all-skipped summary without an unnecessary save.

Preview is transient. Revalidation uses latest successful in-page rows immediately before save, not a captured upload snapshot. This browser-only exercise provides no multi-tab transaction, remote database concurrency or delivery verification. localStorage is origin/browser-profile specific, may fail, and clearing browser data removes imported contacts. No network upload or new storage key.

## Rendering and failure boundary
Use createElement/textContent/replaceChildren for CSV content, filenames, reasons and summaries, matching the existing safe list renderer. Do not use innerHTML interpolation. Keep existing `#status` live region. Structural/read errors discard importable preview only, never committed contacts. Save failure retains preview and only the adapter decides persistence success. UI details and focus rules are in `docs/screen-design.md`.