Skip to content
// Find the listing they asked about, then up to 3 similar ones (same type and city, price within ±20%).
const s = $('Settings (edit me)').first().json;
const lead = $input.first().json;
const L = s.listings;
const norm = (x) => String(x ?? '').toLowerCase().replace(/[^a-z0-9 ]/g, ' ').replace(/\s+/g, ' ').trim();

const asked = L.find((l) => lead.listing_id && l.id.toLowerCase() === lead.listing_id.toLowerCase())
  ?? L.find((l) => lead.property && norm(lead.property).includes(norm(l.address).split(' ').slice(0, 3).join(' ')));
const wantType = lead.intent === 'renter' ? 'rent' : 'sale';
const ref = asked ?? { city: (L.find((l) => norm(lead.property).includes(norm(l.city)))?.city) ?? null, price: null, type: wantType };

const similar = L
  .filter((l) => l.status === 'active' && l.id !== asked?.id && l.type === (asked?.type ?? wantType))
  .filter((l) => !ref.city || l.city === ref.city)
  .filter((l) => !ref.price || Math.abs(l.price - ref.price) / ref.price <= 0.2)
  .sort((a, b) => (ref.price ? Math.abs(a.price - ref.price) - Math.abs(b.price - ref.price) : b.listed_at.localeCompare(a.listed_at)))
  .slice(0, 3);

return [{ json: { ...lead, asked_listing: asked ?? null, matches: lead.intent === 'seller' ? [] : similar } }];