Avanços en taula d'usuaris

This commit is contained in:
Kal 2025-01-07 15:05:58 +01:00
parent f4d51a73cf
commit d18970948a

View File

@ -5,155 +5,206 @@ import { useSubscribe, useTracker, useFind } from 'meteor/react-meteor-data/susp
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
);
// 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}) => {
// 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
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}`);
}}
>
{ (u && esAdministrador) && <div style={{
color: `red`,
fontSize: `xx-small`,
// textAlign: `right`
}}>ADMIN</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");
}}
>
{/* <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}) => {
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());
@ -162,17 +213,10 @@ export const Usuaris = () => {
const usuaris = useTracker("usuaris", () => {
Meteor.subscribe('usuaris');
return Meteor.users.find().fetch()//.filter(u => u._id !== Meteor.userId());
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);
console.log("usuaris: ", usuaris);
// (async () => {
useEffect(() => {
(async () => {
@ -183,34 +227,15 @@ export const Usuaris = () => {
}, []);
// })();
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}
>
display: `inline-block`,
border: `1px solid #6666`,
padding: `.5rem`,
borderRadius: `.3em`,
backgroundColor: `lightcyan`
}}>
{usrSeleccionat && <h2>{usrSeleccionat._id}</h2>}
@ -233,55 +258,48 @@ export const Usuaris = () => {
>
<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" />
<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 l'usuari "${usrSeleccionat.username}". És una operació irreversible. Procedir?`)) {
Meteor.callAsync('eliminaUsuari', usrSeleccionat._id).catch(err => console.error(err));
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 {... {pobles, ambitGeneral, esEditor, rols, usrSeleccionat}} /> }
</div>;
};
return <div onPointerUp={ev => {
!isClickInsideRectangle(ev, refQuadreSeleccionat.current) && setUsrSeleccionat(null);
}}><Suspense fallback={<>Carregant...</>} >
return <Suspense fallback={<>Carregant...</>} >
<h1>Usuaris</h1>
{ esEditor && usrSeleccionat && <QuadreInfo_Usuari /> }
{ esEditor && <QuadreInfo_Usuari /> }
<ul style={{
display: `flex`,
flexWrap: `wrap`,
justifyContent: `space-evenly`,
rowGap: `.3em`,
alignContent: `space-around`
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: `.4em`,
padding: `4px`,
// display: `block`,
// border: `1px solid #6666`,
// borderRadius: `50%`,
// padding: `4px`,
listStyle: `none`,
backgroundColor: `${'lightgreen' || 'lightcoral'}`
// backgroundColor: `${'lightgreen' || 'lightcoral'}`
}}
>
{usr.username}{esEditor && <button onClick={() => {setUsrSeleccionat(usr)}}>Edita</button>}</li>)
{/* {usr.username}{esEditor && <button onClick={() => {setUsrSeleccionat(usr)}}>Edita</button>} */}
<U u={usr} esAdministrador={esEditor} />
</li>)
}</ul>
{esEditor && !usrSeleccionat && <button>+</button>}
</Suspense></div>;
</Suspense>;
};