XaSuMu/imports/ui/Usuaris.jsx
2025-01-07 15:05:58 +01:00

305 lines
9.4 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}) => {
// 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>;
};
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);
// (async () => {
useEffect(() => {
(async () => {
const comprovaAdmin = await Roles.userIsInRoleAsync(userId, ["admin"]);
setEsEditor(comprovaAdmin);
})();
}, []);
// })();
const QuadreInfo_Usuari = () => {
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>
</div>;
};
return <Suspense fallback={<>Carregant...</>} >
<h1>Usuaris</h1>
{ esEditor && <QuadreInfo_Usuari /> }
<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={esEditor} />
</li>)
}</ul>
</Suspense>;
};