Compare commits

..

10 Commits

21 changed files with 2165 additions and 153 deletions

View File

@ -6,19 +6,19 @@
meteor-base@1.5.2 # Packages every Meteor app needs to have
mobile-experience@1.1.2 # Packages for a great mobile UX
mongo@2.0.3-rc310.0 # The database Meteor supports right now
mongo@2.0.3 # The database Meteor supports right now
reactive-var@1.0.13 # Reactive variable for tracker
standard-minifier-css@1.9.3 # CSS minifier run for production mode
standard-minifier-js@3.0.0 # JS minifier run for production mode
es5-shim@4.8.1 # ECMAScript 5 compatibility for older browsers
ecmascript@0.16.10-rc310.0 # Enable ECMAScript2015+ syntax in app code
typescript@5.6.3-rc310.0 # Enable TypeScript syntax in .ts and .tsx modules
shell-server@0.6.1-rc310.0 # Server-side component of the `meteor shell` command
ecmascript@0.16.10 # Enable ECMAScript2015+ syntax in app code
typescript@5.6.3 # Enable TypeScript syntax in .ts and .tsx modules
shell-server@0.6.1 # Server-side component of the `meteor shell` command
hot-module-replacement@0.5.4 # Update client in development without reloading the page
static-html@1.4.0 # Define static page content in .html files
react-meteor-data # React higher-order component for reactively tracking Meteor data
roles@1.0.0-rc310.0
accounts-password@3.0.3-rc310.0
roles@1.0.0
accounts-password@3.0.3
react-meteor-accounts

View File

@ -1 +1 @@
METEOR@3.1-rc.0
METEOR@3.1

View File

@ -1,8 +1,8 @@
accounts-base@3.0.3
accounts-password@3.0.3-rc310.0
accounts-password@3.0.3
allow-deny@2.0.0
autoupdate@2.0.0
babel-compiler@7.11.2-rc310.0
babel-compiler@7.11.2
babel-runtime@1.5.2
base64@1.0.13
binary-heap@1.0.12
@ -12,18 +12,18 @@ callback-hook@1.6.0
check@1.4.4
core-runtime@1.0.0
ddp@1.4.2
ddp-client@3.0.3-rc310.0
ddp-client@3.0.3
ddp-common@1.4.4
ddp-rate-limiter@1.2.2
ddp-server@3.0.3-rc310.0
ddp-server@3.0.3
diff-sequence@1.1.3
dynamic-import@0.7.4
ecmascript@0.16.10-rc310.0
ecmascript@0.16.10
ecmascript-runtime@0.8.3
ecmascript-runtime-client@0.12.2
ecmascript-runtime-server@0.11.1
ejson@1.1.4
email@3.1.1-rc310.0
email@3.1.1
es5-shim@4.8.1
facts-base@1.0.2
fetch@0.1.5
@ -35,22 +35,22 @@ inter-process-messaging@0.1.2
launch-screen@2.0.1
localstorage@1.2.1
logging@1.3.5
meteor@2.0.2-rc310.0
meteor@2.0.2
meteor-base@1.5.2
minifier-css@2.0.0
minifier-js@3.0.1-rc310.0
minimongo@2.0.2-rc310.0
minifier-js@3.0.1
minimongo@2.0.2
mobile-experience@1.1.2
mobile-status-bar@1.1.1
modern-browsers@0.1.11
modules@0.20.3-rc310.0
modules@0.20.3
modules-runtime@0.13.2
modules-runtime-hot@0.14.3
mongo@2.0.3-rc310.0
mongo@2.0.3
mongo-decimal@0.2.0
mongo-dev-server@1.1.1
mongo-id@1.0.9
npm-mongo@6.10.0-rc310.0
npm-mongo@6.10.0
ordered-dict@1.2.0
promise@1.0.0
random@1.2.2
@ -61,18 +61,18 @@ react-meteor-data@3.0.2
reactive-var@1.0.13
reload@1.3.2
retry@1.1.1
roles@1.0.0-rc310.0
roles@1.0.0
routepolicy@1.1.2
sha@1.0.10
shell-server@0.6.1-rc310.0
shell-server@0.6.1
socket-stream-client@0.5.3
standard-minifier-css@1.9.3
standard-minifier-js@3.0.0
static-html@1.4.0
static-html-tools@1.0.0
tracker@1.3.4
typescript@5.6.3-rc310.0
url@1.3.4
webapp@2.0.4-rc310.0
typescript@5.6.3
url@1.3.5
webapp@2.0.4
webapp-hashing@1.1.2
zodern:types@1.0.13

View File

@ -1,5 +1,6 @@
<head>
<title>Meteor App</title>
<title>XaSuMu v0.1</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

View File

@ -0,0 +1,3 @@
import { Mongo } from 'meteor/mongo';
export const NecessitatsCollection = new Mongo.Collection('necessitats');

3
imports/api/tipus.js Normal file
View File

