ENCOA-289

This commit is contained in:
Carlos-Mesquita
2024-12-24 11:52:34 +00:00
parent 8d7b47312e
commit bac2a08748
3 changed files with 74 additions and 7 deletions

View File

@@ -38,6 +38,9 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
await assignToEntity(req.body);
res.status(200).json({"ok": true});
break;
case 'getEntities':
res.status(200).json(await getEntities(req.body.emails))
break;
default:
res.status(400).json({ error: 'Invalid operation!' })
}
@@ -276,6 +279,36 @@ async function getIds(emails: string[]): Promise<Array<{ email: string; id: stri
}));
}
async function getEntities(emails: string[]): Promise<Array<{ email: string; entityLabels: string[] }>> {
const users = await db.collection('users')
.find({ email: { $in: emails } })
.project({ email: 1, entities: 1, _id: 0 })
.toArray();
const entityIds = [...new Set(
users.flatMap(user =>
(user.entities || []).map((entity: any) => entity.id)
)
)];
const entityRecords = await db.collection('entities')
.find({ id: { $in: entityIds } })
.project({ id: 1, label: 1, _id: 0 })
.toArray();
const entityMap = new Map(
entityRecords.map(entity => [entity.id, entity.label])
);
return users.map(user => ({
email: user.email,
entityLabels: (user.entities || [])
.map((entity: any) => entityMap.get(entity.id))
.filter((label: string): label is string => !!label)
}));
}
async function assignToEntity(body: any) {
const { ids, entity } = body;