Revue formulaire édition des abonnés/administrateur site : template wikilerni + optimisation script JS.

This commit is contained in:
Fabrice PENHOËT 2020-09-24 17:09:17 +02:00
parent 0cf5a82418
commit 303bb0e2e1
4 changed files with 479 additions and 541 deletions

View File

@ -2,25 +2,25 @@ module.exports =
{
// API'routes (after "apiUrl" defined in instance.js)
userRoutes: "/user",
subscribeRoute: "/signup",
getGodfatherRoute: "/getgodfatherid",
checkDeleteLinkRoute: "/confirmdelete/",
checkIfIsEmailfreeRoute: "/isemailfree",
checkSubscribeTokenRoute: "/validation/",
checkLoginRoute: "/checklogin/",
connectionRoute: "/login",
getLoginLinkRoute: "/getloginlink",
connectionWithLinkRoute: "/checkloginlink",
getUserInfos: "/get/",
createUserRoute: "/create",
validateUserRoute: "/validate/",
updateUserInfos: "/modify/",
searchUserRoute: "/search/",
getGodChilds: "/getgodchilds/",
checkNewLoginLinkRoute: "/confirmnewlogin/",
checkDeleteLinkRoute: "/confirmdelete/",
getPayments: "/payment/getforoneuser/",
unsubscribeRoute: "/subscription/stop/",
checkSubscribeTokenRoute: "/validation/",
connectionRoute: "/login",
connectionWithLinkRoute: "/checkloginlink",
createUserRoute: "/create",
getAdminStats: "/getadminstats/",
getGodChilds: "/getgodchilds/",
getGodfatherRoute: "/getgodfatherid",
getLoginLinkRoute: "/getloginlink",
getPayments: "/payment/getforoneuser/",
getUserInfos: "/get/",
searchUserRoute: "/search/",
subscribeRoute: "/signup",
unsubscribeRoute: "/subscription/stop/",
updateUserInfos: "/modify/",
validateUserRoute: "/validate/",
// forms : à compléter avec valeurs par défaut, etc. cf modèle
name: { maxlength: 70, required: true },
email: { maxlength: 255, required: true },
@ -28,6 +28,7 @@ module.exports =
newPassword: { minlength: 8, maxlength:72 },
codeGodfather: { maxlength: 255 },
cguOk: { value: "true", required: true },
search: { minlength: 3, required: true },
timeDifferenceMin: -720,
timeDifferenceMax:840,
// JSON dir

View File

@ -1,207 +1,140 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Gestion des abonnés">
<meta name="robots" content="noindex">
<title>Les abonnés</title>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Gestion des abonnés.">
<meta name="robots" content="noindex">
<title>Mon WikiLerni</title>
<!-- Version lisible des scripts : https://gitlab.com/lefablab/wikilerni/-/tree/master/front/src -->
<script src="/JS/polyfill.app.js" defer></script>
<script src="/JS/manageUsers.app.js" defer></script>
<link rel="shortcut icon" href="/img/favicon.ico">
<link rel="stylesheet" href="/themes/default/CSS/pure-min.css">
<link rel="stylesheet" href="/themes/default/CSS/grids-responsive-min.css">
<link rel="stylesheet" href="/themes/default/CSS/wikilerni.css">
<link rel="canonical" href="https://www.wililerni.com/gestion-utilisateurs.html">
</head>
<script src="/JS/polyfill.app.js" defer></script>
<script src="/JS/manageUsers.app.js" defer></script>
<link rel="shortcut icon" href="/img/favicon.ico">
<link rel="stylesheet" href="/themes/wikilerni/css/style.css">
</head>
<body>
<header class="pure-g menu">
<div class="pure-u-1 pure-u-lg-1-8 menu-heading">
<a class="pure-menu-heading" href="/">WikiLerni</a>
</div>
<div class="pure-u-1 pure-u-lg-7-8">
<ul class="pure-g">
<li class="pure-menu-item pure-u-1 pure-u-lg-1-4">
<a class="pure-menu-link" href="/">Accueil</a>
</li>
<li class="pure-menu-item pure-u-1 pure-u-lg-1-4">
<a class="pure-menu-link" href="/connexion.html" id="accountHeadLink">Mon compte</a>
</li>
<li class="pure-menu-item pure-u-1 pure-u-lg-1-4">
<a class="pure-menu-link" href="/a-propos.html">À propos</a>
</li>
<li class="pure-menu-item pure-u-1 pure-u-lg-1-4">
<a class="pure-menu-link" href="/contact.html">Contact</a>
</li>
</ul>
</div>
</header>
<section id="main-content" class="needJS">
<div class="pure-menu pure-menu-horizontal">
<a href="/gestion.html" class="pure-menu-heading pure-menu-link">Gestion WikiLerni</a>
<ul id="classement" class="pure-menu-list">
<li class="pure-menu-item"><a href="/gestion-quizs.html" title="Publication des quizs" class="pure-menu-link" >Les quizs</a></li>
<li class="pure-menu-item"><a href="/gestion-utilisateurs.html" title="Les comptes utilisateurs" class="pure-menu-link">Les abonné(e)s</a></li>
<li class="pure-menu-item"><a href="/sortie.html" title="Sortie des artistes !" class="pure-menu-link">Me déconnecter</a></li>
</ul>
</div>
<div class="content">
<h2 class="content-head is-center" id="infos">Les abonnés</h2>
<form class="pure-form pure-u-1" id="search" method="POST">
<fieldset>
<legend>Chercher un utilisateur</legend>
<input id="search" type="txt" name="search" placeholder="Votre recherche">
<button type="submit" class="pure-button pure-button-primary">Chercher</button>
<body class="cardboard">
<!-- En tête -->
<header class="cardboard">
<a href="/" title="Page d'accueil WikLerni"><img src="/themes/wikilerni/img/wikilerni-purple-2-128.png" alt="WikiLerni (logo)" title="Accéder à la page d'accueil de WikiLerni" /></a>
<ul id="headLinks">
<li><a href="/contact.html" rel="nofollow">Contact</a></li>
<li><a href="/quizs/" id="indexHeadLink" title="Les derniers quizs">Parcourir</a></li>
<li><a href="/connexion.html" id="accountHeadLink">Mon compte</a></li>
<li><a href="/a-propos.html">À propos</a></li>
<li><a href="/" title="Page d'accueil de WikiLerni">Accueil</a></li>
</ul>
</header>
<div id="crash"></div>
<section id="main-content" class="needJS">
<ul id="menu" class="cardboard">
<li><a href="/gestion.html">Gestion WikiLerni</a></li>
<li><a href="/gestion-quizs.html" title="Publication des quizs">Les quizs</a></li>
<li><a href="/gestion-utilisateurs.html" title="Les comptes utilisateurs">Les abonné(e)s</a></li>
<li><a href="/sortie.html">Me déconnecter</a></li>
</ul>
<div id="account" class="cardboard">
<h1 class="cardboard" id="infos">Les abonnés</h1>
<h2>Chercher un abonné</h2>
<form id="searchUsers" method="POST">
<input id="search" type="text" name="search" placeholder="Votre recherche" class="cardboard" />
<div class="input_wrapper"><input type="submit" value="Chercher" class="cardboard" /></div>
<div id="searchResult"></div>
</fieldset>
</form>
<div class="pure-g">
<div class="l-box-lrg pure-u-1">
<div id="message"></div>
<form class="pure-form pure-form-aligned" id="users" method="POST">
<fieldset>
<legend>Informations de l'abonné</legend>
<div id="subscribeIntro"></div>
<div class="pure-control-group">
<label for="name">Nom ou pseudo</label>
<input id="name" type="text" name="name">
<span class="pure-form-message-inline"></span>
</div>
<div class="pure-control-group">
<label for="email">Email</label>
<input id="email" type="email" name="email">
<span class="pure-form-message-inline" id="emailMessage"></span>
</div>
<div class="pure-control-group">
<label for="status">Statut</label>
<select id="status" name="status">
<option value="user">Utilisateur</option>
<option value="creator">Créateur</option>
<option value="manager">Gestionnaire</option>
<option value="admin">Administrateur</option>
</select>
</div>
</form>
<div class="pure-control-group">
<label for="smtp">SMTP</label>
<select id="smtp" name="smtp">
<option value="0">Spirion</option>
<option value="1">Mailjet</option>
</select>
</div>
<h2 id="infos">Informations de l'abonné</h2>
<div id="subscribeIntro"></div>
<div id="message"></div>
<form id="users" method="POST">
<fieldset><label for="name">Nom ou pseudo</label><input id="name" type="text" name="name" class="cardboard"></fieldset>
<fieldset><label for="email">Email</label><input id="email" type="email" name="email" class="cardboard">
<div id="emailMessage"></div></fieldset>
<fieldset>
<label for="status">Statut</label>
<select id="status" name="status" class="cardboard">
<option value="user">Utilisateur</option>
<option value="creator">Créateur</option>
<option value="manager">Gestionnaire</option>
<option value="admin">Administrateur</option>
</select>
</fieldset>
<fieldset>
<label for="smtp">SMTP</label>
<select id="smtp" name="smtp" class="cardboard">
<option value="0">Spirion</option>
<option value="1">Mailjet</option>
</select>
</fieldset>
<fieldset><label for="timeDifference">Décalage horaire</label><input id="timeDifference" type="number" name="timeDifference" readonly class="cardboard"></fieldset>
<fieldset><label for="newPassword">Nouveau mot de passe</label><input id="newPassword" type="password" name="newPassword" class="cardboard">
<div id="newPasswordMessage"><span class="info">Laisser vide sauf si vous souhaitez le changer.</span></div></fieldset>
<fieldset><label for="adminComments">Commentaires</label><textarea id="adminComments" name="adminComments" rows="5" class="cardboard"></textarea></fieldset>
<fieldset><label for="numberOfDays">Durée totale de l'abonnement</label><input id="numberOfDays" type="number" name="numberOfDays" class="cardboard"><span class="info">Depuis la création de son compte.</span></fieldset>
<div class="framed">
<p>Jours valables pour l'abonnement</p>
<ul class="checkbox_li">
<li class="checkbox_li">
<label for="d2" class="check"><input type="checkbox" id="d2" name="d2" value="true" /><div class="checkbox_override"></div> Lundi.</label>
</li>
<li class="checkbox_li">
<label for="d3" class="check"><input type="checkbox" id="d3" name="d3" value="true" /><div class="checkbox_override"></div> Mardi.</label>
</li>
<li class="checkbox_li">
<label for="d4" class="check"><input type="checkbox" id="d4" name="d4" value="true" /><div class="checkbox_override"></div> Mercredi.</label>
</li>
<li class="checkbox_li">
<label for="d5" class="check"><input type="checkbox" id="d5" name="d5" value="true" /><div class="checkbox_override"></div> Jeudi.</label>
</li>
<li class="checkbox_li">
<label for="d6" class="check"><input type="checkbox" id="d6" name="d6" value="true" /><div class="checkbox_override"></div> Vendredi.</label>
</li>
<li class="checkbox_li">
<label for="d7" class="check"><input type="checkbox" id="d7" name="d7" value="true" /><div class="checkbox_override"></div> Samedi.</label>
</li>
<li class="checkbox_li">
<label for="d1" class="check"><input type="checkbox" id="d1" name="d1" value="true" /><div class="checkbox_override"></div> Dimanche.</label>
</li>
</ul>
</div>
<ul class="checkbox_li">
<li class="checkbox_li">
<label for="noticeOk" class="check"><input type="checkbox" id="noticeOk" name="noticeOk" value="true" /><div class="checkbox_override"></div> Reçoit les quizs par email.</label>
</li>
<li class="checkbox_li">
<label for="newsletterOk" class="check"><input type="checkbox" id="newsletterOk" name="newsletterOk" value="true" /><div class="checkbox_override"></div> Reçoit les autres actus par email.</label>
</li>
<li class="checkbox_li">
<label for="validationOk" id="validationOkLabel" class="check"><input type="checkbox" id="validationOk" name="validationOk" value="true" /><div class="checkbox_override"></div> Valider le compte.</label>
</li>
<li class="checkbox_li">
<label for="deleteOk" class="check" id="deleteOkLabel"><input type="checkbox" id="deleteOk" name="deleteOk" value="true" /><div class="checkbox_override"></div> <span class="error">Supprimer ce compte utilisateur.</span></label>
</li>
</ul>
<input type="hidden" name="id" id="id" value="">
<div class="input_wrapper"><input type="submit" value="Valider." class="cardboard" id="submitDatas" /></div>
<div class="input_wrapper"><a href="#users" class="button cardboard" id="wantNewUser">Vider.</a></div>
</form>
<div id="response"></div>
<h2>Payments reçus via l'API WebPortage</h2>
<div id="infosPayments" class="needJS"></div>
<h2>Parrainages</h2>
<div id="infosGodchilds" class="needJS"></div>
</section>
<div class="pure-control-group">
<label for="timeDifference">Décalage horaire</label>
<input id="timeDifference" type="number" name="timeDifference" readonly>
</div>
<div class="pure-control-group">
<label for="newPassword">Nouveau mot de passe</label>
<input id="newPassword" type="password" name="newPassword">
<span class="pure-form-message-inline" id="newPasswordMessage"><b class="information">Laisser vide sauf si vous souhaitez le changer.</b></span>
</div>
<div class="pure-control-group">
<label for="adminComments">Commentaires</label>
<textarea id="adminComments" name="adminComments" rows="5"></textarea>
</div>
<div class="pure-control-group">
<label for="numberOfDays">Durée totale de l'abonnement</label>
<input id="numberOfDays" type="number" name="numberOfDays"><span class="pure-form-message-inline"><i class="information">Depuis la création de son compte.</i></span>
</div>
<div class="pure-controls">
Jours valables pour l'abonnement
<ul class="pure-g">
<li class="pure-u-1 pure-u-lg-1-7"><!-- grille ne fonctionne pas ?! -->
<label for="d2">
<input type="checkbox" id="d2" name="d2" value="true" /> Lundi
</label>
</li>
<li class="pure-u-1 pure-u-lg-1-7">
<label for="d3">
<input type="checkbox" id="d3" name="d3" value="true" /> Mardi
</label>
</li>
<li class="pure-u-1 pure-u-lg-1-7">
<label for="d4">
<input type="checkbox" id="d4" name="d4" value="true" /> Mercredi
</label>
</li>
<li class="pure-u-1 pure-u-lg-1-7">
<label for="d5">
<input type="checkbox" id="d5" name="d5" value="true" /> Jeudi
</label>
</li>
<li class="pure-u-1 pure-u-lg-1-7">
<label for="d6">
<input type="checkbox" id="d6" name="d6" value="true" /> Vendredi
</label>
</li>
</li>
<li class="pure-u-1 pure-u-lg-1-7">
<label for="d7">
<input type="checkbox" id="d7" name="d7" value="true" /> Samedi
</label>
</li>
<li class="pure-u-1 pure-u-lg-1-7">
<label for="d1">
<input type="checkbox" id="d1" name="d1" value="true" /> Dimanche
</label>
</li>
</ul>
</div>
<div class="pure-controls">
<label for="noticeOk" class="pure-checkbox">
<input type="checkbox" id="noticeOk" name="noticeOk" value="true" /> Reçoit les quizs par email.
</label>
<label for="newsletterOk" class="pure-checkbox">
<input type="checkbox" id="newsletterOk" name="newsletterOk" value="true" /> Reçoit les autres actus par email.
</label>
<label for="validationOk" class="pure-checkbox success" id="validationOkLabel">
<input type="checkbox" id="validationOk" name="validationOk" /> Valider le compte.
</label>
<label for="deleteOk" class="pure-checkbox error" id="deleteOkLabel">
<input type="checkbox" id="deleteOk" name="deleteOk" /> Supprimer le compte
</label>
<input type="hidden" name="id" id="id" value="">
<button type="submit" class="pure-button pure-button-primary" id="submitDatas">Valider</button>
<a href="#users" class="pure-button pure-button-primary" id="wantNewUser">Vider</a>
</div>
<div id="response"></div>
<div id="infosPayments" class="needJS"><h4>Payments reçus via l'API WebPortage</h4></div>
<div id="infosGodchilds" class="needJS"><h4>Parrainages</h4></div>
</fieldset>
</form>
</div>
</div>
</div>
</section>
<footer class="footer l-box is-center">
<ul class="pure-g">
<li class="pure-u-1 pure-u-lg-1-5">
<a href="/mentions-legales.html">Crédits</a>
</li>
<li class="pure-u-1 pure-u-lg-1-5">
<a href="/mentions-legales.html">Mentions légales</a>
</li>
<li class="pure-u-1 pure-u-lg-1-5">
<a href="/donnees.html">Données personnelles</a>
</li>
<li><a href="/CGV-CGU.html">CGV &amp; CGU</a></li>
</ul>
</footer>
</body>
<footer class="cardboard">
<ul id="footLinks">
<li><a href="https://framasphere.org/people/7e54b7a0b53201389eef2a0000053625" title="Blog WikiLerni sur diaspora*">Blog</a></li>
<li><a href="/credits.html">Crédits</a></li>
<li><a href="/mentions-legales.html" rel="nofollow">Mentions légales</a></li>
<li><a href="/donnees.html">Données personnelles</a></li>
<li><a href="/CGV-CGU.html" rel="nofollow">CGV &amp; CGU</a></li>
</ul>
</footer>
</body>
</html>

View File

@ -258,7 +258,8 @@ label.check
padding:0;
margin:0;
}
input[type=submit], input[type=text], input[type=email], input[type=password], .button
input[type=submit], input[type=text], input[type=email], input[type=password], input[type=number],
select, textarea, .button
{
background-color: #8c599c;
padding: 10px;
@ -278,7 +279,7 @@ input[type=submit]:hover, .button:hover
margin-top: 2px;
box-shadow: inset 0px 1px 0px rgba(255,255,255,0.66), inset 0px -1px 0px rgba(0, 0, 0,0.66), 0px 0px 5px rgba(0,0,0,0.66);
}
input[type=text], input[type=password], input[type=email]
input[type=text], input[type=password], input[type=email], textarea
{
box-shadow: inset 0 1px 0 rgba(0,0,0,0.66), inset 0 -1px 0 rgba(255,255,255,0.66), inset 0 3px 8px rgba(0,0,0,0.66);
width: 95%;
@ -291,6 +292,13 @@ margin-left: 0;
margin-right: -15px;
opacity:0.0;
}
/* This allow the motion of the button while overing without displacing the content of the page */
.input_wrapper
{
height: 40px;
display: inline-block;
margin: 0.5em;
}
/* The following is a trick to force browser to let me redefine checkbox style */
.checkbox_override
{
@ -350,13 +358,7 @@ text-align:left;
line-height:1.5em;
}
/* This allow the motion of the button while overing without displacing the content of the page : vérifier que cela est utilisé ?
.input_wrapper
{
height: 40px;
display: inline-block;
margin-top: 1em;
}*/
/* Sous-menu pour tags ou utilisateur connecté, etc. */
#menu
{

View File

@ -7,364 +7,366 @@
/// À ajouter :
/// - importation liste de comptes utilisateur à créer
/// - attribution d'un parrain à un utilisateur (via un moteur de recherche). Prévu par le contrôleur.
/// - attribution d'un parrain à un utilisateur (via un moteur de recherche). Déjà prévu par le contrôleur.
// Fichier de configuration côté client :
import { apiUrl, availableLangs, theme } from "../../config/instance.js";
const lang=availableLangs[0];
const configFrontEnd = require("../../views/"+theme+"/config/"+lang+".js");
const configUsers = require("../../config/users.js");
const configTemplate = require("../../views/"+theme+"/config/"+lang+".js");
// Fonctions utiles au script : !! revoir quand le reste sera fini pour vérifier si tout est utile
import { getLocaly, removeLocaly, saveLocaly } from "./tools/clientstorage.js";
// Fonctions utiles au script :
import { getLocaly, removeLocaly } from "./tools/clientstorage.js";
import { addElement } from "./tools/dom.js";
import { helloDev, updateAccountLink } from "./tools/everywhere.js";
import { empyForm, getDatasFromInputs, setAttributesToInputs } from "./tools/forms.js";
import { dateFormat, isEmpty, replaceAll } from "../../tools/main";
import { getUrlParams } from "./tools/url.js";
import { checkSession, getConfig, getPassword } from "./tools/users.js";
import { checkSession, getPassword } from "./tools/users.js";
// Dictionnaires :
const txt = require("../../lang/"+lang+"/general");
const txtUsers = require("../../lang/"+lang+"/user");
const txtSubscriptions = require("../../lang/"+lang+"/subscription");
helloDev();
const txtAddOkMessage = require("../../lang/"+lang+"/general").addOkMessage;
const txtServerError = require("../../lang/"+lang+"/general").serverError;
const txtInfosAdminGodfather = require("../../lang/"+lang+"/user").infosAdminGodfather;
const txtInfosAdminNbGodChilds = require("../../lang/"+lang+"/user").infosAdminNbGodChilds;
const txtInfosUserForAdmin = require("../../lang/"+lang+"/user").infosUserForAdmin;
const txtNeedBeConnected = require("../../lang/"+lang+"/user").needBeConnected;
const txtNotFound = require("../../lang/"+lang+"/user").notFound;
const txtInfosExpiratedAdmin = require("../../lang/"+lang+"/subscription").infosExpiratedAdmin;
const txtInfosNbDaysAdmin = require("../../lang/"+lang+"/subscription").infosNbDaysAdmin;
const txtInfosPaymentsAdmin = require("../../lang/"+lang+"/subscription").infosPaymentsAdmin;
const txtIsNotValided = require("../../lang/"+lang+"/subscription").isNotValided;
// Principaux éléments du DOM manipulés :
const divMain = document.getElementById("main-content");
const divMessage = document.getElementById("message");
const divResponse = document.getElementById("response");
const divCrash = document.getElementById("crash");
const divSubscribeIntro = document.getElementById("subscribeIntro");
const divPaymentsInfos = document.getElementById("infosPayments");
const divGodchildsInfos = document.getElementById("infosGodchilds");
const formUser = document.getElementById("users");
const deleteCheckBox = document.getElementById("deleteOkLabel");
const validationCheckBox = document.getElementById("validationOkLabel");
const btnNewUser = document.getElementById("wantNewUser");
const newPassword = document.getElementById("newPassword");
const timeDifference = document.getElementById("timeDifference");
const formSearch = document.getElementById("search");
const formSearch = document.getElementById("searchUsers");
const divSearchResult = document.getElementById("searchResult");
helloDev();
const initialise = async () =>
{
try
{
const config = await getConfig();
if(!config)
addElement(divMessage, "p", txt.serverError, "", ["error"]);
else
{
const isConnected=await checkSession(["manager", "admin"], "/"+configTemplate.connectionPage, { message: txtNeedBeConnected, color:"error" }, window.location);
if(isConnected)
{
const isConnected=await checkSession(["manager", "admin"], "/"+configFrontEnd.connectionPage, { message: txtUsers.needBeConnected, color:"error" }, window.location);
if(isConnected)
const user=getLocaly("user", true);
updateAccountLink(user.status, configTemplate);
divMain.style.display="block";
if(!isEmpty(getLocaly("message")))
{
const user=getLocaly("user", true);
updateAccountLink(user.status, configFrontEnd);
divMain.style.display="block";
if(!isEmpty(getLocaly("message")))
{
addElement(divMessage, "p", getLocaly("message", true).message, "", [getLocaly("message", true).color], "", false);
removeLocaly("message");
}
// Initialisation du formulaire de recherche :
setAttributesToInputs(config, formSearch);
// Fonction utile pour vider le formulaire, y compris les champs hidden, etc.
// Cache aussi certains champs en mode création
const emptyUserForm = () =>
{
empyForm(formUser);
// Case de suppression cachée par défaut, car inutile pour formulaire de création
deleteCheckBox.style.display="none";
// Case de validation cachée par défaut, car utile que dans certains cas
validationCheckBox.style.display="none";
divSubscribeIntro.innerHTML="";
divPaymentsInfos.innerHTML="";
divGodchildsInfos.innerHTML="";
// Certains navigateurs ont tendance à remplir tout seul les champs password
newPassword.value="";
// En mode création, pas de champ pour changer le mot de passe
newPassword.parentNode.style.display="none";
// Inutile en mode création
timeDifference.parentNode.style.display="none";
}
emptyUserForm();
// Initialise les contraintes du formulaire :
setAttributesToInputs(config, formUser);
// Fonction affichant les infos connues concernant un utilisateur et son abonnement
const showFormUserInfos = (id) =>
{
// on commence par tout vider, des fois que... :
emptyUserForm();
const xhrGetInfos = new XMLHttpRequest();
xhrGetInfos.open("GET", apiUrl+config.userRoutes+config.getUserInfos+id);
xhrGetInfos.onreadystatechange = function()
{
if (this.readyState == XMLHttpRequest.DONE)
{
let response=JSON.parse(this.responseText);
if (this.status === 200 && response.User != undefined)
{
newPassword.parentNode.style.display="block";
timeDifference.parentNode.style.display="block";
const mapText =
{
ID_USER : response.User.id,
DATE_CREA : dateFormat(response.User.createdAt),
DATE_UPDATE : dateFormat(response.User.updatedAt),
DATE_CONNECTION : dateFormat(response.User.connectedAt)
};
let subscribeIntro=replaceAll(txtUsers.infosUserForAdmin, mapText);
for(let data in response.User)
{
if(formUser.elements[data]!==undefined)
{
if(response.User[data]!==true && response.User[data]!==false)// booléen = case à cocher !
formUser.elements[data].value=response.User[data];
else if (response.User[data]==true) // si false, on ne fait rien
formUser.elements[""+data].checked="checked";
}
}
if(response.Subscription != undefined)
{
// nombre de jours de l'abonnement
formUser.elements["numberOfDays"].value=response.Subscription["numberOfDays"];
// infos de l'abonnement
if(response.Subscription.noticeOk==true)
formUser.elements["noticeOk"].checked="checked";
// jours de réception
for(let i in response.Subscription.receiptDays)
formUser.elements["d"+response.Subscription.receiptDays[i]].checked="checked";
const beginSubTS=new Date(response.Subscription.createdAt).getTime();
const nbDaysOk=response.Subscription.numberOfDays-Math.round((Date.now()-beginSubTS)/1000/3600/24);
if(nbDaysOk>0)
subscribeIntro+="<br>"+txtSubscriptions.infosNbDaysAdmin.replace("NB_DAYS", nbDaysOk);
else
subscribeIntro+="<br>"+txtSubscriptions.infosExpiratedAdmin;
addElement(divSubscribeIntro, "p", subscribeIntro, "", ["information"], "", false);
}
else
{
addElement(divSubscribeIntro, "p", txtSubscriptions.isNotValided, "", ["error"]);
validationCheckBox.style.display="block";
}
deleteCheckBox.style.display="block";
// Infos de paiements via API WP
const xhrGetPaymentsInfos = new XMLHttpRequest();
xhrGetPaymentsInfos.open("GET", apiUrl+config.getPayments+response.User.id);
xhrGetPaymentsInfos.onreadystatechange = function()
{
if (this.readyState == XMLHttpRequest.DONE)
{
let responsePay=JSON.parse(this.responseText);
if (this.status === 200)
{
if(responsePay.length!==0)
{
let txtPayments="";
for(let i in responsePay)
{
const mapText =
{
DATE_PAYMENT : dateFormat(responsePay[i].createdAt, "fr"),
AMOUNT : responsePay[i].amount,
CLIENT_NAME : responsePay[i].clientName
};
txtPayments+="<li>"+replaceAll(txtSubscriptions.infosPaymentsAdmin, mapText)+"</li>";
}
addElement(divPaymentsInfos, "ul", txtPayments, "", ["information"], "", false);
divPaymentsInfos.style.display="block"
}
}
}
}
xhrGetPaymentsInfos.setRequestHeader("Authorization", "Bearer "+user.token);
xhrGetPaymentsInfos.send();
// Un parrain ou deux par deux ?
let txtGodchilds="";
if(!isEmpty(response.User.GodfatherId))
{
const xhrGetGodFatherInfos = new XMLHttpRequest();
xhrGetGodFatherInfos.open("GET", apiUrl+config.userRoutes+config.getUserInfos+response.User.GodfatherId);
xhrGetGodFatherInfos.onreadystatechange = function()
{
if (this.readyState == XMLHttpRequest.DONE)
{
let responseGF=JSON.parse(this.responseText);
if (this.status === 200 && responseGF.User != undefined)
txtGodchilds+=txtUsers.infosAdminGodfather+"<a href='/"+configFrontEnd.usersManagementPage+"?id="+responseGF.User.id+"' target='_blank'>"+responseGF.User.name+"</a>"+".<br>";
}
}
xhrGetGodFatherInfos.setRequestHeader("Authorization", "Bearer "+user.token);
xhrGetGodFatherInfos.send();
}
// Des filleuls ?
const xhrGetGodchilds = new XMLHttpRequest();
xhrGetGodchilds.open("GET", apiUrl+config.userRoutes+config.getGodChilds+id);
xhrGetGodchilds.onreadystatechange = function()
{
if (this.readyState == XMLHttpRequest.DONE)
{
let responseGS=JSON.parse(this.responseText);
if (this.status === 200)
{
if(responseGS.length!==0)
{
txtGodchilds+=txtUsers.infosAdminNbGodChilds.replace("#NB", responseGS.length);
for(let i in responseGS)
txtGodchilds+="<a href='/"+configFrontEnd.usersManagementPage+"?id="+responseGS[i].id+"' target='_blank'>"+responseGS[i].name+"</a>";
}
}
}
}
xhrGetGodchilds.setRequestHeader("Authorization", "Bearer "+user.token);
xhrGetGodchilds.send();
if(txtGodchilds!=="")
{
addElement(divGodchildsInfos, "p", txtGodchilds+".", "", ["information"], "", false);
divGodchildsInfos.style.display="block";
}
}
}
}
xhrGetInfos.setRequestHeader("Authorization", "Bearer "+user.token);
xhrGetInfos.send();
}
// Si un id est passé par l'url, on essaye d'afficher l'utilisateur :
let urlDatas=getUrlParams();
if(urlDatas && urlDatas.id!==undefined)
showFormUserInfos(urlDatas.id);
// Besoin d'un coup de Kärcher ?
btnNewUser.addEventListener("click", function(e)
{
emptyUserForm();
});
// Envoi du formulaire des infos de l'utilisateur
formUser.addEventListener("submit", function(e)
{
e.preventDefault();
divResponse.innerHTML="";
let datas=getDatasFromInputs(formUser);
// recomposition des jours valables pour l'abonnement :
datas.receiptDays="";
for(let i=1; i<=7; i++)
{
if(datas["d"+i]!==undefined)
datas.receiptDays+=""+i;
}
if(datas.noticeOk===undefined)
datas.noticeOk="false";
if(datas.newsletterOk===undefined)
datas.newsletterOk="false";
const xhrUserDatas = new XMLHttpRequest();
if(!isEmpty(datas.id) && (datas.deleteOk!==undefined))
xhrUserDatas.open("DELETE", apiUrl+config.userRoutes+"/"+datas.id);
else if(!isEmpty(datas.id) && (datas.validationOk!==undefined))
xhrUserDatas.open("POST", apiUrl+config.userRoutes+config.validateUserRoute+datas.id);
else if(!isEmpty(datas.id))
xhrUserDatas.open("PUT", apiUrl+config.userRoutes+config.updateUserInfos+datas.id);
else
{
datas.password=getPassword(config.password.minlength, config.password.minlength+2);// mot de passe temporaire
xhrUserDatas.open("POST", apiUrl+config.userRoutes+config.createUserRoute);
}
xhrUserDatas.onreadystatechange = function()
{
if (this.readyState == XMLHttpRequest.DONE)
{
let response=JSON.parse(this.responseText);
if (this.status === 201 && response.id!=undefined)
{
addElement(divResponse, "p", txt.addOkMessage, "", ["success"]);
datas.id=response.id;
}
else if (this.status === 200 && response.message!=undefined)
{
if(Array.isArray(response.message))
response.message = response.message.join("<br>");
else
response.message = response.message;
addElement(divResponse, "p", response.message, "", ["success"]);
}
else if (response.errors)
{
if(Array.isArray(response.errors))
response.errors = response.errors.join("<br>");
else
response.errors = txt.serverError;
addElement(divResponse, "p", response.errors, "", ["error"]);
}
else
addElement(divResponse, "p", txt.serverError, "", ["error"]);
if(isEmpty(response.errors))
{
if(datas.deleteOk===undefined)
showFormUserInfos(datas.id);// peut avoir évolué suivant ce qui s'est passé
else
emptyUserForm();
}
}
}
xhrUserDatas.setRequestHeader("Content-Type", "application/json");
xhrUserDatas.setRequestHeader("Authorization", "Bearer "+user.token);
if(datas)
xhrUserDatas.send(JSON.stringify(datas));
});
// Traitement du lancement d'une recherche
formSearch.addEventListener("submit", function(e)
{
e.preventDefault();
let datas=getDatasFromInputs(formSearch);
const xhrSearch = new XMLHttpRequest();
xhrSearch.open("POST", apiUrl+config.userRoutes+config.searchUserRoute);
xhrSearch.onreadystatechange = function()
{
if (this.readyState == XMLHttpRequest.DONE)
{
let response=JSON.parse(this.responseText);
if (this.status === 200 && Array.isArray(response))
{
if(response.length===0)
addElement(divSearchResult, "p", txtUsers.notFound, "", ["information"]);
else
{
let selectHTML="<option value=''></option>";
for(let i in response)
selectHTML+="<option value='"+response[i].id+"'>"+response[i].name+" ("+response[i].email+")</option>";
addElement(divSearchResult, "select", selectHTML, "selectSearch");
const searchSelect=document.getElementById("selectSearch");
searchSelect.addEventListener("change", function()
{
if(searchSelect.value!=="")
showFormUserInfos(searchSelect.value);
});
}
}
else
addElement(divSearchResult, "p", txt.serverError, "", ["error"]);
}
}
xhrSearch.setRequestHeader("Content-Type", "application/json");
xhrSearch.setRequestHeader("Authorization", "Bearer "+user.token);
if(datas)
xhrSearch.send(JSON.stringify(datas));
});
addElement(divMessage, "p", getLocaly("message", true).message, "", [getLocaly("message", true).color], "", false);
removeLocaly("message");
}
// Initialisation du formulaire de recherche :
setAttributesToInputs(configUsers, formSearch);
// Fonction utile pour vider le formulaire, y compris les champs hidden, etc.
// Cache aussi certains champs en mode création
const emptyUserForm = () =>
{
empyForm(formUser);
// Case de suppression cachée par défaut, car inutile pour formulaire de création
deleteCheckBox.style.display="none";
// Case de validation cachée par défaut, car utile que dans certains cas
validationCheckBox.style.display="none";
divSubscribeIntro.innerHTML="";
divPaymentsInfos.innerHTML="";
divGodchildsInfos.innerHTML="";
// Certains navigateurs ont tendance à remplir tout seul les champs configUsers.password
newPassword.value="";
// En mode création, pas de champ pour changer le mot de passe
newPassword.parentNode.style.display="none";
// Inutile en mode création
timeDifference.parentNode.style.display="none";
}
emptyUserForm();
// Initialise les contraintes du formulaire :
setAttributesToInputs(configUsers, formUser);
// Fonction affichant les infos connues concernant un utilisateur et son abonnement
const showFormUserInfos = (id) =>
{
// on commence par tout vider, des fois que... :
emptyUserForm();
const xhrGetInfos = new XMLHttpRequest();
xhrGetInfos.open("GET", apiUrl+configUsers.userRoutes+configUsers.getUserInfos+id);
xhrGetInfos.onreadystatechange = function()
{
if (this.readyState == XMLHttpRequest.DONE)
{
let response=JSON.parse(this.responseText);
if (this.status === 200 && response.User != undefined)
{
newPassword.parentNode.style.display="block";
timeDifference.parentNode.style.display="block";
const mapText =
{
ID_USER : response.User.id,
DATE_CREA : dateFormat(response.User.createdAt),
DATE_UPDATE : dateFormat(response.User.updatedAt),
DATE_CONNECTION : dateFormat(response.User.connectedAt)
};
let subscribeIntro=replaceAll(txtInfosUserForAdmin, mapText);
for(let data in response.User)
{
if(formUser.elements[data]!==undefined)
{
if(response.User[data]!==true && response.User[data]!==false)// booléen = case à cocher !
formUser.elements[data].value=response.User[data];
else if (response.User[data]==true) // si false, on ne fait rien
formUser.elements[""+data].checked="checked";
}
}
if(response.Subscription != undefined)
{
// nombre de jours de l'abonnement
formUser.elements["numberOfDays"].value=response.Subscription["numberOfDays"];
if(response.Subscription.noticeOk==true)
formUser.elements["noticeOk"].checked="checked";
// jours de réception
for(let i in response.Subscription.receiptDays)
formUser.elements["d"+response.Subscription.receiptDays[i]].checked="checked";
const beginSubTS=new Date(response.Subscription.createdAt).getTime();
const nbDaysOk=response.Subscription.numberOfDays-Math.round((Date.now()-beginSubTS)/1000/3600/24);
if(nbDaysOk > 0)
subscribeIntro+="<br>"+txtInfosNbDaysAdmin.replace("NB_DAYS", nbDaysOk);
else
subscribeIntro+="<br>"+txtInfosExpiratedAdmin;
addElement(divSubscribeIntro, "p", subscribeIntro, "", ["info"], "", false);
}
else
{
addElement(divSubscribeIntro, "p", txtIsNotValided, "", ["error"]);
validationCheckBox.style.display="block";
}
deleteCheckBox.style.display="block";
// Infos de paiements via API WP
const xhrGetPaymentsInfos = new XMLHttpRequest();
xhrGetPaymentsInfos.open("GET", apiUrl+configUsers.getPayments+response.User.id);
xhrGetPaymentsInfos.onreadystatechange = function()
{
if (this.readyState == XMLHttpRequest.DONE)
{
let responsePay=JSON.parse(this.responseText);
if (this.status === 200)
{
if(responsePay.length!==0)
{
let txtPayments="";
for(let i in responsePay)
{
const mapText =
{
DATE_PAYMENT : dateFormat(responsePay[i].createdAt, "fr"),
AMOUNT : responsePay[i].amount,
CLIENT_NAME : responsePay[i].clientName
};
txtPayments+="<li>"+replaceAll(txtInfosPaymentsAdmin, mapText)+"</li>";
}
addElement(divPaymentsInfos, "ul", txtPayments, "", ["info"], "", false);
divPaymentsInfos.style.display="block"
}
}
}
}
xhrGetPaymentsInfos.setRequestHeader("Authorization", "Bearer "+user.token);
xhrGetPaymentsInfos.send();
// Un parrain ou deux par deux ?
if(!isEmpty(response.User.GodfatherId))
{
const xhrGetGodFatherInfos = new XMLHttpRequest();
xhrGetGodFatherInfos.open("GET", apiUrl+configUsers.userRoutes+configUsers.getUserInfos+response.User.GodfatherId);
xhrGetGodFatherInfos.onreadystatechange = function()
{
if (this.readyState == XMLHttpRequest.DONE)
{
let responseGF=JSON.parse(this.responseText);
if (this.status === 200 && responseGF.User != undefined)
{
addElement(divGodchildsInfos, "p", txtInfosAdminGodfather+"<a href='/"+configTemplate.usersManagementPage+"?id="+responseGF.User.id+"'>"+responseGF.User.name+"</a>"+".<br>", "", ["info"], "", false);
divGodchildsInfos.style.display="block";
}
}
}
xhrGetGodFatherInfos.setRequestHeader("Authorization", "Bearer "+user.token);
xhrGetGodFatherInfos.send();
}
// Des filleuls ?
let txtGodchilds="";
const xhrGetGodchilds = new XMLHttpRequest();
xhrGetGodchilds.open("GET", apiUrl+configUsers.userRoutes+configUsers.getGodChilds+id);
xhrGetGodchilds.onreadystatechange = function()
{
if (this.readyState == XMLHttpRequest.DONE)
{
let responseGS=JSON.parse(this.responseText);
if (this.status === 200)
{
if(responseGS.length!==0)
{
txtGodchilds+=txtInfosAdminNbGodChilds.replace("#NB", responseGS.length);
for(let i in responseGS)
txtGodchilds+="<a href='/"+configTemplate.usersManagementPage+"?id="+responseGS[i].id+"'>"+responseGS[i].name+"</a>";
addElement(divGodchildsInfos, "p", txtGodchilds+".", "", ["info"], "", false);
divGodchildsInfos.style.display="block";
}
}
}
}
xhrGetGodchilds.setRequestHeader("Authorization", "Bearer "+user.token);
xhrGetGodchilds.send();
}
}
}
xhrGetInfos.setRequestHeader("Authorization", "Bearer "+user.token);
xhrGetInfos.send();
}
// Si un id est passé par l'url, on essaye d'afficher l'utilisateur :
let urlDatas=getUrlParams();
if(urlDatas && urlDatas.id!==undefined)
showFormUserInfos(urlDatas.id);
// Besoin d'un coup de Kärcher ?
btnNewUser.addEventListener("click", function(e)
{
emptyUserForm();
});
// Envoi du formulaire des infos de l'utilisateur
formUser.addEventListener("submit", function(e)
{
e.preventDefault();
divResponse.innerHTML="";
let datas=getDatasFromInputs(formUser);
// recomposition des jours valables pour l'abonnement :
datas.receiptDays="";
for(let i=1; i<=7; i++)
{
if(datas["d"+i]!==undefined)
datas.receiptDays+=""+i;
}
if(datas.noticeOk===undefined)
datas.noticeOk="false";
if(datas.newsletterOk===undefined)
datas.newsletterOk="false";
const xhrUserDatas = new XMLHttpRequest();
if(!isEmpty(datas.id) && (datas.deleteOk!==undefined))
xhrUserDatas.open("DELETE", apiUrl+configUsers.userRoutes+"/"+datas.id);
else if(!isEmpty(datas.id) && (datas.validationOk!==undefined))
xhrUserDatas.open("POST", apiUrl+configUsers.userRoutes+configUsers.validateUserRoute+datas.id);
else if(!isEmpty(datas.id))
xhrUserDatas.open("PUT", apiUrl+configUsers.userRoutes+configUsers.updateUserInfos+datas.id);
else
{
console.log("je suis ici");
datas.password=getPassword(configUsers.password.minlength, configUsers.password.minlength+2);// mot de passe temporaire
xhrUserDatas.open("POST", apiUrl+configUsers.userRoutes+configUsers.createUserRoute);
}
xhrUserDatas.onreadystatechange = function()
{
if (this.readyState == XMLHttpRequest.DONE)
{
let response=JSON.parse(this.responseText);
if (this.status === 201 && response.id!=undefined)
{
addElement(divResponse, "p", txtAddOkMessage, "", ["success"]);
datas.id=response.id;
}
else if (this.status === 200 && response.message!=undefined)
{
if(Array.isArray(response.message))
response.message = response.message.join("<br>");
else
response.message = response.message;
addElement(divResponse, "p", response.message, "", ["success"]);
}
else if (response.errors)
{
if(Array.isArray(response.errors))
response.errors = response.errors.join("<br>");
else
response.errors = txtServerError;
addElement(divResponse, "p", response.errors, "", ["error"]);
}
else
addElement(divResponse, "p", txtServerError, "", ["error"]);
if(isEmpty(response.errors))
{
if(datas.deleteOk===undefined)
showFormUserInfos(datas.id);
else
emptyUserForm();
}
}
}
xhrUserDatas.setRequestHeader("Content-Type", "application/json");
xhrUserDatas.setRequestHeader("Authorization", "Bearer "+user.token);
if(datas)
xhrUserDatas.send(JSON.stringify(datas));
});
// Traitement du lancement d'une recherche
formSearch.addEventListener("submit", function(e)
{
e.preventDefault();
let datas=getDatasFromInputs(formSearch);
const xhrSearch = new XMLHttpRequest();
xhrSearch.open("POST", apiUrl+configUsers.userRoutes+configUsers.searchUserRoute);
xhrSearch.onreadystatechange = function()
{
if (this.readyState == XMLHttpRequest.DONE)
{
let response=JSON.parse(this.responseText);
if (this.status === 200 && Array.isArray(response))
{
if(response.length===0)
addElement(divSearchResult, "p", txtNotFound, "", ["info"]);
else
{
let selectHTML="<option value=''></option>";
for(let i in response)
selectHTML+="<option value='"+response[i].id+"'>"+response[i].name+" ("+response[i].email+")</option>";
addElement(divSearchResult, "select", selectHTML, "selectSearch");
const searchSelect=document.getElementById("selectSearch");
searchSelect.addEventListener("change", function()
{
if(searchSelect.value!=="")
showFormUserInfos(searchSelect.value);
});
}
}
else
addElement(divSearchResult, "p", txtServerError, "", ["error"]);
}
}
xhrSearch.setRequestHeader("Content-Type", "application/json");
xhrSearch.setRequestHeader("Authorization", "Bearer "+user.token);
if(datas)
xhrSearch.send(JSON.stringify(datas));
});
}
}
catch(e)
{
addElement(divCrash, "p", txtServerError, "", ["error"]);
console.error(e);
addElement(divMessage, "p", txt.serverError, "", ["error"]);
}
}
initialise();