67 lines
2.3 KiB
TypeScript
67 lines
2.3 KiB
TypeScript
import {app} from "@/firebase";
|
|
import {Assignment} from "@/interfaces/results";
|
|
import {collection, getDocs, getFirestore, query, where} from "firebase/firestore";
|
|
import {getAllAssignersByCorporate} from "@/utils/groups.be";
|
|
|
|
const db = getFirestore(app);
|
|
|
|
export const getAssignmentsByAssigner = async (id: string, startDate?: Date, endDate?: Date) => {
|
|
const {docs} = await getDocs(
|
|
query(
|
|
collection(db, "assignments"),
|
|
...[
|
|
where("assigner", "==", id),
|
|
...(startDate ? [where("startDate", ">=", startDate.toISOString())] : []),
|
|
// firebase doesnt accept compound queries so we have to filter on the server
|
|
// ...endDate ? [where("endDate", "<=", endDate)] : [],
|
|
],
|
|
),
|
|
);
|
|
if (endDate) {
|
|
return docs.map((x) => ({...(x.data() as Assignment), id: x.id})).filter((x) => new Date(x.endDate) <= endDate) as Assignment[];
|
|
}
|
|
return docs.map((x) => ({...x.data(), id: x.id})) as Assignment[];
|
|
};
|
|
export const getAssignments = async () => {
|
|
const {docs} = await getDocs(collection(db, "assignments"));
|
|
return docs.map((x) => ({...x.data(), id: x.id})) as Assignment[];
|
|
};
|
|
|
|
export const getAssignmentsByAssignerBetweenDates = async (id: string, startDate: Date, endDate: Date) => {
|
|
const {docs} = await getDocs(query(collection(db, "assignments"), where("assigner", "==", id)));
|
|
return docs.map((x) => ({...x.data(), id: x.id})) as Assignment[];
|
|
};
|
|
|
|
export const getAssignmentsByAssigners = async (ids: string[], startDate?: Date, endDate?: Date) => {
|
|
return (await Promise.all(ids.map((id) => getAssignmentsByAssigner(id, startDate, endDate)))).flat();
|
|
};
|
|
|
|
export const getAssignmentsForCorporates = async (idsList: string[], startDate?: Date, endDate?: Date) => {
|
|
const assigners = await Promise.all(
|
|
idsList.map(async (id) => {
|
|
const assigners = await getAllAssignersByCorporate(id);
|
|
return {
|
|
corporateId: id,
|
|
assigners,
|
|
};
|
|
}),
|
|
);
|
|
|
|
const assignments = await Promise.all(
|
|
assigners.map(async (data) => {
|
|
try {
|
|
const assigners = [...new Set([...data.assigners, data.corporateId])];
|
|
const assignments = await getAssignmentsByAssigners(assigners, startDate, endDate);
|
|
return assignments.map((assignment) => ({
|
|
...assignment,
|
|
corporateId: data.corporateId,
|
|
}));
|
|
} catch (err) {
|
|
console.error(err);
|
|
return [];
|
|
}
|
|
}),
|
|
);
|
|
|
|
return assignments.flat();
|
|
} |