Skip to content

Commit e0fa18b

Browse files
committed
Fix IntegrityError on duplicate URN during lead discovery
1 parent 017ced6 commit e0fa18b

2 files changed

Lines changed: 15 additions & 6 deletions

File tree

crm/models/lead.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,19 +50,20 @@ def get_profile(self, session) -> dict | None:
5050

5151
urn = profile.get("urn") or None
5252
if urn and self.urn != urn:
53-
self.urn = urn
54-
self.save(update_fields=["urn"])
53+
if Lead.objects.filter(urn=urn).exclude(pk=self.pk).exists():
54+
logger.warning("URN %s already owned by another lead — skipping for %s", urn, self.public_identifier)
55+
else:
56+
self.urn = urn
57+
self.save(update_fields=["urn"])
5558

5659
return profile
5760

5861
def get_urn(self, session) -> str:
5962
"""LinkedIn URN. Reads cached column; falls back to a live scrape."""
6063
if self.urn:
6164
return self.urn
62-
profile = self.get_profile(session)
63-
if profile and profile.get("urn"):
64-
self.urn = profile["urn"]
65-
self.save(update_fields=["urn"])
65+
self.get_profile(session) # sets self.urn as side-effect
66+
if self.urn:
6667
return self.urn
6768
raise ValueError(f"Lead {self.pk}: could not resolve URN after re-fetch")
6869

linkedin/db/leads.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,17 @@ def create_enriched_lead(session, url: str, profile: Dict[str, Any]) -> Optional
3333
public_id = canonical_pid or url_to_public_id(url)
3434
clean_url = public_id_to_url(public_id)
3535

36+
urn = profile.get("urn") or None
37+
3638
with transaction.atomic():
3739
if Lead.objects.filter(public_identifier=public_id).exists():
3840
return None
41+
if urn and Lead.objects.filter(urn=urn).exists():
42+
logger.info(
43+
"Lead with URN %s already exists — skipping duplicate %s",
44+
urn, public_id,
45+
)
46+
return None
3947
lead = Lead.objects.create(linkedin_url=clean_url, public_identifier=public_id)
4048
_cache_urn_from_profile(lead, profile)
4149

0 commit comments

Comments
 (0)