Skip to content

Commit

Permalink
Implementing polis filter
Browse files Browse the repository at this point in the history
  • Loading branch information
avenmia committed Mar 10, 2024
1 parent 0447677 commit 72f8e64
Showing 1 changed file with 47 additions and 26 deletions.
73 changes: 47 additions & 26 deletions src/server/api/routers/polis.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { z } from "zod";

import { createTRPCRouter, publicProcedure } from "../trpc";
import { PolisSurveys, SurveyRules } from "@prisma/client";

export const polisRouter = createTRPCRouter({
getSurveys: publicProcedure.query(async ({ ctx }) => {
Expand All @@ -10,37 +11,57 @@ export const polisRouter = createTRPCRouter({
}
const { id: userId } = ctx.session.user;

// const userSurveyAnswers = ctx.prisma.userSurveyAnswers.findMany({
// where: { userId: userId },
// select: {
// questionId: true,
// answerId: true,
// },
// });

// const allSurveys = ctx.prisma.polisSurveys.findMany({
// select: {
// id: true,
// title: true,
// description: true,
// }
// });

// const surveyRules = ctx.prisma.surveyRules.findMany({
// select: {
// id: true,
// surveyId: true,
// questionId: true,
// requiredAnswerId: true
// }
// });

return ctx.prisma.polisSurveys.findMany({
const userSurveyAnswers = await ctx.prisma.userSurveyAnswers.findMany({
where: { userId: userId },
select: {
questionId: true,
answerId: true,
},
});

const allSurveys: PolisSurveys[] = await ctx.prisma.polisSurveys.findMany({
select: {
id: true,
title: true,
description: true,
},
});

const surveyRules: SurveyRules[] = await ctx.prisma.surveyRules.findMany({
select: {
id: true,
surveyId: true,
questionId: true,
requiredAnswerId: true,
},
});

const surveysWithRules = new Set(surveyRules.map((rule) => rule.surveyId));

const filteredSurveys: PolisSurveys[] = allSurveys.filter(
(survey) => !surveysWithRules.has(survey.id)
);

surveyRules.map((rule) => {
const surveyId = rule.surveyId;
const questionId = rule.questionId;
const requiredAnswerId = rule.requiredAnswerId;

// Returns all the answers for a certain question
const userAnswer = userSurveyAnswers.find(
(answer) => answer.questionId === questionId
);

if (userAnswer && userAnswer.answerId === requiredAnswerId) {
const filteredSurvey = allSurveys.find(
(survey) => survey.id === surveyId
);
if (filteredSurvey !== undefined) {
filteredSurveys.push(filteredSurvey);
}
}
});

return filteredSurveys;
}),
});

0 comments on commit 72f8e64

Please sign in to comment.