# CRM: example CSV import reconciliation

Fixtures are fictional and use example.test addresses. This is not a client case or evidence of a commercial result.

## Actually tested

Six fictional CSV rows. Initially three are accepted and three rejected: duplicate email, unknown paused status and missing owner. After explicit paused-to-inactive mapping, assigning r5 to sales-c from the fixture directory and merging matching records: five accepted, one merged, zero rejected; all six original rows remain in the ledger. Second import: zero new, five skipped, one merged; five stored records remain. A missing-source-row control is rejected.

## Editable contract

- Rule owner: [name].
- Input version and expected scope: [values].
- Allowed fields, mappings and exceptions: [rules].
- Expected outcome for each case: [examples].
- Repeat-check and evidence retention procedure: [steps].

## Function and independent reproduction

Download both inventory JSON files for this locale. Save them beside model.mjs, copy the function and test code below into model.mjs, and run node model.mjs with Node.js. JSON and Markdown do not execute checks on their own.

```js
function parseCsv(csv) {
  const rows=[];let row=[],cell='',quoted=false;
  for(let i=0;i<csv.length;i++) {
    const c=csv[i];
    if(c==='"'){if(quoted&&csv[i+1]==='"'){cell+='"';i++;}else quoted=!quoted;}
    else if(c===','&&!quoted){row.push(cell);cell='';}
    else if(c==='\n'&&!quoted){row.push(cell.replace(/\r$/,''));rows.push(row);row=[];cell='';}
    else cell+=c;
  }
  if(quoted)throw Error('UNCLOSED_CSV_QUOTE');
  if(cell.length||row.length){row.push(cell.replace(/\r$/,''));rows.push(row);}
  const headers=rows.shift();if(!headers||new Set(headers).size!==headers.length)throw Error('CSV_HEADER');
  return rows.filter(r=>r.some(Boolean)).map(values=>{if(values.length!==headers.length)throw Error('CSV_WIDTH');return Object.fromEntries(headers.map((h,i)=>[h,values[i]]));});
}

function importCsvInventory(input,existingRecords=[]) {
  const rows=parseCsv(input.sourceCsv),observed=rows.map(r=>r.source_row),expected=input.expectedSourceRows;
  const missing=expected.filter(k=>!observed.includes(k)),unexpected=observed.filter(k=>!expected.includes(k)),duplicateSourceRows=[...new Set(observed.filter((k,i)=>observed.indexOf(k)!==i))];
  const scopeComplete=missing.length===0&&unexpected.length===0&&duplicateSourceRows.length===0&&observed.length===expected.length;
  const records=new Map(existingRecords.map(r=>[r.email,{...r}])),seen=new Map(),ledger=[],findings=[];
  const counts={accepted:0,rejected:0,merged:0,skipped:0};
  for(const source of rows) {
    const get=key=>String(source[input.columnMapping[key]]??'').trim();
    const sourceRow=source.source_row,email=get('email').toLowerCase(),rawStatus=get('status');
    const record={id:get('id'),email,status:input.statusMapping[rawStatus]??'',owner:input.ownerCorrections[sourceRow]??get('owner')};
    let code=!record.id?'missing-id':!/^\S+@\S+\.\S+$/.test(email)?'invalid-email':!record.status?'unknown-status':!record.owner?'missing-owner':null;
    let action='accepted',targetSourceRow=null;
    if(!code&&seen.has(email)) {
      const prior=seen.get(email);targetSourceRow=prior.sourceRow;
      if(input.mergeExactDuplicates&&JSON.stringify(prior.record)===JSON.stringify(record))action='merged';
      else code='duplicate-business-key';
    }
    if(!code&&action==='accepted'&&records.has(email)) {
      if(JSON.stringify(records.get(email))===JSON.stringify(record))action='skipped';
      else code='existing-record-conflict';
    }
    if(code){action='rejected';findings.push({sourceRow,code,businessKey:email});}
    else if(action==='accepted')records.set(email,record);
    if(!code&&!seen.has(email))seen.set(email,{sourceRow,record});
    counts[action]++;ledger.push({sourceRow,action,code,targetSourceRow,record});
  }
  const accounted=Object.values(counts).reduce((a,b)=>a+b,0),reconciled=scopeComplete&&accounted===expected.length;
  return {accepted:reconciled&&counts.rejected===0,scopeComplete,reconciled,expectedRows:expected.length,observedRows:observed.length,accountedRows:accounted,missing,unexpected,duplicateSourceRows,counts,findings,ledger,records:[...records.values()],storedRecords:records.size,scope:'Deterministic fixture mapping, row ledger and idempotency only; not a production CRM migration.'};
}

import fs from 'node:fs';
import assert from 'node:assert/strict';
const before = JSON.parse(fs.readFileSync('en-before-inventory.json', 'utf8'));
const after = JSON.parse(fs.readFileSync('en-after-inventory.json', 'utf8'));
assert.equal(importCsvInventory(before).findings.length, 3);
const result = importCsvInventory(after);
assert.equal(result.accepted, true);
assert.deepEqual(result.counts, {accepted:5, rejected:0, merged:1, skipped:0});
const second = importCsvInventory(after, result.records);
assert.deepEqual(second.counts, {accepted:0, rejected:0, merged:1, skipped:5});
assert.equal(second.storedRecords, 5);
const partial = {...after, sourceCsv:after.sourceCsv.split('\n').filter(line=>!line.startsWith('r4,')).join('\n')};
assert.equal(importCsvInventory(partial).accepted, false);
console.log('PASS');
```

## Files

- [before inventory](https://evolkov.tech/wp-content/uploads/reproleaf-guides/crm-data-migration-20261117/en-before-inventory.json)
- [before report](https://evolkov.tech/wp-content/uploads/reproleaf-guides/crm-data-migration-20261117/en-before-report.json)
- [after inventory](https://evolkov.tech/wp-content/uploads/reproleaf-guides/crm-data-migration-20261117/en-after-inventory.json)
- [after report](https://evolkov.tech/wp-content/uploads/reproleaf-guides/crm-data-migration-20261117/en-after-report.json)

Screenshots show an owned local worksheet or form with actual results. This is not the Reproleaf interface. Example data does not establish production CRM readiness, specification quality, security, legal compliance or the absence of all defects.
