XaSuMu/imports/ui/Usuaris.jsx
2025-01-03 10:19:28 +01:00

287 lines
11 KiB
JavaScript

import React, { Suspense, useEffect, useState, useRef, lazy } from 'react';
import { Meteor } from 'meteor/meteor';
import { PoblesCollection } from '/imports/api/pobles.js';
import { useSubscribe, useTracker, useFind } from 'meteor/react-meteor-data/suspense';
import { Roles } from 'meteor/roles';
// import { useUserId } from 'meteor/react-meteor-accounts';
import { BarraNav } from "./BarraNav/BarraNav";
const isClickInsideRectangle = (e, element) => {
const r = element?.getBoundingClientRect();
return (
e.clientX > r.left &&
e.clientX < r.right &&
e.clientY > r.top &&
e.clientY < r.bottom
);
};
const AssignadorDeRols = ({pobles, ambitGeneral, esEditor, rols, usrSeleccionat}) => {
const [creantRol, setCreantRol] = useState(false);
const [ambitsUSel, setAmbitsUSel] = useState([]);
useEffect(() => {
(async () => {
const ambits = await Roles.getScopesForUserAsync(usrSeleccionat?._id);
setAmbitsUSel(ambits);
})();
}, []);
return <div
style={{
display: `block`,
border: `1px solid #6666`,
padding: `.5rem`,
borderRadius: `.3em`,
margin: `1em`,
backgroundColor: `#fffa`
}}
>
<h3>Rols</h3>
<h4>Àmbits</h4>
<h5>General:</h5>
<ul>{
rols?.map(uRol => <li
key={`rol_${uRol}`}
style={{
display: `block`,
border: `1px solid #6666`,
borderRadius: `.4em`,
padding: `4px`,
listStyle: `none`,
backgroundColor: `${'orange'}`,
textAlign: `center`
}}
>
{uRol}
{esEditor && <button onClick={ev => {
ev.preventDefault();
ev.stopPropagation();
confirm(`Vas a retirar el Rol ${uRol} a l'usuari ${usrSeleccionat.username}. Procedir?`) && Meteor.callAsync('retiraRols', uRol, usrSeleccionat._id)
}}>&times;</button>}
</li>)
}</ul>
{/* <ul> */}
{
ambitsUSel?.map(async aus => {
const uRol = await Roles.getRolesForUserAsync(usrSeleccionat._id, {scope: aus, onlyScoped: true});
return <>
<h5>{aus}:</h5>
{
<span style={{
display: `block`,
border: `1px solid #6666`,
borderRadius: `.4em`,
padding: `4px`,
listStyle: `none`,
backgroundColor: `${'orange'}`,
textAlign: `center`
}}>{uRol}
{esEditor && <button onClick={ev => {
ev.preventDefault();
ev.stopPropagation();
confirm(`Vas a retirar el Rol ${uRol} a l'usuari ${usrSeleccionat.username}. Procedir?`) && Meteor.callAsync('retiraRols', uRol, usrSeleccionat._id, aus)
}}>&times;</button>}
</span>
} <br />
</>;
})
}
{/* </ul> */}
{esEditor && creantRol && <div style={{
display: `block`,
border: `1px solid #6666`,
padding: `.5rem`,
borderRadius: `.3em`,
margin: `1em`,
backgroundColor: `#fffa`
}}>
<form action={d => {
Meteor.callAsync('assignaRol', usrSeleccionat._id, d.get('selRol'), d.get('selAmbit'));
}}>
Àmbit: <select name="selAmbit" id="selAmbit"
onChange={ev => setAmbitGeneral(ev.target.value === "general")}
>
{
pobles.sort((a,b) => a.ambitAssociat > b.ambitAssociat).map((pob,i) => <option key={`optAmb_${i}`} value={pob.ambitAssociat}>{pob.ambitAssociat}</option>)
}
<option value={"general"}>General</option>
</select> <br />
Rol: <select name="selRol" id="selRol">
{
ambitGeneral
? <option value={"admin"}>Administrador general</option>
: <>
<option value="monitor_de_poble">Monitor de poble</option>
<option value="encarregat_de_tasques">Encarregat de tasques</option>
<option value="voluntari_de_poble">Voluntairi de poble</option>
</>
}
</select> <br /> <br />
<input type="submit" value="Estableix nou rol" />
</form>
</div>}
{esEditor && usrSeleccionat && <button
onClick={ev => {
ev.preventDefault();
ev.stopPropagation();
return false;
}}
onPointerUp={ev => {
ev.preventDefault();
ev.stopPropagation();
setCreantRol(!creantRol);
return false;
}}
>+</button>}
</div>;
};
export const Usuaris = () => {
const refQuadreSeleccionat = useRef();
const [usrSeleccionat, setUsrSeleccionat] = useState(null);
useSubscribe('pobles');
const pobles = useTracker("pobles", () => PoblesCollection.find().fetchAsync());
const [esEditor, setEsEditor] = useState(false);
const userId = Meteor.userId();
const usuaris = useTracker("usuaris", () => {
Meteor.subscribe('usuaris');
return Meteor.users.find().fetch()//.filter(u => u._id !== Meteor.userId());
});
const rols = useTracker("rols", async () => {
return await Roles.getRolesForUserAsync(usrSeleccionat?._id);
});
// console.log("rols: ", rols);
// console.log("isAdmin: ", isAdmin) ;
// console.log("usuaris: ", usuaris);
// (async () => {
useEffect(() => {
(async () => {
const comprovaAdmin = await Roles.userIsInRoleAsync(userId, ["admin"]);
setEsEditor(comprovaAdmin);
})();
}, []);
// })();
const QuadreInfo_Usuari = () => {
// const [rols, setRols] = useState([]);
const [ambitGeneral, setAmbitGeneral] = useState(false);
let allScopes;
// useEffect( async () => {
// allScopes = await Roles.getScopesForUserAsync(usrSeleccionat?._id);
// // Roles.getRolesForUser(usrSeleccionat?._id).map(uRol => <li>{uRol}</li>);
// // setRols(rols);
// });
return <div style={{
display: `inline-block`,
border: `1px solid #6666`,
padding: `.5rem`,
borderRadius: `.3em`,
backgroundColor: `lightcyan`
}}
ref={refQuadreSeleccionat}
>
{usrSeleccionat && <h2>{usrSeleccionat._id}</h2>}
<form
action={d => {
try {
Meteor.callAsync('editaOAfigPoble',
{
...usrSeleccionat || [],
nomPoble: d.get('nomPoble'),
cp: d.get('cp') || "",
comarca: d.get('comarca') || "",
}).then(() => setUsrSeleccionat(null))
.catch(err => console.error(err));
} catch (err) {
alert(err);
console.error(err);
}
}}
>
<label htmlFor="inUsername">Nom d'usuari: </label><input name="inUsername" type="text" defaultValue={ usrSeleccionat ? usrSeleccionat.username : ""}/><br />
<label htmlFor="inTel">Telèfon: </label><input name="inTel" type="tel" /><br />
<label htmlFor="inEmail">Correu Electrònic: </label><input name="inEmail" type="email" />
<input type='submit' value="Actualitza les dades" />
<button onClick={ev => {
ev.preventDefault();
if (confirm(`Vas a eliminar l'usuari "${usrSeleccionat.username}". És una operació irreversible. Procedir?`)) {
Meteor.callAsync('eliminaUsuari', usrSeleccionat._id).catch(err => console.error(err));
setUsrSeleccionat(null);
}
}}>Elimina</button>
</form>
{ esEditor && <AssignadorDeRols {... {pobles, ambitGeneral, esEditor, rols, usrSeleccionat}} /> }
</div>;
};
return <div onPointerUp={ev => {
!isClickInsideRectangle(ev, refQuadreSeleccionat.current) && setUsrSeleccionat(null);
}}><Suspense fallback={<>Carregant...</>} >
<h1>Usuaris</h1>
{ esEditor && usrSeleccionat && <QuadreInfo_Usuari /> }
<ul style={{
display: `flex`,
flexWrap: `wrap`,
justifyContent: `space-evenly`,
rowGap: `.3em`,
alignContent: `space-around`
}}>{
usuaris
.sort((a,b) => a.username?.toLowerCase() > b.username?.toLowerCase())
.map(usr => <li
key={`usr_${usr._id}`}
style={{
display: `block`,
border: `1px solid #6666`,
borderRadius: `.4em`,
padding: `4px`,
listStyle: `none`,
backgroundColor: `${'lightgreen' || 'lightcoral'}`
}}
>
{usr.username}{esEditor && <button onClick={() => {setUsrSeleccionat(usr)}}>Edita</button>}</li>)
}</ul>
{esEditor && !usrSeleccionat && <button>+</button>}
</Suspense></div>;
};