a↗agentbay.AgentBay を入手
マイアカウント ▾
メニュー
← 実践ガイドへ戻る
実践ガイドの出力

アーキテクチャ

元のファイルをダウンロード ↓

CRM-142のアーキテクチャ

既存の境界(変更なし)

src/contacts.js はinitialContacts、normalEmail(value)、validContact(row)、addContact(rows, row)、searchContacts(rows, query='')をエクスポートします。正規化・検証を再利用し、最終的な連絡先IDと空白除去にはaddContactを使います。 src/storage.js はreadContacts()とasync saveContacts(rows, {fail=false}={})をエクスポートし、置き換える対象は次のみです: agentbay-crm-142-contacts 。180ms待ってから置き換えます。両モジュールは変更しません。 src/app.js は、一覧の描画、検索、Add contactの連携を維持します。

純粋なインポートモジュール

作成するもの: src/import.js 。公開エクスポートは、次の契約で求められるものに正確に合わせます: docs/import-contract.md:

  • previewCSV(text, existing) → {rows, counts: {ready, invalid, duplicate}}。各行: {record, name, email, company, status, reason}。recordは、空でないデータレコードの1始まりの番号で、statusは ready|invalid|duplicate、Readyのreasonは空です。DOM・ストレージへのアクセスや永続化は行いません。
  • mergeReady(preview, existing) → {contacts, added, skipped}。新しい配列を返し、既存の全オブジェクトとデータを維持し、どちらの入力も変更しません。Ready行のフィールドと正規化メールを、渡された現在の連絡先と先に受け入れた行に照らして再検証します。新IDにはaddContactを使います。skippedはpreview.rows.lengthからaddedを引いた値で、新たに競合したReadyレコードも含みます。

フィールド開始、引用符なし、引用符内、引用符後の状態を持つ文字スキャナーを使い、二重化した引用符を処理し、区切りとレコード区切りは引用符の外でのみ扱います。プレビューを返す前に、不正な引用符、閉じた引用符後の文字、閉じていない引用符、過剰なフィールドを拒否します。先頭BOMを除去し、LF/CRLF、引用符付きカンマ、引用符内改行を支援します。ヘッダーを空白除去と小文字化で正規化し、重複とname/email欠落を拒否します。短い行を補い、未知の重複しないヘッダーの値は無視します。全セルが空白のみのレコードは無視します。TextEncoderのUTF-8 byteLengthを100000以下、空でないデータを500レコード以下に制限します。メール予約前にフィールドを検証し、不正な行が後の有効な行を重複にしないようにします。既存の連絡先から正規化メール集合を作り、ファイル内では最初の有効な出現を優先します。

UIの状態と書き込み順序

対象: src/app.js、維持するもの: rows を確定済みの連絡先とします。パネルの段階(closed|select|reading|review|saving)、選択したFile、プレビュー、読み込み世代トークン、同期的な全体のwriteBusyフラグ、failNextSave真偽値を追加します。 renderImport() は、テキストノードとカード、件数、無効状態を生成します。選択・キャンセル時に世代を進め、遅れたfile.text()の結果を無視します。読み込み前にFile.sizeを確認し、previewCSVでもバイト数を再検証します。

AddとImportのすべての書き込みは、アプリが持つ次の一つを使います: persistContacts(makeNext) 非同期コーディネーターです。await前に同期的にwriteBusyを取得し、2回目の試行を拒否し、Add/Importの変更操作を無効にしてから、最新の確定済み行でmakeNextを呼びます。ImportのファクトリーはmergeReady(preview, rows)を呼び、AddはaddContact(rows, input)を{contacts, added:{0} skipped:0}で包み、結果の形を合わせます。このページ内の書き込みを直列化しますが、タブ間ロックではありません。saveContacts(next, {fail})を呼ぶときだけfailNextSaveを消費し、完了後にだけnextをrowsへ公開して描画します。失敗時は確定済み行、入力・プレビュー、再試行操作を維持し、finallyでbusyを解放します。保存キーは消去しません。インポート成功時はプレビューを閉じ、待ち行列やダブルクリックから再利用できないようにします。再検証後の追加が0なら、不要な保存をせず、追加0・全件スキップの正確な要約で一覧へ戻ります。

プレビューは一時的です。保存直前の再検証には、アップロード時のスナップショットではなく、ページ内で最後に保存が成功した行を使います。このブラウザのみの演習には、複数タブ間トランザクション、リモートデータベースの同時実行制御、配信検証はありません。localStorageはオリジンとブラウザプロフィールごとに異なり、失敗する場合があります。ブラウザデータを消すと、インポートした連絡先も消えます。ネットワークへのアップロードや新しい保存キーは追加しません。

描画と失敗の境界

CSV内容、ファイル名、理由、要約には、既存の安全な一覧描画に合わせてcreateElement/textContent/replaceChildrenを使います。innerHTMLへの補間は使いません。既存のライブ領域 #status を維持します。構造・読み込みエラーで破棄するのはインポート可能なプレビューのみで、確定済み連絡先は残します。保存失敗時はプレビューを維持し、永続化の成功はアダプターのみが判断します。UI詳細とフォーカス規則は次を参照してください: docs/screen-design.md.

元のファイルと出所の詳細

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`.