From 8669e29c8f437e50ed51978c38ee73cf3dd2ae61 Mon Sep 17 00:00:00 2001 From: evarisk-kilyan Date: Thu, 13 Mar 2025 11:51:22 +0100 Subject: [PATCH 1/3] #2028 [Question] add: custom not slider percentage --- .../doc_surveydocument_odt.modules.php | 9 +- js/digiquali.min.js | 2 +- js/modules/question.js | 6 +- langs/fr_FR/digiquali.lang | 2 + lib/digiquali_answer.lib.php | 144 ++++++++++++------ view/control/control_card.php | 9 +- view/question/question_card.php | 39 ++++- view/survey/survey_card.php | 9 +- 8 files changed, 165 insertions(+), 55 deletions(-) diff --git a/core/modules/digiquali/digiqualidocuments/surveydocument/doc_surveydocument_odt.modules.php b/core/modules/digiquali/digiqualidocuments/surveydocument/doc_surveydocument_odt.modules.php index 034c17f1..ac30d240 100644 --- a/core/modules/digiquali/digiqualidocuments/surveydocument/doc_surveydocument_odt.modules.php +++ b/core/modules/digiquali/digiqualidocuments/surveydocument/doc_surveydocument_odt.modules.php @@ -303,7 +303,14 @@ public function write_file(SaturneDocuments $objectDocument, Translate $outputLa $percentQuestionCounter++; foreach ($object->lines as $line) { if ($line->fk_question === $questionLinked->id) { - $averagePercentageQuestions += $line->answer; + + $config = json_decode($questionLinked->json, true); + if (!isset($config['config'][$questionLinked->type]['isCursor']) || !empty($config['config'][$questionLinked->type]['isCursor'])) { + $averagePercentageQuestions += $line->answer; + } else { + $averagePercentageQuestions += (($line->answer - 1) / ($config['config'][$questionLinked->type]['step'] - 1)) * 100; + } + } } } diff --git a/js/digiquali.min.js b/js/digiquali.min.js index 82adff1b..a100fb3b 100644 --- a/js/digiquali.min.js +++ b/js/digiquali.min.js @@ -1 +1 @@ -window.digiquali||(window.digiquali={},window.digiquali.scriptsLoaded=!1),window.digiquali.scriptsLoaded||(window.digiquali.init=function(){window.digiquali.load_list_script()},window.digiquali.load_list_script=function(){if(!window.digiquali.scriptsLoaded){var t=void 0,e=void 0;for(t in window.digiquali)for(e in window.digiquali[t].init&&window.digiquali[t].init(),window.digiquali[t])window.digiquali[t]&&window.digiquali[t][e]&&window.digiquali[t][e].init&&window.digiquali[t][e].init();window.digiquali.scriptsLoaded=!0}},window.digiquali.refresh=function(){var t=void 0,e=void 0;for(t in window.digiquali)for(e in window.digiquali[t].refresh&&window.digiquali[t].refresh(),window.digiquali[t])window.digiquali[t]&&window.digiquali[t][e]&&window.digiquali[t][e].refresh&&window.digiquali[t][e].refresh()},$(document).ready(window.digiquali.init)),window.digiquali.control={},window.digiquali.control.init=function(){window.digiquali.control.event()},window.digiquali.control.event=function(){$(document).on("click",".validateButton",window.digiquali.control.getAnswerCounter),$(document).on("change","#fk_sheet",window.digiquali.control.showSelectObjectLinked),$(document).on("click",".clipboard-copy",window.digiquali.control.copyToClipboard),$(document).on("change","#productId",window.digiquali.control.refreshLotSelector),$(document).on("click",".switch-public-control-view",window.digiquali.control.switchPublicControlView),$(document).on("click",".photo-sheet-category",window.digiquali.control.getSheetCategoryID),$(document).on("click",".photo-sheet-sub-category",window.digiquali.control.getSheetSubCategoryID),$(document).on("click",".photo-sheet",window.digiquali.control.getSheetID),$(document).on("click","[data-toggle-action]",function(){var t=$(this).data("toggle-action"),e=$(this).data("toggle-key");t&&e&&window.saturne.utils.toggleSetting.call(this,t,e)})},window.digiquali.control.getAnswerCounter=function(t){let e=0;jQuery("#tablelines").children().each(function(){0<$(this).find(".answer.active").length&&(e+=1)}),document.cookie="answerCounter="+e},window.digiquali.control.showSelectObjectLinked=function(){var t=$(this).val(),e=window.saturne.toolbox.getToken(),i=window.saturne.toolbox.getQuerySeparator(document.URL),i=document.URL+i+"fk_sheet="+t+"&token="+e;window.saturne.loader.display($(".linked-objects")),$.ajax({url:i,type:"POST",processData:!1,contentType:!1,success:function(t){$(".linked-objects").replaceWith($(t).find(".linked-objects"))},error:function(){}})},window.digiquali.control.copyToClipboard=function(t){var e=$(".copy-to-clipboard").attr("value");navigator.clipboard.writeText(e).then(()=>{$(".clipboard-copy").animate({backgroundColor:"#59ed9c"},200,()=>{$(".clipboard-copy").attr("class","fas fa-check clipboard-copy"),$(this).tooltip({items:".clipboard-copy",content:$("#copyToClipboardTooltip").val()}),$(this).tooltip("open"),$(".clipboard-copy").attr("style","")})})},window.digiquali.control.refreshLotSelector=function(t){var e=document.getElementById("add_control_equipment"),e=new FormData(e),i=window.saturne.toolbox.getToken(),e=e.get("productId"),i=document.URL+"&token="+i;i+="&fk_product="+e,window.saturne.loader.display($(".product-lot")),$.ajax({url:i,type:"POST",processData:!1,contentType:!1,success:function(t){$(".product-lot").replaceWith($(t).find(".product-lot"))},error:function(){}})},window.digiquali.control.switchPublicControlView=function(){var t=$(this).data("route");window.saturne.loader.display($(this)),$.ajax({url:document.URL+"&route="+t,type:"POST",processData:!1,contentType:!1,success:function(t){$(".public-card__container").children().fadeOut(300,function(){$("#publicControlHistory").replaceWith($(t).find("#publicControlHistory"))})},error:function(){}})},window.digiquali.control.getSheetCategoryID=function(){let e=$(this).attr("value");var t=window.saturne.toolbox.getToken(),i=window.saturne.toolbox.getQuerySeparator(document.URL);window.saturne.loader.display($(".sheet-images-container")),$.ajax({url:document.URL+i+"sheetCategoryID="+e+"&token="+t,type:"POST",processData:!1,contentType:!1,success:function(t){$(".sheet-images-container").replaceWith($(t).find(".sheet-images-container")),$(".photo-sheet-category[value="+e+"]").css("border","3px solid #0d8aff"),$(".photo-sheet-category[value="+e+"]").addClass("photo-sheet-category-active"),$(".linked-objects").replaceWith($(t).find(".linked-objects"))},error:function(){}})},window.digiquali.control.getSheetSubCategoryID=function(){let e=$(".photo-sheet-category-active").attr("value"),i=$(this).attr("value");var t=window.saturne.toolbox.getToken(),o=window.saturne.toolbox.getQuerySeparator(document.URL);window.saturne.loader.display($(".sheet-images-container")),$.ajax({url:document.URL+o+"sheetCategoryID="+e+"&sheetSubCategoryID="+i+"&token="+t,type:"POST",processData:!1,contentType:!1,success:function(t){$(".sheet-images-container").replaceWith($(t).find(".sheet-images-container")),$(".photo-sheet-category[value="+e+"]").css("border","3px solid #0d8aff"),$(".photo-sheet-category[value="+e+"]").addClass("photo-sheet-category-active"),$(".photo-sheet-sub-category[value="+i+"]").css("border","3px solid #0d8aff"),$(".photo-sheet-sub-category[value="+i+"]").addClass("photo-sheet-sub-category-active"),$(".linked-objects").replaceWith($(t).find(".linked-objects"))},error:function(){}})},window.digiquali.control.getSheetID=function(){let e=$(this).attr("data-object-id");var t=$(".photo-sheet-category-active").attr("value"),i=$(".photo-sheet-sub-category-active").attr("value"),o=window.saturne.toolbox.getToken(),n=window.saturne.toolbox.getQuerySeparator(document.URL);window.saturne.loader.display($(".sheet-elements")),window.saturne.loader.display($(".linked-objects")),$.ajax({url:document.URL+n+"fk_sheet="+e+"&sheetCategoryID="+t+"&sheetSubCategoryID="+i+"&token="+o,type:"POST",processData:!1,contentType:!1,success:function(t){$(".sheet-elements").replaceWith($(t).find(".sheet-elements")),$(".photo-sheet[data-object-id="+e+"]").css("border","3px solid #0d8aff"),$(".linked-objects").replaceWith($(t).find(".linked-objects"))},error:function(){}})},window.digiquali.object={},window.digiquali.object.init=function(){window.digiquali.object.event(),window.digiquali.object.placePercents()},window.digiquali.object.event=function(){$(document).on("change",".object-table.linked-objects select",window.digiquali.object.disableOtherSelectors),$(document).on("click",".answer:not(.disable)",window.digiquali.object.selectAnswer),$(document).on("input",".input-answer:not(.disable)",window.digiquali.object.selectAnswer),$(document).on("keyup",".question-comment",window.digiquali.object.showCommentUnsaved),$(document).on("change",".question-answer",window.digiquali.object.changeStatusQuestion),$(document).on("click",".answer:not(.disable)",window.digiquali.object.changeStatusQuestion),$(document).on("input",'.question-answer[type="range"]',window.digiquali.object.rangePercent)},window.digiquali.object.disableOtherSelectors=function(){var t=document.getElementById("createObjectForm"),t=new FormData(t),e=$(this).attr("id");0<=t.get(e)?$(".object-table.linked-objects").find("select").not("#"+e).attr("disabled",1):$(".object-table.linked-objects").find("select").not("#"+e).removeAttr("disabled")},window.digiquali.object.selectAnswer=function(){var e=$(this).closest(".select-answer.answer-cell"),t=e.attr("data-questionId"),i=$(this).closest(".table-id-"+t).attr("data-publicInterface"),o=$(this).closest(".table-id-"+t).attr("data-autoSave");let n="";var a=$(this).hasClass("answer")?$(this).attr("value"):$(this).val(),s=$(this).closest(".table-id-"+t).find("#comment"+t).val();if($(this).closest(".table-cell").hasClass("select-answer")){if($(this).hasClass("multiple-answers")){$(this).closest("span").toggleClass("active");let t=[];e.find(".multiple-answers.active").each(function(){t.push($(this).attr("value"))}),n=t}else $(this).closest(".table-cell").find(".answer.active").css("background-color","#fff"),$(this).closest(".table-cell").find("span").removeClass("active"),$(this).closest("span").addClass("active"),n=a;$(this).hasClass("active")?(e=$(this).closest(".answer-cell").find(".answer-color-"+$(this).attr("value")).val(),$(this).attr("style",$(this).attr("style")+" background:"+e+";")):$(this).attr("style",$(this).attr("style")+" background:#fff;"),$(this).closest(".answer-cell").find(".question-answer").val(n)}i||1!=o||$(this).hasClass("multiple-answers")?window.digiquali.object.updateButtonsStatus():window.digiquali.object.saveAnswer(t,n,s)},window.digiquali.object.changeStatusQuestion=function(){$(this).closest(".question").addClass("question-complete")},window.digiquali.object.showCommentUnsaved=function(){$(this).hasClass("show-comment-unsaved-message")||$(".question-answer-container").hasClass("question-answer-container-pwa")||($(this).after('

