XaSuMu/imports/ui/Codis.jsx
2025-01-28 17:07:45 +01:00

565 lines
22 KiB
JavaScript

import React, { Suspense, useEffect, useState } from 'react';
import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';
import { NecessitatsCollection } from '/imports/api/necessitats.js';
import { PoblesCollection } from '../api/pobles';
import { CodisCollection } from '../api/codis';
// 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";
// import InfiniteCalendar from 'react-infinite-calendar';
// import 'react-infinite-calendar/styles.css';
function generaCodi() {
return Random.id().slice(0, 5).toUpperCase();
}
export const Codis = () => {
// const [permes, setPermes] = useState(false);
const [esEditor, setEsEditor] = useState(false);
const userId = Meteor.userId();
const [codiSeleccionat, setCodiSeleccionat] = useState(null);
useEffect(() => {
(async () => {
const comprovaAdmin = await Roles.userIsInRoleAsync(userId, ["admin"]);
setEsEditor(comprovaAdmin);
})();
}, []);
// console.log("isAdmin: ", isAdmin) ;
// const [ambitSeleccionat, setAmbitSeleccionat] = useState(null);
const [confecCodObj, setConfecCodObj] = useState({
codi: generaCodi(),
ambit: null,
rol: null,
absCond: "abs",
absActiu: false,
condIni: null,
condFi: null
});
// useSubscribe('necessitats');
// const necessitats = useTracker("necessitats", () => NecessitatsCollection.find().fetchAsync());
useSubscribe('codis');
const codis = useTracker("codis", () => CodisCollection.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 [ambitGeneral, setAmbitGeneral] = useState(ambitSeleccionat === "GENERAL");
const codiDoc = useTracker("valsFormDoc", () => CodisCollection.findOneAsync(codiSeleccionat?._id));
// let selRolVal = codiDoc?.rol || "usuari";
const SelectorDeRol = () => {
// const [docRol, setDocRol] = useState(codiDoc?.rol)
return <>
<label htmlFor="selRol">Rol: </label>
<Select
required
key={Math.random()}
name="selRol"
// filterOption={(opts) => necessitats.find(nec => nec.tipus === tipusSeleccionat._id)}
defaultValue={
codiSeleccionat
? {
label: codiSeleccionat?.rol,
value: codiSeleccionat?.rol
}
: confecCodObj?.rol || null
// ? {
// label: confecCodObj.rol,
// value: confecCodObj.rol
// }
// : null
// docRol && {label: docRol, value: docRol}
}
onChange={v => {
console.log("v: ", v);
console.log("cCO abans: ", confecCodObj);
// setDocRol(v);
setConfecCodObj({
...confecCodObj,
rol: v
});
console.log("cCO despres: ", confecCodObj);
}}
options={
(confecCodObj?.ambit?.value === "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_Codis = () => {
const [actCond, setActCond] = useState(true);
const [codiGenerat, setCodiGenerat] = useState(generaCodi());
const [absCond, setAbsCond] = useState('cond');
const codSelAbsActChecked = codiDoc ? {checked: codiDoc.absActiu} : {defaultChecked: confecCodObj.absActiu};
console.log("cS: ", codiSeleccionat);
console.log("cCO: ", confecCodObj);
return <div style={{
display: `inline-block`,
border: `1px solid #6666`,
padding: `.5rem`,
borderRadius: `.3em`,
backgroundColor: `lightcyan`,
outline: `${codiSeleccionat?._id ? '5px solid black' : 'none'}`
}}>
{/* {ambitSeleccionat && <h1>{ambitSeleccionat?.value}</h1>} */}
<h1>Codis</h1>
{/* <button
onClick={ev => {
ev.preventDefault();
ev.stopPropagation();
setCodiGenerat(generaCodi());
}}
>Genera el codi</button> */}
<div
style={{
fontWeight: `bolder`,
textAlign: `center`,
transform: `scale(2)`
}}
>
<span
style={{
backgroundColor: `white`,
border: `3px solid black`,
padding: `0 .2em`,
margin: `1rem auto`,
}}
>{codiSeleccionat ? codiSeleccionat?.codi : confecCodObj.codi}</span>
</div>
<br />
<p>Tria el rol que adquirirà qui utilitze el codi anterior una vegada activat</p>
<form
action={d => {
// if (d.get('selTipus'))
try {
Meteor.callAsync('editaOAfigCodi', {
...codiGenerat || [],
codi: codiGenerat,
ambit: d.get('selAmbit') || "",
rol: d.get('selRol'),
// act_abs: d.get('activAbs'),
absCond,
absActiu: d.get('absActiu'),
condIni: d.get('condIni'),
condFi: d.get('condFi')
})
.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
required
name="selAmbit"
// formatCreateLabel={(inputValue) => "Crear nou tipus..."}
// filterOption={filterAmbit}
defaultValue={codiDoc && {
label: codiDoc?.ambit,
value: codiDoc?.ambit
} || confecCodObj.ambit}
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={amb => {
// setAmbitSeleccionat(amb);
// console.log("amb: ", amb);
setConfecCodObj({
...confecCodObj,
ambit: amb
});
}}
/>
{/* <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, selRolVal}} /> */}
<br /><br />
<p>Periode de validesa: </p>
<div style={{
border: `1px solid #cccc`,
borderRadius: `.4em`,
margin: `1rem`,
padding: `.6rem`,
backgroundColor: `lightslategray`
}}>
{/* <p>TEMPS REAL:</p> */}
<input
type="radio"
name='absCond'
value="abs"
// defaultChecked={codiDoc?.act_abs === "on"}
// checked={absCond === 'abs'}
// onChange={(ev) => setAbsCond('abs')}
checked={codiSeleccionat && codiSeleccionat.absCond === 'abs' || confecCodObj?.absCond === 'abs'}
onChange={(ev) => setConfecCodObj({
...confecCodObj,
absCond: 'abs'
})}
/>
<label
htmlFor="absCond"
onClick={() => setConfecCodObj({
...confecCodObj,
absCond: 'abs'
})}>Activació absoluta</label>
<br />
{/* L'activació condicionada desactivada fa que no siguen 'required' les dates d'inici i final */}
<input
type="radio"
name='absCond'
value="cond"
// checked={absCond === 'cond'}
// onChange={(ev) => setAbsCond('cond')}
checked={codiSeleccionat && codiSeleccionat.absCond === 'cond' || confecCodObj?.absCond === 'cond'}
onChange={(ev) => setConfecCodObj({
...confecCodObj,
absCond: 'cond'
})}
/>
<label htmlFor="absCond" onClick={
() => setConfecCodObj({
...confecCodObj,
absCond: 'cond'
})
}>Activació condicionada</label>
<br />
<br />
<div style={{
border: `1px solid #6666`,
padding: `0 1rem`,
borderRadius: `.5em`,
backgroundColor: `#fff2`
}}>
{
(codiSeleccionat
&&
codiSeleccionat?.absCond === 'abs'
||
confecCodObj?.absCond === 'abs'
)
&&
<>
<label htmlFor="act_status">Actiu</label>
<input
type="checkbox"
name="absActiu"
id="absActiu"
{...codSelAbsActChecked}
onChange={ev => {
ev.preventDefault();
ev.stopPropagation();
// console.log("ev: ", ev);
if (codiSeleccionat) {
Meteor.callAsync('modActivacioAbsolutaCodi', codiSeleccionat);
setCodiSeleccionat({
...codiSeleccionat,
absActiu: !codiSeleccionat.absActiu
});
}
setConfecCodObj({
...confecCodObj,
absActiu: !confecCodObj.absActiu
});
}}
/>
</>
// codiDoc &&
// Meteor.callAsync('modActivacioAbsolutaCodi', codiDoc);
}
{
codiSeleccionat
&&
codiSeleccionat.absCond === 'cond'
||
confecCodObj?.absCond === 'cond'
&&
<>
<p
style={{
color: `red`
}}
>ATENCIÓ al format! <b>(mm/dd/aaaa)</b></p>
Des de: <input
required={confecCodObj.actCond === 'cond'}
type="date"
name="condIni"
onChange={v => {
console.log("dataIni: ", v.currentTarget.value);
setConfecCodObj({
...confecCodObj,
condIni: v.currentTarget.value
})
}}
defaultValue={confecCodObj.condIni}
/>
<br />
Fins a: <input
required={confecCodObj.
actCond === 'cond'}
type="date"
name="condFi"
onChange={v => {
console.log("dataFi: ", v.currentTarget.value);
setConfecCodObj({
...confecCodObj,
condFi: v.currentTarget.value
})
}}
defaultValue={confecCodObj.condFi}
/>
<br />
</>
}
</div>
</div>
{/* <select name="s.
elPoble">
{
pobles.map((v,i) => <option key={`optPob${i}`}>{v.nomPoble}</option>)
}
</select> */}
<input type='submit' value="Donar d'alta el codi" />
{/* {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>;
};
const
today = new Date(),
lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7)
;
// console.log("codis: ", codis);
return <Suspense fallback={<>Carregant...</>} >
<QuadreInfo_Codis />
<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`
}}>{
codis
// .reverse()
// .sort((a,b) => a?.codi?.editedAt < b?.codi?.editedAt)
.map(cod => <li
key={cod._id}
style={{
display: `block`,
border: `1px solid #6666`,
borderRadius: `.4em`,
padding: `4px`,
listStyle: `none`,
backgroundColor: `${'lightgreen' || 'lightcoral'}`,
position: `relative`,
outline: `${codiSeleccionat?._id === cod._id ? '3px solid black' : 'none'}`
}}
onClick={ev => {
ev.preventDefault();
ev.stopPropagation();
// console.log("codSel: ", codiSeleccionat);
setCodiSeleccionat(codiSeleccionat?._id === cod._id ? null : cod);
}}
>
<span
style={{
width: `5px`,
border: `1px solid #fffa`,
position: `absolute`,
borderRadius: `50%`,
height: `5px`,
right: `2px`,
top: `2px`,
boxShadow: `0 0 14px 5px ${cod.absActiu ? "lime" : "red"}`,
backgroundColor: `${cod.absActiu ? "lime" : "red"}`
}}
onClick={ev => {
ev.preventDefault();
ev.stopPropagation();
Meteor.callAsync('modActivacioAbsolutaCodi', cod);
}}
/>
{cod.codi}
{/* {esEditor && <button onClick={() => {setAmbitSeleccionat({value: cod, label: cod})}}>Edita</button>} */}
</li>)
}</ul>
{/* <InfiniteCalendar
width={400}
height={600}
selected={today}
disabledDays={[0,6]}
minDate={lastWeek}
/> */}
</Suspense>;
};