diff --git a/src/lib/appwrite/matching.ts b/src/lib/appwrite/matching.ts index 6f7f466..d59123e 100644 --- a/src/lib/appwrite/matching.ts +++ b/src/lib/appwrite/matching.ts @@ -32,10 +32,9 @@ export async function matchPropertyToSearches( const searches = searchesResult.rows as unknown as CustomerSearch[]; for (const search of searches) { - if (search.listingType && search.listingType !== property.listingType) continue; - - const score = scoreMatch(property, search); - if (score < SCORE_THRESHOLD) continue; + const listingTypeMismatch = + !!search.listingType && search.listingType !== property.listingType; + const score = listingTypeMismatch ? 0 : scoreMatch(property, search); const existing = await tablesDB.listRows({ databaseId: DATABASE_ID, @@ -47,29 +46,36 @@ export async function matchPropertyToSearches( ], }); - if (existing.rows.length > 0) { - await tablesDB.updateRow(DATABASE_ID, TABLES.propertyMatches, existing.rows[0].$id, { score }); - } else { - await tablesDB.createRow( - DATABASE_ID, - TABLES.propertyMatches, - ID.unique(), - { - tenantId, - propertyId: property.$id, - customerId: search.customerId, - searchId: search.$id, - notified: false, - score, - createdBy, - }, - [ - Permission.read(Role.team(tenantId)), - Permission.update(Role.team(tenantId)), - Permission.delete(Role.team(tenantId, "owner")), - Permission.delete(Role.team(tenantId, "admin")), - ], - ); + const existingId = existing.rows.length > 0 ? existing.rows[0].$id : null; + + if (score >= SCORE_THRESHOLD) { + if (existingId) { + await tablesDB.updateRow(DATABASE_ID, TABLES.propertyMatches, existingId, { score }); + } else { + await tablesDB.createRow( + DATABASE_ID, + TABLES.propertyMatches, + ID.unique(), + { + tenantId, + propertyId: property.$id, + customerId: search.customerId, + searchId: search.$id, + notified: false, + score, + createdBy, + }, + [ + Permission.read(Role.team(tenantId)), + Permission.update(Role.team(tenantId)), + Permission.delete(Role.team(tenantId, "owner")), + Permission.delete(Role.team(tenantId, "admin")), + ], + ); + } + } else if (existingId) { + // Criteria changed → match no longer qualifies → remove stale record + await tablesDB.deleteRow(DATABASE_ID, TABLES.propertyMatches, existingId); } } }