import { i18n } from '../i18n/instance'; export type ParsedContactRow = { id: string; firstName: string; lastName: string; fullName: string; phone: string; email: string; notes: string; isValid: boolean; error?: string; }; export function normalizePhone(rawPhone: string): string { const trimmed = rawPhone.trim(); const hasPlus = trimmed.startsWith('+'); const digitsOnly = trimmed.replace(/\D/g, ''); return hasPlus ? `+${digitsOnly}` : digitsOnly; } /** * Parses CSV text with support for: * - Automatic delimiters (comma, semicolon, tab) * - Quotes and escaped quotes ("") * - UTF-8 BOM * - CRLF or LF line breaks */ export function parseCsvContent(content: string): string[][] { const cleanContent = content.replace(/^\uFEFF/, ''); const lines = cleanContent.split(/\r\n|\n|\r/).filter((l) => l.trim().length > 0); if (lines.length === 0) return []; // Detect the delimiter from the first line const firstLine = lines[0]; const commaCount = (firstLine.match(/,/g) || []).length; const semicolonCount = (firstLine.match(/;/g) || []).length; const tabCount = (firstLine.match(/\t/g) || []).length; let delimiter = ','; if (semicolonCount > commaCount && semicolonCount >= tabCount) { delimiter = ';'; } else if (tabCount > commaCount && tabCount > semicolonCount) { delimiter = '\t'; } const rows: string[][] = []; for (const line of lines) { const row: string[] = []; let insideQuote = false; let currentCell = ''; for (let i = 0; i < line.length; i++) { const char = line[i]; if (char === '"') { if (insideQuote && line[i + 1] === '"') { currentCell += '"'; i++; // Skip the escaped quote } else { insideQuote = !insideQuote; } } else if (char === delimiter && !insideQuote) { row.push(currentCell.trim()); currentCell = ''; } else { currentCell += char; } } row.push(currentCell.trim()); rows.push(row); } return rows; } /** * Parses an Excel XLSX file by extracting sharedStrings and sheet1.xml with * the browser's native DecompressionStream, without external dependencies. */ export async function parseXlsxContent(buffer: ArrayBuffer): Promise { const view = new DataView(buffer); const entries = new Map(); let offset = 0; while (offset < buffer.byteLength - 30) { const sig = view.getUint32(offset, true); if (sig !== 0x04034b50) break; const compression = view.getUint16(offset + 8, true); const compressedSize = view.getUint32(offset + 18, true); const fileNameLen = view.getUint16(offset + 26, true); const extraLen = view.getUint16(offset + 28, true); const nameBytes = new Uint8Array(buffer, offset + 30, fileNameLen); const fileName = new TextDecoder().decode(nameBytes); const dataStart = offset + 30 + fileNameLen + extraLen; if (compressedSize > 0 && dataStart + compressedSize <= buffer.byteLength) { const compressedData = new Uint8Array(buffer, dataStart, compressedSize); if (compression === 0) { entries.set(fileName, compressedData); } else if (compression === 8 && typeof DecompressionStream !== 'undefined') { try { const stream = new Response(compressedData).body?.pipeThrough( new DecompressionStream('deflate-raw'), ); if (stream) { const decompressed = await new Response(stream).arrayBuffer(); entries.set(fileName, new Uint8Array(decompressed)); } } catch { // Ignore files that can't be decompressed } } } offset = dataStart + compressedSize; } // Parse the shared strings const sharedStringsData = entries.get('xl/sharedStrings.xml'); const sharedStrings: string[] = []; if (sharedStringsData) { const xmlText = new TextDecoder().decode(sharedStringsData); const parser = new DOMParser(); const doc = parser.parseFromString(xmlText, 'application/xml'); const siNodes = doc.getElementsByTagName('si'); for (let i = 0; i < siNodes.length; i++) { const tNodes = siNodes[i].getElementsByTagName('t'); let str = ''; for (let j = 0; j < tNodes.length; j++) { str += tNodes[j].textContent ?? ''; } sharedStrings.push(str); } } // Parse sheet1.xml const sheetData = entries.get('xl/worksheets/sheet1.xml'); if (!sheetData) { throw new Error(i18n.t('groupAdd:bulk.noSheet')); } const sheetXml = new TextDecoder().decode(sheetData); const parser = new DOMParser(); const doc = parser.parseFromString(sheetXml, 'application/xml'); const rowNodes = doc.getElementsByTagName('row'); const rows: string[][] = []; for (let i = 0; i < rowNodes.length; i++) { const rowEl = rowNodes[i]; const cNodes = rowEl.getElementsByTagName('c'); const rowValues: string[] = []; for (let j = 0; j < cNodes.length; j++) { const c = cNodes[j]; const isString = c.getAttribute('t') === 's'; const v = c.getElementsByTagName('v')[0]?.textContent ?? ''; if (isString) { const index = parseInt(v, 10); rowValues.push(sharedStrings[index] ?? ''); } else { rowValues.push(v); } } rows.push(rowValues); } return rows; } /** * Normalizes a 2D matrix into contact objects with smart column detection. */ export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[] { if (rawRows.length === 0) return []; const headerRow = rawRows[0].map((h) => h.toLowerCase().trim()); let hasHeader = false; let nameCol = -1; let firstNameCol = -1; let lastNameCol = -1; let phoneCol = -1; let emailCol = -1; let notesCol = -1; for (let i = 0; i < headerRow.length; i++) { const col = headerRow[i]; if (col === 'nombre' || col === 'nome' || col === 'first name' || col === 'firstname') { firstNameCol = i; hasHeader = true; } else if (col === 'apellido' || col === 'sobrenome' || col === 'last name' || col === 'lastname') { lastNameCol = i; hasHeader = true; } else if ( ['nombre completo', 'nome completo', 'full name', 'fullname', 'alumno', 'aluno', 'student'].includes(col) ) { nameCol = i; hasHeader = true; } else if ( col.includes('tel') || col.includes('cel') || col.includes('phone') || col.includes('whatsapp') || col.includes('movil') || col.includes('móvil') ) { phoneCol = i; hasHeader = true; } else if (col.includes('email') || col.includes('correo')) { emailCol = i; hasHeader = true; } else if (col.includes('nota') || col.includes('note') || col.includes('obs')) { notesCol = i; hasHeader = true; } } // Positional fallbacks when no explicit headers were detected if (!hasHeader) { firstNameCol = 0; lastNameCol = 1; phoneCol = 2; emailCol = 3; } else if (firstNameCol === -1 && nameCol === -1) { firstNameCol = 0; } if (phoneCol === -1) { // Look for the first column that looks like a phone number for (let c = 0; c < (rawRows[1]?.length ?? 0); c++) { const sample = rawRows[1][c]; if (/^[\d\s+\-()]{6,}$/.test(sample)) { phoneCol = c; break; } } if (phoneCol === -1) phoneCol = 1; } const dataRows = hasHeader ? rawRows.slice(1) : rawRows; const contacts: ParsedContactRow[] = []; for (let idx = 0; idx < dataRows.length; idx++) { const row = dataRows[idx]; if (row.every((c) => c.trim().length === 0)) continue; let firstName = ''; let lastName = ''; let fullName = ''; if (nameCol !== -1 && row[nameCol]) { fullName = row[nameCol].trim(); const parts = fullName.split(/\s+/); firstName = parts[0] || ''; lastName = parts.slice(1).join(' ') || ''; } else { firstName = (firstNameCol !== -1 ? row[firstNameCol] : '') || ''; lastName = (lastNameCol !== -1 ? row[lastNameCol] : '') || ''; fullName = `${firstName} ${lastName}`.trim(); } const rawPhone = (phoneCol !== -1 ? row[phoneCol] : '') || ''; const phone = normalizePhone(rawPhone); const email = (emailCol !== -1 ? row[emailCol] : '') || ''; const notes = (notesCol !== -1 ? row[notesCol] : '') || ''; const errors: string[] = []; if (!firstName && !fullName) errors.push(i18n.t('groupAdd:bulk.missingName')); if (!phone || phone.replace(/\D/g, '').length < 6) { errors.push(i18n.t('groupAdd:bulk.invalidPhone')); } contacts.push({ id: `row-${idx}-${Math.random().toString(36).slice(2, 6)}`, firstName: firstName || fullName, lastName, fullName: fullName || firstName, phone, email: email.trim(), notes: notes.trim(), isValid: errors.length === 0, error: errors.join(', '), }); } return contacts; } /** * Downloads a sample template in CSV format for the bulk upload. */ export function downloadAttendeeTemplateCsv() { // The template follows the UI language; the parser accepts the headers of // every supported language. const csvContent = [i18n.t('groupAdd:template.header'), ...i18n.t('groupAdd:template.rows').split('\n')].join('\r\n') + '\r\n'; const blob = new Blob([new Uint8Array([0xef, 0xbb, 0xbf]), csvContent], { type: 'text/csv;charset=utf-8;', }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.setAttribute('href', url); link.setAttribute('download', i18n.t('groupAdd:template.fileName')); document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); }