42 lines
1.3 KiB
JavaScript
42 lines
1.3 KiB
JavaScript
// DECISION DETERMINISTICA ESTRICTA (Create vs Update)
|
|
// Llave: el ID de la opp de SUCURSAL (unico en GHL), guardado como custom field
|
|
// "ID Oportunidad Sucursal" en la opp de Marca. Buscamos entre las opps del
|
|
// contacto en Marca una cuyo custom field valga exactamente ese id.
|
|
// - Si hay match -> UPDATE (esa opp exacta).
|
|
// - Si NO hay match -> CREATE (sin fallback por nombre).
|
|
|
|
const result = $input.first().json;
|
|
const opportunities = result.opportunities || [];
|
|
const sucursalOppId = $('Datos de Lead').first().json.Oportunidad.opportunity_id;
|
|
|
|
let action = 'CREATE';
|
|
let opportunityId = null;
|
|
let matchReason = '';
|
|
|
|
const match = opportunities.find(o =>
|
|
(o.customFields || []).some(cf => {
|
|
const v = cf.fieldValueString ?? cf.fieldValue ?? '';
|
|
return String(v) === String(sucursalOppId);
|
|
})
|
|
);
|
|
|
|
if (match) {
|
|
action = 'UPDATE';
|
|
opportunityId = match.id;
|
|
matchReason = 'Match por ID Oportunidad Sucursal';
|
|
} else {
|
|
action = 'CREATE';
|
|
matchReason = 'Sin match por ID Oportunidad Sucursal -> CREATE (contacto tiene ' + opportunities.length + ' opps)';
|
|
}
|
|
|
|
return [{
|
|
json: {
|
|
action,
|
|
opportunityId,
|
|
matchReason,
|
|
sucursalOppId,
|
|
contactId: $('Set Contact ID Resuelto').first().json.contactId,
|
|
totalOppsContacto: opportunities.length
|
|
}
|
|
}];
|