mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 04:45:20 +00:00
Staff can find activities by title with scoped access, municipality+date secondary, and word-start matching on the existing home-search POST.
85 lines
2.4 KiB
TypeScript
85 lines
2.4 KiB
TypeScript
import 'server-only'
|
|
|
|
import type { Payload } from 'payload'
|
|
|
|
import { homeSearchQueryIsActive, normalizeHomeSearchRaw } from '@/lib/campaignHomeSearchContract'
|
|
import type { HomeSearchAdvisorHit } from '@/lib/campaignHomeSearchHits'
|
|
import { isUnrestrictedCampaignRole } from '@/lib/campaignRoles'
|
|
import {
|
|
compareHomeSearchNameRelevance,
|
|
normalizeHomeSearchName,
|
|
} from '@/lib/homeSearchMunicipalityMatch'
|
|
import { matchesNormalizedAtWordStart } from '@/lib/wordStartFilter'
|
|
import type { CampaignUser } from '@/payload-types'
|
|
import { municipalityIdsByAdvisorIds } from '@/utilities/advisorData'
|
|
|
|
export const searchHomeAdvisors = async (
|
|
payload: Payload,
|
|
user: CampaignUser,
|
|
rawQuery: string,
|
|
): Promise<HomeSearchAdvisorHit[]> => {
|
|
if (!isUnrestrictedCampaignRole(user.role)) {
|
|
return []
|
|
}
|
|
|
|
const query = normalizeHomeSearchRaw(rawQuery)
|
|
if (!homeSearchQueryIsActive(query)) {
|
|
return []
|
|
}
|
|
|
|
const normalizedQuery = normalizeHomeSearchName(query)
|
|
|
|
// Intentional admin bypass — unrestricted staff gate already ran in the route.
|
|
const result = await payload.find({
|
|
collection: 'campaignUser',
|
|
where: { role: { equals: 'advisor' } },
|
|
depth: 0,
|
|
limit: 0,
|
|
pagination: false,
|
|
sort: 'name',
|
|
select: { name: true },
|
|
user,
|
|
overrideAccess: false,
|
|
})
|
|
|
|
const matched = result.docs
|
|
.map((doc) => {
|
|
const normalizedName = normalizeHomeSearchName(doc.name)
|
|
if (!matchesNormalizedAtWordStart(normalizedName, normalizedQuery)) {
|
|
return null
|
|
}
|
|
return { id: doc.id, name: doc.name, normalizedName }
|
|
})
|
|
.filter((row): row is NonNullable<typeof row> => row !== null)
|
|
|
|
if (matched.length === 0) {
|
|
return []
|
|
}
|
|
|
|
const advisorIDs = matched.map((row) => row.id)
|
|
const municipalityIdsByAdvisor = await municipalityIdsByAdvisorIds(payload, advisorIDs)
|
|
|
|
return matched
|
|
.map((row) => ({
|
|
normalizedName: row.normalizedName,
|
|
hit: {
|
|
id: row.id,
|
|
name: row.name,
|
|
municipalityCount: municipalityIdsByAdvisor.get(row.id)?.length ?? 0,
|
|
},
|
|
}))
|
|
.sort((left, right) =>
|
|
compareHomeSearchNameRelevance(
|
|
{
|
|
normalizedName: left.normalizedName,
|
|
tieBreakDesc: left.hit.municipalityCount,
|
|
},
|
|
{
|
|
normalizedName: right.normalizedName,
|
|
tieBreakDesc: right.hit.municipalityCount,
|
|
},
|
|
normalizedQuery,
|
|
),
|
|
)
|
|
.map((row) => row.hit)
|
|
}
|