Generate /admin/questions using flask template

This commit is contained in:
Thomas Rubini 2023-03-20 15:51:37 +01:00
parent 30d903db38
commit 1220e570fb
No known key found for this signature in database
GPG Key ID: C7D287C8C1CAC373
3 changed files with 69 additions and 91 deletions

View File

@ -1,4 +1,5 @@
import flask import flask
from sqlalchemy import select, or_
from truthinquiry.ext.database.models import * from truthinquiry.ext.database.models import *
from truthinquiry.ext.database.fsa import db from truthinquiry.ext.database.fsa import db
@ -33,7 +34,29 @@ def npc(npc_id):
@routes_admin.route("/questions") @routes_admin.route("/questions")
def questions(): def questions():
return flask.render_template("admin/questions.html", langs=["FR", "EN"]) lang = "FR"
results = db.session.execute(
select(QuestionType, Text)
.select_from(QuestionType)
.join(Locale)
.join(Text, isouter=True)
.filter(or_(Text.LANG==None, Text.LANG==lang))
.order_by(QuestionType.QUESTION_TYPE_ID)
)
data = []
old_question_type_id = None
for question_type, locale in results:
if question_type.QUESTION_TYPE_ID != old_question_type_id:
old_question_type_id = question_type.QUESTION_TYPE_ID
data.append({"questions": []})
if locale:
data[-1]["questions"].append({"text": locale.TEXT})
return flask.render_template("admin/questions.html", questions=data, langs=["FR", "EN"])
@routes_admin.route("/places") @routes_admin.route("/places")
def places(): def places():

View File

@ -7,41 +7,12 @@ from truthinquiry.ext.database.fsa import db
routes_api_admin = flask.Blueprint("api_admin", __name__) routes_api_admin = flask.Blueprint("api_admin", __name__)
@routes_api_admin.route("/getQuestions", methods=["GET", "POST"])
def get_questions():
lang = flask.request.values.get("lang")
if lang is None:
return {"error": 1, "msg": "lang not set"}
results = db.session.execute(
select(QuestionType, Text)
.select_from(QuestionType)
.join(Locale)
.join(Text, isouter=True)
.filter(or_(Text.LANG==None, Text.LANG==lang))
.order_by(QuestionType.QUESTION_TYPE_ID)
)
data = []
old_question_type_id = None
for question_type, locale in results:
if question_type.QUESTION_TYPE_ID != old_question_type_id:
old_question_type_id = question_type.QUESTION_TYPE_ID
data.append([])
if locale:
data[-1].append({"text": locale.TEXT})
return data
@routes_api_admin.route("/setQuestions", methods=["GET", "POST"]) @routes_api_admin.route("/setQuestions", methods=["GET", "POST"])
def set_questions(): def set_questions():
if not flask.request.json: if not flask.request.json:
return {"error": 1, "msg": "no json set"} return {"error": 1, "msg": "no json set"}
lang = flask.request.json["lang"] lang = flask.request.json["lang"]
question_types = flask.request.json["questions"] all_questions = flask.request.json["questions"]
# Delete old questions # Delete old questions
text_ids_requ = ( text_ids_requ = (
@ -63,8 +34,8 @@ def set_questions():
# set new questions # set new questions
text_obs = [] text_obs = []
for question_lid, questions in zip(question_lids, question_types): for question_lid, questionType in zip(question_lids, all_questions):
for question in questions: for question in questionType["questions"]:
text_obs.append(Text(None, question_lid, lang, question["text"])) text_obs.append(Text(None, question_lid, lang, question["text"]))
db.session.add_all(text_obs) db.session.add_all(text_obs)

View File

@ -1,24 +1,40 @@
<a href="/admin"> go Back </a> <br> <a href="/admin"> go Back </a> <br>
<select id="langs" onchange="langChangedEvent()"> <select id="langs" onchange="changeLang()">
{%for lang in langs%} {%for lang in langs%}
<option value="{{lang}}">{{lang}}</option> <option value="{{lang}}">{{lang}}</option>
{%endfor%} {%endfor%}
</select> </select>
<form id="questionsTag" action="javascript:void(0);"> <section id="allQuestions">
</form> {%for questionType in questions%}
<div class="questionType">
<section class="questionTypeContent">
{%for question in questionType["questions"]%}
<section class="question">
<input value="{{question['text']}}">
<button onclick="deleteEntry(this)">Delete question</button>
</section>
{%endfor%}
</section>
<button onclick="addEntry(this)">Add new</button>
</div>
{%endfor%}
</section>
<br>
<button onclick="saveForm()"> Save changes </button> <button onclick="saveForm()"> Save changes </button>
<style> <style>
.questionTypeTag{ .questionType{
border: thin solid red; border: thin solid red;
margin-top: 20px; margin-top: 20px;
} }
.questionTypeTag input{ .question input{
width: 100%; width: 100%;
margin: 10px;
} }
</style> </style>
@ -26,69 +42,37 @@
<script> <script>
let lang = null; function addEntry(button){
let questionTypeContent = button.parentNode.querySelector(".questionTypeContent");
let newQuestion = questionTypeContent.querySelector(".question").cloneNode(true);
newQuestion.id = "";
newQuestion.querySelector("input").value = "";
questionTypeContent.appendChild(newQuestion);
}
function deleteEntry(buttonNode){
let placeNode = buttonNode.parentNode;
placeNode.parentNode.removeChild(placeNode);
}
function saveForm(){ function saveForm(){
var formData = new FormData(questionsTag); let data = [];
for(let questionTypeNode of allQuestions.querySelectorAll(".questionType")){
let questionsJson = []; let questionsJson = [];
let questionTypeJson = {"questions": questionsJson};
data.push(questionTypeJson);
for(let questionTypeTag of questionsTag.querySelectorAll("fieldset")){ for(let questionNode of questionTypeNode.querySelectorAll("input")){
let questionTypeJson = []; questionsJson.push({"text": questionNode.value})
questionsJson.push(questionTypeJson);
for(let questionTag of questionTypeTag.children){
questionTypeJson.push({"text": questionTag.value})
} }
} }
if(lang!==null){ makeAPIRequest("admin/setQuestions", {"questions": data, "lang": "FR"}, {"content": "json"})
makeAPIRequest("admin/setQuestions", {"questions": questionsJson, "lang": lang}, {"content": "json"})
}
} }
let lastQueriedData = []; function changeLang(){
async function changeLang(newLang){
lang = null;
console.log("Changing language to "+newLang);
resp = await makeAPIRequest("admin/getQuestions", {"lang": newLang});
questionsTag.innerHTML = '';
for(let questionType of resp){
let questionTypeTag = document.createElement("fieldset")
questionTypeTag.className = 'questionTypeTag';
questionsTag.appendChild(questionTypeTag);
function addNewInput(value=""){
let questionTag = document.createElement("input");
questionTypeTag.appendChild(questionTag);
questionTag.value = value;
} }
for(let question of questionType){
addNewInput(question.text);
}
let addNewTag = document.createElement("input")
addNewTag.type = 'button'
addNewTag.value = "Add new";
addNewTag.onclick = () => addNewInput();
questionsTag.appendChild(addNewTag);
}
lang = newLang;
}
function langChangedEvent(){
changeLang(langs.value)
}
changeLang(langs.value);
</script> </script>