From 3a416832a7441498379c72ec44763608277596fc Mon Sep 17 00:00:00 2001 From: Abhishek Sonwal Date: Mon, 15 Jun 2026 13:00:18 +0530 Subject: [PATCH 1/4] feat(contacts): enhance CSV import functionality with tag assignment - Introduced `parseContactCsv` for improved CSV parsing, replacing the previous inline parsing logic. - Added support for importing tags alongside contacts, allowing users to assign tags during the import process. - Implemented `assignImportedContactTags` to handle tag assignments after contact creation. - Updated the import result state to include the number of tags assigned and added relevant success and info notifications for users. - Enhanced the import modal description to clarify the format for tag input in CSV files. --- src/components/contacts/import-modal.tsx | 156 ++++++++++++--------- src/lib/contacts/parse-contact-csv.test.ts | 65 +++++++++ src/lib/contacts/parse-contact-csv.ts | 100 +++++++++++++ src/lib/contacts/resolve-import-tags.ts | 127 +++++++++++++++++ 4 files changed, 379 insertions(+), 69 deletions(-) create mode 100644 src/lib/contacts/parse-contact-csv.test.ts create mode 100644 src/lib/contacts/parse-contact-csv.ts create mode 100644 src/lib/contacts/resolve-import-tags.ts diff --git a/src/components/contacts/import-modal.tsx b/src/components/contacts/import-modal.tsx index 392a33d..c2d0d66 100644 --- a/src/components/contacts/import-modal.tsx +++ b/src/components/contacts/import-modal.tsx @@ -8,6 +8,12 @@ import { isUniqueViolation, normalizeKey, } from '@/lib/contacts/dedupe'; +import { parseContactCsv } from '@/lib/contacts/parse-contact-csv'; +import { + assignImportedContactTags, + resolveImportTagIds, + type ContactTagAssignment, +} from '@/lib/contacts/resolve-import-tags'; import { toast } from 'sonner'; import { Dialog, @@ -26,75 +32,19 @@ interface ImportModalProps { onImported: () => void; } -interface ParsedRow { - phone: string; - name?: string; - email?: string; - company?: string; -} - -function parseCSV(text: string): ParsedRow[] { - const lines = text.trim().split(/\r?\n/); - if (lines.length < 2) return []; - - const headerLine = lines[0]; - const headers = headerLine.split(',').map((h) => h.trim().toLowerCase().replace(/["']/g, '')); - - const phoneIdx = headers.indexOf('phone'); - if (phoneIdx === -1) return []; - - const nameIdx = headers.indexOf('name'); - const emailIdx = headers.indexOf('email'); - const companyIdx = headers.indexOf('company'); - - const rows: ParsedRow[] = []; - for (let i = 1; i < lines.length; i++) { - const line = lines[i].trim(); - if (!line) continue; - - // Simple CSV parse (handles quoted fields) - const values: string[] = []; - let current = ''; - let inQuotes = false; - for (const char of line) { - if (char === '"') { - inQuotes = !inQuotes; - } else if (char === ',' && !inQuotes) { - values.push(current.trim()); - current = ''; - } else { - current += char; - } - } - values.push(current.trim()); - - const phone = values[phoneIdx]?.replace(/["']/g, '').trim(); - if (!phone) continue; - - rows.push({ - phone, - name: nameIdx >= 0 ? values[nameIdx]?.replace(/["']/g, '').trim() || undefined : undefined, - email: emailIdx >= 0 ? values[emailIdx]?.replace(/["']/g, '').trim() || undefined : undefined, - company: - companyIdx >= 0 ? values[companyIdx]?.replace(/["']/g, '').trim() || undefined : undefined, - }); - } - - return rows; -} - export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps) { const supabase = createClient(); - const { accountId } = useAuth(); + const { accountId, canEditSettings } = useAuth(); const fileInputRef = useRef(null); const [file, setFile] = useState(null); - const [parsedRows, setParsedRows] = useState([]); + const [parsedRows, setParsedRows] = useState>([]); const [importing, setImporting] = useState(false); const [result, setResult] = useState<{ imported: number; skipped: number; failed: number; + tagsAssigned: number; } | null>(null); function reset() { @@ -117,7 +67,7 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps setResult(null); const text = await selected.text(); - const rows = parseCSV(text); + const rows = parseContactCsv(text); if (rows.length === 0) { toast.error('No valid rows found. Ensure CSV has a "phone" column header.'); @@ -168,9 +118,19 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps return true; }); - // 3) Batch insert the genuinely-new rows in chunks of 50. The DB - // unique index is the backstop: a 23505 (race, or a format - // that normalizes equal) counts as skipped, not failed. + // 3) Resolve tag names → ids (create missing tags for admin+). + const allTagNames = toInsert.flatMap((row) => row.tagNames); + const { tagIdByKey, skippedNames } = await resolveImportTagIds(supabase, { + accountId, + userId: user.id, + tagNames: allTagNames, + canCreateTags: canEditSettings, + }); + + const tagAssignments: ContactTagAssignment[] = []; + + // 4) Batch insert contacts in chunks of 50. The DB unique index is + // the backstop: a 23505 counts as skipped, not failed. const chunkSize = 50; for (let i = 0; i < toInsert.length; i += chunkSize) { const chunk = toInsert.slice(i, i + chunkSize); @@ -191,10 +151,23 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps if (error) { // Retry individually so one bad/duplicate row doesn't sink // the whole chunk. - for (const row of rows) { - const { error: singleErr } = await supabase.from('contacts').insert(row); - if (!singleErr) { + for (let j = 0; j < rows.length; j++) { + const row = rows[j]; + const source = chunk[j]; + const { data: singleData, error: singleErr } = await supabase + .from('contacts') + .insert(row) + .select('id') + .single(); + + if (!singleErr && singleData) { imported++; + if (source.tagNames.length > 0) { + tagAssignments.push({ + contactId: singleData.id, + tagNames: source.tagNames, + }); + } } else if (isUniqueViolation(singleErr)) { skipped++; } else { @@ -202,15 +175,44 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps } } } else { - imported += data?.length ?? chunk.length; + const inserted = data ?? []; + imported += inserted.length; + for (let j = 0; j < inserted.length; j++) { + const source = chunk[j]; + if (!source || source.tagNames.length === 0) continue; + tagAssignments.push({ + contactId: inserted[j].id, + tagNames: source.tagNames, + }); + } } } - setResult({ imported, skipped, failed }); + // 5) Wire tags onto the contacts we just created. + const tagsAssigned = await assignImportedContactTags( + supabase, + tagAssignments, + tagIdByKey, + ); + + setResult({ imported, skipped, failed, tagsAssigned }); if (imported > 0) { toast.success(`${imported} contact${imported !== 1 ? 's' : ''} imported`); onImported(); } + if (tagsAssigned > 0) { + toast.success( + `${tagsAssigned} tag assignment${tagsAssigned !== 1 ? 's' : ''} applied`, + ); + } + if (skippedNames.length > 0) { + const sample = skippedNames.slice(0, 3).join(', '); + const more = + skippedNames.length > 3 ? ` (+${skippedNames.length - 3} more)` : ''; + toast.info( + `Unknown tags skipped (create them in Settings first): ${sample}${more}`, + ); + } if (skipped > 0) { toast.info(`${skipped} duplicate${skipped !== 1 ? 's' : ''} skipped`); } @@ -226,6 +228,7 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps } const preview = parsedRows.slice(0, 5); + const hasTagsColumn = parsedRows.some((row) => row.tagNames.length > 0); return ( @@ -234,7 +237,8 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps Import Contacts Upload a CSV file with a "phone" column (required). Optional columns: - name, email, company. + name, email, company, tags (comma-separated tag names — quote the + cell if a tag list contains commas, e.g. "VIP, Lead"). @@ -287,6 +291,9 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps Name Email Company + {hasTagsColumn && ( + Tags + )} @@ -296,6 +303,11 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps {row.name || '-'} {row.email || '-'} {row.company || '-'} + {hasTagsColumn && ( + + {row.tagNames.length > 0 ? row.tagNames.join(', ') : '-'} + + )} ))} @@ -320,6 +332,12 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps {result.imported} imported )} + {result.tagsAssigned > 0 && ( +
+ + {result.tagsAssigned} tag{result.tagsAssigned !== 1 ? 's' : ''} assigned +
+ )} {result.skipped > 0 && (
diff --git a/src/lib/contacts/parse-contact-csv.test.ts b/src/lib/contacts/parse-contact-csv.test.ts new file mode 100644 index 0000000..06c34e3 --- /dev/null +++ b/src/lib/contacts/parse-contact-csv.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from "vitest"; +import { parseContactCsv, parseTagCell } from "./parse-contact-csv"; + +describe("parseTagCell", () => { + it("splits comma-separated tags and trims whitespace", () => { + expect(parseTagCell(" VIP , Lead , ")).toEqual(["VIP", "Lead"]); + }); + + it("splits semicolon-separated tags", () => { + expect(parseTagCell("VIP; Lead; Customer")).toEqual([ + "VIP", + "Lead", + "Customer", + ]); + }); + + it("de-dupes case-insensitively", () => { + expect(parseTagCell("vip, VIP, Lead")).toEqual(["vip", "Lead"]); + }); + + it("returns empty for blank values", () => { + expect(parseTagCell("")).toEqual([]); + expect(parseTagCell(undefined)).toEqual([]); + }); +}); + +describe("parseContactCsv", () => { + it("parses optional tags column", () => { + const csv = `phone,name,tags ++15551234567,Alice,"VIP, Lead" ++15559876543,Bob,Customer`; + + expect(parseContactCsv(csv)).toEqual([ + { + phone: "+15551234567", + name: "Alice", + email: undefined, + company: undefined, + tagNames: ["VIP", "Lead"], + }, + { + phone: "+15559876543", + name: "Bob", + email: undefined, + company: undefined, + tagNames: ["Customer"], + }, + ]); + }); + + it("returns empty tagNames when tags column is absent", () => { + const csv = `phone,name ++15551234567,Alice`; + + expect(parseContactCsv(csv)).toEqual([ + { + phone: "+15551234567", + name: "Alice", + email: undefined, + company: undefined, + tagNames: [], + }, + ]); + }); +}); diff --git a/src/lib/contacts/parse-contact-csv.ts b/src/lib/contacts/parse-contact-csv.ts new file mode 100644 index 0000000..95381cb --- /dev/null +++ b/src/lib/contacts/parse-contact-csv.ts @@ -0,0 +1,100 @@ +/** + * CSV parsing for the contacts import modal. Shared + unit-tested so + * tag-column handling stays aligned with phone/name/email/company. + */ + +export interface ParsedContactRow { + phone: string; + name?: string; + email?: string; + company?: string; + /** Tag names from the optional `tags` column (comma/semicolon separated). */ + tagNames: string[]; +} + +/** Split a CSV cell into unique tag names (case-insensitive de-dupe). */ +export function parseTagCell(value: string | undefined): string[] { + if (!value?.trim()) return []; + + const seen = new Set(); + const names: string[] = []; + + for (const part of value.split(/[,;]/)) { + const name = part.trim(); + if (!name) continue; + const key = name.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + names.push(name); + } + + return names; +} + +export function parseContactCsv(text: string): ParsedContactRow[] { + const lines = text.trim().split(/\r?\n/); + if (lines.length < 2) return []; + + const headers = lines[0] + .split(",") + .map((h) => h.trim().toLowerCase().replace(/["']/g, "")); + + const phoneIdx = headers.indexOf("phone"); + if (phoneIdx === -1) return []; + + const nameIdx = headers.indexOf("name"); + const emailIdx = headers.indexOf("email"); + const companyIdx = headers.indexOf("company"); + const tagsIdx = headers.indexOf("tags"); + + const rows: ParsedContactRow[] = []; + + for (let i = 1; i < lines.length; i++) { + const line = lines[i].trim(); + if (!line) continue; + + const values = parseCsvLine(line); + const phone = values[phoneIdx]?.replace(/["']/g, "").trim(); + if (!phone) continue; + + rows.push({ + phone, + name: + nameIdx >= 0 + ? values[nameIdx]?.replace(/["']/g, "").trim() || undefined + : undefined, + email: + emailIdx >= 0 + ? values[emailIdx]?.replace(/["']/g, "").trim() || undefined + : undefined, + company: + companyIdx >= 0 + ? values[companyIdx]?.replace(/["']/g, "").trim() || undefined + : undefined, + tagNames: + tagsIdx >= 0 ? parseTagCell(values[tagsIdx]?.replace(/["']/g, "")) : [], + }); + } + + return rows; +} + +/** Simple CSV line parse (handles quoted fields). */ +function parseCsvLine(line: string): string[] { + const values: string[] = []; + let current = ""; + let inQuotes = false; + + for (const char of line) { + if (char === '"') { + inQuotes = !inQuotes; + } else if (char === "," && !inQuotes) { + values.push(current.trim()); + current = ""; + } else { + current += char; + } + } + values.push(current.trim()); + return values; +} diff --git a/src/lib/contacts/resolve-import-tags.ts b/src/lib/contacts/resolve-import-tags.ts new file mode 100644 index 0000000..9a3f75d --- /dev/null +++ b/src/lib/contacts/resolve-import-tags.ts @@ -0,0 +1,127 @@ +import type { SupabaseClient } from "@supabase/supabase-js"; + +const DEFAULT_TAG_COLOR = "#3b82f6"; + +export interface ResolveImportTagsResult { + /** Lowercase tag name → tag id. */ + tagIdByKey: Map; + /** Names that could not be matched and were not created. */ + skippedNames: string[]; +} + +/** + * Resolve tag names from a CSV import to tag ids. Existing account tags + * are matched case-insensitively. Missing names are created when + * `canCreateTags` is true (admin+); otherwise they are reported in + * `skippedNames`. + */ +export async function resolveImportTagIds( + supabase: SupabaseClient, + params: { + accountId: string; + userId: string; + tagNames: string[]; + canCreateTags: boolean; + defaultColor?: string; + }, +): Promise { + const { accountId, userId, tagNames, canCreateTags } = params; + const defaultColor = params.defaultColor ?? DEFAULT_TAG_COLOR; + + const uniqueNames: string[] = []; + const seen = new Set(); + for (const raw of tagNames) { + const name = raw.trim(); + if (!name) continue; + const key = name.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + uniqueNames.push(name); + } + + const { data: existing, error: fetchError } = await supabase + .from("tags") + .select("id, name") + .eq("account_id", accountId); + + if (fetchError) throw fetchError; + + const tagIdByKey = new Map(); + for (const tag of existing ?? []) { + const key = tag.name.trim().toLowerCase(); + if (!tagIdByKey.has(key)) tagIdByKey.set(key, tag.id); + } + + const skippedNames: string[] = []; + const toCreate: string[] = []; + + for (const name of uniqueNames) { + const key = name.toLowerCase(); + if (tagIdByKey.has(key)) continue; + if (canCreateTags) toCreate.push(name); + else skippedNames.push(name); + } + + if (toCreate.length > 0) { + const { data: created, error: createError } = await supabase + .from("tags") + .insert( + toCreate.map((name) => ({ + user_id: userId, + account_id: accountId, + name, + color: defaultColor, + })), + ) + .select("id, name"); + + if (createError) throw createError; + + for (const tag of created ?? []) { + tagIdByKey.set(tag.name.trim().toLowerCase(), tag.id); + } + } + + return { tagIdByKey, skippedNames }; +} + +export interface ContactTagAssignment { + contactId: string; + tagNames: string[]; +} + +/** Insert contact_tags rows for imported contacts (ignores duplicates). */ +export async function assignImportedContactTags( + supabase: SupabaseClient, + assignments: ContactTagAssignment[], + tagIdByKey: Map, +): Promise { + const rows: { contact_id: string; tag_id: string }[] = []; + + for (const { contactId, tagNames } of assignments) { + const assignedTagIds = new Set(); + for (const name of tagNames) { + const tagId = tagIdByKey.get(name.trim().toLowerCase()); + if (!tagId || assignedTagIds.has(tagId)) continue; + assignedTagIds.add(tagId); + rows.push({ contact_id: contactId, tag_id: tagId }); + } + } + + if (rows.length === 0) return 0; + + const chunkSize = 100; + let assigned = 0; + + for (let i = 0; i < rows.length; i += chunkSize) { + const chunk = rows.slice(i, i + chunkSize); + const { error } = await supabase.from("contact_tags").upsert(chunk, { + onConflict: "contact_id,tag_id", + ignoreDuplicates: true, + }); + if (error) throw error; + assigned += chunk.length; + } + + return assigned; +} From 73062cf06d876b1d74b7c5f615d2e48434249444 Mon Sep 17 00:00:00 2001 From: Abhishek Sonwal Date: Mon, 15 Jun 2026 13:12:00 +0530 Subject: [PATCH 2/4] feat(contacts): enhance import modal with tag preview and CSV parsing improvements - Added `ImportPreviewTags` component to display tags with color coding in the import modal. - Updated `parseContactCsv` to return an object containing both parsed rows and a flag indicating the presence of a tags column. - Modified state management in the import modal to handle tags and their colors, improving user experience during contact import. - Adjusted the import modal to conditionally render the tags column based on the presence of tags in the preview. --- src/components/contacts/import-modal.tsx | 75 ++++++++++++++++++++-- src/lib/contacts/parse-contact-csv.test.ts | 56 ++++++++-------- src/lib/contacts/parse-contact-csv.ts | 14 ++-- 3 files changed, 109 insertions(+), 36 deletions(-) diff --git a/src/components/contacts/import-modal.tsx b/src/components/contacts/import-modal.tsx index c2d0d66..876064b 100644 --- a/src/components/contacts/import-modal.tsx +++ b/src/components/contacts/import-modal.tsx @@ -8,7 +8,7 @@ import { isUniqueViolation, normalizeKey, } from '@/lib/contacts/dedupe'; -import { parseContactCsv } from '@/lib/contacts/parse-contact-csv'; +import { parseContactCsv, type ParsedContactRow } from '@/lib/contacts/parse-contact-csv'; import { assignImportedContactTags, resolveImportTagIds, @@ -26,6 +26,41 @@ import { import { Button } from '@/components/ui/button'; import { Upload, FileText, Loader2, CheckCircle, XCircle, AlertTriangle } from 'lucide-react'; +const DEFAULT_TAG_COLOR = '#3b82f6'; + +function ImportPreviewTags({ + tagNames, + tagColorByKey, +}: { + tagNames: string[]; + tagColorByKey: Map; +}) { + if (tagNames.length === 0) { + return -; + } + + return ( +
+ {tagNames.map((name) => { + const color = tagColorByKey.get(name.trim().toLowerCase()) ?? DEFAULT_TAG_COLOR; + return ( + + {name} + + ); + })} +
+ ); +} + interface ImportModalProps { open: boolean; onOpenChange: (open: boolean) => void; @@ -38,7 +73,9 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps const fileInputRef = useRef(null); const [file, setFile] = useState(null); - const [parsedRows, setParsedRows] = useState>([]); + const [parsedRows, setParsedRows] = useState([]); + const [hasTagsColumn, setHasTagsColumn] = useState(false); + const [tagColorByKey, setTagColorByKey] = useState>(new Map()); const [importing, setImporting] = useState(false); const [result, setResult] = useState<{ imported: number; @@ -50,6 +87,8 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps function reset() { setFile(null); setParsedRows([]); + setHasTagsColumn(false); + setTagColorByKey(new Map()); setResult(null); if (fileInputRef.current) fileInputRef.current.value = ''; } @@ -67,15 +106,34 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps setResult(null); const text = await selected.text(); - const rows = parseContactCsv(text); + const { rows, hasTagsColumn: csvHasTags } = parseContactCsv(text); if (rows.length === 0) { toast.error('No valid rows found. Ensure CSV has a "phone" column header.'); setParsedRows([]); + setHasTagsColumn(false); + setTagColorByKey(new Map()); return; } setParsedRows(rows); + setHasTagsColumn(csvHasTags); + + if (csvHasTags && accountId) { + const { data: tags } = await supabase + .from('tags') + .select('name, color') + .eq('account_id', accountId); + + const colors = new Map(); + for (const tag of tags ?? []) { + const key = tag.name.trim().toLowerCase(); + if (!colors.has(key)) colors.set(key, tag.color); + } + setTagColorByKey(colors); + } else { + setTagColorByKey(new Map()); + } } async function handleImport() { @@ -228,7 +286,7 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps } const preview = parsedRows.slice(0, 5); - const hasTagsColumn = parsedRows.some((row) => row.tagNames.length > 0); + const previewHasTags = hasTagsColumn || preview.some((row) => row.tagNames.length > 0); return ( @@ -291,7 +349,7 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps Name Email Company - {hasTagsColumn && ( + {previewHasTags && ( Tags )} @@ -303,9 +361,12 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps {row.name || '-'} {row.email || '-'} {row.company || '-'} - {hasTagsColumn && ( + {previewHasTags && ( - {row.tagNames.length > 0 ? row.tagNames.join(', ') : '-'} + )} diff --git a/src/lib/contacts/parse-contact-csv.test.ts b/src/lib/contacts/parse-contact-csv.test.ts index 06c34e3..5fcf4a1 100644 --- a/src/lib/contacts/parse-contact-csv.test.ts +++ b/src/lib/contacts/parse-contact-csv.test.ts @@ -30,36 +30,42 @@ describe("parseContactCsv", () => { +15551234567,Alice,"VIP, Lead" +15559876543,Bob,Customer`; - expect(parseContactCsv(csv)).toEqual([ - { - phone: "+15551234567", - name: "Alice", - email: undefined, - company: undefined, - tagNames: ["VIP", "Lead"], - }, - { - phone: "+15559876543", - name: "Bob", - email: undefined, - company: undefined, - tagNames: ["Customer"], - }, - ]); + expect(parseContactCsv(csv)).toEqual({ + hasTagsColumn: true, + rows: [ + { + phone: "+15551234567", + name: "Alice", + email: undefined, + company: undefined, + tagNames: ["VIP", "Lead"], + }, + { + phone: "+15559876543", + name: "Bob", + email: undefined, + company: undefined, + tagNames: ["Customer"], + }, + ], + }); }); it("returns empty tagNames when tags column is absent", () => { const csv = `phone,name +15551234567,Alice`; - expect(parseContactCsv(csv)).toEqual([ - { - phone: "+15551234567", - name: "Alice", - email: undefined, - company: undefined, - tagNames: [], - }, - ]); + expect(parseContactCsv(csv)).toEqual({ + hasTagsColumn: false, + rows: [ + { + phone: "+15551234567", + name: "Alice", + email: undefined, + company: undefined, + tagNames: [], + }, + ], + }); }); }); diff --git a/src/lib/contacts/parse-contact-csv.ts b/src/lib/contacts/parse-contact-csv.ts index 95381cb..9a7b9e3 100644 --- a/src/lib/contacts/parse-contact-csv.ts +++ b/src/lib/contacts/parse-contact-csv.ts @@ -31,16 +31,22 @@ export function parseTagCell(value: string | undefined): string[] { return names; } -export function parseContactCsv(text: string): ParsedContactRow[] { +export interface ParseContactCsvResult { + rows: ParsedContactRow[]; + /** True when the CSV header includes a `tags` column. */ + hasTagsColumn: boolean; +} + +export function parseContactCsv(text: string): ParseContactCsvResult { const lines = text.trim().split(/\r?\n/); - if (lines.length < 2) return []; + if (lines.length < 2) return { rows: [], hasTagsColumn: false }; const headers = lines[0] .split(",") .map((h) => h.trim().toLowerCase().replace(/["']/g, "")); const phoneIdx = headers.indexOf("phone"); - if (phoneIdx === -1) return []; + if (phoneIdx === -1) return { rows: [], hasTagsColumn: false }; const nameIdx = headers.indexOf("name"); const emailIdx = headers.indexOf("email"); @@ -76,7 +82,7 @@ export function parseContactCsv(text: string): ParsedContactRow[] { }); } - return rows; + return { rows, hasTagsColumn: tagsIdx >= 0 }; } /** Simple CSV line parse (handles quoted fields). */ From b780fddb3bb4d0e5edbbbdbef973f3ba5b1f9c2e Mon Sep 17 00:00:00 2001 From: Abhishek Sonwal Date: Mon, 15 Jun 2026 13:27:56 +0530 Subject: [PATCH 3/4] feat(contacts): enhance import modal with company column support and improved CSV parsing - Updated `parseContactCsv` to include a flag for the presence of a company column in the CSV. - Modified the import modal state management to handle the new company column, improving user experience during contact import. - Enhanced the `ImportPreviewTags` component to conditionally render based on the presence of company data. - Adjusted the UI to better display tag and company information in the import preview. --- src/components/contacts/import-modal.tsx | 335 +++++++++++++++------ src/lib/contacts/parse-contact-csv.test.ts | 2 + src/lib/contacts/parse-contact-csv.ts | 16 +- 3 files changed, 251 insertions(+), 102 deletions(-) diff --git a/src/components/contacts/import-modal.tsx b/src/components/contacts/import-modal.tsx index 876064b..8450b0f 100644 --- a/src/components/contacts/import-modal.tsx +++ b/src/components/contacts/import-modal.tsx @@ -1,6 +1,6 @@ 'use client'; -import { useState, useRef } from 'react'; +import { useMemo, useRef, useState } from 'react'; import { createClient } from '@/lib/supabase/client'; import { useAuth } from '@/hooks/use-auth'; import { @@ -14,6 +14,7 @@ import { resolveImportTagIds, type ContactTagAssignment, } from '@/lib/contacts/resolve-import-tags'; +import { cn } from '@/lib/utils'; import { toast } from 'sonner'; import { Dialog, @@ -24,9 +25,45 @@ import { DialogFooter, } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; -import { Upload, FileText, Loader2, CheckCircle, XCircle, AlertTriangle } from 'lucide-react'; +import { + Upload, + FileText, + Loader2, + CheckCircle, + XCircle, + AlertTriangle, + Tag, +} from 'lucide-react'; const DEFAULT_TAG_COLOR = '#3b82f6'; +const PREVIEW_LIMIT = 5; + +function truncateFilename(name: string, max = 48): string { + if (name.length <= max) return name; + const ext = name.includes('.') ? name.slice(name.lastIndexOf('.')) : ''; + const base = name.slice(0, name.length - ext.length); + const keep = max - ext.length - 1; + return `${base.slice(0, Math.max(keep, 12))}…${ext}`; +} + +function PreviewCell({ + value, + mono, + maxWidth = 'max-w-[9rem]', +}: { + value: string; + mono?: boolean; + maxWidth?: string; +}) { + return ( + + {value} + + ); +} function ImportPreviewTags({ tagNames, @@ -36,24 +73,30 @@ function ImportPreviewTags({ tagColorByKey: Map; }) { if (tagNames.length === 0) { - return -; + return —; } return ( -
+
{tagNames.map((name) => { const color = tagColorByKey.get(name.trim().toLowerCase()) ?? DEFAULT_TAG_COLOR; + const isKnown = tagColorByKey.has(name.trim().toLowerCase()); return ( - {name} + + {name} ); })} @@ -75,6 +118,7 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps const [file, setFile] = useState(null); const [parsedRows, setParsedRows] = useState([]); const [hasTagsColumn, setHasTagsColumn] = useState(false); + const [hasCompanyColumn, setHasCompanyColumn] = useState(false); const [tagColorByKey, setTagColorByKey] = useState>(new Map()); const [importing, setImporting] = useState(false); const [result, setResult] = useState<{ @@ -88,14 +132,15 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps setFile(null); setParsedRows([]); setHasTagsColumn(false); + setHasCompanyColumn(false); setTagColorByKey(new Map()); setResult(null); if (fileInputRef.current) fileInputRef.current.value = ''; } - function handleOpenChange(open: boolean) { - if (!open) reset(); - onOpenChange(open); + function handleOpenChange(next: boolean) { + if (!next) reset(); + onOpenChange(next); } async function handleFileChange(e: React.ChangeEvent) { @@ -106,18 +151,21 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps setResult(null); const text = await selected.text(); - const { rows, hasTagsColumn: csvHasTags } = parseContactCsv(text); + const { rows, hasTagsColumn: csvHasTags, hasCompanyColumn: csvHasCompany } = + parseContactCsv(text); if (rows.length === 0) { toast.error('No valid rows found. Ensure CSV has a "phone" column header.'); setParsedRows([]); setHasTagsColumn(false); + setHasCompanyColumn(false); setTagColorByKey(new Map()); return; } setParsedRows(rows); setHasTagsColumn(csvHasTags); + setHasCompanyColumn(csvHasCompany); if (csvHasTags && accountId) { const { data: tags } = await supabase @@ -152,12 +200,9 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps let skipped = 0; let failed = 0; - // 1) De-dupe within the file by normalized phone (keep first). const { unique, duplicates: inFileDupes } = dedupeByPhone(parsedRows); skipped += inFileDupes; - // 2) Skip numbers already in this account. One read of the - // generated `phone_normalized` column (migration 022) → Set. const { data: existingRows } = await supabase .from('contacts') .select('phone_normalized') @@ -176,7 +221,6 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps return true; }); - // 3) Resolve tag names → ids (create missing tags for admin+). const allTagNames = toInsert.flatMap((row) => row.tagNames); const { tagIdByKey, skippedNames } = await resolveImportTagIds(supabase, { accountId, @@ -186,10 +230,8 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps }); const tagAssignments: ContactTagAssignment[] = []; - - // 4) Batch insert contacts in chunks of 50. The DB unique index is - // the backstop: a 23505 counts as skipped, not failed. const chunkSize = 50; + for (let i = 0; i < toInsert.length; i += chunkSize) { const chunk = toInsert.slice(i, i + chunkSize); const rows = chunk.map((row) => ({ @@ -207,8 +249,6 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps .select('id'); if (error) { - // Retry individually so one bad/duplicate row doesn't sink - // the whole chunk. for (let j = 0; j < rows.length; j++) { const row = rows[j]; const source = chunk[j]; @@ -246,7 +286,6 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps } } - // 5) Wire tags onto the contacts we just created. const tagsAssigned = await assignImportedContactTags( supabase, tagAssignments, @@ -285,44 +324,90 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps } } - const preview = parsedRows.slice(0, 5); - const previewHasTags = hasTagsColumn || preview.some((row) => row.tagNames.length > 0); + const preview = parsedRows.slice(0, PREVIEW_LIMIT); + const previewHasTags = + hasTagsColumn || preview.some((row) => row.tagNames.length > 0); + const previewHasCompany = + hasCompanyColumn && preview.some((row) => row.company?.trim()); + + const tagStats = useMemo(() => { + const names = new Set(); + let rowsWithTags = 0; + for (const row of parsedRows) { + if (row.tagNames.length === 0) continue; + rowsWithTags++; + for (const name of row.tagNames) names.add(name.trim().toLowerCase()); + } + return { unique: names.size, rowsWithTags }; + }, [parsedRows]); return ( - - - Import Contacts - - Upload a CSV file with a "phone" column (required). Optional columns: - name, email, company, tags (comma-separated tag names — quote the - cell if a tag list contains commas, e.g. "VIP, Lead"). - - + +
+ + Import Contacts + + Upload a CSV with a required{' '} + + phone + {' '} + column. Optional:{' '} + + name + + ,{' '} + + email + + ,{' '} + + company + + ,{' '} + + tags + {' '} + (comma-separated; quote multi-tag cells). + + -
- {/* Upload area */}
fileInputRef.current?.click()} - className="flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed border-slate-700 p-6 cursor-pointer hover:border-primary/50 transition-colors" + onKeyDown={(e) => { + if (e.key === 'Enter' || e.key === ' ') fileInputRef.current?.click(); + }} + className={cn( + 'group flex cursor-pointer flex-col items-center justify-center gap-2 rounded-xl border border-dashed p-5 transition-all', + file + ? 'border-primary/35 bg-primary/[0.04]' + : 'border-slate-700/80 bg-slate-950/40 hover:border-primary/40 hover:bg-slate-950/70', + )} > {file ? ( <> - -

{file.name}

-

- {parsedRows.length} row{parsedRows.length !== 1 ? 's' : ''} detected +

+ +
+

+ {truncateFilename(file.name)}

+ + {parsedRows.length} row{parsedRows.length !== 1 ? 's' : ''} ready + ) : ( <> - -

- Click to upload CSV file -

-

- CSV with "phone" column required -

+
+ +
+

Click to choose a CSV file

+

.csv up to your browser limit

)}
@@ -334,80 +419,131 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps onChange={handleFileChange} className="hidden" /> +
- {/* Preview table */} +
{preview.length > 0 && !result && ( -
-

- Preview (first {preview.length} rows) -

-
- - - - - - - - {previewHasTags && ( - - )} - - - - {preview.map((row, i) => ( - - - - - +
+
+

+ Preview · first {preview.length} +

+
+ {tagStats.rowsWithTags > 0 && ( + + + {tagStats.unique} tag{tagStats.unique !== 1 ? 's' : ''} ·{' '} + {tagStats.rowsWithTags} contact + {tagStats.rowsWithTags !== 1 ? 's' : ''} + + )} +
+
+ +
+
+
PhoneNameEmailCompanyTags
{row.phone}{row.name || '-'}{row.email || '-'}{row.company || '-'}
+ + + + + + {previewHasCompany && ( + + )} {previewHasTags && ( - + )} - ))} - -
+ Phone + + Name + + Email + + Company + - - + Tags +
+ + + {preview.map((row, i) => ( + + + + + + + + + + + {previewHasCompany && ( + + + + )} + {previewHasTags && ( + + + + )} + + ))} + + +
- {parsedRows.length > 5 && ( -

- ...and {parsedRows.length - 5} more rows + + {parsedRows.length > PREVIEW_LIMIT && ( +

+ + {parsedRows.length - PREVIEW_LIMIT} more row + {parsedRows.length - PREVIEW_LIMIT !== 1 ? 's' : ''} not shown

)}
)} - {/* Results */} {result && ( -
-

Import Complete

-
+
+

Import complete

+
{result.imported > 0 && ( -
- +
+ {result.imported} imported
)} {result.tagsAssigned > 0 && ( -
- +
+ {result.tagsAssigned} tag{result.tagsAssigned !== 1 ? 's' : ''} assigned
)} {result.skipped > 0 && ( -
- - {result.skipped} duplicate{result.skipped !== 1 ? 's' : ''} skipped +
+ + {result.skipped} skipped
)} {result.failed > 0 && ( -
- +
+ {result.failed} failed
)} @@ -416,7 +552,7 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps )}
- + )} diff --git a/src/lib/contacts/parse-contact-csv.test.ts b/src/lib/contacts/parse-contact-csv.test.ts index 5fcf4a1..ac9a92e 100644 --- a/src/lib/contacts/parse-contact-csv.test.ts +++ b/src/lib/contacts/parse-contact-csv.test.ts @@ -32,6 +32,7 @@ describe("parseContactCsv", () => { expect(parseContactCsv(csv)).toEqual({ hasTagsColumn: true, + hasCompanyColumn: false, rows: [ { phone: "+15551234567", @@ -57,6 +58,7 @@ describe("parseContactCsv", () => { expect(parseContactCsv(csv)).toEqual({ hasTagsColumn: false, + hasCompanyColumn: false, rows: [ { phone: "+15551234567", diff --git a/src/lib/contacts/parse-contact-csv.ts b/src/lib/contacts/parse-contact-csv.ts index 9a7b9e3..199b42c 100644 --- a/src/lib/contacts/parse-contact-csv.ts +++ b/src/lib/contacts/parse-contact-csv.ts @@ -35,18 +35,24 @@ export interface ParseContactCsvResult { rows: ParsedContactRow[]; /** True when the CSV header includes a `tags` column. */ hasTagsColumn: boolean; + /** True when the CSV header includes a `company` column. */ + hasCompanyColumn: boolean; } export function parseContactCsv(text: string): ParseContactCsvResult { const lines = text.trim().split(/\r?\n/); - if (lines.length < 2) return { rows: [], hasTagsColumn: false }; + if (lines.length < 2) { + return { rows: [], hasTagsColumn: false, hasCompanyColumn: false }; + } const headers = lines[0] .split(",") .map((h) => h.trim().toLowerCase().replace(/["']/g, "")); const phoneIdx = headers.indexOf("phone"); - if (phoneIdx === -1) return { rows: [], hasTagsColumn: false }; + if (phoneIdx === -1) { + return { rows: [], hasTagsColumn: false, hasCompanyColumn: false }; + } const nameIdx = headers.indexOf("name"); const emailIdx = headers.indexOf("email"); @@ -82,7 +88,11 @@ export function parseContactCsv(text: string): ParseContactCsvResult { }); } - return { rows, hasTagsColumn: tagsIdx >= 0 }; + return { + rows, + hasTagsColumn: tagsIdx >= 0, + hasCompanyColumn: companyIdx >= 0, + }; } /** Simple CSV line parse (handles quoted fields). */ From f39ca606294b04170853abb70ab2ce7fc46de559 Mon Sep 17 00:00:00 2001 From: Abhishek Sonwal Date: Tue, 16 Jun 2026 12:59:03 +0530 Subject: [PATCH 4/4] refactor(contacts): improve code readability and formatting in import modal and CSV parsing - Reformatted code in `import-modal.tsx` for better readability, including consistent indentation and line breaks. - Enhanced `parse-contact-csv.ts` and `parse-contact-csv.test.ts` with consistent string delimiters and improved whitespace handling. - Updated comments for clarity and consistency across the import functionality. - Ensured consistent use of single quotes for strings throughout the files. --- src/components/contacts/import-modal.tsx | 164 +++++++++++++++------ src/lib/contacts/parse-contact-csv.test.ts | 50 +++---- src/lib/contacts/parse-contact-csv.ts | 30 ++-- src/lib/contacts/resolve-import-tags.ts | 39 +++-- 4 files changed, 182 insertions(+), 101 deletions(-) diff --git a/src/components/contacts/import-modal.tsx b/src/components/contacts/import-modal.tsx index 8450b0f..0a05ef7 100644 --- a/src/components/contacts/import-modal.tsx +++ b/src/components/contacts/import-modal.tsx @@ -8,7 +8,10 @@ import { isUniqueViolation, normalizeKey, } from '@/lib/contacts/dedupe'; -import { parseContactCsv, type ParsedContactRow } from '@/lib/contacts/parse-contact-csv'; +import { + parseContactCsv, + type ParsedContactRow, +} from '@/lib/contacts/parse-contact-csv'; import { assignImportedContactTags, resolveImportTagIds, @@ -57,7 +60,11 @@ function PreviewCell({ }) { return ( {value} @@ -77,14 +84,15 @@ function ImportPreviewTags({ } return ( -
+
{tagNames.map((name) => { - const color = tagColorByKey.get(name.trim().toLowerCase()) ?? DEFAULT_TAG_COLOR; + const color = + tagColorByKey.get(name.trim().toLowerCase()) ?? DEFAULT_TAG_COLOR; const isKnown = tagColorByKey.has(name.trim().toLowerCase()); return ( void; } -export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps) { +export function ImportModal({ + open, + onOpenChange, + onImported, +}: ImportModalProps) { const supabase = createClient(); const { accountId, canEditSettings } = useAuth(); const fileInputRef = useRef(null); @@ -119,7 +131,9 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps const [parsedRows, setParsedRows] = useState([]); const [hasTagsColumn, setHasTagsColumn] = useState(false); const [hasCompanyColumn, setHasCompanyColumn] = useState(false); - const [tagColorByKey, setTagColorByKey] = useState>(new Map()); + const [tagColorByKey, setTagColorByKey] = useState>( + new Map() + ); const [importing, setImporting] = useState(false); const [result, setResult] = useState<{ imported: number; @@ -151,11 +165,16 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps setResult(null); const text = await selected.text(); - const { rows, hasTagsColumn: csvHasTags, hasCompanyColumn: csvHasCompany } = - parseContactCsv(text); + const { + rows, + hasTagsColumn: csvHasTags, + hasCompanyColumn: csvHasCompany, + } = parseContactCsv(text); if (rows.length === 0) { - toast.error('No valid rows found. Ensure CSV has a "phone" column header.'); + toast.error( + 'No valid rows found. Ensure CSV has a "phone" column header.' + ); setParsedRows([]); setHasTagsColumn(false); setHasCompanyColumn(false); @@ -194,23 +213,29 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps } = await supabase.auth.getSession(); const user = session?.user; if (!user) throw new Error('Not authenticated'); - if (!accountId) throw new Error('Your profile is not linked to an account.'); + if (!accountId) + throw new Error('Your profile is not linked to an account.'); let imported = 0; let skipped = 0; let failed = 0; + // 1) De-dupe within the file by normalized phone (keep first). const { unique, duplicates: inFileDupes } = dedupeByPhone(parsedRows); skipped += inFileDupes; + // 2) Skip numbers already in this account. One read of the + // generated `phone_normalized` column (migration 022) → Set. const { data: existingRows } = await supabase .from('contacts') .select('phone_normalized') .eq('account_id', accountId); const existing = new Set( (existingRows ?? []) - .map((r) => (r as { phone_normalized: string | null }).phone_normalized) - .filter((p): p is string => !!p), + .map( + (r) => (r as { phone_normalized: string | null }).phone_normalized + ) + .filter((p): p is string => !!p) ); const toInsert = unique.filter((row) => { @@ -221,15 +246,25 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps return true; }); + // 3) Resolve tag names → ids (admin+ may auto-create missing tags). + // Skip the round-trip when the import carries no tag names. const allTagNames = toInsert.flatMap((row) => row.tagNames); - const { tagIdByKey, skippedNames } = await resolveImportTagIds(supabase, { - accountId, - userId: user.id, - tagNames: allTagNames, - canCreateTags: canEditSettings, - }); + let tagIdByKey = new Map(); + let skippedNames: string[] = []; + if (allTagNames.length > 0) { + ({ tagIdByKey, skippedNames } = await resolveImportTagIds(supabase, { + accountId, + userId: user.id, + tagNames: allTagNames, + canCreateTags: canEditSettings, + })); + } const tagAssignments: ContactTagAssignment[] = []; + + // 4) Batch insert the genuinely-new rows in chunks of 50. The DB + // unique index is the backstop: a 23505 (race, or a format + // that normalizes equal) counts as skipped, not failed. const chunkSize = 50; for (let i = 0; i < toInsert.length; i += chunkSize) { @@ -249,6 +284,8 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps .select('id'); if (error) { + // Retry individually so one bad/duplicate row doesn't sink + // the whole chunk. for (let j = 0; j < rows.length; j++) { const row = rows[j]; const source = chunk[j]; @@ -275,6 +312,9 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps } else { const inserted = data ?? []; imported += inserted.length; + // inserted[j] ↔ chunk[j] only holds because a single INSERT + // preserves RETURNING order. If this path is ever split into + // parallel inserts, zip by phone or returned id instead. for (let j = 0; j < inserted.length; j++) { const source = chunk[j]; if (!source || source.tagNames.length === 0) continue; @@ -286,20 +326,29 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps } } - const tagsAssigned = await assignImportedContactTags( - supabase, - tagAssignments, - tagIdByKey, - ); + // 5) Wire tags onto the contacts we just created. Failure here must + // not mask a successful contact import. + let tagsAssigned = 0; + try { + tagsAssigned = await assignImportedContactTags( + supabase, + tagAssignments, + tagIdByKey + ); + } catch { + toast.warning('Contacts imported, but some tag assignments failed.'); + } setResult({ imported, skipped, failed, tagsAssigned }); if (imported > 0) { - toast.success(`${imported} contact${imported !== 1 ? 's' : ''} imported`); + toast.success( + `${imported} contact${imported !== 1 ? 's' : ''} imported` + ); onImported(); } if (tagsAssigned > 0) { toast.success( - `${tagsAssigned} tag assignment${tagsAssigned !== 1 ? 's' : ''} applied`, + `${tagsAssigned} tag assignment${tagsAssigned !== 1 ? 's' : ''} applied` ); } if (skippedNames.length > 0) { @@ -307,14 +356,16 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps const more = skippedNames.length > 3 ? ` (+${skippedNames.length - 3} more)` : ''; toast.info( - `Unknown tags skipped (create them in Settings first): ${sample}${more}`, + `Unknown tags skipped (create them in Settings first): ${sample}${more}` ); } if (skipped > 0) { toast.info(`${skipped} duplicate${skipped !== 1 ? 's' : ''} skipped`); } if (failed > 0) { - toast.error(`${failed} contact${failed !== 1 ? 's' : ''} failed to import`); + toast.error( + `${failed} contact${failed !== 1 ? 's' : ''} failed to import` + ); } } catch (err: unknown) { const message = err instanceof Error ? err.message : 'Import failed'; @@ -325,8 +376,12 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps } const preview = parsedRows.slice(0, PREVIEW_LIMIT); + // Tags: OR — show when the CSV declares a column or preview rows carry + // values, so an all-empty tags column still renders for validation. const previewHasTags = hasTagsColumn || preview.some((row) => row.tagNames.length > 0); + // Company: AND — hide unless the CSV declares it and preview has data, + // avoiding an all-dash column that wastes horizontal space. const previewHasCompany = hasCompanyColumn && preview.some((row) => row.company?.trim()); @@ -346,8 +401,10 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps
- Import Contacts - + + Import Contacts + + Upload a CSV with a required{' '} phone @@ -377,19 +434,20 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps tabIndex={0} onClick={() => fileInputRef.current?.click()} onKeyDown={(e) => { - if (e.key === 'Enter' || e.key === ' ') fileInputRef.current?.click(); + if (e.key === 'Enter' || e.key === ' ') + fileInputRef.current?.click(); }} className={cn( 'group flex cursor-pointer flex-col items-center justify-center gap-2 rounded-xl border border-dashed p-5 transition-all', file ? 'border-primary/35 bg-primary/[0.04]' - : 'border-slate-700/80 bg-slate-950/40 hover:border-primary/40 hover:bg-slate-950/70', + : 'hover:border-primary/40 border-slate-700/80 bg-slate-950/40 hover:bg-slate-950/70' )} > {file ? ( <> -
- +
+

- {parsedRows.length} row{parsedRows.length !== 1 ? 's' : ''} ready + {parsedRows.length} row{parsedRows.length !== 1 ? 's' : ''}{' '} + ready ) : ( @@ -406,8 +465,12 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps

-

Click to choose a CSV file

-

.csv up to your browser limit

+

+ Click to choose a CSV file +

+

+ .csv up to your browser limit +

)}
@@ -425,13 +488,13 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps {preview.length > 0 && !result && (
-

+

Preview · first {preview.length}

{tagStats.rowsWithTags > 0 && ( - + {tagStats.unique} tag{tagStats.unique !== 1 ? 's' : ''} ·{' '} {tagStats.rowsWithTags} contact {tagStats.rowsWithTags !== 1 ? 's' : ''} @@ -445,22 +508,22 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps - - - {previewHasCompany && ( - )} {previewHasTags && ( - )} @@ -472,8 +535,12 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps key={i} className="bg-slate-900/40 transition-colors hover:bg-slate-800/30" > -
+ Phone + Name + Email + Company + Tags - + + Import complete

{result.imported > 0 && ( -
+
{result.imported} imported
@@ -532,7 +599,8 @@ export function ImportModal({ open, onOpenChange, onImported }: ImportModalProps {result.tagsAssigned > 0 && (
- {result.tagsAssigned} tag{result.tagsAssigned !== 1 ? 's' : ''} assigned + {result.tagsAssigned} tag + {result.tagsAssigned !== 1 ? 's' : ''} assigned
)} {result.skipped > 0 && ( diff --git a/src/lib/contacts/parse-contact-csv.test.ts b/src/lib/contacts/parse-contact-csv.test.ts index ac9a92e..d25670f 100644 --- a/src/lib/contacts/parse-contact-csv.test.ts +++ b/src/lib/contacts/parse-contact-csv.test.ts @@ -1,31 +1,31 @@ -import { describe, expect, it } from "vitest"; -import { parseContactCsv, parseTagCell } from "./parse-contact-csv"; +import { describe, expect, it } from 'vitest'; +import { parseContactCsv, parseTagCell } from './parse-contact-csv'; -describe("parseTagCell", () => { - it("splits comma-separated tags and trims whitespace", () => { - expect(parseTagCell(" VIP , Lead , ")).toEqual(["VIP", "Lead"]); +describe('parseTagCell', () => { + it('splits comma-separated tags and trims whitespace', () => { + expect(parseTagCell(' VIP , Lead , ')).toEqual(['VIP', 'Lead']); }); - it("splits semicolon-separated tags", () => { - expect(parseTagCell("VIP; Lead; Customer")).toEqual([ - "VIP", - "Lead", - "Customer", + it('splits semicolon-separated tags', () => { + expect(parseTagCell('VIP; Lead; Customer')).toEqual([ + 'VIP', + 'Lead', + 'Customer', ]); }); - it("de-dupes case-insensitively", () => { - expect(parseTagCell("vip, VIP, Lead")).toEqual(["vip", "Lead"]); + it('de-dupes case-insensitively', () => { + expect(parseTagCell('vip, VIP, Lead')).toEqual(['vip', 'Lead']); }); - it("returns empty for blank values", () => { - expect(parseTagCell("")).toEqual([]); + it('returns empty for blank values', () => { + expect(parseTagCell('')).toEqual([]); expect(parseTagCell(undefined)).toEqual([]); }); }); -describe("parseContactCsv", () => { - it("parses optional tags column", () => { +describe('parseContactCsv', () => { + it('parses optional tags column', () => { const csv = `phone,name,tags +15551234567,Alice,"VIP, Lead" +15559876543,Bob,Customer`; @@ -35,24 +35,24 @@ describe("parseContactCsv", () => { hasCompanyColumn: false, rows: [ { - phone: "+15551234567", - name: "Alice", + phone: '+15551234567', + name: 'Alice', email: undefined, company: undefined, - tagNames: ["VIP", "Lead"], + tagNames: ['VIP', 'Lead'], }, { - phone: "+15559876543", - name: "Bob", + phone: '+15559876543', + name: 'Bob', email: undefined, company: undefined, - tagNames: ["Customer"], + tagNames: ['Customer'], }, ], }); }); - it("returns empty tagNames when tags column is absent", () => { + it('returns empty tagNames when tags column is absent', () => { const csv = `phone,name +15551234567,Alice`; @@ -61,8 +61,8 @@ describe("parseContactCsv", () => { hasCompanyColumn: false, rows: [ { - phone: "+15551234567", - name: "Alice", + phone: '+15551234567', + name: 'Alice', email: undefined, company: undefined, tagNames: [], diff --git a/src/lib/contacts/parse-contact-csv.ts b/src/lib/contacts/parse-contact-csv.ts index 199b42c..fbeeaff 100644 --- a/src/lib/contacts/parse-contact-csv.ts +++ b/src/lib/contacts/parse-contact-csv.ts @@ -46,18 +46,18 @@ export function parseContactCsv(text: string): ParseContactCsvResult { } const headers = lines[0] - .split(",") - .map((h) => h.trim().toLowerCase().replace(/["']/g, "")); + .split(',') + .map((h) => h.trim().toLowerCase().replace(/["']/g, '')); - const phoneIdx = headers.indexOf("phone"); + const phoneIdx = headers.indexOf('phone'); if (phoneIdx === -1) { return { rows: [], hasTagsColumn: false, hasCompanyColumn: false }; } - const nameIdx = headers.indexOf("name"); - const emailIdx = headers.indexOf("email"); - const companyIdx = headers.indexOf("company"); - const tagsIdx = headers.indexOf("tags"); + const nameIdx = headers.indexOf('name'); + const emailIdx = headers.indexOf('email'); + const companyIdx = headers.indexOf('company'); + const tagsIdx = headers.indexOf('tags'); const rows: ParsedContactRow[] = []; @@ -66,25 +66,25 @@ export function parseContactCsv(text: string): ParseContactCsvResult { if (!line) continue; const values = parseCsvLine(line); - const phone = values[phoneIdx]?.replace(/["']/g, "").trim(); + const phone = values[phoneIdx]?.replace(/["']/g, '').trim(); if (!phone) continue; rows.push({ phone, name: nameIdx >= 0 - ? values[nameIdx]?.replace(/["']/g, "").trim() || undefined + ? values[nameIdx]?.replace(/["']/g, '').trim() || undefined : undefined, email: emailIdx >= 0 - ? values[emailIdx]?.replace(/["']/g, "").trim() || undefined + ? values[emailIdx]?.replace(/["']/g, '').trim() || undefined : undefined, company: companyIdx >= 0 - ? values[companyIdx]?.replace(/["']/g, "").trim() || undefined + ? values[companyIdx]?.replace(/["']/g, '').trim() || undefined : undefined, tagNames: - tagsIdx >= 0 ? parseTagCell(values[tagsIdx]?.replace(/["']/g, "")) : [], + tagsIdx >= 0 ? parseTagCell(values[tagsIdx]?.replace(/["']/g, '')) : [], }); } @@ -98,15 +98,15 @@ export function parseContactCsv(text: string): ParseContactCsvResult { /** Simple CSV line parse (handles quoted fields). */ function parseCsvLine(line: string): string[] { const values: string[] = []; - let current = ""; + let current = ''; let inQuotes = false; for (const char of line) { if (char === '"') { inQuotes = !inQuotes; - } else if (char === "," && !inQuotes) { + } else if (char === ',' && !inQuotes) { values.push(current.trim()); - current = ""; + current = ''; } else { current += char; } diff --git a/src/lib/contacts/resolve-import-tags.ts b/src/lib/contacts/resolve-import-tags.ts index 9a3f75d..618cc60 100644 --- a/src/lib/contacts/resolve-import-tags.ts +++ b/src/lib/contacts/resolve-import-tags.ts @@ -1,6 +1,6 @@ -import type { SupabaseClient } from "@supabase/supabase-js"; +import type { SupabaseClient } from '@supabase/supabase-js'; -const DEFAULT_TAG_COLOR = "#3b82f6"; +const DEFAULT_TAG_COLOR = '#3b82f6'; export interface ResolveImportTagsResult { /** Lowercase tag name → tag id. */ @@ -14,6 +14,9 @@ export interface ResolveImportTagsResult { * are matched case-insensitively. Missing names are created when * `canCreateTags` is true (admin+); otherwise they are reported in * `skippedNames`. + * + * Unlike the manual contact form (existing tags only), import may + * auto-create missing tag definitions for admin+ callers. */ export async function resolveImportTagIds( supabase: SupabaseClient, @@ -23,7 +26,7 @@ export async function resolveImportTagIds( tagNames: string[]; canCreateTags: boolean; defaultColor?: string; - }, + } ): Promise { const { accountId, userId, tagNames, canCreateTags } = params; const defaultColor = params.defaultColor ?? DEFAULT_TAG_COLOR; @@ -39,10 +42,14 @@ export async function resolveImportTagIds( uniqueNames.push(name); } + if (uniqueNames.length === 0) { + return { tagIdByKey: new Map(), skippedNames: [] }; + } + const { data: existing, error: fetchError } = await supabase - .from("tags") - .select("id, name") - .eq("account_id", accountId); + .from('tags') + .select('id, name') + .eq('account_id', accountId); if (fetchError) throw fetchError; @@ -64,16 +71,16 @@ export async function resolveImportTagIds( if (toCreate.length > 0) { const { data: created, error: createError } = await supabase - .from("tags") + .from('tags') .insert( toCreate.map((name) => ({ user_id: userId, account_id: accountId, name, color: defaultColor, - })), + })) ) - .select("id, name"); + .select('id, name'); if (createError) throw createError; @@ -90,11 +97,17 @@ export interface ContactTagAssignment { tagNames: string[]; } -/** Insert contact_tags rows for imported contacts (ignores duplicates). */ +/** + * Insert contact_tags rows for imported contacts (ignores duplicates). + * + * Returns the number of contact–tag pairs *requested* for upsert, not + * rows actually inserted — `ignoreDuplicates` can drop pairs that already + * exist without changing the returned count. + */ export async function assignImportedContactTags( supabase: SupabaseClient, assignments: ContactTagAssignment[], - tagIdByKey: Map, + tagIdByKey: Map ): Promise { const rows: { contact_id: string; tag_id: string }[] = []; @@ -115,8 +128,8 @@ export async function assignImportedContactTags( for (let i = 0; i < rows.length; i += chunkSize) { const chunk = rows.slice(i, i + chunkSize); - const { error } = await supabase.from("contact_tags").upsert(chunk, { - onConflict: "contact_id,tag_id", + const { error } = await supabase.from('contact_tags').upsert(chunk, { + onConflict: 'contact_id,tag_id', ignoreDuplicates: true, }); if (error) throw error;