Compare commits

..

14 Commits

11 changed files with 381 additions and 64 deletions

View File

@ -98,9 +98,16 @@ func msgCurrentState(survey *Survey) (msg WSMessage) {
Action: "pause",
}
} else {
var correction map[string]int
if survey.Corrected {
correction = getCorrectionString(*survey.Direct)
}
msg = WSMessage{
Action: "new_question",
QuestionId: survey.Direct,
Action: "new_question",
QuestionId: survey.Direct,
Corrected: survey.Corrected,
Corrections: correction,
}
}
return
@ -146,13 +153,15 @@ func WSWriteAll(message WSMessage) {
}
type WSMessage struct {
Action string `json:"action"`
SurveyId *int64 `json:"survey,omitempty"`
QuestionId *int64 `json:"question,omitempty"`
Stats map[string]interface{} `json:"stats,omitempty"`
UserId *int64 `json:"user,omitempty"`
Response string `json:"value,omitempty"`
Timer uint `json:"timer,omitempty"`
Action string `json:"action"`
SurveyId *int64 `json:"survey,omitempty"`
QuestionId *int64 `json:"question,omitempty"`
Stats map[string]interface{} `json:"stats,omitempty"`
UserId *int64 `json:"user,omitempty"`
Response string `json:"value,omitempty"`
Corrected bool `json:"corrected,omitempty"`
Corrections map[string]int `json:"corrections,omitempty"`
Timer uint `json:"timer,omitempty"`
}
func (s *Survey) WSWriteAll(message WSMessage) {
@ -229,6 +238,25 @@ loopadmin:
log.Println(u.Login, "admin disconnected")
}
func getCorrectionString(qid int64) (ret map[string]int) {
q, err := getQuestion(int(qid))
if err != nil {
return
}
cts, err := q.GetCorrectionTemplates()
if err != nil {
return
}
ret = map[string]int{}
for _, ct := range cts {
ret[ct.RegExp] = ct.Score
}
return
}
func SurveyWSAdmin(c *gin.Context) {
u := c.MustGet("LoggedUser").(*User)
survey := c.MustGet("survey").(*Survey)
@ -274,15 +302,29 @@ func SurveyWSAdmin(c *gin.Context) {
if *survey.Direct != 0 {
var z int64 = 0
survey.Direct = &z
survey.Corrected = false
survey.Update()
}
go func() {
go func(corrected bool) {
time.Sleep(time.Duration(OffsetQuestionTimer+v.Timer) * time.Millisecond)
survey.WSWriteAll(WSMessage{Action: "pause"})
WSAdminWriteAll(WSMessage{Action: "pause", SurveyId: &survey.Id})
}()
if corrected {
survey.Corrected = v.Corrected
survey.Update()
survey.WSWriteAll(WSMessage{Action: "new_question", QuestionId: v.QuestionId, Corrected: true, Corrections: getCorrectionString(*v.QuestionId)})
} else {
survey.WSWriteAll(WSMessage{Action: "pause"})
WSAdminWriteAll(WSMessage{Action: "pause", SurveyId: &survey.Id})
}
}(v.Corrected)
v.Corrected = false
} else {
survey.Direct = v.QuestionId
survey.Corrected = v.Corrected
if v.Corrected {
v.Corrections = getCorrectionString(*v.QuestionId)
}
}
_, err = survey.Update()
if err != nil {

50
help.go
View File

@ -1,8 +1,10 @@
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
@ -10,7 +12,7 @@ import (
func declareAPIAdminHelpRoutes(router *gin.RouterGroup) {
router.GET("/help", func(c *gin.Context) {
nhs, err := getNeedHelps()
nhs, err := getNeedHelps("WHERE date_treated IS NULL")
if err != nil {
log.Println("Unable to getNeedHelps:", err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "An error occurs during need helps retrieval. Please retry."})
@ -19,6 +21,29 @@ func declareAPIAdminHelpRoutes(router *gin.RouterGroup) {
c.JSON(http.StatusOK, nhs)
})
needhelpsRoutes := router.Group("/help/:hid")
needhelpsRoutes.Use(needHelpHandler)
needhelpsRoutes.PUT("", func(c *gin.Context) {
current := c.MustGet("needhelp").(*NeedHelp)
var new NeedHelp
if err := c.ShouldBindJSON(&new); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": err.Error()})
return
}
new.Id = current.Id
if err := new.Update(); err != nil {
log.Println("Unable to Update needhelp:", err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("An error occurs during needhelp entry updation: %s", err.Error())})
return
} else {
c.JSON(http.StatusOK, new)
}
})
}
func declareAPIAuthHelpRoutes(router *gin.RouterGroup) {
@ -36,6 +61,19 @@ func declareAPIAuthHelpRoutes(router *gin.RouterGroup) {
})
}
func needHelpHandler(c *gin.Context) {
if hid, err := strconv.Atoi(string(c.Param("hid"))); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": "Bad need help identifier."})
return
} else if nh, err := getNeedHelp(hid); err != nil {
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"errmsg": "Need help entry not found."})
return
} else {
c.Set("needhelp", nh)
c.Next()
}
}
type NeedHelp struct {
Id int64 `json:"id"`
IdUser int64 `json:"id_user"`
@ -44,8 +82,8 @@ type NeedHelp struct {
DateTreated *time.Time `json:"treated,omitempty"`
}
func getNeedHelps() (nh []NeedHelp, err error) {
if rows, errr := DBQuery("SELECT id_need_help, id_user, date, comment, date_treated FROM user_need_help"); errr != nil {
func getNeedHelps(cond string) (nh []NeedHelp, err error) {
if rows, errr := DBQuery("SELECT id_need_help, id_user, date, comment, date_treated FROM user_need_help " + cond); errr != nil {
return nil, errr
} else {
defer rows.Close()
@ -65,6 +103,12 @@ func getNeedHelps() (nh []NeedHelp, err error) {
}
}
func getNeedHelp(id int) (n *NeedHelp, err error) {
n = new(NeedHelp)
err = DBQueryRow("SELECT id_need_help, id_user, date, comment, date_treated FROM user_need_help WHERE id_need_help=?", id).Scan(&n.Id, &n.IdUser, &n.Date, &n.Comment, &n.DateTreated)
return
}
func (u *User) NewNeedHelp() (NeedHelp, error) {
if res, err := DBExec("INSERT INTO user_need_help (id_user, comment) VALUES (?, ?)", u.Id, ""); err != nil {
return NeedHelp{}, err

View File

@ -1,6 +1,8 @@
package main
import (
"database/sql"
"errors"
"log"
"net/http"
"strconv"
@ -27,7 +29,7 @@ func declareAPIAuthResponsesRoutes(router *gin.RouterGroup) {
}
var responses []Response
if err := c.ShouldBindJSON(responses); err != nil {
if err := c.ShouldBindJSON(&responses); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": err.Error()})
return
}
@ -45,7 +47,7 @@ func declareAPIAuthResponsesRoutes(router *gin.RouterGroup) {
}
for _, response := range responses {
if !uauth.IsAdmin && !s.Shown && (s.Direct == nil || *s.Direct != response.IdQuestion) {
if !uauth.IsAdmin && !s.Shown && (s.Corrected || s.Direct == nil || *s.Direct != response.IdQuestion) {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"errmsg": "Cette question n'est pas disponible"})
return
} else if len(response.Answer) > 0 {
@ -142,7 +144,7 @@ func declareAPIAuthQuestionResponsesRoutes(router *gin.RouterGroup) {
q := c.MustGet("question").(*Question)
res, err := q.GetMyResponse(u, false)
if err != nil {
if err != nil && !errors.Is(err, sql.ErrNoRows) {
log.Printf("Unable to GetMyResponse(uid=%d;qid=%d;false): %s", u.Id, q.Id, err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "An error occurs during response retrieval."})
return

View File

@ -31,34 +31,41 @@
return req;
}
let req_proposals = null;
export let proposals = null;
let req_responses = null;
let mean = null;
if (question.kind == "int") {
req_responses = question.getResponses();
req_responses.then((responses) => {
const proposal_idx = { };
for (const res of responses) {
if (proposal_idx[res.value]) {
data.datasets[0].values[proposal_idx[res.value]] += 1;
} else {
data.labels.push(res.value);
data.datasets[0].values.push(1);
proposal_idx[res.value] = new String(data.labels.length - 1);
}
}
});
} else {
req_proposals = refreshProposals();
}
let data = {
export let data = {
labels: [],
datasets: [
{
values: []
}
]
};
};
if (!proposals) {
if (question.kind == "int") {
req_responses = question.getResponses();
req_responses.then((responses) => {
const values = [];
const proposal_idx = { };
for (const res of responses) {
if (proposal_idx[res.value]) {
data.datasets[0].values[proposal_idx[res.value]] += 1;
values.push(Number(res.value));
} else {
data.labels.push(res.value);
data.datasets[0].values.push(1);
proposal_idx[res.value] = new String(data.labels.length - 1);
}
}
mean = Math.trunc(values.reduce((p, e) => p + e) / values.length*10)/10;
});
} else {
req_proposals = refreshProposals();
}
}
</script>
<div class="{className}">
@ -74,7 +81,16 @@
<span>Récupération des réponses&hellip;</span>
</div>
{:then}
<Chart data={data} type="pie" maxSlices="9" />
{#if mean !== null}
<div class="text-center">
Moyenne représentative&nbsp;: <strong>{mean}</strong>
</div>
{/if}
{#if question.kind === "mcq"}
<Chart data={data} type="bar" />
{:else}
<Chart data={data} type="pie" maxSlices="9" />
{/if}
{/await}
{/await}
</div>

View File

@ -19,6 +19,35 @@
templates = templates;
}
function genTemplates() {
question.getProposals().then((proposals) => {
let i = 0;
for (const p of proposals) {
// Search proposal in templates
let found = false;
for (const tpl of templates) {
if (tpl.regexp.indexOf(p.id.toString()) !== -1) {
found = true;
break;
}
}
if (!found) {
const ct = new CorrectionTemplate()
ct.id_question = question.id;
ct.regexp = p.id.toString();
ct.label = String.fromCharCode(97 + i);
ct.save().then((ct) => {
templates.push(ct);
templates = templates;
});
}
i++;
}
})
}
function delTemplate(tpl) {
tpl.delete().then(() => {
const idx = templates.findIndex((e) => e.id === tpl.id);
@ -109,4 +138,13 @@
>
<i class="bi bi-plus"></i> Ajouter un template
</button>
{#if question.kind == "mcq" || question.kind == "ucq"}
<button
type="button"
class="btn btn-outline-info me-1"
on:click={genTemplates}
>
<i class="bi bi-magic"></i> Générer les templates
</button>
{/if}
</div>

View File

@ -14,6 +14,7 @@
export let qid;
export let response_history = null;
export let readonly = false;
export let corrections = {};
export let survey = null;
export let value = "";
@ -91,6 +92,8 @@
kind={question.kind}
{proposals}
readonly
live={survey.direct !== null}
{corrections}
bind:value={value}
on:change={() => { dispatch("change"); }}
/>
@ -108,6 +111,8 @@
kind={question.kind}
{proposals}
{readonly}
live={survey.direct !== null}
{corrections}
bind:value={value}
on:change={() => { dispatch("change"); }}
/>
@ -132,7 +137,7 @@
></textarea>
{/if}
{#if survey && survey.corrected}
{#if survey && survey.corrected && response_history}
<ResponseCorrected
response={response_history}
{survey}

View File

@ -5,9 +5,11 @@
export let edit = false;
export let proposals = [];
export let live = false;
export let kind = 'mcq';
export let prefixid = '';
export let readonly = false;
export let corrections = {};
export let id_question = 0;
export let value;
@ -28,12 +30,14 @@
}
</script>
<div class:d-flex={live} class:justify-content-around={live}>
{#each proposals as proposal, pid (proposal.id)}
<div class="form-check">
{#if kind == 'mcq'}
<input
type="checkbox"
class="form-check-input"
class:btn-check={live}
class:form-check-input={!live}
disabled={readonly}
name={prefixid + 'proposal' + proposal.id_question}
id={prefixid + 'p' + proposal.id}
@ -44,7 +48,8 @@
{:else}
<input
type="radio"
class="form-check-input"
class:btn-check={live}
class:form-check-input={!live}
disabled={readonly}
name={prefixid + 'proposal' + proposal.id_question}
id={prefixid + 'p' + proposal.id}
@ -84,7 +89,14 @@
</form>
{:else}
<label
class="form-check-label"
class:form-check-label={!live}
class:btn={live}
class:btn-lg={live}
class:btn-primary={live && !corrections && value.indexOf(proposal.id.toString()) != -1}
class:btn-outline-primary={live && !corrections && value.indexOf(proposal.id.toString()) == -1}
class:btn-success={live && corrections && corrections[proposal.id] == 0}
class:btn-outline-warning={live && corrections && corrections[proposal.id] != 0 && corrections[proposal.id] != -100}
class:btn-outline-danger={live && corrections && corrections[proposal.id] == -100}
for={prefixid + 'p' + proposal.id}
>
{proposal.label}
@ -92,6 +104,7 @@
{/if}
</div>
{/each}
</div>
{#if edit}
{#if kind == 'mcq'}
<input

View File

@ -51,10 +51,51 @@ export async function getUserScore(uid, survey) {
}
}
export class UserNeedingHelp {
constructor(res) {
if (res) {
this.update(res);
}
}
update({ id, id_user, date, comment, treated }) {
this.id = id;
this.id_user = id_user;
this.date = new Date(date);
this.comment = comment;
if (treated) {
this.treated = new Date(treated);
} else {
this.treated = null;
}
}
mark_treated() {
this.treated = new Date();
}
async save() {
const res = await fetch(this.id?`api/help/${this.id}`:'api/help', {
method: this.id?'PUT':'POST',
headers: {'Accept': 'application/json'},
body: JSON.stringify(this),
});
if (res.status == 200) {
const data = await res.json()
this.update(data);
return data;
} else {
throw new Error((await res.json()).errmsg);
}
}
}
export async function getUserNeedingHelp() {
const res = await fetch(`api/help`, {headers: {'Accept': 'application/json'}})
if (res.status == 200) {
return await res.json();
return (await res.json()).map((nh) => {
return new UserNeedingHelp(nh)
});
} else {
throw new Error((await res.json()).errmsg);
}

View File

@ -1,10 +1,24 @@
<script lang="ts">
import { user } from '../stores/user';
import { getUser, getUserNeedingHelp } from '../lib/users';
import DateFormat from '../components/DateFormat.svelte';
import SurveyList from '../components/SurveyList.svelte';
import ValidateSubmissions from '../components/ValidateSubmissions.svelte';
let direct = null;
let users_needing_help = [];
$: if ($user && $user.is_admin) {
users_needing_help = getUserNeedingHelp();
}
async function mark_needhelp_treated(unh) {
unh.mark_treated();
unh.save().then(() => {
users_needing_help = getUserNeedingHelp();
});
}
</script>
<div class="card bg-light">
@ -29,7 +43,7 @@
{#if $user.is_admin}
<p class="lead">Demande d'aide&nbsp;:</p>
{#await getUserNeedingHelp()}
{#await users_needing_help}
<span class="spinner-border spinner-border" role="status" aria-hidden="true"></span>
{:then nhs}
<ul style="columns: 2">
@ -40,7 +54,14 @@
{:then u}
<a href="users/{u.id}">{u.login}</a>
{/await}
({user.date})
(<DateFormat date={user.date} dateStyle="medium" timeStyle="medium" />)
<button
type="button"
class="btn btn-sm btn-info"
on:click={e => {mark_needhelp_treated(user)}}
>
<i class="bi bi-check" title="Marquer la demande d'aide comme traîtée"></i>
</button>
</li>
{/each}
</ul>

View File

@ -11,6 +11,7 @@
<script>
import { user } from '../../../stores/user';
import CorrectionPieChart from '../../../components/CorrectionPieChart.svelte';
import SurveyAdmin from '../../../components/SurveyAdmin.svelte';
import SurveyBadge from '../../../components/SurveyBadge.svelte';
import { getSurvey } from '../../../lib/surveys';
@ -43,7 +44,8 @@
let wsstats = null;
let current_question = null;
let responses = {};
let timer = 20000;
let corrected = false;
let timer = 20;
let timer_end = null;
let timer_remain = 0;
let timer_cancel = null;
@ -83,6 +85,52 @@
responsesbyid = tmp;
}
let graph_data = {labels:[]};
async function reset_graph_data(questionid) {
if (questionid) {
const labels = [];
const flabels = [];
let question = null;
for (const q of await req_questions) {
if (q.id == current_question) {
question = q;
}
}
if (question) {
for (const p of await question.getProposals()) {
flabels.push(p.id.toString());
labels.push(p.label);
}
}
graph_data = {
labels,
flabels,
datasets: [
{
values: labels.map(() => 0)
}
]
}
}
if (current_question && responses[current_question] && graph_data.labels.length != 0) {
const values = graph_data.datasets[0].values.map(() => 0);
for (const u in responses[current_question]) {
const res = responses[current_question][u];
for (const r of res.split(',')) {
let idx = graph_data.flabels.indexOf(r);
values[idx] += 1;
}
}
graph_data.datasets[0].values = values;
}
}
let asks = [];
function wsconnect() {
if (ws !== null) return;
@ -98,7 +146,7 @@
ws.addEventListener("close", (e) => {
ws_up = false;
console.log('Socket is closed. Reconnect will be attempted in 1 second.', e);
console.log('Socket is closed. Reconnect will be attempted in 1 second.');
ws = null;
updateSurvey();
setTimeout(function() {
@ -106,10 +154,6 @@
}, 1500);
});
ws.onerror((evt) => {
console.log('onerror', evt)
})
ws.addEventListener("error", (err) => {
ws_up = false;
console.log('Socket closed due to error.', err);
@ -118,7 +162,6 @@
ws.addEventListener("message", (message) => {
const data = JSON.parse(message.data);
console.log(data);
if (data.action && data.action == "new_question") {
current_question = data.question;
if (timer_cancel) {
@ -131,11 +174,14 @@
} else {
timer_end = null;
}
reset_graph_data(data.question);
} else if (data.action && data.action == "stats") {
wsstats = data.stats;
} else if (data.action && data.action == "new_response") {
if (!responses[data.question]) responses[data.question] = {};
if (!responses[data.question]) responses[data.question] = { };
responses[data.question][data.user] = data.value;
reset_graph_data();
} else if (data.action && data.action == "new_ask") {
asks.push({"id": data.question, "content": data.value, "userid": data.user});
asks = asks;
@ -221,7 +267,7 @@
disabled
value={timer_remain}
>
<span class="input-group-text">ms</span>
<span class="input-group-text">s</span>
</div>
{:else}
<div class="input-group input-group-sm float-end" style="max-width: 150px;">
@ -231,7 +277,7 @@
bind:value={timer}
placeholder="Valeur du timer"
>
<span class="input-group-text">ms</span>
<span class="input-group-text">s</span>
</div>
{/if}
<button
@ -253,9 +299,20 @@
class="btn btn-sm btn-primary"
disabled={!current_question || !ws_up}
on:click={() => { ws.send('{"action":"pause"}')} }
title="Passer sur une scène sans question"
>
<i class="bi bi-pause-fill"></i>
</button>
<button
type="button"
class="btn btn-sm"
class:btn-outline-success={!corrected}
class:btn-success={corrected}
on:click={() => { corrected = !corrected } }
title="La prochaine question est affichée corrigée"
>
<i class="bi bi-eye"></i>
</button>
</th>
</tr>
</thead>
@ -282,9 +339,11 @@
<td>
<button
type="button"
class="btn btn-sm btn-primary"
class="btn btn-sm"
class:btn-primary={!corrected}
class:btn-success={corrected}
disabled={question.id === current_question || !ws_up}
on:click={() => { ws.send('{"action":"new_question", "timer": 0, "question":' + question.id + '}')} }
on:click={() => { ws.send('{"action":"new_question", "corrected": ' + corrected + ', "timer": 0, "question":' + question.id + '}')} }
>
<i class="bi bi-play-fill"></i>
</button>
@ -292,10 +351,18 @@
type="button"
class="btn btn-sm btn-danger"
disabled={question.id === current_question || !ws_up}
on:click={() => { ws.send('{"action":"new_question", "timer": ' + timer + ',"question":' + question.id + '}')} }
on:click={() => { ws.send('{"action":"new_question", "corrected": ' + corrected + ', "timer": ' + timer * 1000 + ',"question":' + question.id + '}')} }
>
<i class="bi bi-stopwatch-fill"></i>
</button>
<a
href="/surveys/{survey.id}/responses/{question.id}"
target="_blank"
type="button"
class="btn btn-sm btn-success"
>
<i class="bi bi-files"></i>
</a>
</td>
</tr>
{/each}
@ -401,6 +468,17 @@
<span>Chargement des propositions &hellip;</span>
</div>
{:then proposals}
{#if current_question == question.id}
<CorrectionPieChart
{question}
{proposals}
data={graph_data}
/>
{:else}
<CorrectionPieChart
{question}
/>
{/if}
<div class="card mb-4">
<table class="table table-sm table-striped table-hover mb-0">
<tbody>
@ -428,6 +506,17 @@
<span>Chargement des propositions &hellip;</span>
</div>
{:then proposals}
{#if current_question == question.id}
<CorrectionPieChart
{question}
{proposals}
data={graph_data}
/>
{:else}
<CorrectionPieChart
{question}
/>
{/if}
<div class="card mb-4">
<table class="table table-sm table-striped table-hover mb-0">
<tbody>

View File

@ -89,6 +89,8 @@
console.log(data);
if (data.action && data.action == "new_question") {
show_question = data.question;
survey.corrected = data.corrected;
corrections = data.corrections;
if (timer_cancel) {
clearInterval(timer_cancel);
timer_cancel = null;
@ -155,9 +157,11 @@
});
});
}
let corrections = {};
</script>
{#await surveyP then survey}
{#await surveyP then unused}
{#if $user && $user.is_admin}
<a href="surveys/{survey.id}/admin" class="btn btn-primary ms-1 float-end" title="Aller à l'interface d'administration"><i class="bi bi-pencil"></i></a>
<a href="surveys/{survey.id}/responses" class="btn btn-success ms-1 float-end" title="Voir les réponses"><i class="bi bi-files"></i></a>
@ -185,8 +189,10 @@
</div>
{:then question}
<QuestionForm
{survey}
{question}
readonly={timer >= 100}
readonly={timer >= 100 || survey.corrected}
{corrections}
bind:value={value}
on:change={sendValue}
>
@ -200,7 +206,7 @@
<button
class="btn btn-primary"
>
Soumettre la réponse
Soumettre cette réponse
</button>
{/if}
{/await}
@ -226,7 +232,7 @@
class="form-control"
bind:value={myQuestion}
autofocus
placeholder="Remarques, soucis, choses pas claires? Demandez!"
placeholder="Remarques, soucis, choses pas claires? Levez la main ou écrivez ici!"
></textarea>
<button
class="d-sm-none btn btn-primary"