XaSuMu/imports/ui/Codis.jsx
2025-01-07 12:08:38 +01:00

250 lines
9.1 KiB
JavaScript

import React, { Suspense, useEffect, useState, useRef, lazy } from 'react';
import { Meteor } from 'meteor/meteor';;
import { NecessitatsCollection } from '/imports/api/necessitats.js';
import { PoblesCollection } from '../api/pobles';
import { TipusCollection } from '../api/tipus';
import { useSubscribe, useTracker, useFind } from 'meteor/react-meteor-data/suspense';
import { Roles } from 'meteor/roles';
// import { useUserId } from 'meteor/react-meteor-accounts';
import Select from 'react-select';
import CreatableSelect from 'react-select/creatable';
import AsyncCreatableSelect from 'react-select/async-creatable';
import { BarraNav } from "./BarraNav/BarraNav";
export const Codis = () => {
// const [permes, setPermes] = useState(false);
const [esEditor, setEsEditor] = useState(false);
const userId = Meteor.userId();
useEffect(() => {
(async () => {
const comprovaAdmin = await Roles.userIsInRoleAsync(userId, ["admin"]);
setEsEditor(comprovaAdmin);
})();
}, []);
// console.log("isAdmin: ", isAdmin) ;
let ambitSeleccionat = null;
useSubscribe('necessitats');
const necessitats = useTracker("necessitats", () => NecessitatsCollection.find().fetchAsync());
useSubscribe('pobles');
const pobles = useTracker("pobles", () => PoblesCollection.find().fetchAsync());
const ambits = pobles?.map(p => p?.ambitAssociat);
// console.log("ambits: ", ambits);
// useSubscribe('tipus');
// const ambits = useTracker("ambits", () => Collection.find().fetchAsync());
// console.log("tipus: ", tipus);
// console.log("necessitats: ", necessitats);
// console.log("tipusSeleccionat: ", tipusSeleccionat);
// const filterAmbit = (inputValue) => {
// return ambits.filter((i) =>
// i.toLowerCase().includes(inputValue.toLowerCase())
// );
// };
const SelectorDeRol = ({ambitSeleccionat}) => {
return <>
<label htmlFor="selRol">Rol: </label>
<Select
key={Math.random()}
name="selRol"
// filterOption={(opts) => necessitats.find(nec => nec.tipus === tipusSeleccionat._id)}
options={
(ambitSeleccionat == "GENERAL")
? [
{
value: "admin",
label: "administrador"
},
{
value: "usuari",
label: "usuari"
}
]
: [
{
value: "monitor_de_poble",
label: "monitor_de_poble"
},
{
value: "encarregat_de_tasques",
label: "encarregat_de_tasques"
},
{
value: "voluntari_de_poble",
label: "voluntari_de_poble"
}
]
}
/>
</>;
}
const QuadreInfo_Tipus = () => {
return <div style={{
display: `inline-block`,
border: `1px solid #6666`,
padding: `.5rem`,
borderRadius: `.3em`,
backgroundColor: `lightcyan`
}}>
{ambitSeleccionat && <h1>{ambitSeleccionat}</h1>}
<h1>Codis</h1>
<p>Tria el rol que adquirirà qui utilitze el codi.</p>
<form
action={d => {
// if (d.get('selTipus'))
try {
Meteor.callAsync('editaOAfigNecessitat', {
...tipusSeleccionat || [],
titol: d.get('titol'),
tipus: d.get('selTipus') || "",
poble: d.get('selPoble')
})
.then(() => setAmbitSeleccionat(null))
.catch(err => console.error(err))
;
} catch (err) {
alert(err);
console.error(err);
}
}}
>
<label htmlFor="selAmbit">Àmbit: </label>
{/* Si
l'usuari és ADMINISTRADOR o té permisos de responsabilitat, podrà crear nous Tipus al CREAR o a l'EDITAR
si no
tansols podrà assignar a un tipus predefinit o al de ALTRES
*/}
<Select
name="selAmbit"
// formatCreateLabel={(inputValue) => "Crear nou tipus..."}
// filterOption={filterAmbit}
options={
[...
ambits
.map((v,i) => ({
value: v,
label: v
}))
.sort((a,b) => a.label.toLowerCase() > b.label.toLowerCase()),
{
value: "GENERAL",
label: "GENERAL"
}
]
}
// onCreateOption={(inputValue) => Meteor.callAsync('afigT', {titol: inputValue})}
isSearchable
// loadOptions={tipus.map((v,i) => ({value: v, label: v.titol}))}
onChange={ev => {
ambitSeleccionat = ev.value;
console.log("ambitSeleccionat: ", ambitSeleccionat);
}}
/>
{/* <select name="selTipus">
<option value="moble">Moble</option>
<option value="maquinari">Maquinari</option>
<option value="menjar">Menjar i beguda</option>
<option value="infantil">Infantils</option>
<option value="higiene">Higiene</option>
</select> */}
<br />
<SelectorDeRol {... {ambitSeleccionat}} />
<br />
<label htmlFor="titol">Títol: </label>
<input type="text" name='titol' />
<br /><br />
<label htmlFor="poble">Poble: </label>
<CreatableSelect name="selPoble" options={pobles.map((v,i) => ({value: v._id, label: v.nomPoble})) } />
{/* <select name="selPoble">
{
pobles.map((v,i) => <option key={`optPob${i}`}>{v.nomPoble}</option>)
}
</select> */}
<br />
<input type='submit' value="Enviar" />
{ambitSeleccionat && esEditor && <button onClick={ev => {
ev.preventDefault();
if (confirm(`Vas a eliminar el poble "${pobleSeleccionat.nomPoble}". És una operació irreversible. Procedir?`)) {
Meteor.callAsync('eliminaPoble', pobleSeleccionat._id).catch(err => console.error(err));
setNecessitatSeleccionada(null);
}
}}>Elimina</button>}
</form>
</div>;
};
return <Suspense fallback={<>Carregant...</>} >
<QuadreInfo_Tipus />
<br /><br />
{/* <AsyncCreatableSelect
cacheOptions
defaultOptions={tipus.map((v,i) => ({value: v, label: v.titol})) }
loadOptions={tipus.map((v,i) => ({value: v, label: v.titol}))}
/> */}
{/* <SelectSearch options={options} value="sv" name="language" placeholder="Choose your language" /> */}
<ul style={{
display: `flex`,
flexWrap: `wrap`,
justifyContent: `space-evenly`,
rowGap: `.3em`,
alignContent: `space-around`
}}>{
ambits
.sort((a,b) => a.toLowerCase() > b.toLowerCase())
.map(amb => <li
key={amb}
style={{
display: `block`,
border: `1px solid #6666`,
borderRadius: `.4em`,
padding: `4px`,
listStyle: `none`,
backgroundColor: `${'lightgreen' || 'lightcoral'}`
}}
>
{amb}{esEditor && <button onClick={() => {setTipusSeleccionat(titol)}}>Edita</button>}
</li>)
}</ul>
</Suspense>;
};