Seth Claude Sonnet 5 commited on
Commit
4b1d42b
·
1 Parent(s): 6a71a79

Fix Category revert bug on Contacts page, generalize sync to all company fields

Browse files

- Contacts.jsx built its own local companyDetails object for the
editor instead of passing raw_data straight through — that object
was missing a Category key entirely, so the field always read as
empty and every autosave round-trip re-synced the form from that
same Category-less object, snapping the dropdown back to "-".
- Generalized the previous Category-only propagation into full-field
propagation: editing industry, employees, revenue, website, city,
state, country, or category anywhere (Contact/Lead/Company/Deal)
now pushes to the Company row and every Contact/Lead sharing that
company name, not just Category.
- _sync_companies_from_contacts now also tops up any blank field on
an already-existing Company row from the richest matching contact,
fixing Company rows that got stuck sparse after an early sync —
never overwrites a field that already has a value, synced or
manually edited.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

backend/app/main.py CHANGED
@@ -3876,8 +3876,9 @@ async def patch_contact(contact_id: int, body: ContactPatchRequest, t: TenantCon
3876
  contact.title = _safe_str(data["title"])
3877
  _sync_contact_raw_from_columns(contact)
3878
  _merge_contact_raw_company_details(contact, data)
3879
- if "category" in data:
3880
- _propagate_category_everywhere(db, t.tenant_id, contact.company, data["category"])
 
3881
  db.commit()
3882
  db.refresh(contact)
3883
  return {
@@ -4114,7 +4115,11 @@ def _contacts_for_company(db: Session, tenant_id: int, company_name: str) -> Lis
4114
  def _sync_companies_from_contacts(db: Session, tenant_id: int) -> int:
4115
  """Creates a Company row for any distinct Contact.company value that doesn't already have a
4116
  case-insensitive name match, seeded from the contact with the most non-empty company detail
4117
- fields. Safe to call on every list load — never touches an existing Company row."""
 
 
 
 
4118
  contacts = (
4119
  db.query(Contact)
4120
  .filter(Contact.tenant_id == tenant_id, Contact.company.isnot(None), Contact.company != "")
@@ -4122,8 +4127,8 @@ def _sync_companies_from_contacts(db: Session, tenant_id: int) -> int:
4122
  )
4123
  if not contacts:
4124
  return 0
4125
- existing_names = {
4126
- (c.name or "").strip().lower()
4127
  for c in db.query(Company).filter(Company.tenant_id == tenant_id).all()
4128
  }
4129
  richest_by_key: Dict[str, tuple] = {}
@@ -4132,8 +4137,6 @@ def _sync_companies_from_contacts(db: Session, tenant_id: int) -> int:
4132
  if not name:
4133
  continue
4134
  key = name.lower()
4135
- if key in existing_names:
4136
- continue
4137
  details = _contact_company_details_dict(c)
4138
  richness = sum(1 for k, v in details.items() if k != "Company Name" and v)
4139
  prev = richest_by_key.get(key)
@@ -4141,42 +4144,73 @@ def _sync_companies_from_contacts(db: Session, tenant_id: int) -> int:
4141
  richest_by_key[key] = (richness, name, details)
4142
 
4143
  created = 0
 
4144
  for key, (richness, name, details) in richest_by_key.items():
4145
- db.add(
4146
- Company(
4147
- tenant_id=tenant_id,
4148
- name=name,
4149
- category=details.get("Category", ""),
4150
- company_name_for_emails=details.get("Company Name for Emails", ""),
4151
- industry=details.get("Industry", ""),
4152
- employees=details.get("# Employees", ""),
4153
- annual_revenue=details.get("Annual Revenue", ""),
4154
- last_raised_at=details.get("Last Raised At", ""),
4155
- website=details.get("Website", ""),
4156
- city=details.get("City", ""),
4157
- state=details.get("State", ""),
4158
- country=details.get("Country", ""),
4159
- source="synced_from_contacts",
 
 
 
4160
  )
4161
- )
4162
- created += 1
4163
- if created:
 
 
 
 
 
 
 
 
 
 
 
 
4164
  db_commit_with_retry(db)
4165
  return created
4166
 
4167
 
4168
- def _propagate_category_to_contacts_and_leads(
4169
- db: Session, tenant_id: int, company_name: str, category: str
 
 
 
 
 
 
 
 
 
 
 
 
 
4170
  ) -> None:
4171
- """Category is a company-level attribute — whenever it's set anywhere (the Company page, or
4172
- a Contact/Lead/Deal's Company details card), every other record sharing that company name
4173
- (case-insensitive) is updated to match, so it never drifts between the four places it's
4174
- editable. Does NOT touch the Company row itself — callers that aren't already the Company
4175
- row use _propagate_category_everywhere for that."""
 
 
4176
  name = _safe_str(company_name).strip()
4177
- if not name:
4178
  return
4179
- category = _safe_str(category)
4180
 
4181
  contacts = (
4182
  db.query(Contact)
@@ -4185,7 +4219,7 @@ def _propagate_category_to_contacts_and_leads(
4185
  )
4186
  for c in contacts:
4187
  rd = dict(c.raw_data or {})
4188
- rd["Category"] = category
4189
  c.raw_data = rd
4190
 
4191
  leads = (
@@ -4199,7 +4233,7 @@ def _propagate_category_to_contacts_and_leads(
4199
  for lead in leads:
4200
  rw = dict(lead.raw_webhook) if isinstance(lead.raw_webhook, dict) else {}
4201
  cd = dict(rw.get("company_details") or {}) if isinstance(rw.get("company_details"), dict) else {}
4202
- cd["Category"] = category
4203
  rw["company_details"] = cd
4204
  lead.raw_webhook = rw
4205
  lead.updated_at = datetime.utcnow()
@@ -4207,23 +4241,32 @@ def _propagate_category_to_contacts_and_leads(
4207
  db_commit_with_retry(db)
4208
 
4209
 
4210
- def _propagate_category_everywhere(db: Session, tenant_id: int, company_name: str, category: str) -> None:
4211
- """Like _propagate_category_to_contacts_and_leads, but also upserts the Company row itself —
4212
- for callers (Contact/Lead/Deal patches) that aren't already editing the Company row directly."""
 
 
 
 
4213
  name = _safe_str(company_name).strip()
4214
- if not name:
4215
  return
4216
  company = (
4217
  db.query(Company)
4218
  .filter(Company.tenant_id == tenant_id, func.lower(Company.name) == name.lower())
4219
  .first()
4220
  )
4221
- if company:
4222
- company.category = _safe_str(category)
4223
- company.updated_at = datetime.utcnow()
4224
- else:
4225
- db.add(Company(tenant_id=tenant_id, name=name, category=_safe_str(category), source="synced_from_contacts"))
4226
- _propagate_category_to_contacts_and_leads(db, tenant_id, name, category)
 
 
 
 
 
4227
 
4228
 
4229
  @app.get("/api/companies")
@@ -4392,7 +4435,7 @@ async def patch_company(
4392
  if taken:
4393
  raise HTTPException(status_code=409, detail="Another company already uses this name")
4394
  company.name = name
4395
- for field in (
4396
  "category",
4397
  "company_name_for_emails",
4398
  "industry",
@@ -4403,12 +4446,14 @@ async def patch_company(
4403
  "city",
4404
  "state",
4405
  "country",
4406
- ):
 
4407
  if field in data:
4408
  setattr(company, field, _safe_str(data[field]))
4409
  company.updated_at = datetime.utcnow()
4410
- if "category" in data:
4411
- _propagate_category_to_contacts_and_leads(db, t.tenant_id, company.name, data["category"])
 
4412
  db.commit()
4413
  db.refresh(company)
4414
  contacts = _contacts_for_company(db, t.tenant_id, company.name)
@@ -5929,8 +5974,9 @@ async def patch_lead(lead_id: int, body: CrmLeadPatchRequest, t: TenantContext =
5929
  rw["company_details"] = cd
5930
  row.raw_webhook = rw
5931
  row.updated_at = datetime.utcnow()
5932
- if "category" in data:
5933
- _propagate_category_everywhere(db, t.tenant_id, row.company_name, data["category"])
 
5934
  db.commit()
5935
  db.refresh(row)
5936
  return _crm_lead_to_dict(row)
@@ -6466,8 +6512,9 @@ async def patch_deal(deal_id: int, body: CrmDealPatchRequest, t: TenantContext =
6466
  rd = dict(c.raw_data or {})
6467
  rd["Country"] = _safe_str(data["country"])
6468
  c.raw_data = rd
6469
- if "category" in data:
6470
- _propagate_category_everywhere(db, t.tenant_id, c.company, data["category"])
 
6471
  db.add(c)
6472
  row.updated_at = datetime.utcnow()
6473
  db.commit()
 
3876
  contact.title = _safe_str(data["title"])
3877
  _sync_contact_raw_from_columns(contact)
3878
  _merge_contact_raw_company_details(contact, data)
3879
+ company_fields = {k: data[k] for k in COMPANY_DETAIL_PATCH_FIELDS if k in data}
3880
+ if company_fields:
3881
+ _propagate_company_fields_everywhere(db, t.tenant_id, contact.company, company_fields)
3882
  db.commit()
3883
  db.refresh(contact)
3884
  return {
 
4115
  def _sync_companies_from_contacts(db: Session, tenant_id: int) -> int:
4116
  """Creates a Company row for any distinct Contact.company value that doesn't already have a
4117
  case-insensitive name match, seeded from the contact with the most non-empty company detail
4118
+ fields. Also tops up any BLANK field on an already-existing Company row from the richest
4119
+ matching contact — this is what keeps a Company row from getting stuck with sparse data
4120
+ forever if it was first synced before richer contact data existed. Never overwrites a field
4121
+ that already has a value, whether that value came from an earlier sync or a manual edit.
4122
+ Safe to call on every list load."""
4123
  contacts = (
4124
  db.query(Contact)
4125
  .filter(Contact.tenant_id == tenant_id, Contact.company.isnot(None), Contact.company != "")
 
4127
  )
4128
  if not contacts:
4129
  return 0
4130
+ existing_by_key = {
4131
+ (c.name or "").strip().lower(): c
4132
  for c in db.query(Company).filter(Company.tenant_id == tenant_id).all()
4133
  }
4134
  richest_by_key: Dict[str, tuple] = {}
 
4137
  if not name:
4138
  continue
4139
  key = name.lower()
 
 
4140
  details = _contact_company_details_dict(c)
4141
  richness = sum(1 for k, v in details.items() if k != "Company Name" and v)
4142
  prev = richest_by_key.get(key)
 
4144
  richest_by_key[key] = (richness, name, details)
4145
 
4146
  created = 0
4147
+ touched = 0
4148
  for key, (richness, name, details) in richest_by_key.items():
4149
+ existing = existing_by_key.get(key)
4150
+ if existing is None:
4151
+ db.add(
4152
+ Company(
4153
+ tenant_id=tenant_id,
4154
+ name=name,
4155
+ category=details.get("Category", ""),
4156
+ company_name_for_emails=details.get("Company Name for Emails", ""),
4157
+ industry=details.get("Industry", ""),
4158
+ employees=details.get("# Employees", ""),
4159
+ annual_revenue=details.get("Annual Revenue", ""),
4160
+ last_raised_at=details.get("Last Raised At", ""),
4161
+ website=details.get("Website", ""),
4162
+ city=details.get("City", ""),
4163
+ state=details.get("State", ""),
4164
+ country=details.get("Country", ""),
4165
+ source="synced_from_contacts",
4166
+ )
4167
  )
4168
+ created += 1
4169
+ continue
4170
+ changed = False
4171
+ for col, raw_key in _COMPANY_COLUMN_TO_RAW_KEY.items():
4172
+ if getattr(existing, col, ""):
4173
+ continue
4174
+ value = details.get(raw_key, "")
4175
+ if value:
4176
+ setattr(existing, col, value)
4177
+ changed = True
4178
+ if changed:
4179
+ existing.updated_at = datetime.utcnow()
4180
+ touched += 1
4181
+
4182
+ if created or touched:
4183
  db_commit_with_retry(db)
4184
  return created
4185
 
4186
 
4187
+ # Company row column name for each COMPANY_DETAIL_PATCH_FIELDS py_key — identical except
4188
+ # "country_region" (the patch-body key, kept for backwards compat with existing request shapes)
4189
+ # maps to the Company model's "country" column.
4190
+ _COMPANY_FIELD_TO_COLUMN = {
4191
+ **{k: k for k in COMPANY_DETAIL_PATCH_FIELDS if k != "country_region"},
4192
+ "country_region": "country",
4193
+ }
4194
+ # Reverse: Company column name -> Apollo-style raw_data key (e.g. "country" -> "Country"), for
4195
+ # patch_company, which already uses Company's own column names rather than the country_region-style
4196
+ # py_keys the Contact/Lead/Deal patch bodies use.
4197
+ _COMPANY_COLUMN_TO_RAW_KEY = {col: COMPANY_DETAIL_PATCH_FIELDS[k] for k, col in _COMPANY_FIELD_TO_COLUMN.items()}
4198
+
4199
+
4200
+ def _propagate_company_fields_to_contacts_and_leads(
4201
+ db: Session, tenant_id: int, company_name: str, raw_fields: Dict[str, str]
4202
  ) -> None:
4203
+ """Every company-detail field (industry, employees, website, category, ...) is a
4204
+ company-level attribute — whenever any of them is set anywhere (the Company page, or a
4205
+ Contact/Lead/Deal's Company details card), every other record sharing that company name
4206
+ (case-insensitive) is updated to match, so none of them drift between the four places
4207
+ they're editable. `raw_fields` is keyed by the Apollo-style raw_data key (e.g. "Industry",
4208
+ "Category"), not the patch-body py_key. Does NOT touch the Company row itself — callers that
4209
+ aren't already the Company row use _propagate_company_fields_everywhere for that."""
4210
  name = _safe_str(company_name).strip()
4211
+ if not name or not raw_fields:
4212
  return
4213
+ clean_fields = {k: _safe_str(v) for k, v in raw_fields.items()}
4214
 
4215
  contacts = (
4216
  db.query(Contact)
 
4219
  )
4220
  for c in contacts:
4221
  rd = dict(c.raw_data or {})
4222
+ rd.update(clean_fields)
4223
  c.raw_data = rd
4224
 
4225
  leads = (
 
4233
  for lead in leads:
4234
  rw = dict(lead.raw_webhook) if isinstance(lead.raw_webhook, dict) else {}
4235
  cd = dict(rw.get("company_details") or {}) if isinstance(rw.get("company_details"), dict) else {}
4236
+ cd.update(clean_fields)
4237
  rw["company_details"] = cd
4238
  lead.raw_webhook = rw
4239
  lead.updated_at = datetime.utcnow()
 
4241
  db_commit_with_retry(db)
4242
 
4243
 
4244
+ def _propagate_company_fields_everywhere(
4245
+ db: Session, tenant_id: int, company_name: str, py_fields: Dict[str, str]
4246
+ ) -> None:
4247
+ """Like _propagate_company_fields_to_contacts_and_leads, but also upserts the Company row
4248
+ itself — for callers (Contact/Lead/Deal patches) that aren't already editing the Company row
4249
+ directly. `py_fields` is keyed by patch-body py_key (e.g. "industry", "category"), matching
4250
+ COMPANY_DETAIL_PATCH_FIELDS."""
4251
  name = _safe_str(company_name).strip()
4252
+ if not name or not py_fields:
4253
  return
4254
  company = (
4255
  db.query(Company)
4256
  .filter(Company.tenant_id == tenant_id, func.lower(Company.name) == name.lower())
4257
  .first()
4258
  )
4259
+ if not company:
4260
+ company = Company(tenant_id=tenant_id, name=name, source="synced_from_contacts")
4261
+ db.add(company)
4262
+ for py_key, value in py_fields.items():
4263
+ col = _COMPANY_FIELD_TO_COLUMN.get(py_key)
4264
+ if col:
4265
+ setattr(company, col, _safe_str(value))
4266
+ company.updated_at = datetime.utcnow()
4267
+
4268
+ raw_fields = {COMPANY_DETAIL_PATCH_FIELDS[k]: v for k, v in py_fields.items() if k in COMPANY_DETAIL_PATCH_FIELDS}
4269
+ _propagate_company_fields_to_contacts_and_leads(db, tenant_id, name, raw_fields)
4270
 
4271
 
4272
  @app.get("/api/companies")
 
4435
  if taken:
4436
  raise HTTPException(status_code=409, detail="Another company already uses this name")
4437
  company.name = name
4438
+ company_columns = (
4439
  "category",
4440
  "company_name_for_emails",
4441
  "industry",
 
4446
  "city",
4447
  "state",
4448
  "country",
4449
+ )
4450
+ for field in company_columns:
4451
  if field in data:
4452
  setattr(company, field, _safe_str(data[field]))
4453
  company.updated_at = datetime.utcnow()
4454
+ raw_fields = {_COMPANY_COLUMN_TO_RAW_KEY[f]: data[f] for f in company_columns if f in data}
4455
+ if raw_fields:
4456
+ _propagate_company_fields_to_contacts_and_leads(db, t.tenant_id, company.name, raw_fields)
4457
  db.commit()
4458
  db.refresh(company)
4459
  contacts = _contacts_for_company(db, t.tenant_id, company.name)
 
5974
  rw["company_details"] = cd
5975
  row.raw_webhook = rw
5976
  row.updated_at = datetime.utcnow()
5977
+ company_fields = {k: data[k] for k in COMPANY_DETAIL_PATCH_FIELDS if k in data}
5978
+ if company_fields:
5979
+ _propagate_company_fields_everywhere(db, t.tenant_id, row.company_name, company_fields)
5980
  db.commit()
5981
  db.refresh(row)
5982
  return _crm_lead_to_dict(row)
 
6512
  rd = dict(c.raw_data or {})
6513
  rd["Country"] = _safe_str(data["country"])
6514
  c.raw_data = rd
6515
+ company_fields = {k: data[k] for k in COMPANY_DETAIL_PATCH_FIELDS if k in data}
6516
+ if company_fields:
6517
+ _propagate_company_fields_everywhere(db, t.tenant_id, c.company, company_fields)
6518
  db.add(c)
6519
  row.updated_at = datetime.utcnow()
6520
  db.commit()
frontend/src/pages/Contacts.jsx CHANGED
@@ -94,6 +94,7 @@ export default function Contacts() {
94
  City: rd['City'] ?? '',
95
  State: rd['State'] ?? '',
96
  Country: rd['Country'] ?? '',
 
97
  };
98
  }, [selectedContactDetails]);
99
 
 
94
  City: rd['City'] ?? '',
95
  State: rd['State'] ?? '',
96
  Country: rd['Country'] ?? '',
97
+ Category: rd['Category'] ?? '',
98
  };
99
  }, [selectedContactDetails]);
100