1
0
mirror of https://gitlab.com/comunic/comunicapiv2 synced 2025-02-20 16:02:40 +00:00
comunicapiv2/src/helpers/SurveyHelper.ts

121 lines
2.4 KiB
TypeScript
Raw Normal View History

import { Survey, SurveyChoice } from "../entities/Survey";
import { DatabaseHelper } from "./DatabaseHelper";
/**
* Survey helper
*
* @author Pierre HUBERT
*/
/**
* Survey info table
*/
const SURVEY_INFO_TABLE = "sondage";
/**
* Survey choices table
*/
const SURVEY_CHOICES_TABLE = "sondage_choix";
/**
* Survey responses table
*/
const SURVEY_RESPONSE_TABLE = "sondage_reponse";
/**
* Survey helper
*/
export class SurveyHelper {
/**
* Get information about the survey of a post
*
* @param postID The ID of the associated post
*/
public static async GetInfo(postID: number) : Promise<Survey> {
// Get main information about the survey
const surveyRow = await DatabaseHelper.QueryRow({
table: SURVEY_INFO_TABLE,
where: {
ID_texte: postID
}
});
if(surveyRow == null)
throw new Error("Could not find survey for post " + postID + " !");
const survey = this.DBToSurveyInfo(surveyRow);
// Get the choices of the survey
const choices = await DatabaseHelper.Query({
table: SURVEY_CHOICES_TABLE,
tableAlias: "c",
joins: [
{
table: SURVEY_RESPONSE_TABLE,
tableAlias: "r",
condition: "c.ID = r.ID_sondage_choix"
}
],
where: {
"c.ID_sondage": survey.id
},
groupBy: "c.ID",
fields: ["c.*", "COUNT(*) AS count_choice"]
});
choices.forEach((row) => survey.choices.push(this.DBToSurveyChoice(row)));
return survey;
}
/**
* Get the choice of a user for a survey
*
* @param surveyID Target survey
* @param userID Target user
*/
public static async GetUserChoice(surveyID: number, userID: number) {
const result = await DatabaseHelper.QueryRow({
table: SURVEY_RESPONSE_TABLE,
where: {
ID_utilisateurs: userID,
ID_sondage: surveyID
}
});
return result == null ? 0 /* no response yet */ : result.ID_sondage_choix;
}
/**
* Turn a database entry into a survey object
*
* @param row The row to transform
*/
private static DBToSurveyInfo(row: any) : Survey {
return new Survey({
id: row.ID,
userID: row.ID_utilisateurs,
postID: row.ID_texte,
timeCreate: new Date(row.date_creation).getTime()/1000,
question: row.question,
choices: []
});
}
/**
* Turn a database entry into a survey choice
*
* @param row The row to transform
*/
private static DBToSurveyChoice(row: any) : SurveyChoice {
return {
id: row.ID,
name: row.Choix,
count: row.count_choice
};
}
}