XaSuMu/imports/ui/Usuaris.jsx

546 lines
18 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 { Meteor } from 'meteor/meteor';
// import React, {useState, useEffect, Suspense} from 'react';
// import { useTracker, useFind } from 'meteor/react-meteor-data/suspense';
// import { FilesCol } from '/imports/api/files.js';
import { useNavigate, Link } from 'react-router-dom';
// import { Roles } from 'meteor/roles';
// import { useUserContext } from '/imports/api/contexts/AppContext';
// import { groupBy } from 'lodash';
//import Radium from 'radium';
// const IndicadorMissatges = ({notif}) => {
// return <span style={{
// position: `relative`
// }}>
// {notif && <span className='fas fa-solid fa-envelope' />}
// <span style={{
// borderRadius: `50%`,
// background: notif ? `red` : ``,
// position: `absolute`,
// width: `.4em`,
// aspectRatio: `1 / 1`
// }}/>
// </span>;
// };
const U = ({u, esAdministrador, setUsrSeleccionat}) => {
const [adm, setAdm] = useState(false);
const [mon, setMon] = useState(false);
const [enc, setEnc] = useState(false);
const [vol, setVol] = useState(false);
(async () => {
const esAdmin = await Roles.userIsInRoleAsync(u._id, ["admin"]);
setAdm(esAdmin);
const esMonit = await Roles.userIsInRoleAsync(u._id, ["monitor_de_poble"], {anyScope: true});
setMon(esMonit);
const esEncar = await Roles.userIsInRoleAsync(u._id, ["encarregat_de_tasques"], {anyScope: true});
setEnc(esEncar);
const esVolun = await Roles.userIsInRoleAsync(u._id, ["voluntari_de_poble"], {anyScope: true});
setVol(esVolun);
// setEsAdministrador(comprovaAdmin);
})();
// console.log("adm: ", adm);
// console.log("mon: ", mon);
// console.log("enc: ", enc);
// console.log("vol: ", vol);
// const [esAdministrador, setEsAdministrador] = useState(false);
// const u = useTracker("user", async () => await Meteor.userAsync());
// const userId = Meteor.userId();
// useEffect(() => {
// (async () => {
// const comprovaAdmin = await Roles.userIsInRoleAsync(userId, ["admin"]);
// setEsAdministrador(comprovaAdmin);
// })();
// }, [Meteor.userId()]);
// const u = useUserContext();
// console.log("UUU: ", u);
const navigate = useNavigate();
// const files = useTracker(() => {
// const filesHandle = Meteor.subscribe('files.avatar');
// // const docsReadyYet = filesHandle.ready();
// const files = FilesCol?.find({"meta.userId": Meteor.userId()}, {sort: {name: 1}}).fetch(); // Meteor.userId() ?? "nop"
// return files;
// });
// const uname = useTracker(() => Meteor.user({ fields: { 'username': 1 } })?.username );
// const [mostraMenu, setMostraMenu] = useState(false);
//const avatarLink = u.avatarLink;
// alert("avLnk: ", u.profile.avatarLink);
return <Suspense fallback="Carregant...">
<div
key={`u_${u._id}`}
style={{
// color: `lightblue`,
top: `1em`,
// right: `1em`,
left: `1em`,
cursor: `pointer`,
background: `yellow`,
border: `lightblue 3px solid`,
//padding: `.15em`,
borderRadius: `50%`,
fontWeight: `bold`,
display: `inline-block`,
// padding: `0px .9rem`
padding: `0px 1.2rem`,
position: `relative`,
height: `69%`
}}
// onMouseEnter={ev => {
// setMostraMenu(true);
// }}
// title="Logout"
onClick={ev => {
ev.stopPropagation();
ev.preventDefault();
// console.log("u: ", u);
navigate(`/${u.username}`);
}}
>
<div style={{
position: `absolute`
}}>
{ (u && adm) && <div style={{
color: `red`,
fontSize: `xx-small`,
// textAlign: `right`
}}>ADMIN</div> }
{ (u && mon) && <div style={{
color: `red`,
fontSize: `xx-small`,
// textAlign: `right`
}}>mon</div> }
{ (u && enc) && <div style={{
color: `red`,
fontSize: `xx-small`,
// textAlign: `right`
}}>enc</div> }
{ (u && vol) && <div style={{
color: `red`,
fontSize: `xx-small`,
// textAlign: `right`
}}>vol</div> }
</div>
<img
style={{
width: `3em`,
height: `3em`,
borderRadius: `50%`,
overflow: `hidden`,
verticalAlign: `middle`,
margin: `.3em`,
border: `solid 4px whitesmoke`,
display: `block`
}}
src={u?.profile?.avatarLink}
/>
<span style={{
verticalAlign: `middle`,
textAlign: `center`,
display: `block`,
}}>{u?.username}</span>
<span
style={{
verticalAlign: `middle`,
margin: `0.3em 0.3em 0.3em auto`,
padding: `.2em`,
// border: `2px solid grey`,
color: `grey`,
// borderRadius: `.3em`
}}
onClick={ev => {
ev.preventDefault();
ev.stopPropagation();
// alert("Click en missatges");
}}
>
{<button onClick={() => {setUsrSeleccionat(u)}}>Edita</button>}
{/* <IndicadorMissatges notif={false} /> */}
</span>
</div>
{
// mostraMenu &&
// <div style={{
// position: `absolute`,
// background: `white`,
// // right: `0`,
// left: 0,
// top: `5em`,
// padding: `.4em .5em`,
// border: `1px #aaa`,
// cursor: `pointer`,
// zIndex: `200`
// }}
// // onMouseLeave={ev => {
// // setMostraMenu(false);
// // }}
// >
// {/* <Link to="/c/config"> */}
// <div className="menuOp" style={{
// padding: `.2em`
// }}
// onClick={ev => {
// //setEditaPerfil(true);
// ev.stopPropagation();
// ev.preventDefault();
// navigate(`/c/config`);
// }}
// >Configuración</div>
// {/* </Link> */}
// <div className="menuOp" style={{
// padding: `.2em`
// }}
// onClick={() => {
// Meteor.logout(err => {
// err && alert(`Problema: ${err}`);
// });
// navigate(`/`);
// }}
// >Cierra la sesión</div>
// </div>
}
<br /><br />
</Suspense>;
};
const AssignadorDeRols = ({pobles, ambitGeneral, esEditor, rols, usrSeleccionat, ambitsUSel}) => {
const [creantRol, setCreantRol] = useState(false);
// const [ambitsUSel, setAmbitsUSel] = useState([]);
// let ambitsUSel;
// let ambitsUSel = [];
// useEffect(() => {
// (async () => {
// const ambits = await Roles.getScopesForUserAsync(usrSeleccionat?._id);
// // console.log("ambitsUSel: ", ambitsUSel);
// // ambitsUSel = ambits;
// // setAmbitsUSel(ambits);
// ambitsUSel = ambits;
// // console.log("ambitsUSel: ", ambitsUSel);
// })();
// }, []);
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 => {
console.log("usrSeleccionat: ", usrSeleccionat);
console.log("ambitsUSel: ", ambitsUSel);
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>;
};
const QuadreInfo_Usuari = ({usrSeleccionat, esEditor, pobles, rols, ambitsUSel}) => {
return <div style={{
display: `inline-block`,
border: `1px solid #6666`,
padding: `.5rem`,
borderRadius: `.3em`,
backgroundColor: `lightcyan`
}}>
{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" /><br />
<input type='submit' value="Actualitzar la Població" />
<button onClick={ev => {
ev.preventDefault();
if (confirm(`Vas a eliminar el poble "${usrSeleccionat.nomPoble}". És una operació irreversible. Procedir?`)) {
Meteor.callAsync('eliminaPoble', usrSeleccionat._id).catch(err => console.error(err));
setUsrSeleccionat(null);
}
}}>Elimina</button>
</form>
{ esEditor && <AssignadorDeRols {... {esEditor, usrSeleccionat, rols, pobles, ambitsUSel}} /> }
</div>;
};
export const Usuaris = () => {
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());
});
// console.log("isAdmin: ", isAdmin) ;
console.log("usuaris: ", usuaris);
// const [ambitsUSel, setAmbitsUSel] = useState([]);
// (async () => {
let ambitsUSel = [];
useEffect(() => {
(async () => {
const comprovaAdmin = await Roles.userIsInRoleAsync(userId, ["admin"]);
setEsEditor(comprovaAdmin);
const ambits = await Roles.getScopesForUserAsync(usrSeleccionat?._id);
setAmbitsUSel(ambits);
// console.log("ambitsUSel: ", ambitsUSel);
})();
}, []);
const rols = useTracker("rols", async () => {
return await Roles.getRolesForUserAsync(usrSeleccionat?._id);
});
// })();
// const [monitors, setMonitors] = useState(false);
// const [encarregats, setEncarregats] = useState(false);
// const [voluntaris, setVoluntaris] = useState(false);
// const [administradors, setAdministradors] = useState(false);
// let mon, mons, enc, encs, vol, vols;
// let
// administradors,
// monitors,
// encarregats,
// voluntaris
// ;
// (async () => {
// const admins = await Roles.getUsersInRoleAsync("administrador");
// // console.log("admins: ", admins);
// administradors = await admins?.fetchAsync();
// console.log("administradors: ", administradors);
// const mons = await Roles.getUsersInRoleAsync("monitor_de_poble");
// // console.log("mons: ", mons);
// monitors = await mons?.fetchAsync();
// console.log("monitors: ", monitors);
// const encs = await Roles.getUsersInRoleAsync("encarregat_de_tasques");
// // console.log("encs: ", encs);
// encarregats = await encs?.fetchAsync();
// console.log("encarregats: ", encarregats);
// const vols = await Roles.getUsersInRoleAsync("voluntari_de_poble");
// // console.log("vols: ", vols);
// voluntaris = await vols?.fetchAsync();
// console.log("voluntaris: ", voluntaris);
// })();
return <Suspense fallback={<>Carregant...</>} >
<h1>Usuaris</h1>
{ esEditor && <QuadreInfo_Usuari {... {usrSeleccionat, esEditor, pobles, rols, ambitsUSel}} /> }
<ul style={{
display: `flex`,
flexWrap: `wrap`,
justifyContent: `space-evenly`,
rowGap: `.3em`,
alignContent: `space-around`,
scale: `.7`
}}>{
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: `50%`,
// padding: `4px`,
listStyle: `none`,
// backgroundColor: `${'lightgreen' || 'lightcoral'}`
}}
>
{/* {usr.username}{esEditor && <button onClick={() => {setUsrSeleccionat(usr)}}>Edita</button>} */}
<U u={usr} esAdministrador={usr._id === Meteor.userId() && esEditor} setUsrSeleccionat={setUsrSeleccionat} />
</li>)
}</ul>
</Suspense>;
};