Commentaire non enregistré

'),$(this).addClass("show-comment-unsaved-message")),window.digiquali.object.updateButtonsStatus()},window.digiquali.object.updateButtonsStatus=function(){$("#saveButton").removeClass("butActionRefused"),$("#saveButton").addClass("butAction"),$("#saveButton").css("background","#0d8aff"),$(".fa-circle").css("display","inline"),$("#saveButton").attr("onclick",'$("#saveObject").submit()'),$(".validateButton").removeClass("butAction"),$("#dialog-confirm-actionButtonValidate").removeAttr("id"),$(".validateButton").addClass("butActionRefused")},window.digiquali.object.saveAnswer=function(t,e,i){var o=window.saturne.toolbox.getToken(),n=window.saturne.toolbox.getQuerySeparator(document.URL);window.saturne.loader.display($(".table-id-"+t)),$.ajax({url:document.URL+n+"action=save&token="+o,type:"POST",data:JSON.stringify({autoSave:!0,questionId:t,answer:e,comment:i}),processData:!1,contentType:!1,success:function(t){$(".fiche").replaceWith($(t).find(".fiche")),$("#dialog-confirm-actionButtonValidate>.confirmmessage").replaceWith($(t).find("#dialog-confirm-actionButtonValidate>.confirmmessage"))},error:function(){}})},window.digiquali.object.rangePercent=function(){var t=window.saturne.toolbox.isPhone(),e=$(this),i=parseFloat(e.val()),o=parseInt(e.attr("min")),n=parseInt(e.attr("max")),a=e.width(),s=e.position().left,d=e.position().top,c=t?36:70,l=(e.parent().find(".range-percent").remove(),(Math.round(100*i)/100).toFixed(2)),r=$(''+l+"%"),d=(t||r.css("transform","translateX(0)"),r.addClass("badge badge-primary"),r.css("top",d-1.05*c/2-(t?10:5)+"px"),(i-o)/(n-o)),i=s+Math.round(d*a-(t?0:c/4)+-c*(d-.5));r.css("left",i),e.attr("value",l),e.parent().append(r)},window.digiquali.object.placePercents=function(){$('.question-answer[type="range"]').each(function(){window.digiquali.object.rangePercent.call(this)})},window.digiquali.question={},window.digiquali.question.init=function(){window.digiquali.question.event()},window.digiquali.question.event=function(){$(document).on("click",".clicked-photo-preview",window.digiquali.question.previewPhoto),$(document).on("click",".ui-dialog-titlebar-close",window.digiquali.question.closePreviewPhoto),$(document).on("click","#show_photo",window.digiquali.question.showPhoto),$(document).on("click",".answer-picto .item, .wpeo-table .item",window.digiquali.question.selectAnswerPicto),$(document).on("change",'select[data-type="question-type"]',window.digiquali.question.changeQuestionType)},window.digiquali.question.previewPhoto=function(){$(this).hasClass("photo-ok")?$("#dialogforpopup").attr("style","border: 10px solid #47e58e"):$(this).hasClass("photo-ko")&&$("#dialogforpopup").attr("style","border: 10px solid #e05353")},window.digiquali.question.closePreviewPhoto=function(){$("#dialogforpopup").attr("style","border:")},window.digiquali.question.showPhoto=function(){var t=$(this);t.closest(".question-table").find(".linked-medias").toggleClass("hidden",!t.prop("checked"))},window.digiquali.question.selectAnswerPicto=function(){var t=$(this).closest(".wpeo-dropdown");$(this).closest(".content").removeClass("active"),t.find(".dropdown-toggle span").hide(),t.find(".dropdown-toggle.button-picto").html($(this).closest(".wpeo-tooltip-event").html()),t.find(".input-hidden-picto").val($(this).data("label"))},window.digiquali.question.changeQuestionType=function(){"Percentage"===$(this).val()?$(document).find("#percentage-question-step").removeClass("hidden"):$(document).find("#percentage-question-step").addClass("hidden")},window.digiquali.sheet={},window.digiquali.sheet.init=function(){window.digiquali.sheet.event()},window.digiquali.sheet.event=function(){},window.digiquali.task={},window.digiquali.task.init=function(){window.digiquali.task.event()},window.digiquali.task.event=function(){$(document).on("input","#answer-task-label",window.digiquali.task.updateModalTaskAddButton),$(document).on("click",".answer-task-create:not(.button-disable)",window.digiquali.task.createTask),$(document).on("click",".answer-task-save",window.digiquali.task.updateTask),$(document).on("click",".question__action .delete-task",window.digiquali.task.deleteTask),$(document).on("change",'.question__action-check input[type="checkbox"]',window.digiquali.task.checkTask),$(document).on("click",".answer-task-timespent-create",window.digiquali.task.createTaskTimeSpent),$(document).on("click",".answer-task-timespent-update",window.digiquali.task.updateTaskTimeSpent),$(document).on("click",".answer-task-timespent-delete",window.digiquali.task.deleteTaskTimeSpent)},window.digiquali.task.updateModalTaskAddButton=function(){var t=$(this),e=t.closest("#answer_task_add").find(".wpeo-button.answer-task-create");0{$(".clipboard-copy").animate({backgroundColor:"#59ed9c"},200,()=>{$(".clipboard-copy").attr("class","fas fa-check clipboard-copy"),$(this).tooltip({items:".clipboard-copy",content:$("#copyToClipboardTooltip").val()}),$(this).tooltip("open"),$(".clipboard-copy").attr("style","")})})},window.digiquali.control.refreshLotSelector=function(t){var e=document.getElementById("add_control_equipment"),e=new FormData(e),i=window.saturne.toolbox.getToken(),e=e.get("productId"),i=document.URL+"&token="+i;i+="&fk_product="+e,window.saturne.loader.display($(".product-lot")),$.ajax({url:i,type:"POST",processData:!1,contentType:!1,success:function(t){$(".product-lot").replaceWith($(t).find(".product-lot"))},error:function(){}})},window.digiquali.control.switchPublicControlView=function(){var t=$(this).data("route");window.saturne.loader.display($(this)),$.ajax({url:document.URL+"&route="+t,type:"POST",processData:!1,contentType:!1,success:function(t){$(".public-card__container").children().fadeOut(300,function(){$("#publicControlHistory").replaceWith($(t).find("#publicControlHistory"))})},error:function(){}})},window.digiquali.control.getSheetCategoryID=function(){let e=$(this).attr("value");var t=window.saturne.toolbox.getToken(),i=window.saturne.toolbox.getQuerySeparator(document.URL);window.saturne.loader.display($(".sheet-images-container")),$.ajax({url:document.URL+i+"sheetCategoryID="+e+"&token="+t,type:"POST",processData:!1,contentType:!1,success:function(t){$(".sheet-images-container").replaceWith($(t).find(".sheet-images-container")),$(".photo-sheet-category[value="+e+"]").css("border","3px solid #0d8aff"),$(".photo-sheet-category[value="+e+"]").addClass("photo-sheet-category-active"),$(".linked-objects").replaceWith($(t).find(".linked-objects"))},error:function(){}})},window.digiquali.control.getSheetSubCategoryID=function(){let e=$(".photo-sheet-category-active").attr("value"),i=$(this).attr("value");var t=window.saturne.toolbox.getToken(),o=window.saturne.toolbox.getQuerySeparator(document.URL);window.saturne.loader.display($(".sheet-images-container")),$.ajax({url:document.URL+o+"sheetCategoryID="+e+"&sheetSubCategoryID="+i+"&token="+t,type:"POST",processData:!1,contentType:!1,success:function(t){$(".sheet-images-container").replaceWith($(t).find(".sheet-images-container")),$(".photo-sheet-category[value="+e+"]").css("border","3px solid #0d8aff"),$(".photo-sheet-category[value="+e+"]").addClass("photo-sheet-category-active"),$(".photo-sheet-sub-category[value="+i+"]").css("border","3px solid #0d8aff"),$(".photo-sheet-sub-category[value="+i+"]").addClass("photo-sheet-sub-category-active"),$(".linked-objects").replaceWith($(t).find(".linked-objects"))},error:function(){}})},window.digiquali.control.getSheetID=function(){let e=$(this).attr("data-object-id");var t=$(".photo-sheet-category-active").attr("value"),i=$(".photo-sheet-sub-category-active").attr("value"),o=window.saturne.toolbox.getToken(),n=window.saturne.toolbox.getQuerySeparator(document.URL);window.saturne.loader.display($(".sheet-elements")),window.saturne.loader.display($(".linked-objects")),$.ajax({url:document.URL+n+"fk_sheet="+e+"&sheetCategoryID="+t+"&sheetSubCategoryID="+i+"&token="+o,type:"POST",processData:!1,contentType:!1,success:function(t){$(".sheet-elements").replaceWith($(t).find(".sheet-elements")),$(".photo-sheet[data-object-id="+e+"]").css("border","3px solid #0d8aff"),$(".linked-objects").replaceWith($(t).find(".linked-objects"))},error:function(){}})},window.digiquali.object={},window.digiquali.object.init=function(){window.digiquali.object.event(),window.digiquali.object.placePercents()},window.digiquali.object.event=function(){$(document).on("change",".object-table.linked-objects select",window.digiquali.object.disableOtherSelectors),$(document).on("click",".answer:not(.disable)",window.digiquali.object.selectAnswer),$(document).on("input",".input-answer:not(.disable)",window.digiquali.object.selectAnswer),$(document).on("keyup",".question-comment",window.digiquali.object.showCommentUnsaved),$(document).on("change",".question-answer",window.digiquali.object.changeStatusQuestion),$(document).on("click",".answer:not(.disable)",window.digiquali.object.changeStatusQuestion),$(document).on("input",'.question-answer[type="range"]',window.digiquali.object.rangePercent)},window.digiquali.object.disableOtherSelectors=function(){var t=document.getElementById("createObjectForm"),t=new FormData(t),e=$(this).attr("id");0<=t.get(e)?$(".object-table.linked-objects").find("select").not("#"+e).attr("disabled",1):$(".object-table.linked-objects").find("select").not("#"+e).removeAttr("disabled")},window.digiquali.object.selectAnswer=function(){var e=$(this).closest(".select-answer.answer-cell"),t=e.attr("data-questionId"),i=$(this).closest(".table-id-"+t).attr("data-publicInterface"),o=$(this).closest(".table-id-"+t).attr("data-autoSave");let n="";var a=$(this).hasClass("answer")?$(this).attr("value"):$(this).val(),s=$(this).closest(".table-id-"+t).find("#comment"+t).val();if($(this).closest(".table-cell").hasClass("select-answer")){if($(this).hasClass("multiple-answers")){$(this).closest("span").toggleClass("active");let t=[];e.find(".multiple-answers.active").each(function(){t.push($(this).attr("value"))}),n=t}else $(this).closest(".table-cell").find(".answer.active").css("background-color","#fff"),$(this).closest(".table-cell").find("span").removeClass("active"),$(this).closest("span").addClass("active"),n=a;$(this).hasClass("active")?(e=$(this).closest(".answer-cell").find(".answer-color-"+$(this).attr("value")).val(),$(this).attr("style",$(this).attr("style")+" background:"+e+";")):$(this).attr("style",$(this).attr("style")+" background:#fff;"),$(this).closest(".answer-cell").find(".question-answer").val(n)}i||1!=o||$(this).hasClass("multiple-answers")?window.digiquali.object.updateButtonsStatus():window.digiquali.object.saveAnswer(t,n,s)},window.digiquali.object.changeStatusQuestion=function(){$(this).closest(".question").addClass("question-complete")},window.digiquali.object.showCommentUnsaved=function(){$(this).hasClass("show-comment-unsaved-message")||$(".question-answer-container").hasClass("question-answer-container-pwa")||($(this).after('

