4433 foundRows.push(...(found?.rows || [])); 4434 } 4435 const prospectsByPhone = new Map(); 4436 for (const prospect of foundRows) { 4437 const phone = normalizePhone(prospect.telephone); 4438 if (phone && !prospectsByPhone.has(phone)) prospectsByPhone.set(phone, prospect); 4439 } 4440 const ventesByPhone = new Map(); 4441 for (const vente of ventes || []) { 4442 const client = parseJsonObject(vente?.client); 4443 const phone = normalizePhone(client.telephone || client.phone || client.tel || client.mobile); 4444 if (!phone) continue; 4445 const matching = ventesByPhone.get(phone) || []; 4446 matching.push(vente); 4447 ventesByPhone.set(phone, matching); 4448 } 4449 let inserted = 0; 4450 let updated = 0; 4451 let linked = 0; 4452 for (const candidate of candidates) { 4453 let prospect = prospectsByPhone.get(candidate.phone); 4454 if (!prospect) { 4455 const result = await context.call('tables', 'rows_insert', { 4456 table: 'prospects', 4457 rows: [{ 4458 telephone: `+33${candidate.phone}`, 4459 statut: 'converti', 4460 source: 'sales_sync', 4461 centre_lock_id: candidate.centreId, 4462 centre_lock_until: candidate.lockUntil, 4463 centre_lock_source: 'sale', 4464 created_at_iso: now.toISOString(), 4465 updated_at_iso: now.toISOString(), 4466 }], 4467 }); 4468 prospect = { id: Number(result?.ids?.[0] || result?.rows?.[0]?.id || 0), telephone: `+33${candidate.phone}` }; 4469 if (!prospect.id) throw new Error(`Could not create prospect for sale phone ending ${candidate.phone.slice(-4)}`); 4470 prospectsByPhone.set(candidate.phone, prospect); 4471 inserted++; 4472 } else { 4473 const existingUntil = Date.parse(String(prospect.centre_lock_until || '')); 4474 const existingSaleStart = String(prospect.centre_lock_source || '') === 'sale' && Number.isFinite(existingUntil) 4475 ? existingUntil - 90 * 24 * 60 * 60 * 1000 4476 : Number.POSITIVE_INFINITY; 4477 const incomingStart = Date.parse(candidate.soldAt); 4478 if (String(prospect.centre_lock_source || '') !== 'sale' || incomingStart < existingSaleStart || existingUntil <= now.getTime()) { 4479 await context.call('tables', 'rows_update', { 4480 table: 'prospects', 4481 id: Number(prospect.id), 4482 fields: { 4483 centre_lock_id: candidate.centreId, 4484 centre_lock_until: candidate.lockUntil, 4485 centre_lock_source: 'sale', 4486 updated_at_iso: now.toISOString(), 4487 }, 4488 }); 4489 Object.assign(prospect, { 4490 centre_lock_id: candidate.centreId, 4491 centre_lock_until: candidate.lockUntil, 4492 centre_lock_source: 'sale', 4493 });