feat: P2.3 Folder Sharing + P2.5 Email Import + P2.6 Contact Import + P2.7 Free/Busy
- P2.3: Folder sharing system — ShareFolderDialog, sharing-store, sharing-settings - P2.5: Email import (.eml, .tgz, .zip) with dedup and progress - P2.6: Contact import (vCard + CSV) with auto-mapping - P2.7: Free/Busy view grid with color-coded slots
This commit is contained in:
@@ -2,26 +2,39 @@
|
||||
|
||||
import { useState, useRef, useCallback } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Upload, FileText, AlertTriangle, X, Check } from "lucide-react";
|
||||
import { Upload, FileText, AlertTriangle, X, Check, ChevronDown } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { parseVCard, detectDuplicates } from "@/lib/vcard";
|
||||
import type { ContactCard } from "@/lib/jmap/types";
|
||||
import type { ContactCard, AddressBook } from "@/lib/jmap/types";
|
||||
import { getContactDisplayName, getContactPrimaryEmail } from "@/stores/contact-store";
|
||||
import {
|
||||
parseCSV,
|
||||
autoMapColumns,
|
||||
mapRowToContact,
|
||||
detectDuplicatesByEmail,
|
||||
type CsvColumnMapping,
|
||||
type CsvParseResult,
|
||||
} from "@/lib/contact-csv-import";
|
||||
|
||||
type FileType = "vcf" | "csv" | null;
|
||||
|
||||
interface ContactImportDialogProps {
|
||||
existingContacts: ContactCard[];
|
||||
addressBooks?: AddressBook[];
|
||||
onImport: (contacts: ContactCard[]) => Promise<number>;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function ContactImportDialog({
|
||||
existingContacts,
|
||||
addressBooks,
|
||||
onImport,
|
||||
onClose,
|
||||
}: ContactImportDialogProps) {
|
||||
const t = useTranslations("contacts");
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const [fileType, setFileType] = useState<FileType>(null);
|
||||
const [parsed, setParsed] = useState<ContactCard[]>([]);
|
||||
const [selected, setSelected] = useState<Set<number>>(new Set());
|
||||
const [duplicates, setDuplicates] = useState<Map<number, string>>(new Map());
|
||||
@@ -29,41 +42,111 @@ export function ContactImportDialog({
|
||||
const [result, setResult] = useState<number | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [csvData, setCsvData] = useState<CsvParseResult | null>(null);
|
||||
const [mapping, setMapping] = useState<CsvColumnMapping | null>(null);
|
||||
const [targetBookId, setTargetBookId] = useState("");
|
||||
const [showPreview, setShowPreview] = useState(false);
|
||||
|
||||
const ALLOWED_ACCEPT = ".vcf,.vcard,.csv,text/csv,text/vcard";
|
||||
|
||||
const books = addressBooks || [];
|
||||
const defaultBookId =
|
||||
books.find((b) => b.isDefault)?.id || books[0]?.id || "";
|
||||
const effectiveBookId = targetBookId || defaultBookId;
|
||||
const bookOptions = books.map((b) => ({
|
||||
value: b.id,
|
||||
label: b.name,
|
||||
}));
|
||||
|
||||
const handleFileChange = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setError(null);
|
||||
setResult(null);
|
||||
setFileType(null);
|
||||
setParsed([]);
|
||||
setSelected(new Set());
|
||||
setDuplicates(new Map());
|
||||
setCsvData(null);
|
||||
setMapping(null);
|
||||
setShowPreview(false);
|
||||
setTargetBookId("");
|
||||
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
setError(t("import.file_too_large"));
|
||||
return;
|
||||
}
|
||||
|
||||
const name = file.name.toLowerCase();
|
||||
|
||||
try {
|
||||
const text = await file.text();
|
||||
const contacts = parseVCard(text);
|
||||
if (name.endsWith(".csv") || file.type === "text/csv") {
|
||||
setFileType("csv");
|
||||
const text = await file.text();
|
||||
const result = parseCSV(text);
|
||||
|
||||
if (contacts.length === 0) {
|
||||
setError(t("import.no_contacts"));
|
||||
return;
|
||||
if (result.rows.length === 0) {
|
||||
setError(t("import.no_contacts"));
|
||||
return;
|
||||
}
|
||||
|
||||
setCsvData(result);
|
||||
setMapping(autoMapColumns(result.headers));
|
||||
setTargetBookId(defaultBookId);
|
||||
} else {
|
||||
setFileType("vcf");
|
||||
const text = await file.text();
|
||||
const contacts = parseVCard(text);
|
||||
|
||||
if (contacts.length === 0) {
|
||||
setError(t("import.no_contacts"));
|
||||
return;
|
||||
}
|
||||
|
||||
const dupes = detectDuplicates(existingContacts, contacts);
|
||||
setParsed(contacts);
|
||||
setDuplicates(dupes);
|
||||
|
||||
const initialSelected = new Set<number>();
|
||||
contacts.forEach((_, idx) => {
|
||||
if (!dupes.has(idx)) initialSelected.add(idx);
|
||||
});
|
||||
setSelected(initialSelected);
|
||||
}
|
||||
|
||||
const dupes = detectDuplicates(existingContacts, contacts);
|
||||
setParsed(contacts);
|
||||
setDuplicates(dupes);
|
||||
|
||||
const initialSelected = new Set<number>();
|
||||
contacts.forEach((_, idx) => {
|
||||
if (!dupes.has(idx)) initialSelected.add(idx);
|
||||
});
|
||||
setSelected(initialSelected);
|
||||
} catch (error) {
|
||||
console.error('Failed to parse vCard:', error);
|
||||
} catch (err) {
|
||||
console.error("Failed to parse file:", err);
|
||||
setError(t("import.parse_error"));
|
||||
}
|
||||
}, [existingContacts, t]);
|
||||
}, [existingContacts, t, defaultBookId]);
|
||||
|
||||
const applyCsvMapping = useCallback(() => {
|
||||
if (!csvData || !mapping) return;
|
||||
|
||||
const bookIds = effectiveBookId ? { [effectiveBookId]: true } : {};
|
||||
const contacts: ContactCard[] = [];
|
||||
|
||||
for (const row of csvData.rows) {
|
||||
const contact = mapRowToContact(row, mapping, bookIds);
|
||||
if (contact) contacts.push(contact);
|
||||
}
|
||||
|
||||
if (contacts.length === 0) {
|
||||
setError(t("import.no_contacts"));
|
||||
return;
|
||||
}
|
||||
|
||||
const dupes = detectDuplicatesByEmail(existingContacts, contacts);
|
||||
setParsed(contacts);
|
||||
setDuplicates(dupes);
|
||||
|
||||
const initialSelected = new Set<number>();
|
||||
contacts.forEach((_, idx) => {
|
||||
if (!dupes.has(idx)) initialSelected.add(idx);
|
||||
});
|
||||
setSelected(initialSelected);
|
||||
setShowPreview(true);
|
||||
}, [csvData, mapping, effectiveBookId, existingContacts, t]);
|
||||
|
||||
const toggleSelect = (idx: number) => {
|
||||
const next = new Set(selected);
|
||||
@@ -91,14 +174,160 @@ export function ContactImportDialog({
|
||||
try {
|
||||
const count = await onImport(toImport);
|
||||
setResult(count);
|
||||
} catch (error) {
|
||||
console.error('Failed to import contacts:', error);
|
||||
} catch (err) {
|
||||
console.error("Failed to import contacts:", err);
|
||||
setError(t("import.failed"));
|
||||
} finally {
|
||||
setIsImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const renderCsvMapping = () => {
|
||||
if (!csvData || !mapping) return null;
|
||||
|
||||
const fields: Array<{ key: keyof CsvColumnMapping; label: string }> = [
|
||||
{ key: "firstName", label: t("import.csv_first_name") },
|
||||
{ key: "lastName", label: t("import.csv_last_name") },
|
||||
{ key: "email", label: t("import.csv_email") },
|
||||
{ key: "phone", label: t("import.csv_phone") },
|
||||
{ key: "company", label: t("import.csv_company") },
|
||||
{ key: "jobTitle", label: t("import.csv_job_title") },
|
||||
{ key: "address", label: t("import.csv_address") },
|
||||
{ key: "city", label: t("import.csv_city") },
|
||||
{ key: "region", label: t("import.csv_region") },
|
||||
{ key: "postcode", label: t("import.csv_postcode") },
|
||||
{ key: "country", label: t("import.csv_country") },
|
||||
{ key: "website", label: t("import.csv_website") },
|
||||
{ key: "note", label: t("import.csv_note") },
|
||||
{ key: "nickname", label: t("import.csv_nickname") },
|
||||
];
|
||||
|
||||
const headerOptions = csvData.headers.map((h, i) => ({
|
||||
value: String(i),
|
||||
label: h,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-medium">{t("import.csv_map_columns")}</p>
|
||||
<div className="grid grid-cols-2 gap-2 max-h-64 overflow-y-auto">
|
||||
{fields.map(({ key, label }) => (
|
||||
<div key={key} className="flex items-center gap-2">
|
||||
<label className="text-xs text-muted-foreground w-24 flex-shrink-0 truncate">
|
||||
{label}
|
||||
</label>
|
||||
<select
|
||||
value={mapping[key] >= 0 ? String(mapping[key]) : "-1"}
|
||||
onChange={(e) => {
|
||||
setMapping((prev) => prev ? {
|
||||
...prev,
|
||||
[key]: parseInt(e.target.value, 10),
|
||||
} : null);
|
||||
}}
|
||||
className="flex-1 px-2 py-1 text-xs rounded border border-border bg-muted text-foreground focus:outline-none focus:ring-1 focus:ring-ring"
|
||||
dir="auto"
|
||||
>
|
||||
<option value="-1">{t("import.csv_ignore")}</option>
|
||||
{headerOptions.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{books.length > 0 && (
|
||||
<div className="flex items-center gap-2 pt-2">
|
||||
<label className="text-xs text-muted-foreground flex-shrink-0">
|
||||
{t("import.csv_address_book")}
|
||||
</label>
|
||||
<select
|
||||
value={effectiveBookId}
|
||||
onChange={(e) => setTargetBookId(e.target.value)}
|
||||
className="px-2 py-1 text-xs rounded border border-border bg-muted text-foreground focus:outline-none focus:ring-1 focus:ring-ring"
|
||||
dir="auto"
|
||||
>
|
||||
{bookOptions.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2 pt-1">
|
||||
<Button size="sm" onClick={applyCsvMapping}>
|
||||
{t("import.csv_preview")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setFileType(null);
|
||||
setCsvData(null);
|
||||
setMapping(null);
|
||||
if (fileRef.current) fileRef.current.value = "";
|
||||
}}
|
||||
>
|
||||
{t("form.cancel")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const renderCsvPreview = () => {
|
||||
if (!csvData || !mapping || !showPreview) return null;
|
||||
const previewRows = csvData.rows.slice(0, 5);
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm font-medium">{t("import.csv_preview_title", { count: parsed.length })}</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowPreview(false)}
|
||||
>
|
||||
{t("import.csv_back")}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="border rounded-md overflow-x-auto">
|
||||
<table className="w-full text-xs">
|
||||
<thead>
|
||||
<tr className="bg-muted">
|
||||
{csvData.headers.map((h, i) => (
|
||||
<th key={i} className="px-2 py-1.5 text-start font-medium text-muted-foreground whitespace-nowrap">
|
||||
{h}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{previewRows.map((row, ri) => (
|
||||
<tr key={ri} className="border-t border-border">
|
||||
{row.map((cell, ci) => (
|
||||
<td key={ci} className="px-2 py-1.5 truncate max-w-[150px]">
|
||||
{cell}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={applyCsvMapping}>
|
||||
{t("import.csv_load_all")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="px-6 py-4 border-b border-border flex items-center justify-between">
|
||||
@@ -119,12 +348,12 @@ export function ContactImportDialog({
|
||||
{t("import.close")}
|
||||
</Button>
|
||||
</div>
|
||||
) : parsed.length === 0 ? (
|
||||
) : fileType === null ? (
|
||||
<>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept=".vcf,.vcard"
|
||||
accept={ALLOWED_ACCEPT}
|
||||
onChange={handleFileChange}
|
||||
className="hidden"
|
||||
/>
|
||||
@@ -141,7 +370,7 @@ export function ContactImportDialog({
|
||||
>
|
||||
<Upload className="w-8 h-8" />
|
||||
<p className="text-sm font-medium">{t("import.drop_hint")}</p>
|
||||
<p className="text-xs">{t("import.file_types")}</p>
|
||||
<p className="text-xs">{t("import.file_types_csv")}</p>
|
||||
</button>
|
||||
|
||||
{error && (
|
||||
@@ -151,6 +380,10 @@ export function ContactImportDialog({
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : fileType === "csv" && csvData && !showPreview ? (
|
||||
renderCsvMapping()
|
||||
) : fileType === "csv" && csvData && showPreview ? (
|
||||
renderCsvPreview()
|
||||
) : (
|
||||
<>
|
||||
{error && (
|
||||
@@ -217,7 +450,23 @@ export function ContactImportDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{parsed.length > 0 && result === null && (
|
||||
{parsed.length > 0 && result === null && fileType !== "csv" && (
|
||||
<div className="flex items-center justify-between px-6 py-4 border-t border-border">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("import.selected", { count: selected.size })}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={onClose} disabled={isImporting}>
|
||||
{t("form.cancel")}
|
||||
</Button>
|
||||
<Button onClick={handleImport} disabled={isImporting || selected.size === 0}>
|
||||
{isImporting ? t("import.importing") : t("import.import_button")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{fileType === "csv" && showPreview && parsed.length > 0 && result === null && (
|
||||
<div className="flex items-center justify-between px-6 py-4 border-t border-border">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("import.selected", { count: selected.size })}
|
||||
|
||||
Reference in New Issue
Block a user