@ -0,0 +1,3 @@
import { Mongo } from 'meteor/mongo';
export const TipusCollection = new Mongo.Collection('tipus');

16
imports/roles.js Normal file
View File

@ -0,0 +1,16 @@
export const ROLS_GLOBALS = {
ADMINISTRADOR: 'admin',
USUARI: 'usuari'
}; // as const;
// export type GlobalRolesKeys = keyof typeof GLOBAL_ROLES;
// export type GlobalRolesValues = (typeof GLOBAL_ROLES)[GlobalRolesKeys];
export const ROLS_DE_POBLE = {
MONITOR: 'monitor_de_poble',
ENCARREGAT: 'encarregat_de_tasques',
VOLUNTARI: 'voluntari_de_poble'
}; // as const;
// export type TeamRolesKeys = keyof typeof TEAM_ROLES;
// export type TeamRolesValues = (typeof TEAM_ROLES)[TeamRolesKeys];

View File

@ -1,100 +1,55 @@
import React, { Suspense, useEffect, useState, useRef } from 'react';
import React, { Suspense, useEffect, useState, useRef, lazy } from 'react';
import { Meteor } from 'meteor/meteor';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import { Login } from './Login';
import { useUserId } from 'meteor/react-meteor-accounts';
import { PoblesCollection } from '/imports/api/pobles.js';
import { useSubscribe, useTracker, useFind } from 'meteor/react-meteor-data/suspense';
import { Pobles } from './Pobles';
import { Necessitats } from './Necessitats';
import { Tipus } from './Tipus';
import { BarraNav } from './BarraNav/BarraNav';
const Pobles = () => {
import { UserStat } from './BarraNav/UserStat';
import { Usuaris } from './Usuaris';
const [pobleSeleccionat, setPobleSeleccionat] = useState(null);
useSubscribe('pobles');
const pobles = useTracker("pobles", () => PoblesCollection.find().fetchAsync());
const Loguejat = lazy(async () => await import('/imports/ui/Loguejat.jsx'));
const QuadreInfo_Poble = () => {
return <>
<h1>{pobleSeleccionat._id}</h1>
<form action={d => {
try {
Meteor.callAsync('editaOAfigPoble',
{
createdAt: new Date(),
nomPoble: d.get('nomPoble'),
cp: d.get('cp') || "",
comarca: d.get('comarca') || "",
}, pobleSeleccionat
).catch(err => console.error(err));
} catch (err) {
alert(err);
console.error(err);
}
}}>
<label htmlFor="nomPoble">Població: </label><input name="nomPoble" type="text" defaultValue={pobleSeleccionat.nomPoble}/><br />
<label htmlFor="comarca">Comarca: </label><input name="comarca" type="text" /><br />
<label htmlFor="cp">Codi Postal: </label><input name="cp" type="text" /><br />
<input type='submit' value="Crear la Població" />
</form></>;
};
export const App = () => {
return <Suspense fallback={<>Carregant...</>} >
{pobleSeleccionat && <QuadreInfo_Poble />}
const user = useTracker("user", async () => await Meteor.userAsync());
const userId = Meteor.userId();
<ul>{
pobles
.sort((a,b) => a.nomPoble.toLowerCase() > b.nomPoble.toLowerCase())
.map(pob => <li key={`pob_${pob._id}`}>{pob.nomPoble}<button onClick={() => {setPobleSeleccionat(pob)}}>Edita</button><button>&times;</button></li>)
}</ul>
</Suspense>;
};
const [esAdministrador, setEsAdministrador] = useState(false);
const Loguejat = () => {
// const u = useTracker("user", async () => await Meteor.userAsync());
const userId = useUserId();
return userId ? <div>
useEffect(() => {
(async () => {
const comprovaAdmin = await Roles.userIsInRoleAsync(userId, ["admin"]);
setEsAdministrador(comprovaAdmin);
})();
}, [user]);
// const userId = await Meteor.userAsync();
<Link to="/pobles" >Pobles</Link>
return <BrowserRouter
future={{
v7_relativeSplatPath: true,
v7_startTransition: true,
}}
>
{Meteor.userId() && <UserStat esAdministrador={esAdministrador} setEsAdministrador={setEsAdministrador} />}
<button onClick={() => Meteor.logout()} >Logout</button>
<BarraNav esAdministrador={esAdministrador} setEsAdministrador={setEsAdministrador} />
<p>- poble (que cada poble només tinga accés a lo del seu poble, la resta de pobles no els han de poder tocar): Alaquàs / Albal / Aldaia / Alfafar / Algemesí / Alginet / Alcàsser / Benetússer / Beniparrell / Carlet / Catarroja / Dosaigües / Godelleta / Guadassuar / Iàtova / L'Alcúdia / Llocnou de la Corona / Massanassa / Paiporta / Parke Alkosa / Picanya / Sedaví / Setaigües / Utiel / València-Castellar Oliveral / València-Forn d'Alcedo / València-La Torre / Xest / Xiva / Llombai / Tremolar </p>
<p>- estat: impossible de trobar / disponible / pendent / enviada / ha arribat (que cada poble puga tocar aquestes opcions dels subministres per al seu poble)</p>
<p>- tipus de subministre: maquinària / menjar i beguda / productes infantils / higiene i neteja / sanitari / roba i calçat / ferramentes / necessitats especials / EPIs / electrònica / per a animals / roba de llit, mantes, cortines i mantells / vaixella i utensilis de cuina / papereria i material escolar / mobiliari i electrodomèstics /altres</p>
<p>- necessitat (que la plataforma et dóne un desplegable amb totes les necessitats que s'han demanat fins ara en eixa categoria i pugues buscar, però també afegir-ne coses noves) - que la plataforma demane en aquest punt que siguen tant específiques com puguen (que no em fiquen com a necessitat "mobles" sinó per exemple "rentadora")</p>
<p>- NOMÉS EN CAS DE MOBILIARI I ELECTRODOMÈSTICS:
---- adreça de la casa o lloc on s'ha de dur (tenda, casa, baix...)
---- que afegisquen dies i horaris en què estaran a eixa adreça
---- especificar que el contacte que afegisquen ha de ser necessàriament de la persona que ho va a rebre en la casa o espai
</p>
- que la plataforma recullga la data en la que es fa una petició de subministres
- que la plataforma recullga la data en la que el subministre es canvia a l'estat "ha arribat)
- Nom del contacte
- Telèfon de contacte
- Punt de descàrrega
I després amb opció de visualitzar totes les necessitats que s'han incorporat prèviament al teu poble i assenyalar "ha arribat" en les que ja no necessites
Nosaltres hauríem de tindre opció de filtrar les necessitats per pobles i condicions (per poder vore, per exemple, totes les necessitats pendents de tots els pobles, o només les necessitats pendents d'Alaquàs)
</div>
: <Link to="/login">Login</Link>
;
};
export const App = () => (
<BrowserRouter>
<Routes>
<Route path="/" element={ <Loguejat /> } />
<Route path="/" element={ <Suspense fallback={<>Carregant...</>}>{user ? <Loguejat /> : <Login/>}</Suspense> } />
<Route path="/usuaris" element={ <Usuaris /> } />
<Route path="/pobles" element={ <Pobles /> } />
<Route path="/necessitats" element={ <Necessitats /> } />
<Route path="/tipus" element={ <Tipus /> } />
<Route path="/login" element={ <Login /> } />
</Routes>
</BrowserRouter>
);
};

View File

@ -0,0 +1,44 @@
import React, {useState, useEffect, lazy} from "react";
import { Link } from 'react-router-dom';
import { Roles } from 'meteor/roles';
import { PanellSeccions } from "./PanellSeccions/PanellSeccions";
const SeccióPobles = lazy(async () => {
const module = await import('/imports/ui/BarraNav/PanellSeccions/PanellSeccions.jsx');
return ({ default: module.SeccióPobles });
});
const SeccióNecessitats = lazy(async () => {
const module = await import('/imports/ui/BarraNav/PanellSeccions/PanellSeccions.jsx');
return ({ default: module.SeccióNecessitats });
});
const SeccióTipus = lazy(async () => {
const module = await import('/imports/ui/BarraNav/PanellSeccions/PanellSeccions.jsx');
return ({ default: module.SeccióTipus });
});
const SeccióUsuaris = lazy(async () => {
const module = await import('/imports/ui/BarraNav/PanellSeccions/PanellSeccions.jsx');
return ({ default: module.SeccióUsuaris });
});
const BarraNav = ({esAdministrador, setEsAdministrador}) => {
const userId = Meteor.userId();
// const [esAdministrador, setEsAdministrador] = useState(false);
// useEffect(() => {
// (async () => {
// const comprovaAdmin = await Roles.userIsInRoleAsync(userId, ["admin"]);
// setEsAdministrador(comprovaAdmin);
// })();
// }, [esAdministrador]);
return <PanellSeccions >
{ esAdministrador && <SeccióUsuaris />}
<SeccióPobles />
<SeccióNecessitats />
<SeccióTipus />
</PanellSeccions>;
};
export { BarraNav };

View File

@ -0,0 +1,48 @@
import React from "react";
import { Link } from "react-router-dom";
export const BotóSecció = ({titol, linkto}) => {
return <div style={{
border: `1px solid #aaaa`,
borderRadius: `.3rem`,
padding: `.2rem`,
backgroundColor: `lightblue`,
margin: `.5rem`
}}>
<Link to={linkto} >{titol}</Link>
</div>;
};
export const SeccióPobles = () => <BotóSecció
titol="Pobles"
linkto="/pobles"
/>;
export const SeccióNecessitats = () => <BotóSecció
titol="Necessitats"
linkto="/necessitats"
/>;
export const SeccióTipus = () => <BotóSecció
titol="Tipus"
linkto="/tipus"
/>;
export const SeccióUsuaris = () => <BotóSecció
titol="Usuaris"
linkto="/usuaris"
/>;
export const PanellSeccions = ({children}) => {
return <><div style={{
display: `flex`,
border: `1px solid #cccc`,
padding: `.5rem`,
borderRadius: `.5rem`,
backgroundColor: `lightslategray`
}}>{children}</div>
<br />
</>;
};

View File

@ -0,0 +1,199 @@
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';
import { useLongTap } from '../hooks';
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 UserStat = ({esAdministrador, setEsAdministrador}) => {
// const [esAdministrador, setEsAdministrador] = useState(false);
const { onPointerDown, onPointerUp, onPointerCancel, onPointerOut } = useLongTap(() => {
alert('Long tap detected!');
});
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: `.7em`,
fontWeight: `bold`,
display: `inline-block`
}}
// onMouseEnter={ev => {
// setMostraMenu(true);
// }}
// // title="Logout"
// onClick={ev => {
// ev.stopPropagation();
// ev.preventDefault();
// // console.log("u: ", u);
// navigate(`/${u.username}`);
// }}
onPointerDown={onPointerDown}
onPointerUp={onPointerUp}
onPointerCancel={onPointerCancel}
onPointerOut={onPointerOut}
>
{ (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`
}}
src={u?.profile?.avatarLink}
/>
<span style={{
verticalAlign: `middle`,
margin: `0.3em 0.3em 0.3em auto`
}}>{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 { UserStat };

View File

@ -4,14 +4,14 @@ import { useNavigate } from 'react-router-dom';
import { Meteor } from 'meteor/meteor';
export const Login= () => {
export const Login = () => {
const [isLogin, setIsLogin] = useState( { initialState: true } );
const navigate = useNavigate();
const handleLogin = (e) => {
e.preventDefault();
console.dir(e);
console.dir(e.target.elements.email.value);
// console.dir(e);
// console.dir(e.target.elements.email.value);
// console.dir(e.target.elements.password.value);
const email = e.target.elements.email.value;
const password = e.target.elements.password.value;
@ -27,7 +27,7 @@ export const Login= () => {
const handleRegistration = (e) => {
e.preventDefault();
console.dir(e);
// console.dir(e);
const username = e.target.elements.username.value;
const email = e.target.elements.email.value;
const password = e.target.elements.password.value;
@ -48,33 +48,39 @@ export const Login= () => {
if (isLogin) {
return <form onSubmit={handleLogin}>
<label htmlFor="email">E-mail</label>
<label htmlFor="email">Correu electrònic o nom d'usuari: </label>
<input id="email" type="email" required />
<br />
<label htmlFor="password">Password</label>
<label htmlFor="password">Contrasenya: </label>
<input id="password" type="password" required />
<br />
<button type="submit">Login</button>
<button onClick={() => setIsLogin( false )}>Register a new account</button>
<button type="submit">Entra</button>
<button onClick={() => setIsLogin( false )}>Registra un compte nou</button>
</form>
}
return (
<form onSubmit={handleRegistration}>
<label htmlFor="username">Username</label>
<label htmlFor="username">Nom d'usuari: </label>
<input id="username" type="text" required />
<br />
<label htmlFor="email">E-mail</label>
<label htmlFor="email">Correu electrònic: </label>
<input id="email" type="email" required />
<br />
<label htmlFor="password">Password</label>
<label htmlFor="password">Contrasenya: </label>
<input id="password" type="password" required />
<br />
<label htmlFor="password2">Repeat password</label>
<label htmlFor="password2">Repeteix la contrasenya: </label>
<input id="password2" type="password" required />
<br />
<button type="submit">Register</button>
<button onClick={() => setIsLogin( true )}>Login instead</button>
<label htmlFor="tel">Telèfon: </label>
<input id="tel" type="tel" required />
<br />
<label htmlFor="codi">Codi d'entrada (opcional): </label>
<input id="codi" type="text" />
<br />
<button type="submit">Registrar</button>
<button onClick={() => setIsLogin( true )}>Torna per accedir</button>
</form>
);
};

48
imports/ui/Loguejat.jsx Normal file
View File

@ -0,0 +1,48 @@
import React from "react";
import { useUserId } from 'meteor/react-meteor-accounts';
import { Link } from 'react-router-dom';
// import { styled } from 'styled-components'
// import { BarraNav } from "./BarraNav/BarraNav";
// if (loguejat)
const Loguejat = () => {
const userId = useUserId();
return userId ? <div>
<button onClick={() => Meteor.logout()} >Logout</button>
<br /><br />
{/* <BarraNav /> */}
<p>- poble (que cada poble només tinga accés a lo del seu poble, la resta de pobles no els han de poder tocar): Alaquàs / Albal / Aldaia / Alfafar / Algemesí / Alginet / Alcàsser / Benetússer / Beniparrell / Carlet / Catarroja / Dosaigües / Godelleta / Guadassuar / Iàtova / L'Alcúdia / Llocnou de la Corona / Massanassa / Paiporta / Parke Alkosa / Picanya / Sedaví / Setaigües / Utiel / València-Castellar Oliveral / València-Forn d'Alcedo / València-La Torre / Xest / Xiva / Llombai / Tremolar </p>
<p>- estat: impossible de trobar / disponible / pendent / enviada / ha arribat (que cada poble puga tocar aquestes opcions dels subministres per al seu poble)</p>
<p>- tipus de subministre: maquinària / menjar i beguda / productes infantils / higiene i neteja / sanitari / roba i calçat / ferramentes / necessitats especials / EPIs / electrònica / per a animals / roba de llit, mantes, cortines i mantells / vaixella i utensilis de cuina / papereria i material escolar / mobiliari i electrodomèstics /altres</p>
<p>- necessitat (que la plataforma et dóne un desplegable amb totes les necessitats que s'han demanat fins ara en eixa categoria i pugues buscar, però també afegir-ne coses noves) - que la plataforma demane en aquest punt que siguen tant específiques com puguen (que no em fiquen com a necessitat "mobles" sinó per exemple "rentadora")</p>
<p>- NOMÉS EN CAS DE MOBILIARI I ELECTRODOMÈSTICS:
---- adreça de la casa o lloc on s'ha de dur (tenda, casa, baix...)
---- que afegisquen dies i horaris en què estaran a eixa adreça
---- especificar que el contacte que afegisquen ha de ser necessàriament de la persona que ho va a rebre en la casa o espai
</p>
- que la plataforma recullga la data en la que es fa una petició de subministres
- que la plataforma recullga la data en la que el subministre es canvia a l'estat "ha arribat)
- Nom del contacte
- Telèfon de contacte
- Punt de descàrrega
I després amb opció de visualitzar totes les necessitats que s'han incorporat prèviament al teu poble i assenyalar "ha arribat" en les que ja no necessites
Nosaltres hauríem de tindre opció de filtrar les necessitats per pobles i condicions (per poder vore, per exemple, totes les necessitats pendents de tots els pobles, o només les necessitats pendents d'Alaquàs)
</div>
: <Link to="/login">Entra o Registra't</Link>;
};
export default Loguejat;

179
imports/ui/Necessitats.jsx Normal file
View File

@ -0,0 +1,179 @@
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 Necessitats = () => {
// 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) ;
const [necessitatSeleccionada, setNecessitatSeleccionada] = useState(null);
useSubscribe('necessitats');
const necessitats = useTracker("necessitats", () => NecessitatsCollection.find().fetchAsync());
useSubscribe('pobles');
const pobles = useTracker("pobles", () => PoblesCollection.find().fetchAsync());
useSubscribe('tipus');
const tipus = useTracker("tipus", () => TipusCollection.find().fetchAsync());
const QuadreInfo_Necessitats = () => {
return <div style={{
display: `inline-block`,
border: `1px solid #6666`,
padding: `.5rem`,
borderRadius: `.3em`,
backgroundColor: `lightcyan`
}}>
{necessitatSeleccionada && <h2>{necessitatSeleccionada._id}</h2>}
<h1>Necessitats</h1>
<form
action={d => {
if (d.get('selTipus'))
try {
Meteor.callAsync('afigNecessitat', {
...necessitatSeleccionada || [],
titol: d.get('titol'),
tipus: d.get('selTipus') || "",
poble: d.get('selPoble')
})
.then(() => setNecessitatSeleccionada(null))
.catch(err => console.error(err))
;
} catch (err) {
alert(err);
console.error(err);
}
}}
>
<label htmlFor="taTitol">Títol</label> <br />
<textarea name='taTitol' placeholder='Títol de la necessitat...'></textarea>
<br /><br />
<label htmlFor="tipus">Tipus</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
*/}
<AsyncCreatableSelect
name="selTipus"
formatCreateLabel={(inputValue) => "Crear nou tipus..."}
defaultOptions={tipus.map((v,i) => ({value: v._id, label: v.titol})).sort((a,b) => a.label.toLowerCase() > b.label.toLowerCase()) }
onCreateOption={(inputValue) => Meteor.callAsync('afigTipus', {titol: inputValue})}
// loadOptions={tipus.map((v,i) => ({value: v, label: v.titol}))}
/>
{/* <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 />
<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 />
<label htmlFor="taDescripcio">Descripció: </label> <br />
<textarea name="taDescripcio" id="taDescripcio" placeholder='Observacions i detalls particulars...'></textarea> <br />
<br />
<fieldset style={{
borderRadius: `.4em`,
border: `1px solid #6666`
}}>
<legend>Contacte</legend>
<input required type="text" name="inContacte" id="inContacte" placeholder='Nom' /> <br />
<input required type="text" name="inTelefon" id="inTelefon" placeholder='Telèfon' /> <br />
<input required type="text" name="inEMail" id="inEMail" placeholder='Correu electrònic' /> <br />
<input type="text" name="inAdreça" id="inAdreça" placeholder='Adreça' /> <br />
</fieldset>
<br />
<input type='submit' value="Enviar" />
{necessitatSeleccionada && 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_Necessitats />
<br /><br />
<ul style={{
display: `flex`,
flexWrap: `wrap`,
justifyContent: `space-evenly`,
rowGap: `.3em`,
alignContent: `space-around`
}}>{
necessitats
.sort((a,b) => a.titol?.toLowerCase() > b.titol?.toLowerCase())
.map(nec => <li
key={`nec_${nec._id}`}
style={{
display: `block`,
border: `1px solid #6666`,
borderRadius: `.4em`,
padding: `4px`,
listStyle: `none`,
backgroundColor: `${'lightgreen' || 'lightcoral'}`
}}
>
{nec.titol}{esEditor && <button onClick={() => {setNecessitatSeleccionada(nec)}}>Edita</button>}</li>)
}</ul>
</Suspense>;
};

106
imports/ui/Pobles.jsx Normal file
View File

@ -0,0 +1,106 @@
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 { BarraNav } from "./BarraNav/BarraNav";
export const Pobles = () => {
const [pobleSeleccionat, setPobleSeleccionat] = useState(null);
useSubscribe('pobles');
// const pobles = useTracker("pobles", () => PoblesCollection.find().fetchAsync());
const pobles = useFind(PoblesCollection, [{}, {sort: {nomPoble: 1}}]);
const [esEditor, setEsEditor] = useState(false);
const userId = Meteor.userId();
// console.log("isAdmin: ", isAdmin) ;
// (async () => {
useEffect(() => {
(async () => {
const comprovaAdmin = await Roles.userIsInRoleAsync(userId, ["admin"]);
setEsEditor(comprovaAdmin);
})();
}, []);
// })();
const QuadreInfo_Poble = () => {
return <div style={{
display: `inline-block`,
border: `1px solid #6666`,
padding: `.5rem`,
borderRadius: `.3em`,
backgroundColor: `lightcyan`
}}>
{pobleSeleccionat && <h2>{pobleSeleccionat._id}</h2>}
<h1>Pobles</h1>
<form
action={d => {
try {
Meteor.callAsync('editaOAfigPoble',
{
...pobleSeleccionat || [],
nomPoble: d.get('nomPoble'),
cp: d.get('cp') || "",
comarca: d.get('comarca') || "",
}).then(() => setPobleSeleccionat(null))
.catch(err => console.error(err));
} catch (err) {
alert(err);
console.error(err);
}
}}
>
<label htmlFor="nomPoble">Població: </label><input name="nomPoble" type="text" defaultValue={ pobleSeleccionat ? pobleSeleccionat.nomPoble : ""}/><br />
<label htmlFor="comarca">Comarca: </label><input name="comarca" type="text" /><br />
<label htmlFor="cp">Codi Postal: </label><input name="cp" type="text" /><br />
<input type='submit' value="Actualitzar la Població" />
<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));
setPobleSeleccionat(null);
}
}}>Elimina</button>
</form>
</div>;
};
return <Suspense fallback={<>Carregant...</>} >
{ esEditor && <QuadreInfo_Poble /> }
<ul style={{
display: `flex`,
flexWrap: `wrap`,
justifyContent: `space-evenly`,
rowGap: `.3em`,
alignContent: `space-around`
}}>{
pobles
.sort((a,b) => a.nomPoble?.toLowerCase() > b.nomPoble?.toLowerCase())
.map(pob => <li
key={`pob_${pob._id}`}
style={{
display: `block`,
border: `1px solid #6666`,
borderRadius: `.4em`,
padding: `4px`,
listStyle: `none`,
backgroundColor: `${'lightgreen' || 'lightcoral'}`
}}
>
{pob.nomPoble}{esEditor && <button onClick={() => {setPobleSeleccionat(pob)}}>Edita</button>}</li>)
}</ul>
</Suspense>;
};

193
imports/ui/Tipus.jsx Normal file
View File

@ -0,0 +1,193 @@
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 Tipus = () => {
// 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) ;
const [tipusSeleccionat, setNecessitatSeleccionat] = useState(null);
useSubscribe('necessitats');
const necessitats = useTracker("necessitats", () => NecessitatsCollection.find().fetchAsync());
useSubscribe('pobles');
const pobles = useTracker("pobles", () => PoblesCollection.find().fetchAsync());
useSubscribe('tipus');
const tipus = useTracker("tipus", () => TipusCollection.find().fetchAsync());
// console.log("tipus: ", tipus);
// console.log("necessitats: ", necessitats);
// console.log("tipusSeleccionat: ", tipusSeleccionat);
const filterTipus = (inputValue) => {
return tipus.filter((i) =>
i.titol.toLowerCase().includes(inputValue.toLowerCase())
);
};
const QuadreInfo_Tipus = () => {
return <div style={{
display: `inline-block`,
border: `1px solid #6666`,
padding: `.5rem`,
borderRadius: `.3em`,
backgroundColor: `lightcyan`
}}>
{tipusSeleccionat && <h1>{tipusSeleccionat._id}</h1>}
<h1>Tipus</h1>
<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(() => setTipusSeleccionat(null))
.catch(err => console.error(err))
;
} catch (err) {
alert(err);
console.error(err);
}
}}
>
<label htmlFor="tipus">Tipus: </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
*/}
<AsyncCreatableSelect
name="selTipus"
formatCreateLabel={(inputValue) => "Crear nou tipus..."}
defaultOptions={tipus.map((v,i) => ({value: v._id, label: v.titol})).sort((a,b) => a.label.toLowerCase() > b.label.toLowerCase()) }
onCreateOption={(inputValue) => Meteor.callAsync('afigTipus', {titol: inputValue})}
isSearchable
// loadOptions={tipus.map((v,i) => ({value: v, label: v.titol}))}
/>
{/* <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 />
<label htmlFor="selNecessitat">Necessitat: </label>
<Select
name="selNecessitat"
// filterOption={(opts) => necessitats.find(nec => nec.tipus === tipusSeleccionat._id)}
options={necessitats.map((v,i) => ({value: v._id, label: v.titol})).sort((a,b) => a.label.toLowerCase() > b.label.toLowerCase()) }
/>
<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" />
{tipusSeleccionat && 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`
}}>{
tipus
.sort((a,b) => a.titol?.toLowerCase() > b.titol?.toLowerCase())
.map(titol => <li
key={`titol_${titol._id}`}
style={{
display: `block`,
border: `1px solid #6666`,
borderRadius: `.4em`,
padding: `4px`,
listStyle: `none`,
backgroundColor: `${'lightgreen' || 'lightcoral'}`
}}
>
{titol.titol}{esEditor && <button onClick={() => {setTipusSeleccionat(titol)}}>Edita</button>}</li>)
}</ul>
</Suspense>;
};

107
imports/ui/Usuaris.jsx Normal file
View File

@ -0,0 +1,107 @@
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';
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`
}}>{
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`,
listStyle: `none`,
backgroundColor: `${'lightgreen' || 'lightcoral'}`
}}
>
{usr.username}{esEditor && <button onClick={() => {setUsrSeleccionat(usr)}}>Edita</button>}</li>)
}</ul>
</Suspense>;
};

46
imports/ui/hooks.jsx Normal file
View File

@ -0,0 +1,46 @@
import { useState, useEffect } from 'react';
const useLongTap = (onLongTap, duration = 500) => {
const [isPressing, setIsPressing] = useState(false);
const [startTime, setStartTime] = useState(null);
useEffect(() => {
if (isPressing && startTime) {
const elapsedTime = performance.now() - startTime;
if (elapsedTime >= duration) {
onLongTap();
setIsPressing(false);
setStartTime(null);
}
}
}, [isPressing, startTime, onLongTap, duration]);
const handlePointerDown = (event) => {
setIsPressing(true);
setStartTime(performance.now());
};
const handlePointerUp = () => {
setIsPressing(false);
setStartTime(null);
};
const handlePointerCancel = () => {
setIsPressing(false);
setStartTime(null);
};
const handlePointerOut = () => {
setIsPressing(false);
setStartTime(null);
};
return {
onPointerDown: handlePointerDown,
onPointerUp: handlePointerUp,
onPointerCancel: handlePointerCancel,
onPointerOut: handlePointerOut,
};
};
export { useLongTap };

970
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -10,9 +10,11 @@
"dependencies": {
"@babel/runtime": "^7.20.7",
"meteor-node-stubs": "^1.2.5",
"react": "19.0.0-rc.1",
"react-dom": "19.0.0-rc.1",
"react-router-dom": "^6.28.0"
"react": "19",
"react-dom": "19",
"react-router-dom": "^6.28.0",
"react-select": "^5.8.3",
"styled-components": "^6.1.13"
},
"meteor": {
"mainModule": {

View File

@ -2,6 +2,11 @@ import { Meteor } from 'meteor/meteor';
import { PoblesCollection } from '/imports/api/pobles.js';
import { check } from "meteor/check";
import { Roles } from 'meteor/roles';
import { ROLS_GLOBALS, ROLS_DE_POBLE } from '../imports/roles';
import { NecessitatsCollection } from '../imports/api/necessitats';
import { TipusCollection } from '../imports/api/tipus';
async function insertPoble({ nomPoble, cp, comarca }) {
await PoblesCollection.insertAsync({ nomPoble, cp, comarca, createdAt: new Date() });
}
@ -179,24 +184,151 @@ Meteor.startup(async () => {
return PoblesCollection.find();
});
Meteor.publish("necessitats", function () {
return NecessitatsCollection.find();
});
Meteor.publish("tipus", function () {
return TipusCollection.find();
});
Meteor.publish('usuaris', async function (uid) {
const esAdmin = await Roles.userIsInRoleAsync(Meteor.userId(), "admin");
const userRoles = await Roles.getRolesForUserAsync(Meteor.userId());
console.log("userRoles: ", userRoles);
if (uid) {
return Meteor.users.find({_id: uid},{fields: {username: 1, avatarId: 1, avatarLink: 1}});
}
return Meteor.users.find({},{fields: {username: 1, avatarId: 1, avatarLink: 1}});
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
try {
await Roles.createRoleAsync(ROLS_GLOBALS.ADMINISTRADOR, { unlessExists: true });
await Roles.createRoleAsync(ROLS_GLOBALS.USUARI, { unlessExists: true });
await Roles.createRoleAsync(ROLS_DE_POBLE.MONITOR, { unlessExists: true });
await Roles.createRoleAsync(ROLS_DE_POBLE.ENCARREGAT, { unlessExists: true });
await Roles.createRoleAsync(ROLS_DE_POBLE.VOLUNTARI, { unlessExists: true });
await Roles.addRolesToParentAsync([ROLS_DE_POBLE.VOLUNTARI, ROLS_DE_POBLE.ENCARREGAT], ROLS_DE_POBLE.MONITOR);
await Roles.addRolesToParentAsync([ROLS_DE_POBLE.VOLUNTARI, ROLS_DE_POBLE.ENCARREGAT, ROLS_DE_POBLE.MONITOR, ROLS_GLOBALS.USUARI], ROLS_GLOBALS.ADMINISTRADOR);
} catch (err) {
console.error(err.message);
}
// Publish user's own roles
Meteor.publish(null, function () {
if (this.userId) {
return Meteor.roleAssignment.find({ "user._id": this.userId });
}
this.ready();
});
// Publish roles for specific scope
// Meteor.publish("scopeRoles", function (scope) {
// if (this.userId) {
// return Meteor.roleAssignment.find({ scope: scope });
// }
// this.ready();
// });
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Meteor.methods({
'editaOAfigPoble': async function (poble) {
const esAdmin = await Roles.userIsInRoleAsync(Meteor.userId(), "admin");
try {
if (poble.nomPoble) {
return await PoblesCollection.insertAsync({
console.log(`EDICIÓ DE POBLE sol·licitada per a "${poble.nomPoble}". Comprovant si ${Meteor.userId()} és Admin: `, esAdmin);
if (esAdmin && poble.nomPoble) {
return await PoblesCollection.upsertAsync(
{
_id: poble._id
}, {
$set: {
...poble,
usuari: Meteor.userId(),
createdAt: new Date()
});
editedAt: new Date()
}
}
);
} else {
throw new Error("El nom del poble no és vàlid");
}
} catch (e) {
console.error(e);
}
},
'afigNecessitat': async function (necessitat) {
const esAdmin = await Roles.userIsInRoleAsync(Meteor.userId(), "admin");
try {
console.log(`CREACIÓ DE NECESSITAT sol·licitada per a "${necessitat.titol}". Comprovant si ${Meteor.userId()} és Admin: `, esAdmin);
if (esAdmin && necessitat.titol) {
return await NecessitatsCollection.upsertAsync(
{
_id: necessitat._id
}, {
$set: {
...necessitat,
usuari: Meteor.userId(),
editedAt: new Date()
}
}
);
} else {
throw new Error("No tens permís o el títol no està correcte");
}
} catch (e) {
console.error(e);
}
},
'eliminaPoble': async function (pobleId) {
const esAdmin = await Roles.userIsInRoleAsync(Meteor.userId(), "admin");
try {
console.log(`ELIMINACIÓ DE POBLE sol·licitada per a ${pobleId}. Comprovant si ${Meteor.userId()} és Admin: `, esAdmin);
if (esAdmin && pobleId) {
return await PoblesCollection.removeAsync(pobleId);
} else {
throw new Error("El nom del poble no és vàlid");
}
} catch (e) {
console.error(e);
}
},
'afigTipus': async function (tipus) {
const esAdmin = await Roles.userIsInRoleAsync(Meteor.userId(), "admin");
try {
console.log(`CREACIÓ DE TIPUS sol·licitada per a "${tipus.titol}". Comprovant si ${Meteor.userId()} és Admin: `, esAdmin);
if (esAdmin && tipus.titol) {
return await TipusCollection.upsertAsync(
{
_id: tipus._id
}, {
$set: {
...tipus,
usuari: Meteor.userId(),
editedAt: new Date()
}
}
);
} else {
throw new Error("El nom del poble no és vàlid");
}
} catch (e) {
console.error(e);
}
},
});
});