// ── Booking API — crée une demande client dans ERPNext ──────────────────────── import { BASE_URL } from 'src/config/erpnext' import { getCSRF } from './auth' const SLOT_LABELS = { matin: 'Matin (8h00 – 12h00)', aprem: 'Après-midi (12h00 – 17h00)', soir: 'Soirée (17h00 – 20h00)', } function buildDescription (data) { const dateLabel = { today: "Aujourd'hui", tomorrow: 'Demain' }[data.date] ?? data.date return [ `SERVICE: ${data.service.label}`, data.serviceNote ? `Détail: ${data.serviceNote}` : null, `ADRESSE: ${data.address}`, `DATE: ${dateLabel} — ${SLOT_LABELS[data.slot] ?? data.slot}`, data.urgent ? '*** URGENT — intervention dans les 2h ***' : null, '---', `Client: ${data.contact.name}`, `Téléphone: ${data.contact.phone}`, data.contact.email ? `Courriel: ${data.contact.email}` : null, data.contact.note ? `Note: ${data.contact.note}` : null, ].filter(Boolean).join('\n') } function localRef () { return 'DSP-' + Date.now().toString(36).toUpperCase().slice(-6) } export async function createBooking (data) { const csrf = await getCSRF().catch(() => '') // Try ERPNext Lead (CRM module — standard in ERPNext) try { const r = await fetch(`${BASE_URL}/api/resource/Lead`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json', 'X-Frappe-CSRF-Token': csrf }, body: JSON.stringify({ lead_name: data.contact.name, mobile_no: data.contact.phone, email_id: data.contact.email || '', source: 'Dispatch Booking', notes: buildDescription(data), status: 'Open', lead_owner: '', }), }) const body = await r.json().catch(() => ({})) if (r.ok && body.data?.name) return body.data.name } catch (_) { /* fall through */ } // Fallback: localStorage + generated ref const ref = localRef() const list = JSON.parse(localStorage.getItem('dispatch_bookings') || '[]') list.push({ ref, ...data, created: new Date().toISOString() }) localStorage.setItem('dispatch_bookings', JSON.stringify(list)) return ref }