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.
This commit is contained in:
egecankomur
2026-05-05 20:03:49 +03:00
parent a40e68254b
commit d9aff26376
+33 -27
View File
@@ -32,10 +32,9 @@ export async function matchPropertyToSearches(
const searches = searchesResult.rows as unknown as CustomerSearch[]; const searches = searchesResult.rows as unknown as CustomerSearch[];
for (const search of searches) { for (const search of searches) {
if (search.listingType && search.listingType !== property.listingType) continue; const listingTypeMismatch =
!!search.listingType && search.listingType !== property.listingType;
const score = scoreMatch(property, search); const score = listingTypeMismatch ? 0 : scoreMatch(property, search);
if (score < SCORE_THRESHOLD) continue;
const existing = await tablesDB.listRows({ const existing = await tablesDB.listRows({
databaseId: DATABASE_ID, databaseId: DATABASE_ID,
@@ -47,29 +46,36 @@ export async function matchPropertyToSearches(
], ],
}); });
if (existing.rows.length > 0) { const existingId = existing.rows.length > 0 ? existing.rows[0].$id : null;
await tablesDB.updateRow(DATABASE_ID, TABLES.propertyMatches, existing.rows[0].$id, { score });
} else { if (score >= SCORE_THRESHOLD) {
await tablesDB.createRow( if (existingId) {
DATABASE_ID, await tablesDB.updateRow(DATABASE_ID, TABLES.propertyMatches, existingId, { score });
TABLES.propertyMatches, } else {
ID.unique(), await tablesDB.createRow(
{ DATABASE_ID,
tenantId, TABLES.propertyMatches,
propertyId: property.$id, ID.unique(),
customerId: search.customerId, {
searchId: search.$id, tenantId,
notified: false, propertyId: property.$id,
score, customerId: search.customerId,
createdBy, searchId: search.$id,
}, notified: false,
[ score,
Permission.read(Role.team(tenantId)), createdBy,
Permission.update(Role.team(tenantId)), },
Permission.delete(Role.team(tenantId, "owner")), [
Permission.delete(Role.team(tenantId, "admin")), 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);
} }
} }
} }