Commentaire non enregistré

'),$(this).addClass("show-comment-unsaved-message")),window.digiquali.object.updateButtonsStatus()},window.digiquali.object.updateButtonsStatus=function(){$("#saveButton").removeClass("butActionRefused"),$("#saveButton").addClass("butAction"),$("#saveButton").css("background","#0d8aff"),$(".fa-circle").css("display","inline"),$("#saveButton").attr("onclick",'$("#saveObject").submit()'),$(".validateButton").removeClass("butAction"),$("#dialog-confirm-actionButtonValidate").removeAttr("id"),$(".validateButton").addClass("butActionRefused")},window.digiquali.object.saveAnswer=function(t,e,i){var o=window.saturne.toolbox.getToken(),n=window.saturne.toolbox.getQuerySeparator(document.URL);window.saturne.loader.display($(".table-id-"+t)),$.ajax({url:document.URL+n+"action=save&token="+o,type:"POST",data:JSON.stringify({autoSave:!0,questionId:t,answer:e,comment:i}),processData:!1,contentType:!1,success:function(t){$(".fiche").replaceWith($(t).find(".fiche")),$("#dialog-confirm-actionButtonValidate>.confirmmessage").replaceWith($(t).find("#dialog-confirm-actionButtonValidate>.confirmmessage"))},error:function(){}})},window.digiquali.object.rangePercent=function(){var t=window.saturne.toolbox.isPhone(),e=$(this),i=parseFloat(e.val()),o=parseInt(e.attr("min")),n=parseInt(e.attr("max")),a=e.width(),s=e.position().left,d=e.position().top,c=t?36:70,l=(e.parent().find(".range-percent").remove(),(Math.round(100*i)/100).toFixed(2)),r=$(''+l+"%"),d=(t||r.css("transform","translateX(0)"),r.addClass("badge badge-primary"),r.css("top",d-1.05*c/2-(t?10:5)+"px"),(i-o)/(n-o)),i=s+Math.round(d*a-(t?0:c/4)+-c*(d-.5));r.css("left",i),e.attr("value",l),e.parent().append(r)},window.digiquali.object.placePercents=function(){$('.question-answer[type="range"]').each(function(){window.digiquali.object.rangePercent.call(this)})},window.digiquali.question={},window.digiquali.question.init=function(){window.digiquali.question.event()},window.digiquali.question.event=function(){$(document).on("click",".clicked-photo-preview",window.digiquali.question.previewPhoto),$(document).on("click",".ui-dialog-titlebar-close",window.digiquali.question.closePreviewPhoto),$(document).on("click","#show_photo",window.digiquali.question.showPhoto),$(document).on("click",".answer-picto .item, .wpeo-table .item",window.digiquali.question.selectAnswerPicto),$(document).on("change",'select[data-type="question-type"]',window.digiquali.question.changeQuestionType)},window.digiquali.question.previewPhoto=function(){$(this).hasClass("photo-ok")?$("#dialogforpopup").attr("style","border: 10px solid #47e58e"):$(this).hasClass("photo-ko")&&$("#dialogforpopup").attr("style","border: 10px solid #e05353")},window.digiquali.question.closePreviewPhoto=function(){$("#dialogforpopup").attr("style","border:")},window.digiquali.question.showPhoto=function(){var t=$(this);t.closest(".question-table").find(".linked-medias").toggleClass("hidden",!t.prop("checked"))},window.digiquali.question.selectAnswerPicto=function(){var t=$(this).closest(".wpeo-dropdown");$(this).closest(".content").removeClass("active"),t.find(".dropdown-toggle span").hide(),t.find(".dropdown-toggle.button-picto").html($(this).closest(".wpeo-tooltip-event").html()),t.find(".input-hidden-picto").val($(this).data("label"))},window.digiquali.question.changeQuestionType=function(){"Percentage"===$(this).val()?($(document).find("#percentage-question-step").fadeIn(),$(document).find("#percentage-question-is-percentage").fadeIn()):($(document).find("#percentage-question-step").fadeOut(),$(document).find("#percentage-question-is-percentage").fadeOut())},window.digiquali.sheet={},window.digiquali.sheet.init=function(){window.digiquali.sheet.event()},window.digiquali.sheet.event=function(){},window.digiquali.task={},window.digiquali.task.init=function(){window.digiquali.task.event()},window.digiquali.task.event=function(){$(document).on("input","#answer-task-label",window.digiquali.task.updateModalTaskAddButton),$(document).on("click",".answer-task-create:not(.button-disable)",window.digiquali.task.createTask),$(document).on("click",".answer-task-save",window.digiquali.task.updateTask),$(document).on("click",".question__action .delete-task",window.digiquali.task.deleteTask),$(document).on("change",'.question__action-check input[type="checkbox"]',window.digiquali.task.checkTask),$(document).on("click",".answer-task-timespent-create",window.digiquali.task.createTaskTimeSpent),$(document).on("click",".answer-task-timespent-update",window.digiquali.task.updateTaskTimeSpent),$(document).on("click",".answer-task-timespent-delete",window.digiquali.task.deleteTaskTimeSpent)},window.digiquali.task.updateModalTaskAddButton=function(){var t=$(this),e=t.closest("#answer_task_add").find(".wpeo-button.answer-task-create");0 'N/A', 'position' => 4 ], + 'smile' => [ + 'name' => $langs->transnoentities('Smile'), + 'picto_source' => '', + 'position' => 5 + ], + 'meh' => [ + 'name' => $langs->transnoentities('Meh'), + 'picto_source' => '', + 'position' => 6 + ], + 'sad' => [ + 'name' => $langs->transnoentities('Sad'), + 'picto_source' => '', + 'position' => 7 + ] ]; return $pictosArray; } +/** + * Interpolate between two colors in a gradient + * + * @param array $gradient Array of colors with their positions + * @param float $percentage Percentage to interpolate + * @return string Interpolated color in hex format + */ +function interpolateColor(array $gradient, float $percentage): string { + ksort($gradient); + $positions = array_keys($gradient); + + // Find the positions surrounding the percentage + $pos1 = 0; + foreach ($positions as $pos) { + if ($pos <= $percentage) { + $pos1 = $pos; + } else { + $pos2 = $pos; + break; + } + } + + // If exact match or at edge of gradient + if (!isset($pos2) || $pos1 == $percentage) { + return $gradient[$pos1]; + } + + // Extract RGB components + list($r1, $g1, $b1) = sscanf($gradient[$pos1], "#%02x%02x%02x"); + list($r2, $g2, $b2) = sscanf($gradient[$pos2], "#%02x%02x%02x"); + + // Calculate interpolation factor + $ratio = ($percentage - $pos1) / ($pos2 - $pos1); + + // Interpolate RGB values + $r = round($r1 + ($r2 - $r1) * $ratio); + $g = round($g1 + ($g2 - $g1) * $ratio); + $b = round($b1 + ($b2 - $b1) * $ratio); + + return sprintf("#%02X%02X%02X", $r, $g, $b); +} + /** * Show answer from question object in HTML output format (textarea, range, select, ...) * @@ -120,54 +177,51 @@ function show_answer_from_question(Question $question, CommonObject $object, str $disabled = ($object->status > $object::STATUS_DRAFT ? ' disabled' : ''); $questionConfig = json_decode($question->json, true)['config']; - switch ($question->type) { - case 'Text': - $out .= '
'; - $out .= ''; - $out .= '
'; - break; - case 'Percentage': - $step = 100; - if (!empty($questionConfig[$question->type]['step'])) { - $step = $questionConfig[$question->type]['step']; - } + if ($question->type == 'Text') { + $out .= '
'; + $out .= ''; + $out .= '
'; + } else if ($question->type == 'Percentage' && $questionConfig[$question->type]['isCursor']) { + $step = 100; + if (!empty($questionConfig[$question->type]['step'])) { + $step = $questionConfig[$question->type]['step']; + } - $out .= '
'; - $out .= img_picto('', 'fontawesome_fa-frown_fas_#D53C3D_3em', 'class="range-image"'); - $out .= ''; - $out .= img_picto('', 'fontawesome_fa-grin_fas_#57AD39_3em', 'class="range-image"'); - $out .= '
'; - break; - case 'Range': - $out .= '
'; - $out .= ''; - $out .= '
'; - break; - case 'UniqueChoice': - case 'OkKo': - case 'OkKoToFixNonApplicable': - case 'MultipleChoices': - $answers = $answer->fetchAll('ASC', 'position', 0, 0, ['customsql' => 't.status = ' . Answer::STATUS_VALIDATED . ' AND t.fk_question = ' . $question->id]); - $pictos = get_answer_pictos_array(); - - if (strpos($questionAnswer, ',') !== false) { - $questionAnswers = explode(',', $questionAnswer); - } else { - $questionAnswers = [$questionAnswer]; - } + $out .= '
'; + $out .= img_picto('', 'fontawesome_fa-frown_fas_#D53C3D_3em', 'class="range-image"'); + $out .= ''; + $out .= img_picto('', 'fontawesome_fa-grin_fas_#57AD39_3em', 'class="range-image"'); + $out .= '
'; + } else if ($question->type == 'Range') { + $out .= '
'; + $out .= ''; + $out .= '
'; + } else if ($question->type == 'UniqueChoice' || + $question->type == 'OkKo' || + $question->type == 'OkKoToFixNonApplicable' || + $question->type == 'MultipleChoices' || + ($question->type == 'Percentage' && !$questionConfig[$question->type]['isCursor'])) { + + $answers = $answer->fetchAll('ASC', 'position', 0, 0, ['customsql' => 't.status = ' . Answer::STATUS_VALIDATED . ' AND t.fk_question = ' . $question->id]); + $pictos = get_answer_pictos_array(); - $out .= '
'; - $out .= ''; - if (is_array($answers) && !empty($answers)) { - foreach($answers as $answer) { - $out .= ''; - $out .= ''; - $out .= !empty($answer->pictogram) ? $pictos[$answer->pictogram]['picto_source'] : $answer->value; - $out .= ''; - } + if (strpos($questionAnswer, ',') !== false) { + $questionAnswers = explode(',', $questionAnswer); + } else { + $questionAnswers = [$questionAnswer]; + } + + $out .= '
'; + $out .= ''; + if (is_array($answers) && !empty($answers)) { + foreach($answers as $answer) { + $out .= ''; + $out .= ''; + $out .= !empty($answer->pictogram) ? $pictos[$answer->pictogram]['picto_source'] : $answer->value; + $out .= ''; } - $out .= '
'; - break; + } + $out .= '
'; } return $out; diff --git a/view/control/control_card.php b/view/control/control_card.php index 93752e5c..54181aa5 100644 --- a/view/control/control_card.php +++ b/view/control/control_card.php @@ -726,7 +726,14 @@ $percentQuestionCounter++; foreach ($object->lines as $line) { if ($line->fk_question === $questionLinked->id) { - $averagePercentageQuestions += $line->answer; + + $config = json_decode($questionLinked->json, true); + if (!isset($config['config'][$questionLinked->type]['isCursor']) || !empty($config['config'][$questionLinked->type]['isCursor'])) { + $averagePercentageQuestions += $line->answer; + } else { + $averagePercentageQuestions += (($line->answer - 1) / ($config['config'][$questionLinked->type]['step'] - 1)) * 100; + } + } } } diff --git a/view/question/question_card.php b/view/question/question_card.php index 374e1050..29fa7c4e 100644 --- a/view/question/question_card.php +++ b/view/question/question_card.php @@ -284,9 +284,9 @@ $objectConfig = ['config' => []]; if (GETPOSTISSET('step') && !empty(GETPOSTINT('step'))) { - $objectConfig['config'][$object->type]['step'] = GETPOSTINT('step'); - } - + $objectConfig['config'][$object->type]['step'] = GETPOSTINT('step'); + $objectConfig['config'][$object->type]['isCursor'] = GETPOST('is_cursor') == 'on' ? 1 : 0; + } $result = $object->create($user); if ($result > 0) { @@ -329,6 +329,25 @@ $answer->create($user); } + if ($object->type == 'Percentage' && !$objectConfig['config'][$object->type]['isCursor']) { + $count = 0; + for ($i = 0; $i < 100; $i += 100 / ($objectConfig['config'][$object->type]['step'] - 1)) { + + $answer->fk_question = $result; + $answer->value = ceil($i); + $answer->pictogram = $i > 66 ? 'smile' : ($i > 33 ? 'meh' : 'sad'); + $answer->color = interpolateColor([0 => '#D53C3D', 25 =>'#ED911D', 50 => '#F2C32E', 75 => '#92D444', 100 => '#57AD39'], $i); + $answer->create($user); + $count++; + } + if ($count < $objectConfig['config'][$object->type]['step'] && $answer->value != 100) { + $answer->fk_question = $result; + $answer->value = 100; + $answer->pictogram = 'smile'; + $answer->color = '#57AD39'; + $answer->create($user); + } + } $urltogo = $backtopage ? str_replace('__ID__', $result, $backtopage) : $backurlforlist; $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $urltogo); // New method to autoselect project after a New on another form object creation @@ -750,6 +769,12 @@ print ''; print ''; + // Is percentage or emoji question type + print ''; + print ''; + print $form->textwithpicto('', $langs->transnoentities('IsCursorPercentageTooltip')); + print ''; + // Description -- Description print ''; $doleditor = new DolEditor('description', GETPOST('description'), '', 90, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_3, '90%'); @@ -878,6 +903,12 @@ print ''; print ''; + // Is percentage or emoji question type + print ''; + print 'type]['isCursor']) ? '' : ' checked=""') . '>'; + print $form->textwithpicto('', $langs->transnoentities('IsCursorPercentageTooltip')); + print ''; + //Description -- Description print ''; $doleditor = new DolEditor('description', $object->description, '', 90, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_3, '90%'); @@ -1156,7 +1187,7 @@ print ''; } - if ($object->type == 'MultipleChoices' || $object->type == 'UniqueChoice' || $object->type == 'OkKo' || $object->type == 'OkKoToFixNonApplicable') { + if ($object->type == 'MultipleChoices' || $object->type == 'UniqueChoice' || $object->type == 'OkKo' || $object->type == 'OkKoToFixNonApplicable' || ($object->type == 'Percentage' && !$objectConfig[$object->type]['isCursor'])) { $pictosArray = get_answer_pictos_array(); diff --git a/view/survey/survey_card.php b/view/survey/survey_card.php index 70c2ad88..b36914e5 100644 --- a/view/survey/survey_card.php +++ b/view/survey/survey_card.php @@ -532,7 +532,14 @@ $percentQuestionCounter++; foreach ($object->lines as $line) { if ($line->fk_question === $questionLinked->id) { - $averagePercentageQuestions += $line->answer; + + $config = json_decode($questionLinked->json, true); + if (!isset($config['config'][$questionLinked->type]['isCursor']) || !empty($config['config'][$questionLinked->type]['isCursor'])) { + $averagePercentageQuestions += $line->answer; + } else { + $averagePercentageQuestions += (($line->answer - 1) / ($config['config'][$questionLinked->type]['step'] - 1)) * 100; + } + } } } From 69d3912d62cbc06532b84a5c442d11e0fcfdb010 Mon Sep 17 00:00:00 2001 From: Nicolas Domenech Date: Thu, 13 Mar 2025 15:26:41 +0100 Subject: [PATCH 2/3] #2028 [Question] fix: percentage calcul and missing trigger --- ...9_modDigiQuali_DigiQualiTriggers.class.php | 19 ++++++++++++++++++- view/control/control_card.php | 10 ++++++---- view/survey/survey_card.php | 10 ++++++---- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/core/triggers/interface_99_modDigiQuali_DigiQualiTriggers.class.php b/core/triggers/interface_99_modDigiQuali_DigiQualiTriggers.class.php index acd5cef6..a9313744 100644 --- a/core/triggers/interface_99_modDigiQuali_DigiQualiTriggers.class.php +++ b/core/triggers/interface_99_modDigiQuali_DigiQualiTriggers.class.php @@ -183,7 +183,8 @@ public function runTrigger($action, $object, User $user, Translate $langs, Conf // Load Digiquali libraries require_once __DIR__ . '/../../class/sheet.class.php'; - $sheet = new Sheet($this->db); + $sheet = new Sheet($this->db); + $objectLine = new SurveyLine($this->db); $sheet->fetch($object->fk_sheet); if ($sheet->success_rate > 0) { @@ -191,6 +192,22 @@ public function runTrigger($action, $object, User $user, Translate $langs, Conf $object->setValueFrom('success_rate', $object->success_rate, '', '', 'text', '', $user); } + $sheet->fetchObjectLinked($object->fk_sheet, 'digiquali_' . $sheet->element); + if (!empty($sheet->linkedObjects['digiquali_question'])) { + foreach ($sheet->linkedObjects['digiquali_question'] as $question) { + $objectLine->ref = $objectLine->getNextNumRef(); + $fk_element = 'fk_'. $object->element; + $objectLine->$fk_element = $object->id; + $objectLine->fk_question = $question->id; + $objectLine->answer = ''; + $objectLine->comment = ''; + $objectLine->entity = $conf->entity; + $objectLine->status = 1; + + $objectLine->create($user); + } + } + if ($object->context != 'createfromclone') { $elementArray = get_sheet_linkable_objects(); if (!empty($elementArray)) { diff --git a/view/control/control_card.php b/view/control/control_card.php index 54181aa5..d826a2db 100644 --- a/view/control/control_card.php +++ b/view/control/control_card.php @@ -725,15 +725,17 @@ $percentQuestionCounter++; foreach ($object->lines as $line) { - if ($line->fk_question === $questionLinked->id) { - + if ($line->fk_question === $questionLinked->id && is_numeric($line->answer)) { $config = json_decode($questionLinked->json, true); if (!isset($config['config'][$questionLinked->type]['isCursor']) || !empty($config['config'][$questionLinked->type]['isCursor'])) { $averagePercentageQuestions += $line->answer; + } elseif ($line->answer - 1 == 0) { + $averagePercentageQuestions += 0; + } elseif ($line->answer == $config['config'][$questionLinked->type]['step']) { + $averagePercentageQuestions += 100; } else { - $averagePercentageQuestions += (($line->answer - 1) / ($config['config'][$questionLinked->type]['step'] - 1)) * 100; + $averagePercentageQuestions += (($line->answer) / ($config['config'][$questionLinked->type]['step'])) * 100; } - } } } diff --git a/view/survey/survey_card.php b/view/survey/survey_card.php index b36914e5..29cead67 100644 --- a/view/survey/survey_card.php +++ b/view/survey/survey_card.php @@ -531,15 +531,17 @@ $percentQuestionCounter++; foreach ($object->lines as $line) { - if ($line->fk_question === $questionLinked->id) { - + if ($line->fk_question === $questionLinked->id && is_numeric($line->answer)) { $config = json_decode($questionLinked->json, true); if (!isset($config['config'][$questionLinked->type]['isCursor']) || !empty($config['config'][$questionLinked->type]['isCursor'])) { $averagePercentageQuestions += $line->answer; + } elseif ($line->answer - 1 == 0) { + $averagePercentageQuestions += 0; + } elseif ($line->answer == $config['config'][$questionLinked->type]['step']) { + $averagePercentageQuestions += 100; } else { - $averagePercentageQuestions += (($line->answer - 1) / ($config['config'][$questionLinked->type]['step'] - 1)) * 100; + $averagePercentageQuestions += (($line->answer) / ($config['config'][$questionLinked->type]['step'])) * 100; } - } } } From 4595840d71976114d4a7a2ce2468dbeaf93936c2 Mon Sep 17 00:00:00 2001 From: evarisk-kilyan Date: Fri, 14 Mar 2025 17:54:36 +0100 Subject: [PATCH 3/3] #2028 [Question] fix: percenatage calcul and modify --- class/control.class.php | 9 +- .../doc_controldocument_odt.modules.php | 16 +++- .../doc_surveydocument_odt.modules.php | 36 ++++++-- core/modules/modDigiQuali.class.php | 86 ++++++++++--------- core/tpl/digiquali_survey_list.tpl.php | 6 +- view/control/control_card.php | 23 ++--- view/question/question_card.php | 33 ++++++- view/survey/survey_card.php | 22 ++--- 8 files changed, 154 insertions(+), 77 deletions(-) diff --git a/class/control.class.php b/class/control.class.php index 3951c796..8697a75b 100644 --- a/class/control.class.php +++ b/class/control.class.php @@ -1047,6 +1047,7 @@ public function getNbControlsByMonth(): array */ public function getControlListsByNextControl(): array { + // require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; global $langs; // Graph Title parameters. @@ -1065,6 +1066,10 @@ public function getControlListsByNextControl(): array if (is_array($controls) && !empty($controls)) { foreach ($controls as $control) { $control->fetchObjectLinked('', '', $control->id, 'digiquali_control', 'OR', 1, 'sourcetype', 0); + if (!empty($control->projectid)) { + $control->fk_project = $control->projectid; + $control->fetch_project(); + } $linkedObjectsInfos = $control->getLinkedObjectsWithQcFrequency($elementArray); $linkedObjects = $linkedObjectsInfos['linkedObjects']; $qcFrequencyArray = $linkedObjectsInfos['qcFrequencyArray']; @@ -1076,11 +1081,9 @@ public function getControlListsByNextControl(): array require_once __DIR__ . '/sheet.class.php'; $userTmp = new User($this->db); - $project = new Project($this->db); $sheet = new Sheet($this->db); $userTmp->fetch($control->fk_user_controller); - $project->fetch($control->projectid); $sheet->fetch($control->fk_sheet); if (!empty($control->next_control_date)) { @@ -1091,7 +1094,7 @@ public function getControlListsByNextControl(): array $arrayControlListsByNextControl[$control->id]['Ref']['value'] = $control->getNomUrl(1); $arrayControlListsByNextControl[$control->id]['LinkedObject']['value'] = $currentObject->getNomUrl(1); $arrayControlListsByNextControl[$control->id]['UserController']['value'] = $userTmp->getNomUrl(1); - $arrayControlListsByNextControl[$control->id]['Project']['value'] = $project->id > 0 ? $project->getNomUrl(1) : ''; + $arrayControlListsByNextControl[$control->id]['Project']['value'] = $control->project->id > 0 ? $control->project->getNomUrl(1) : ''; $arrayControlListsByNextControl[$control->id]['Sheet']['value'] = $sheet->getNomUrl(1); $arrayControlListsByNextControl[$control->id]['ControlDate']['value'] = dol_print_date($control->date_creation, 'day'); $arrayControlListsByNextControl[$control->id]['NextControl']['value'] = '
' . $nextControl . '
' . $langs->trans('Days') . '
'; diff --git a/core/modules/digiquali/digiqualidocuments/controldocument/doc_controldocument_odt.modules.php b/core/modules/digiquali/digiqualidocuments/controldocument/doc_controldocument_odt.modules.php index aa30a0e9..dd100802 100644 --- a/core/modules/digiquali/digiqualidocuments/controldocument/doc_controldocument_odt.modules.php +++ b/core/modules/digiquali/digiqualidocuments/controldocument/doc_controldocument_odt.modules.php @@ -142,6 +142,7 @@ public function fillTagsLines(Odf $odfHandler, Translate $outputLangs, array $mo $questionAnswerLine = array_shift($controldets); $tmpArray['ref_answer'] = $questionAnswerLine->ref; $tmpArray['comment'] = $questionAnswerLine->comment ? dol_htmlentitiesbr_decode(strip_tags($questionAnswerLine->comment, '
')) : $langs->transnoentities('NoObservations'); + $tmpArray['answer'] = ''; $answerResult = $questionAnswerLine->answer; @@ -166,7 +167,20 @@ public function fillTagsLines(Odf $odfHandler, Translate $outputLangs, array $mo $tmpArray['answer'] = $answerResult; break; case 'Percentage' : - $tmpArray['answer'] = $answerResult . ' %'; + $config = json_decode($question->json, true); + + if (!isset($config['config'][$question->type]['isCursor']) || !empty($config['config'][$question->type]['isCursor'])) { + $tmpArray['answer'] .= $questionAnswerLine->answer; + } else { + $result = $answer->fetch('', '', ' AND t.status = ' . Answer::STATUS_VALIDATED . ' AND t.fk_question = ' . $question->id . ' AND t.position = ' . $questionAnswerLine->answer); + if ($result <= 0) { + $tmpArray['answer'] = '0'; + } else { + $tmpArray['answer'] = $answer->value; + } + } + + $tmpArray['answer'] .= ' %'; break; case 'MultipleChoices' : $answers = explode(',', $answerResult); diff --git a/core/modules/digiquali/digiqualidocuments/surveydocument/doc_surveydocument_odt.modules.php b/core/modules/digiquali/digiqualidocuments/surveydocument/doc_surveydocument_odt.modules.php index ac30d240..249d4f2c 100644 --- a/core/modules/digiquali/digiqualidocuments/surveydocument/doc_surveydocument_odt.modules.php +++ b/core/modules/digiquali/digiqualidocuments/surveydocument/doc_surveydocument_odt.modules.php @@ -117,6 +117,7 @@ public function fillTagsLines(Odf $odfHandler, Translate $outputLangs, array $mo $tmpArray['description'] = strip_tags($question->description); $tmpArray['ref_answer'] = $line->ref; $tmpArray['comment'] = dol_htmlentitiesbr_decode(strip_tags($line->comment, '
')); + $tmpArray['answer'] = ''; $answersArray = []; $answers = $answer->fetchAll('ASC', 'position', 0, 0, ['fk_question' => $line->fk_question]); @@ -137,7 +138,20 @@ public function fillTagsLines(Odf $odfHandler, Translate $outputLangs, array $mo $tmpArray['answer'] = $line->answer; break; case 'Percentage' : - $tmpArray['answer'] = $line->answer . ' %'; + $config = json_decode($question->json, true); + + if (!isset($config['config'][$question->type]['isCursor']) || !empty($config['config'][$question->type]['isCursor'])) { + $tmpArray['answer'] .= $line->answer; + } else { + $result = $answer->fetch('', '', ' AND t.status = ' . Answer::STATUS_VALIDATED . ' AND t.fk_question = ' . $question->id . ' AND t.position = ' . $line->answer); + if ($result <= 0) { + $tmpArray['answer'] = '0'; + } else { + $tmpArray['answer'] = $answer->value; + } + } + + $tmpArray['answer'] .= ' %'; break; case 'MultipleChoices' : $tmpArray['answer'] = ''; @@ -295,6 +309,8 @@ public function write_file(SaturneDocuments $objectDocument, Translate $outputLa $averagePercentageQuestions = 0; $percentQuestionCounter = 0; + $answer = new Answer($this->db); + foreach ($sheet->linkedObjects['digiquali_question'] as $questionLinked) { if ($questionLinked->type !== 'Percentage') { continue; // Skip non-percentage questions @@ -302,15 +318,17 @@ public function write_file(SaturneDocuments $objectDocument, Translate $outputLa $percentQuestionCounter++; foreach ($object->lines as $line) { - if ($line->fk_question === $questionLinked->id) { - - $config = json_decode($questionLinked->json, true); - if (!isset($config['config'][$questionLinked->type]['isCursor']) || !empty($config['config'][$questionLinked->type]['isCursor'])) { - $averagePercentageQuestions += $line->answer; - } else { - $averagePercentageQuestions += (($line->answer - 1) / ($config['config'][$questionLinked->type]['step'] - 1)) * 100; - } + $config = json_decode($questionLinked->json, true); + if ($line->fk_question === $questionLinked->id && is_numeric($line->answer) && (!isset($config['config'][$question->type]['isCursor']) || !empty($config['config'][$question->type]['isCursor']))) { + $averagePercentageQuestions += $line->answer; + } else { + $result = $answer->fetch('', '', ' AND t.status = ' . Answer::STATUS_VALIDATED . ' AND t.fk_question = ' . $questionLinked->id . ' AND t.position = ' . $line->answer); + + if ($result <= 0) { + continue; // Skip if answer is not valid + } + $averagePercentageQuestions += $answer->value; } } } diff --git a/core/modules/modDigiQuali.class.php b/core/modules/modDigiQuali.class.php index 8921182e..948dd842 100644 --- a/core/modules/modDigiQuali.class.php +++ b/core/modules/modDigiQuali.class.php @@ -828,48 +828,56 @@ public function init($options = ''): int dolibarr_set_const($this->db, 'DIGIQUALI_QUESTION_BACKWARD_COMPATIBILITY', 1, 'integer', 0, '', $conf->entity); } - if (getDolGlobalInt('DIGIQUALI_CONTROL_ANSWER_BACKWARD') == 0 && $result > 0) { + if (getDolGlobalInt('DIGIQUALI_ANSWER_BACKWARD') == 0 && $result > 0) { require_once __DIR__ . '/../../class/control.class.php'; - require_once __DIR__ . '/../../class/sheet.class.php'; - - $control = new Control($this->db); - $sheet = new Sheet($this->db); - $objectLine = new ControlLine($this->db); - - $controls = $control->fetchAll(); - if (is_array($controls) && !empty($controls)) { - foreach ($controls as $control) { - if (empty($control->fk_sheet)) { - continue; - } - - $sheet->fetch($control->fk_sheet); - $sheet->fetchObjectLinked($control->fk_sheet, 'digiquali_' . $sheet->element); - if (empty($sheet->linkedObjects['digiquali_question'])) { - continue; - } - - $firstQuestion = current($sheet->linkedObjects['digiquali_question']); - $res = $objectLine->fetchFromParentWithQuestion($control->id, $firstQuestion->id); - if (empty($res)) { - foreach ($sheet->linkedObjects['digiquali_question'] as $question) { - $objectLine->ref = $objectLine->getNextNumRef(); - $fk_element = 'fk_'. $control->element; - $objectLine->$fk_element = $control->id; - $objectLine->fk_question = $question->id; - $objectLine->answer = ''; - $objectLine->comment = ''; - $objectLine->entity = $conf->entity; - $objectLine->status = 1; - - $objectLine->create($user); - } - } - } - } + require_once __DIR__ . '/../../class/survey.class.php'; + require_once __DIR__ . '/../../class/sheet.class.php'; + + $control = new Control($this->db); + $survey = new Survey($this->db); + $sheet = new Sheet($this->db); + $controlLine = new ControlLine($this->db); + $surveyLine = new SurveyLine($this->db); + + + $elements = [$control, $survey]; + $lines = [$controlLine, $surveyLine]; + foreach ($elements as $idx => $elementObject) { + $arrayElements = $elementObject->fetchAll(); + if (is_array($arrayElements) && !empty($arrayElements)) { + foreach ($arrayElements as $element) { + if (empty($element->fk_sheet)) { + continue; + } + + $sheet->fetch($element->fk_sheet); + $sheet->fetchObjectLinked($element->fk_sheet, 'digiquali_' . $sheet->element); + if (empty($sheet->linkedObjects['digiquali_question'])) { + continue; + } + + $firstQuestion = current($sheet->linkedObjects['digiquali_question']); + $res = $lines[$idx]->fetchFromParentWithQuestion($element->id, $firstQuestion->id); + if (empty($res)) { + foreach ($sheet->linkedObjects['digiquali_question'] as $question) { + $lines[$idx]->ref = $lines[$idx]->getNextNumRef(); + $fk_element = 'fk_'. $element->element; + $lines[$idx]->$fk_element = $element->id; + $lines[$idx]->fk_question = $question->id; + $lines[$idx]->answer = ''; + $lines[$idx]->comment = ''; + $lines[$idx]->entity = $conf->entity; + $lines[$idx]->status = 1; + + $lines[$idx]->create($user); + } + } + } + } + } - dolibarr_set_const($this->db, 'DIGIQUALI_CONTROL_ANSWER_BACKWARD', 1, 'integer', 0, '', $conf->entity); + dolibarr_set_const($this->db, 'DIGIQUALI_ANSWER_BACKWARD', 1, 'integer', 0, '', $conf->entity); } require_once DOL_DOCUMENT_ROOT . '/cron/class/cronjob.class.php'; diff --git a/core/tpl/digiquali_survey_list.tpl.php b/core/tpl/digiquali_survey_list.tpl.php index 2254d7cd..15a9ebba 100644 --- a/core/tpl/digiquali_survey_list.tpl.php +++ b/core/tpl/digiquali_survey_list.tpl.php @@ -611,8 +611,10 @@ $sheet->fetch($object->fk_sheet); $sheet->fetchObjectLinked($object->fk_sheet, 'digiquali_' . $sheet->element, null, '', 'OR', 1, 'position'); $questions = $sheet->linkedObjects['digiquali_question']; - foreach ($questions as $question) { - $questions[$question->id] = $question; + if (is_array($questions) && !empty($questions)) { + foreach ($questions as $question) { + $questions[$question->id] = $question; + } } $answers = []; diff --git a/view/control/control_card.php b/view/control/control_card.php index d826a2db..9909ebeb 100644 --- a/view/control/control_card.php +++ b/view/control/control_card.php @@ -717,25 +717,26 @@ $averagePercentageQuestions = 0; $percentQuestionCounter = 0; + $answer = new Answer($db); + if (is_array($sheet->linkedObjects['digiquali_question']) && !empty($sheet->linkedObjects['digiquali_question'])) { foreach ($sheet->linkedObjects['digiquali_question'] as $questionLinked) { if ($questionLinked->type !== 'Percentage') { continue; // Skip non-percentage questions } - $percentQuestionCounter++; foreach ($object->lines as $line) { - if ($line->fk_question === $questionLinked->id && is_numeric($line->answer)) { - $config = json_decode($questionLinked->json, true); - if (!isset($config['config'][$questionLinked->type]['isCursor']) || !empty($config['config'][$questionLinked->type]['isCursor'])) { - $averagePercentageQuestions += $line->answer; - } elseif ($line->answer - 1 == 0) { - $averagePercentageQuestions += 0; - } elseif ($line->answer == $config['config'][$questionLinked->type]['step']) { - $averagePercentageQuestions += 100; - } else { - $averagePercentageQuestions += (($line->answer) / ($config['config'][$questionLinked->type]['step'])) * 100; + $config = json_decode($questionLinked->json, true); + + if ($line->fk_question === $questionLinked->id && is_numeric($line->answer) && (!isset($config['config'][$question->type]['isCursor']) || !empty($config['config'][$question->type]['isCursor']))) { + $averagePercentageQuestions += $line->answer; + } else { + $result = $answer->fetch('', '', ' AND t.status = ' . Answer::STATUS_VALIDATED . ' AND t.fk_question = ' . $questionLinked->id . ' AND t.position = ' . $line->answer); + + if ($result <= 0) { + continue; // Skip if answer is not valid } + $averagePercentageQuestions += $answer->value; } } } diff --git a/view/question/question_card.php b/view/question/question_card.php index 29fa7c4e..73dd75f1 100644 --- a/view/question/question_card.php +++ b/view/question/question_card.php @@ -491,6 +491,17 @@ $object->$type = ''; } } + + $oldConfig = json_decode($object->json, true) ?? []; + + $objectConfig = ['config' => []]; + if ($object->type == 'Percentage') { + $objectConfig['config'][$object->type]['step'] = !empty(GETPOSTINT('step')) ? GETPOSTINT('step') : $oldConfig['config'][$object->type]['step']; + $objectConfig['config'][$object->type]['isCursor'] = GETPOST('is_cursor') == 'on' ? 1 : 0; + } + + $object->json = json_encode($objectConfig); + $result = $object->update($user); $newType = $object->type; @@ -538,7 +549,25 @@ } } + if (!empty($oldConfig['config'][$object->type]['isCursor']) && empty($objectConfig['config'][$object->type]['isCursor'])) { + $count = 0; + for ($i = 0; $i < 100; $i += 100 / ($objectConfig['config'][$object->type]['step'] - 1)) { + $answer->fk_question = $result; + $answer->value = ceil($i); + $answer->pictogram = $i > 66 ? 'smile' : ($i > 33 ? 'meh' : 'sad'); + $answer->color = interpolateColor([0 => '#D53C3D', 25 =>'#ED911D', 50 => '#F2C32E', 75 => '#92D444', 100 => '#57AD39'], $i); + $answer->create($user); + $count++; + } + if ($count < $objectConfig['config'][$object->type]['step'] && $answer->value != 100) { + $answer->fk_question = $result; + $answer->value = 100; + $answer->pictogram = 'smile'; + $answer->color = '#57AD39'; + $answer->create($user); + } + } } $urltogo = $backtopage ? str_replace('__ID__', $result, $backtopage) : $backurlforlist; @@ -900,12 +929,12 @@ // Step for percentage question type default hidden print ''; - print ''; + print 'type]['isCursor']) || $objectConfig['config'][$object->type]['isCursor'] ? '' : 'disabled') . '>'; print ''; // Is percentage or emoji question type print ''; - print 'type]['isCursor']) ? '' : ' checked=""') . '>'; + print 'type]['isCursor']) && !$objectConfig['config'][$object->type]['isCursor'] ? '' : ' checked') . ' ' . (!isset($objectConfig['config'][$object->type]['isCursor']) || $objectConfig['config'][$object->type]['isCursor'] ? '' : 'disabled') .'>'; print $form->textwithpicto('', $langs->transnoentities('IsCursorPercentageTooltip')); print ''; diff --git a/view/survey/survey_card.php b/view/survey/survey_card.php index 29cead67..0aef2ab9 100644 --- a/view/survey/survey_card.php +++ b/view/survey/survey_card.php @@ -524,6 +524,8 @@ $averagePercentageQuestions = 0; $percentQuestionCounter = 0; + $answer = new Answer($db); + foreach ($sheet->linkedObjects['digiquali_question'] as $questionLinked) { if ($questionLinked->type !== 'Percentage') { continue; // Skip non-percentage questions @@ -531,17 +533,17 @@ $percentQuestionCounter++; foreach ($object->lines as $line) { - if ($line->fk_question === $questionLinked->id && is_numeric($line->answer)) { - $config = json_decode($questionLinked->json, true); - if (!isset($config['config'][$questionLinked->type]['isCursor']) || !empty($config['config'][$questionLinked->type]['isCursor'])) { - $averagePercentageQuestions += $line->answer; - } elseif ($line->answer - 1 == 0) { - $averagePercentageQuestions += 0; - } elseif ($line->answer == $config['config'][$questionLinked->type]['step']) { - $averagePercentageQuestions += 100; - } else { - $averagePercentageQuestions += (($line->answer) / ($config['config'][$questionLinked->type]['step'])) * 100; + $config = json_decode($question->json, true); + + if ($line->fk_question === $questionLinked->id && is_numeric($line->answer) && (!isset($config['config'][$question->type]['isCursor']) || !empty($config['config'][$question->type]['isCursor']))) { + $averagePercentageQuestions += $line->answer; + } else { + $result = $answer->fetch('', '', ' AND t.status = ' . Answer::STATUS_VALIDATED . ' AND t.fk_question = ' . $questionLinked->id . ' AND t.position = ' . $line->answer); + + if ($result <= 0) { + continue; // Skip if answer is not valid } + $averagePercentageQuestions += $answer->value; } } }