구현 계획
원본 다운로드 ↓CRM-142 Import Contacts 구현 계획
에이전트 작업자 대상: 이번 실행은 계획만 수행합니다. 이후 실행도 네이티브 실행과 단일 에이전트 방식을 유지하며 추가 스킬, 커밋, 워크트리 또는 위임은 없습니다. 사용자/프로젝트 지침이 원본 실행 하위 스킬 템플릿보다 우선합니다.
목표: 연락처를 잃거나 미리보기 중 저장하지 않고 검토한 CSV 연락처를 기존 로컬 목록으로 가져옵니다.
아키텍처: 새 가져오기 모듈에 순수 파싱/분류/병합을 두고 기존 앱에 인라인 패널과 직렬화한 쓰기를 둡니다. 기존 연락처/저장 어댑터는 변경하지 않습니다.
기술 스택: 일반 HTML/CSS/브라우저 ES 모듈, localStorage, Node >=24 내장 테스트 실행기. 의존성은 없습니다.
명세: docs/brainstorming.md, docs/screen-design.md, docs/architecture.md; 고정된 요구 사항 위치: tickets/CRM-142.md 및 docs/import-contract.md.
전체 제약
애플리케이션 변경 대상만: index.html, style.css, src/app.js, 새 파일 src/import.js. 테스트, 예시, 티켓, 서버, 패키지, AGENTS.md 및 기존 도우미 모듈 2개는 변경하지 않습니다. 외부 서비스, 의존성 변경, 동반 도구 실행, 전역 설치, 커밋, 배포 또는 게시는 없습니다. 로그인, 서버 데이터베이스, 필드 매핑 도우미, 원격 업로드, 실제 CRM 계정 또는 백그라운드 작업은 없습니다. 100,000 UTF-8 바이트와 비어 있지 않은 데이터 레코드 500개로 제한하고 업로드 전에 표시합니다. 미리보기는 저장하지 않습니다. 기존 검색/Add는 유지합니다. 이 단계에서는 구현이 승인되지 않았습니다.
검토 중점
변경할 수 없는 모듈 테스트가 많은 파싱 사례를 다루지만 UI/저장 동작을 입증하지는 않습니다. 담당 작업에 다음 수동 검증을 포함하세요:
- 작업 3: 빠른 Add/Import와 이중 확인이 저장 경쟁이나 연락처 손실을 만들면 안 됩니다.
- 작업 3: 저장 실패 시 미리보기와 기존 영속 데이터를 유지하고 재시도 시 연락처를 각각 한 번만 추가해야 합니다.
- 작업 2: 선택/취소 이후 늦게 완료된 파일 읽기가 오래된 미리보기를 복원하면 안 됩니다.
- 작업 4: HTML처럼 보이는 셀은 미리보기와 목록에서 문자 그대로 표시되며 요소를 삽입하면 안 됩니다.
- 작업 4: 키보드 포커스/상태와 긴 값이 320px에서도 사용 가능해야 합니다.
작업 1: 순수 CSV 미리보기 및 병합
파일: 생성할 파일: src/import.js; 변경 없이 사용할 항목: src/contacts.js; 변경 없이 확인할 항목: tests/import.test.js 및 tests/contacts.test.js. 인터페이스: 생성할 결과: previewCSV(text: string, existing: Contact[]): Preview 및 mergeReady(preview: Preview, existing: Contact[]): {contacts: Contact[], added: number, skipped: number}. Contact는 기존의 다음 구조를 사용합니다: {id,name,email,company} ; Preview는 다음과 같습니다: {rows: {record:number,name:string,email:string,company:string,status:'ready'|'invalid'|'duplicate',reason:string}[], counts:{ready:number,invalid:number,duplicate:number}}. 다음에서 normalEmail, validContact 및 addContact를 사용합니다: src/contacts.js.
- [ ] 실행할 명령:
node --test tests/import.test.js구현 전에 실행합니다. 현재 트리에서는 다음 항목이 없다는 오류가 예상되며src/import.js제품 동작의 실패가 아닙니다. 테스트를 수정하지 마세요. - [ ] 다음에서 스캐너/제한/헤더 규칙을 포함한 previewCSV를 구현합니다:
docs/architecture.md; 미리보기를 반환하기 전에 구조 검증을 완료해야 합니다. 중복 추적 전에 필드를 분류하고 비어 있지 않은 모든 레코드와 정확한 개수를 유지합니다. - [ ] 전달된 현재 연락처와 Ready 레코드를 다시 확인하는 mergeReady를 구현합니다. 입력과 기존 연락처를 유지하고 addContact로 ID를 추가하며 파일에서 추가하지 않은 모든 레코드를 건너뜀으로 계산합니다.
- [ ] 실행할 명령:
node --test tests/import.test.js tests/contacts.test.js; 기존 테스트 17개가 모두 통과해야 합니다(가져오기 12개, 연락처 5개). 이는 따옴표, BOM/CRLF, 선택 company, 빈 레코드, 잘못된 구조, 앞선 잘못된 중복 행, 병합 재검증, 불변성 및 제한을 검증합니다. - [ ] 저장된 테스트를 편집하지 않고 인라인 Node 모듈 assertion 검증을 실행합니다. 정확히 100,000바이트의 ASCII 입력은 허용하고 100,001은 거부해야 합니다. 공백을 제거한 대소문자 혼합 헤더 허용, 정규화된 중복 헤더 거부, 공백뿐인 레코드 무시, 짧은 레코드 채우기, 미지의 헤더 값 무시, 닫는 따옴표 뒤 문자 거부를 확인합니다. 문서의 선택을 따릅니다. 파싱할 대상:
samples/customer-contacts.csvinitialContacts와 함께 사용하고 다음 개수를 확인합니다:{ready:3,invalid:1,duplicate:2}, 행 길이 6,, 병합 added 3/skipped 3/contacts 길이 5.
작업 2: 인라인 업로드 및 전체 검토
파일: 수정할 항목: index.html, src/app.js, style.css 만 수정하며 작업 1에 의존합니다. 인터페이스: 작업 1의 previewCSV와 Preview를 사용합니다. 앱 내부에 생성할 항목: renderImport() 및 다음에 설명된 상태: docs/architecture.md; 기존 요소를 유지합니다: #search, #contacts, #status, #add 및 그 동작. 레이블이 있는 인라인 섹션과 파일 입력을 추가하며 컨트롤의 접근 가능한 이름은 다음과 같습니다: Import contacts, CSV file, Review CSV, Import ready contacts, Cancel import, Back to contacts, Fail next save.
- [ ] 다음에 따라 컨트롤, 제한/도움말 및 검토 컨테이너를 추가합니다:
docs/screen-design.md; 작업 3의 저장 경로를 연결하기 전까지 확인을 비활성화합니다. - [ ] 열기, 파일 선택, 명시적인 Review CSV, 취소 및 Back을 연결합니다. 세대 토큰으로 비동기 읽기를 보호하고 새 입력마다 이전 오류/미리보기를 지웁니다. textContent로 모든 레코드의 필드/상태/사유 및 개수를 표시합니다.
- [ ] 기존 연락처 스타일과 보이는 포커스를 유지하면서 레이블 카드, 줄바꿈되는 버튼 및 긴 텍스트에 한정된 반응형 스타일을 추가합니다.
- [ ] 다음을 사용합니다:
npm start및http://127.0.0.1:8830, 예시를 선택하면 카드 6개와 개수 3/1/2가 나와야 합니다. Cancel/Back은 목록, 검색 및 저장된 값을 유지해야 합니다. 잘못된 파일을 선택하면 오류와 비활성화된 확인이 표시되고 이후 유효한 파일을 선택하면 이전 오류가 사라져야 합니다. 읽는 중 빠르게 선택/취소해도 오래된 미리보기가 돌아오면 안 됩니다. 이는 나중에 실행할 브라우저 검증이며 현재 결과를 주장하는 것이 아닙니다.
작업 3: 직렬화된 확인, 실패 및 재시도
파일: 수정할 항목: src/app.js 만 수정합니다(컨트롤은 작업 2에 정의됨). 작업 1–2에 의존합니다. 인터페이스: mergeReady 및 기존 addContact/readContacts/saveContacts를 사용합니다. 앱 내부에 생성할 항목: persistContacts(makeNext) 조정자이며 makeNext는 현재 확정된 Contact[]를 받고 다음을 반환합니다: {contacts:Contact[], added:number, skipped:number} (Add는 새 행 하나를 이 구조로 맞춥니다). Promise는 저장 후 결과를 반환하고 busy/실패 시 거부합니다. 새 공개 API나 저장 어댑터 변경은 없습니다.
- [ ] 기존 Add 및 Import 저장을 동기 busy 보호와 다음 조정자를 거치게 합니다:
docs/architecture.md. Import는 확인 시 다시 병합하며 업로드 중 다음 연락처를 미리 계산하지 않습니다. 저장 중 변경 컨트롤을 비활성화합니다. 저장 성공 후에만 rows를 반영하며 catch/finally에서 성공 메시지를 표시하지 않습니다. - [ ] Fail next save를 다음 실제 어댑터 저장에서 소비되는 레이블 체크박스로 연결합니다. 실패는 미리보기와 확정 목록을 유지하고 busy를 해제하며 재시도를 복구합니다. 취소는 쓰지 않습니다. 재검증 후 추가가 0개면 저장을 생략하고 실제 개수를 알립니다.
- [ ] 가져오기 성공 시 미리보기와 검색을 지우고 같은 목록을 렌더링하며 실제 추가/건너뜀 개수를 알리고 포커스를 복원합니다. Ready가 0개일 때 확인 비활성화 및 동기 보호로 반복 제출을 방지합니다.
- [ ] 새 브라우저에서 예시를 가져옵니다. added 3/skipped 3,, 총 5,개여야 하며 검색으로 Jordan을 찾고 Add로 새 고유 연락처를 추가할 수 있어야 합니다. 새로고침 후 모든 저장된 연락처가 유지되어야 합니다.
- [ ] 새 컨텍스트: 예시 미리보기 후 Jordan을 수동 추가하고 확인합니다. added 2/skipped 4 및 수동 연락처 유지가 예상됩니다. 확인을 더블 클릭하고 180ms 저장 중 Add를 시도해도 중복 가져오기, 겹치는 저장 또는 연락처 손실이 없어야 합니다.
- [ ] 새 컨텍스트: 예시 미리보기 후 Fail next save를 켜고 확인합니다. 목록/저장소가 그대로이고 레코드 6개 미리보기와 실패 상태가 유지되어야 합니다. 재시도 시 added 3/skipped 3이 한 번 발생하고 새로고침 후 연락처 5개가 있어야 합니다. Add 실패도 확인해 회귀를 방지합니다. Ready가 없는 미리보기는 확인할 수 없어야 합니다.
작업 4: 인수 검증 및 범위 검토
파일: 허용된 애플리케이션 파일만 검토하고 테스트는 변경하지 않습니다. 작업 1–3에 의존합니다. 인터페이스: 기존 Contacts UI 전체와 작업 2의 컨트롤이며 새 API는 없습니다.
- [ ] 실행할 명령:
npm test; 변경하지 않은 테스트 17개가 모두 통과해야 합니다. 이를 브라우저 저장소/접근성 검증과 동일하게 보지 않습니다. - [ ] 미리보기와 가져온 목록에서 예시 레코드 6을 브라우저로 확인합니다. 다음이 문자 그대로 표시되어야 합니다:
<img src=x onerror=alert(1)>, img 요소나 실행은 없어야 합니다. 따옴표 안 여러 줄 company 및 긴 이메일/company가 읽기 쉽게 줄바꿈되는지 확인합니다. - [ ] 320px와 데스크톱에서 키보드만으로 업로드/검토/취소/확인 및 Add를 조작합니다. 레이블, 논리적 탭 순서, 보이는 포커스, 검토 제목 포커스, 개수/오류/성공 실시간 알림, 취소 시 포커스 복원 및 가로 페이지 스크롤 없음을 검증합니다. 포커스 트랩은 없고 예시 레코드 6개에 모두 접근할 수 있어야 합니다.
- [ ] 잘못된 헤더/따옴표/초과 필드 및 너무 큰 입력이 기존 연락처를 변경하지 않는지 확인합니다. 레코드 501개는 거부하고 500개는 허용해야 합니다. Ready 행이 없는 미리보기도 포함합니다.
- [ ] 변경 내용을 확인합니다. 구현 중 허용된 애플리케이션 경로 4개만 변경되고 고정 파일과 선택 산출물은 그대로여야 합니다. 실제 테스트/브라우저 결과와 제한을 보고합니다. 운영자 검토를 위해 멈추고 커밋하거나 배포하지 않습니다.
원본 파일 및 출처 세부 정보
output/docs/implementation-plan.md.txt · SHA-256 f20d8893150a7b9a6b0a44bfdc711d92b535cf9f8fcb7de224c4892b75c5cbf1
# CRM-142 Import Contacts Implementation Plan
> For agentic workers: planning only in this run. Later execution stays native and single-agent; no additional skills, commits, worktrees or delegation. User/project instructions override the upstream execution-subskill template.
**Goal:** Import reviewed CSV contacts into the existing local list without losing contacts or saving during preview.
**Architecture:** Pure parsing/classification/merge in a new import module; inline panel and serialized writes in the existing app. Existing contacts/storage adapters remain unchanged.
**Tech Stack:** Plain HTML/CSS/browser ES modules, localStorage; Node >=24 built-in test runner, no dependencies.
**Spec:** `docs/brainstorming.md`, `docs/screen-design.md`, `docs/architecture.md`; fixed requirements in `tickets/CRM-142.md` and `docs/import-contract.md`.
## Global constraints
Application changes only: `index.html`, `style.css`, `src/app.js`, new `src/import.js`. Tests, samples, ticket, server, package, AGENTS.md and both existing helper modules are immutable. No external services, dependency changes, companion execution, global installation, commits, deployment or publishing. No login, server database, field-mapping wizard, remote uploads, live CRM account or background jobs. Limit 100,000 UTF-8 bytes and 500 nonblank data records; display limits before upload. Preview never persists. Existing search/Add remain working. No implementation is authorized in this phase.
## Review focus
The immutable module tests cover many parsing cases but do not prove UI/storage behavior. Include these targeted manual checks in the owning tasks:
1. Task 3: rapid Add/Import and double confirmation cannot race a save or lose contacts.
2. Task 3: failed save retains preview and old persisted data; retry adds each contact once.
3. Task 2: late file reads after selection/cancel cannot restore stale previews.
4. Task 4: HTML-looking cells remain literal text in both preview and list; no injected element.
5. Task 4: keyboard focus/status and long values remain usable at 320px.
## Task 1: Pure CSV preview and merge
**Files:** Create `src/import.js`; consume unchanged `src/contacts.js`; verify unchanged `tests/import.test.js` and `tests/contacts.test.js`.
**Interfaces:** Produce `previewCSV(text: string, existing: Contact[]): Preview` and `mergeReady(preview: Preview, existing: Contact[]): {contacts: Contact[], added: number, skipped: number}`. Contact is the existing `{id,name,email,company}` shape; Preview is `{rows: {record:number,name:string,email:string,company:string,status:'ready'|'invalid'|'duplicate',reason:string}[], counts:{ready:number,invalid:number,duplicate:number}}`. Consume normalEmail, validContact and addContact from `src/contacts.js`.
- [ ] Run `node --test tests/import.test.js` before implementation; with the current tree expect missing `src/import.js`, not a product behavior failure. Do not edit tests.
- [ ] Implement previewCSV with scanner/limits/header decisions in `docs/architecture.md`; ensure structural validation completes before returning any preview. Classify fields before duplicate tracking, keeping every nonblank record and exact counts.
- [ ] Implement mergeReady, rechecking Ready records against its supplied current contacts. Preserve inputs and old contacts, add IDs through addContact, count every non-added file record as skipped.
- [ ] Run `node --test tests/import.test.js tests/contacts.test.js`; expect all 17 existing tests to pass (12 import, 5 contacts). These prove quoting, BOM/CRLF, optional company, blank records, malformed structures, invalid-first duplicates, merge revalidation, immutability and limits.
- [ ] Run an inline Node module assertion probe (no saved test edits): exact 100,000-byte ASCII input accepted and 100,001 rejected; trimmed mixed-case headers accepted; duplicate normalized headers rejected; whitespace-only records ignored; short records padded; unknown header values ignored; characters after closing quote rejected. Match the documented choices. Parse `samples/customer-contacts.csv` with initialContacts and assert counts `{ready:3,invalid:1,duplicate:2}`, rows length 6, merged added 3/skipped 3/contacts length 5.
## Task 2: Inline upload and complete review
**Files:** Modify `index.html`, `src/app.js`, `style.css` only; depends on Task 1.
**Interfaces:** Consume previewCSV and Preview from Task 1. Produce app-local `renderImport()` and state described in `docs/architecture.md`; keep existing `#search`, `#contacts`, `#status`, `#add` and their behavior. Add a labelled inline section and file input; control accessible names are `Import contacts`, `CSV file`, `Review CSV`, `Import ready contacts`, `Cancel import`, `Back to contacts`, `Fail next save`.
- [ ] Add controls, limit/help text and review container according to `docs/screen-design.md`; keep confirmation disabled until the save path in Task 3 is connected.
- [ ] Connect opening, file selection, explicit Review CSV, cancellation and Back; guard asynchronous reads with a generation token and clear prior errors/preview on new input. Show every record with fields/status/reason and counts using textContent.
- [ ] Add narrow responsive styles for labelled record cards, wrapped buttons and long text, retaining existing contact styling and visible focus.
- [ ] With `npm start` and `http://127.0.0.1:8830`, select the sample: expect six cards and 3/1/2 counts. Cancel/Back must preserve list, search and stored value. Select a malformed file: expect error and disabled confirmation; select a valid file afterward: old error disappears. Select/cancel rapidly while reading: no stale preview returns. These are browser checks for later execution, not claims of current results.
## Task 3: Serialized confirmation, failure and retry
**Files:** Modify `src/app.js` only (controls already defined in Task 2). Depends on Tasks 1–2.
**Interfaces:** Consume mergeReady and existing addContact/readContacts/saveContacts. Produce app-local `persistContacts(makeNext)` coordinator, where makeNext receives current committed Contact[] and returns `{contacts:Contact[], added:number, skipped:number}` (Add adapts its one new row to this shape). Promise resolves that result after storage; rejects on busy/failure. No new exported API or storage adapter changes.
- [ ] Route existing Add and Import saves through the synchronous busy guard and coordinator in `docs/architecture.md`. Import remerges at confirmation; do not precompute next contacts during upload. Disable mutation controls while saving. Publish rows only after successful storage; no success message in catch/finally.
- [ ] Wire Fail next save as a labelled checkbox consumed by the next actual adapter save. Failure retains preview and committed list, releases busy and restores retry; cancellation never writes. For zero additions after revalidation skip storage and report actual counts.
- [ ] On successful import clear preview and search, render the same list, announce actual added/skipped counts and restore focus. Ensure disabled zero-Ready confirmation and synchronous guarding prevent repeat submissions.
- [ ] In a fresh browser import the sample: expect added 3/skipped 3, total 5, search finds Jordan, Add still adds a unique contact, and reload retains all saved contacts.
- [ ] Fresh context: preview sample, Add Jordan manually, then confirm; expect added 2/skipped 4 and preservation of the manual contact. Double-click confirm and attempt Add during the 180ms save: no duplicate import, overlapping save or lost contact.
- [ ] Fresh context: preview sample, arm Fail next save and confirm; expect unchanged list/storage and retained six-record preview with failure status. Retry: expect added 3/skipped 3 once, then reload and verify five contacts. Also exercise failed Add to ensure no regression. Zero-Ready preview must not allow confirmation.
## Task 4: Acceptance verification and scope review
**Files:** Review only allowed application files; tests remain unchanged. Depends on Tasks 1–3.
**Interfaces:** Full existing Contacts UI plus the Task 2 controls; no new API.
- [ ] Run `npm test`; expect all 17 immutable tests to pass. Do not equate this with browser storage/accessibility coverage.
- [ ] Browser check sample record 6 in preview and imported list: literal `<img src=x onerror=alert(1)>`, no img element or execution. Check a quoted multiline company and a long email/company for readable wrapping.
- [ ] At 320px and desktop, operate upload/review/cancel/confirm and Add using keyboard only. Verify labels, logical tab order, visible focus, review-heading focus, live counts/errors/success, cancellation focus restoration and no horizontal page scroll. No focus trap; all six sample records reachable.
- [ ] Check malformed headers/quotes/extra fields and oversized input leave stored contacts unchanged; confirm 501 records rejected and 500 accepted. Include a preview with no Ready rows.
- [ ] Inspect diff: only the four allowed application paths changed during implementation; immutable files and selection artifacts unchanged. Report actual test/browser outcomes and any limitation. Stop for operator review; do not commit or deploy.