From d9aff26376fdcde88c4d4b5213bfde15e5d3635f Mon Sep 17 00:00:00 2001 From: egecankomur Date: Tue, 5 May 2026 20:03:49 +0300 Subject: [PATCH] fix: delete stale matches when score drops below threshold or listing type changes matchPropertyToSearches now: - scores every search (listing type mismatch = 0 score) - score >= 20: create or update match - score < 20 AND existing match: delete stale record Prevents outdated match records after criteria/weight updates. --- src/lib/appwrite/matching.ts | 60 ++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 27 deletions(-) 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); } } }