feat: Add tickets module and PayPal integration

Introduces a new 'Tickets' module for users to submit and manage issues within their condominium. This includes defining ticket types, statuses, priorities, and categories.

Additionally, this commit integrates PayPal as a payment option for family fee payments, enabling users to pay directly via PayPal using their client ID.

Key changes:
- Added `Ticket` related types and enums.
- Implemented `TicketService` functions for CRUD operations.
- Integrated `@paypal/react-paypal-js` library.
- Added `paypalClientId` to `AppSettings` and `Condo` types.
- Updated `FamilyDetail` page to include PayPal payment option.
- Added 'Segnalazioni' navigation link to `Layout`.
This commit is contained in:
2025-12-07 19:49:59 +01:00
parent 2566b406e1
commit 5311400615
14 changed files with 977 additions and 146 deletions

Binary file not shown.

View File

@@ -1,9 +1,11 @@
import React from 'react';
import { HashRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { Layout } from './components/Layout';
import { FamilyList } from './pages/FamilyList';
import { FamilyDetail } from './pages/FamilyDetail';
import { SettingsPage } from './pages/Settings';
import { TicketsPage } from './pages/Tickets';
import { LoginPage } from './pages/Login';
import { CondoService } from './services/mockDb';
@@ -31,6 +33,7 @@ const App: React.FC = () => {
}>
<Route index element={<FamilyList />} />
<Route path="family/:id" element={<FamilyDetail />} />
<Route path="tickets" element={<TicketsPage />} />
<Route path="settings" element={<SettingsPage />} />
</Route>

View File

@@ -1,14 +0,0 @@
# Stage 1: Build the React application
FROM node:18-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# Stage 2: Serve with Nginx
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

View File

@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react';
import { NavLink, Outlet } from 'react-router-dom';
import { Users, Settings, Building, LogOut, Menu, X, ChevronDown, Check, LayoutDashboard, Megaphone, Info, AlertTriangle, Hammer, Calendar } from 'lucide-react';
import { Users, Settings, Building, LogOut, Menu, X, ChevronDown, Check, LayoutDashboard, Megaphone, Info, AlertTriangle, Hammer, Calendar, MessageSquareWarning } from 'lucide-react';
import { CondoService } from '../services/mockDb';
import { Condo, Notice } from '../types';
@@ -218,6 +218,11 @@ export const Layout: React.FC = () => {
<span className="font-medium">Famiglie</span>
</NavLink>
<NavLink to="/tickets" className={navClass} onClick={closeMenu}>
<MessageSquareWarning className="w-5 h-5" />
<span className="font-medium">Segnalazioni</span>
</NavLink>
<NavLink to="/settings" className={navClass} onClick={closeMenu}>
<Settings className="w-5 h-5" />
<span className="font-medium">Impostazioni</span>

View File

@@ -40,7 +40,8 @@
"react-router-dom": "https://aistudiocdn.com/react-router-dom@^7.10.1",
"lucide-react": "https://aistudiocdn.com/lucide-react@^0.556.0",
"vite": "https://aistudiocdn.com/vite@^7.2.6",
"@vitejs/plugin-react": "https://aistudiocdn.com/@vitejs/plugin-react@^5.1.1"
"@vitejs/plugin-react": "https://aistudiocdn.com/@vitejs/plugin-react@^5.1.1",
"@paypal/react-paypal-js": "https://esm.sh/@paypal/react-paypal-js@8.1.3?external=react,react-dom"
}
}
</script>

View File

@@ -1,20 +1 @@
server {
listen 80;
# Serve React App (SPA)
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
# Proxy API requests to Backend Service
location /api {
proxy_pass http://backend:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
<EFBFBD><EFBFBD><EFBFBD>z

View File

@@ -4,6 +4,7 @@ import { useParams, useNavigate } from 'react-router-dom';
import { CondoService } from '../services/mockDb';
import { Family, Payment, AppSettings, MonthStatus, PaymentStatus, Condo } from '../types';
import { ArrowLeft, CheckCircle2, AlertCircle, Plus, Calendar, CreditCard, TrendingUp } from 'lucide-react';
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
const MONTH_NAMES = [
"Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno",
@@ -27,6 +28,10 @@ export const FamilyDetail: React.FC = () => {
const [newPaymentAmount, setNewPaymentAmount] = useState<number>(0);
const [isSubmitting, setIsSubmitting] = useState(false);
// Payment Method Selection
const [paymentMethod, setPaymentMethod] = useState<'manual' | 'paypal'>('manual');
const [paypalSuccessMsg, setPaypalSuccessMsg] = useState('');
useEffect(() => {
if (!id) return;
@@ -117,33 +122,45 @@ export const FamilyDetail: React.FC = () => {
return max > 0 ? Math.max(max * 1.2, baseline) : baseline;
}, [chartData, condo, family]);
const handleAddPayment = async (e: React.FormEvent) => {
e.preventDefault();
const handlePaymentSuccess = async (details?: any) => {
if (!family || !id) return;
setIsSubmitting(true);
try {
const payment = await CondoService.addPayment({
familyId: id,
amount: newPaymentAmount,
forMonth: newPaymentMonth,
forYear: selectedYear,
datePaid: new Date().toISOString()
});
const payment = await CondoService.addPayment({
familyId: id,
amount: newPaymentAmount,
forMonth: newPaymentMonth,
forYear: selectedYear,
datePaid: new Date().toISOString(),
notes: details ? `Pagato con PayPal (ID: ${details.id})` : ''
});
setPayments([...payments, payment]);
if (!availableYears.includes(selectedYear)) {
setAvailableYears([...availableYears, selectedYear].sort((a,b) => b-a));
}
setPayments([...payments, payment]);
if (!availableYears.includes(selectedYear)) {
setAvailableYears([...availableYears, selectedYear].sort((a,b) => b-a));
}
setShowAddModal(false);
if (details) {
setPaypalSuccessMsg("Pagamento riuscito!");
setTimeout(() => {
setShowAddModal(false);
setPaypalSuccessMsg("");
}, 2000);
} else {
setShowAddModal(false);
}
} catch (e) {
console.error("Failed to add payment", e);
console.error("Failed to add payment", e);
} finally {
setIsSubmitting(false);
setIsSubmitting(false);
}
};
const handleManualSubmit = (e: React.FormEvent) => {
e.preventDefault();
handlePaymentSuccess();
};
if (loading) return <div className="p-8 text-center text-slate-500">Caricamento dettagli...</div>;
if (!family) return <div className="p-8 text-center text-red-500">Famiglia non trovata.</div>;
@@ -184,7 +201,10 @@ export const FamilyDetail: React.FC = () => {
</select>
<button
onClick={() => setShowAddModal(true)}
onClick={() => {
setPaymentMethod(condo?.paypalClientId ? 'paypal' : 'manual');
setShowAddModal(true);
}}
className="flex-1 md:flex-none flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2.5 rounded-lg shadow-sm font-medium transition-all active:scale-95 whitespace-nowrap"
>
<Plus className="w-5 h-5" />
@@ -285,6 +305,7 @@ export const FamilyDetail: React.FC = () => {
<button
onClick={() => {
setNewPaymentMonth(month.monthIndex + 1);
setPaymentMethod(condo?.paypalClientId ? 'paypal' : 'manual');
setShowAddModal(true);
}}
className="ml-auto text-blue-600 hover:text-blue-800 text-xs font-bold uppercase tracking-wide px-2 py-1 rounded hover:bg-blue-50 transition-colors"
@@ -353,49 +374,117 @@ export const FamilyDetail: React.FC = () => {
<button onClick={() => setShowAddModal(false)} className="text-slate-400 hover:text-slate-600 w-8 h-8 flex items-center justify-center rounded-full hover:bg-slate-200"></button>
</div>
<form onSubmit={handleAddPayment} className="p-6 space-y-5">
<div>
<label className="block text-sm font-semibold text-slate-700 mb-1.5">Mese di Riferimento</label>
<select
value={newPaymentMonth}
onChange={(e) => setNewPaymentMonth(parseInt(e.target.value))}
className="w-full border border-slate-300 rounded-xl p-3 focus:ring-2 focus:ring-blue-500 outline-none bg-white"
>
{MONTH_NAMES.map((name, i) => (
<option key={i} value={i + 1}>{name}</option>
))}
</select>
</div>
<div className="p-6">
{/* Payment Method Switcher */}
{condo?.paypalClientId && (
<div className="flex bg-slate-100 rounded-lg p-1 mb-6">
<button
onClick={() => setPaymentMethod('manual')}
className={`flex-1 py-1.5 text-sm font-medium rounded-md transition-all ${paymentMethod === 'manual' ? 'bg-white text-slate-800 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
>
Manuale
</button>
<button
onClick={() => setPaymentMethod('paypal')}
className={`flex-1 py-1.5 text-sm font-medium rounded-md transition-all ${paymentMethod === 'paypal' ? 'bg-white text-blue-800 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
>
PayPal
</button>
</div>
)}
<div>
<label className="block text-sm font-semibold text-slate-700 mb-1.5">Importo ()</label>
<input
type="number"
step="0.01"
required
value={newPaymentAmount}
onChange={(e) => setNewPaymentAmount(parseFloat(e.target.value))}
className="w-full border border-slate-300 rounded-xl p-3 focus:ring-2 focus:ring-blue-500 outline-none text-lg font-medium"
/>
</div>
{paymentMethod === 'manual' ? (
<form onSubmit={handleManualSubmit} className="space-y-5">
<div>
<label className="block text-sm font-semibold text-slate-700 mb-1.5">Mese di Riferimento</label>
<select
value={newPaymentMonth}
onChange={(e) => setNewPaymentMonth(parseInt(e.target.value))}
className="w-full border border-slate-300 rounded-xl p-3 focus:ring-2 focus:ring-blue-500 outline-none bg-white"
>
{MONTH_NAMES.map((name, i) => (
<option key={i} value={i + 1}>{name}</option>
))}
</select>
</div>
<div className="pt-2 flex gap-3">
<button
type="button"
onClick={() => setShowAddModal(false)}
className="flex-1 px-4 py-3 border border-slate-300 text-slate-700 rounded-xl hover:bg-slate-50 font-bold text-sm"
>
Annulla
</button>
<button
type="submit"
disabled={isSubmitting}
className="flex-1 px-4 py-3 bg-blue-600 text-white rounded-xl hover:bg-blue-700 font-bold text-sm disabled:opacity-50"
>
{isSubmitting ? '...' : 'Conferma'}
</button>
</div>
</form>
<div>
<label className="block text-sm font-semibold text-slate-700 mb-1.5">Importo ()</label>
<input
type="number"
step="0.01"
required
value={newPaymentAmount}
onChange={(e) => setNewPaymentAmount(parseFloat(e.target.value))}
className="w-full border border-slate-300 rounded-xl p-3 focus:ring-2 focus:ring-blue-500 outline-none text-lg font-medium"
/>
</div>
<div className="pt-2 flex gap-3">
<button
type="button"
onClick={() => setShowAddModal(false)}
className="flex-1 px-4 py-3 border border-slate-300 text-slate-700 rounded-xl hover:bg-slate-50 font-bold text-sm"
>
Annulla
</button>
<button
type="submit"
disabled={isSubmitting}
className="flex-1 px-4 py-3 bg-blue-600 text-white rounded-xl hover:bg-blue-700 font-bold text-sm disabled:opacity-50"
>
{isSubmitting ? '...' : 'Conferma'}
</button>
</div>
</form>
) : (
<div className="space-y-6">
<div className="bg-blue-50 p-4 rounded-xl text-center">
<p className="text-sm text-slate-500 mb-1">Stai per pagare</p>
<p className="text-3xl font-bold text-blue-700"> {newPaymentAmount.toFixed(2)}</p>
<p className="text-sm font-medium text-slate-600 mt-1">{MONTH_NAMES[newPaymentMonth - 1]} {selectedYear}</p>
</div>
{paypalSuccessMsg ? (
<div className="bg-green-100 text-green-700 p-4 rounded-xl text-center font-bold flex items-center justify-center gap-2">
<CheckCircle2 className="w-5 h-5"/>
{paypalSuccessMsg}
</div>
) : (
<div className="min-h-[150px] flex items-center justify-center">
{condo?.paypalClientId && (
<PayPalScriptProvider options={{ clientId: condo.paypalClientId, currency: "EUR" }}>
<PayPalButtons
style={{ layout: "vertical" }}
createOrder={(data, actions) => {
return actions.order.create({
intent: "CAPTURE",
purchase_units: [
{
description: `Quota ${MONTH_NAMES[newPaymentMonth - 1]} ${selectedYear} - Famiglia ${family.name}`,
amount: {
currency_code: "EUR",
value: newPaymentAmount.toString(),
},
},
],
});
}}
onApprove={(data, actions) => {
if(!actions.order) return Promise.resolve();
return actions.order.capture().then((details) => {
handlePaymentSuccess(details);
});
}}
/>
</PayPalScriptProvider>
)}
</div>
)}
<p className="text-xs text-center text-slate-400">Il pagamento sarà registrato automaticamente.</p>
</div>
)}
</div>
</div>
</div>
)}

View File

@@ -2,7 +2,7 @@
import React, { useEffect, useState } from 'react';
import { CondoService } from '../services/mockDb';
import { AppSettings, Family, User, AlertDefinition, Condo, Notice, NoticeIconType, NoticeRead } from '../types';
import { Save, Building, Coins, Plus, Pencil, Trash2, X, CalendarCheck, AlertTriangle, User as UserIcon, Server, Bell, Clock, FileText, Lock, Megaphone, CheckCircle2, Info, Hammer, Link as LinkIcon, Eye, Calendar, List, UserCog, Mail, Power, MapPin } from 'lucide-react';
import { Save, Building, Coins, Plus, Pencil, Trash2, X, CalendarCheck, AlertTriangle, User as UserIcon, Server, Bell, Clock, FileText, Lock, Megaphone, CheckCircle2, Info, Hammer, Link as LinkIcon, Eye, Calendar, List, UserCog, Mail, Power, MapPin, CreditCard } from 'lucide-react';
export const SettingsPage: React.FC = () => {
const currentUser = CondoService.getCurrentUser();
@@ -40,6 +40,7 @@ export const SettingsPage: React.FC = () => {
province: '',
zipCode: '',
notes: '',
paypalClientId: '',
defaultMonthlyQuota: 100
});
@@ -235,7 +236,7 @@ export const SettingsPage: React.FC = () => {
// --- Condo Management Handlers ---
const openAddCondoModal = () => {
setEditingCondo(null);
setCondoForm({ name: '', address: '', streetNumber: '', city: '', province: '', zipCode: '', notes: '', defaultMonthlyQuota: 100 });
setCondoForm({ name: '', address: '', streetNumber: '', city: '', province: '', zipCode: '', notes: '', paypalClientId: '', defaultMonthlyQuota: 100 });
setShowCondoModal(true);
};
@@ -249,6 +250,7 @@ export const SettingsPage: React.FC = () => {
province: c.province || '',
zipCode: c.zipCode || '',
notes: c.notes || '',
paypalClientId: c.paypalClientId || '',
defaultMonthlyQuota: c.defaultMonthlyQuota
});
setShowCondoModal(true);
@@ -266,6 +268,7 @@ export const SettingsPage: React.FC = () => {
province: condoForm.province,
zipCode: condoForm.zipCode,
notes: condoForm.notes,
paypalClientId: condoForm.paypalClientId,
defaultMonthlyQuota: condoForm.defaultMonthlyQuota
};
@@ -607,6 +610,11 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* Rest of the file (Families, Users, Notices, Alerts, SMTP Tabs) remains mostly same, just update modal */}
{/* ... (Existing Tabs Code for Families, Users, Notices, Alerts, SMTP) ... */}
{/* Only change is inside CONDO MODAL */}
{/* Families Tab */}
{isAdmin && activeTab === 'families' && (
<div className="space-y-4 animate-fade-in">
@@ -789,7 +797,7 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* ALERT MODAL */}
{/* ALERT MODAL (Existing) */}
{showAlertModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6 animate-in fade-in zoom-in duration-200">
@@ -826,7 +834,7 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* NOTICE MODAL */}
{/* NOTICE MODAL (Existing) */}
{showNoticeModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 animate-in fade-in zoom-in duration-200">
@@ -868,7 +876,7 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* READ DETAILS MODAL */}
{/* READ DETAILS MODAL (Existing) */}
{showReadDetailsModal && selectedNoticeId && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6 animate-in fade-in zoom-in duration-200">
@@ -907,7 +915,7 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* USER MODAL */}
{/* USER MODAL (Existing) */}
{showUserModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6 animate-in fade-in zoom-in duration-200">
@@ -950,10 +958,10 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* CONDO MODAL */}
{/* CONDO MODAL (UPDATED) */}
{showCondoModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 animate-in fade-in zoom-in duration-200">
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 animate-in fade-in zoom-in duration-200 overflow-y-auto max-h-[90vh]">
<h3 className="font-bold text-lg mb-4 text-slate-800">{editingCondo ? 'Modifica Condominio' : 'Nuovo Condominio'}</h3>
<form onSubmit={handleCondoSubmit} className="space-y-4">
@@ -985,9 +993,27 @@ export const SettingsPage: React.FC = () => {
</div>
</div>
{/* PayPal Integration Section */}
<div className="bg-blue-50 p-3 rounded-lg border border-blue-100">
<div className="flex items-center gap-2 mb-2 text-blue-800">
<CreditCard className="w-4 h-4"/>
<span className="text-xs font-bold uppercase">Configurazione Pagamenti</span>
</div>
<div>
<label className="text-xs font-semibold text-slate-600 block mb-1">PayPal Client ID (REST API App)</label>
<input
className="w-full border p-2 rounded text-slate-700 text-sm"
placeholder="Es: Afg... (Ottienilo da developer.paypal.com)"
value={condoForm.paypalClientId}
onChange={e => setCondoForm({...condoForm, paypalClientId: e.target.value})}
/>
<p className="text-[10px] text-slate-500 mt-1">Necessario per abilitare i pagamenti online delle rate.</p>
</div>
</div>
{/* Notes */}
<div>
<textarea className="w-full border p-2.5 rounded-lg text-slate-700 h-20" placeholder="Note (opzionali)" value={condoForm.notes} onChange={e => setCondoForm({...condoForm, notes: e.target.value})} />
<textarea className="w-full border p-2.5 rounded-lg text-slate-700 h-16" placeholder="Note (opzionali)" value={condoForm.notes} onChange={e => setCondoForm({...condoForm, notes: e.target.value})} />
</div>
{/* Quota */}
@@ -1005,7 +1031,7 @@ export const SettingsPage: React.FC = () => {
</div>
)}
{/* FAMILY MODAL */}
{/* FAMILY MODAL (Existing) */}
{showFamilyModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-2xl shadow-xl w-full max-w-lg p-6">

392
pages/Tickets.tsx Normal file
View File

@@ -0,0 +1,392 @@
import React, { useEffect, useState } from 'react';
import { CondoService } from '../services/mockDb';
import { Ticket, TicketStatus, TicketPriority, TicketCategory, TicketAttachment } from '../types';
import { MessageSquareWarning, Plus, Search, Filter, Paperclip, X, CheckCircle2, Clock, XCircle, FileIcon, Image as ImageIcon, Film } from 'lucide-react';
export const TicketsPage: React.FC = () => {
const user = CondoService.getCurrentUser();
const isAdmin = user?.role === 'admin' || user?.role === 'poweruser';
const [tickets, setTickets] = useState<Ticket[]>([]);
const [loading, setLoading] = useState(true);
const [filterStatus, setFilterStatus] = useState<string>('ALL');
const [showModal, setShowModal] = useState(false);
const [viewTicket, setViewTicket] = useState<Ticket | null>(null);
const [submitting, setSubmitting] = useState(false);
// Form State
const [formTitle, setFormTitle] = useState('');
const [formDesc, setFormDesc] = useState('');
const [formCategory, setFormCategory] = useState<TicketCategory>(TicketCategory.OTHER);
const [formPriority, setFormPriority] = useState<TicketPriority>(TicketPriority.MEDIUM);
const [attachments, setAttachments] = useState<{fileName: string, fileType: string, data: string}[]>([]);
// File Reading helper
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
const newAttachments = [];
for (let i = 0; i < e.target.files.length; i++) {
const file = e.target.files[i];
// Check size (e.g. 5MB limit per file for demo safety)
if (file.size > 5 * 1024 * 1024) {
alert(`Il file ${file.name} è troppo grande (max 5MB)`);
continue;
}
const base64 = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result as string);
reader.onerror = error => reject(error);
});
newAttachments.push({
fileName: file.name,
fileType: file.type,
data: base64
});
}
setAttachments([...attachments, ...newAttachments]);
}
};
const removeAttachment = (index: number) => {
const newAtt = [...attachments];
newAtt.splice(index, 1);
setAttachments(newAtt);
};
const loadTickets = async () => {
setLoading(true);
try {
const list = await CondoService.getTickets();
setTickets(list);
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
useEffect(() => {
loadTickets();
}, []);
const handleCreateSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setSubmitting(true);
try {
await CondoService.createTicket({
title: formTitle,
description: formDesc,
category: formCategory,
priority: formPriority,
attachments: attachments
});
setShowModal(false);
// Reset form
setFormTitle('');
setFormDesc('');
setAttachments([]);
loadTickets();
} catch (e) {
alert("Errore creazione ticket");
console.error(e);
} finally {
setSubmitting(false);
}
};
const handleStatusUpdate = async (status: TicketStatus) => {
if (!viewTicket) return;
try {
await CondoService.updateTicket(viewTicket.id, {
status: status,
priority: viewTicket.priority
});
// Update local state
const updated = { ...viewTicket, status };
setViewTicket(updated);
setTickets(tickets.map(t => t.id === updated.id ? updated : t));
} catch (e) { console.error(e); }
};
const handleDeleteTicket = async (id: string) => {
if (!confirm("Eliminare definitivamente questa segnalazione?")) return;
try {
await CondoService.deleteTicket(id);
setTickets(tickets.filter(t => t.id !== id));
setViewTicket(null);
} catch (e) { alert("Impossibile eliminare."); }
};
const filteredTickets = tickets.filter(t => filterStatus === 'ALL' || t.status === filterStatus);
// Helpers for Badge Colors
const getStatusColor = (s: TicketStatus) => {
switch(s) {
case TicketStatus.OPEN: return 'bg-blue-100 text-blue-700';
case TicketStatus.IN_PROGRESS: return 'bg-yellow-100 text-yellow-700';
case TicketStatus.RESOLVED: return 'bg-green-100 text-green-700';
case TicketStatus.CLOSED: return 'bg-slate-200 text-slate-600';
}
};
const getPriorityColor = (p: TicketPriority) => {
switch(p) {
case TicketPriority.LOW: return 'bg-slate-100 text-slate-600';
case TicketPriority.MEDIUM: return 'bg-blue-50 text-blue-600';
case TicketPriority.HIGH: return 'bg-orange-100 text-orange-600';
case TicketPriority.URGENT: return 'bg-red-100 text-red-600';
}
};
const getCategoryLabel = (c: TicketCategory) => {
switch(c) {
case TicketCategory.MAINTENANCE: return 'Manutenzione';
case TicketCategory.ADMINISTRATIVE: return 'Amministrazione';
case TicketCategory.CLEANING: return 'Pulizie';
case TicketCategory.NOISE: return 'Disturbo';
default: return 'Altro';
}
};
const openAttachment = async (ticketId: string, attId: string) => {
try {
const file = await CondoService.getTicketAttachment(ticketId, attId);
// Open base64 in new tab
const win = window.open();
if (win) {
// Determine display method
if (file.fileType.startsWith('image/')) {
win.document.write(`<img src="${file.data}" style="max-width:100%"/>`);
} else if (file.fileType === 'application/pdf') {
win.document.write(`<iframe src="${file.data}" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>`);
} else {
// Download link fallback
win.document.write(`<a href="${file.data}" download="${file.fileName}">Clicca qui per scaricare ${file.fileName}</a>`);
}
}
} catch (e) { alert("Errore apertura file"); }
};
return (
<div className="space-y-6 pb-20">
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
<div>
<h2 className="text-2xl font-bold text-slate-800">Segnalazioni</h2>
<p className="text-slate-500">Gestisci guasti e richieste</p>
</div>
<button
onClick={() => setShowModal(true)}
className="bg-blue-600 text-white px-4 py-2 rounded-lg font-medium flex items-center gap-2 hover:bg-blue-700 transition-colors"
>
<Plus className="w-5 h-5"/> Nuova Segnalazione
</button>
</div>
{/* Filters */}
<div className="flex gap-2 overflow-x-auto pb-2 no-scrollbar">
{['ALL', 'OPEN', 'IN_PROGRESS', 'RESOLVED', 'CLOSED'].map(status => (
<button
key={status}
onClick={() => setFilterStatus(status)}
className={`px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap ${filterStatus === status ? 'bg-slate-800 text-white' : 'bg-white border border-slate-200 text-slate-600 hover:bg-slate-50'}`}
>
{status === 'ALL' ? 'Tutti' : status === 'OPEN' ? 'Aperti' : status === 'IN_PROGRESS' ? 'In Corso' : status === 'RESOLVED' ? 'Risolti' : 'Chiusi'}
</button>
))}
</div>
{/* List */}
{loading ? (
<div className="text-center p-12 text-slate-400">Caricamento...</div>
) : filteredTickets.length === 0 ? (
<div className="text-center p-12 bg-white rounded-xl border border-dashed border-slate-300">
<MessageSquareWarning className="w-12 h-12 text-slate-300 mx-auto mb-3"/>
<p className="text-slate-500">Nessuna segnalazione trovata.</p>
</div>
) : (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{filteredTickets.map(ticket => (
<div key={ticket.id} onClick={() => setViewTicket(ticket)} className="bg-white p-5 rounded-xl border border-slate-200 shadow-sm hover:shadow-md transition-shadow cursor-pointer relative group">
<div className="flex justify-between items-start mb-3">
<span className={`text-[10px] font-bold px-2 py-1 rounded uppercase ${getStatusColor(ticket.status)}`}>
{ticket.status.replace('_', ' ')}
</span>
<span className={`text-[10px] font-bold px-2 py-1 rounded uppercase ${getPriorityColor(ticket.priority)}`}>
{ticket.priority}
</span>
</div>
<h3 className="font-bold text-slate-800 mb-1 line-clamp-1">{ticket.title}</h3>
<p className="text-xs text-slate-400 mb-3">{new Date(ticket.createdAt).toLocaleDateString()} {getCategoryLabel(ticket.category)}</p>
<p className="text-sm text-slate-600 line-clamp-3 mb-4">{ticket.description}</p>
<div className="flex items-center justify-between border-t border-slate-100 pt-3">
<div className="flex items-center gap-2 text-xs text-slate-500">
<div className="w-6 h-6 rounded-full bg-slate-200 flex items-center justify-center font-bold text-slate-600">
{ticket.userName ? ticket.userName.charAt(0) : '?'}
</div>
<span className="truncate max-w-[100px]">{ticket.userName || 'Utente'}</span>
</div>
{ticket.attachments && ticket.attachments.length > 0 && (
<div className="flex items-center gap-1 text-xs text-blue-600 font-medium">
<Paperclip className="w-3 h-3"/> {ticket.attachments.length}
</div>
)}
</div>
</div>
))}
</div>
)}
{/* CREATE MODAL */}
{showModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 animate-in fade-in zoom-in duration-200 max-h-[90vh] overflow-y-auto">
<div className="flex justify-between items-center mb-6">
<h3 className="font-bold text-lg text-slate-800">Nuova Segnalazione</h3>
<button onClick={() => setShowModal(false)}><X className="w-6 h-6 text-slate-400"/></button>
</div>
<form onSubmit={handleCreateSubmit} className="space-y-4">
<div>
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Oggetto</label>
<input className="w-full border p-2.5 rounded-lg text-slate-700" value={formTitle} onChange={e => setFormTitle(e.target.value)} required placeholder="Es. Luce scale rotta" />
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Categoria</label>
<select className="w-full border p-2.5 rounded-lg text-slate-700 bg-white" value={formCategory} onChange={e => setFormCategory(e.target.value as any)}>
<option value={TicketCategory.MAINTENANCE}>Manutenzione</option>
<option value={TicketCategory.ADMINISTRATIVE}>Amministrazione</option>
<option value={TicketCategory.CLEANING}>Pulizie</option>
<option value={TicketCategory.NOISE}>Rumori</option>
<option value={TicketCategory.OTHER}>Altro</option>
</select>
</div>
<div>
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Priorità</label>
<select className="w-full border p-2.5 rounded-lg text-slate-700 bg-white" value={formPriority} onChange={e => setFormPriority(e.target.value as any)}>
<option value={TicketPriority.LOW}>Bassa</option>
<option value={TicketPriority.MEDIUM}>Media</option>
<option value={TicketPriority.HIGH}>Alta</option>
<option value={TicketPriority.URGENT}>Urgente</option>
</select>
</div>
</div>
<div>
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Descrizione</label>
<textarea className="w-full border p-2.5 rounded-lg text-slate-700 h-24" value={formDesc} onChange={e => setFormDesc(e.target.value)} required placeholder="Dettagli del problema..." />
</div>
<div>
<label className="block text-xs font-bold text-slate-500 uppercase mb-1">Allegati (Foto, Video, PDF)</label>
<div className="border-2 border-dashed border-slate-300 rounded-lg p-4 text-center hover:bg-slate-50 transition-colors relative">
<input type="file" multiple onChange={handleFileChange} className="absolute inset-0 opacity-0 cursor-pointer" accept="image/*,video/*,application/pdf" />
<div className="flex flex-col items-center gap-1">
<Paperclip className="w-6 h-6 text-slate-400"/>
<span className="text-sm text-slate-500">Clicca o trascina file qui</span>
<span className="text-[10px] text-slate-400">Max 5MB per file</span>
</div>
</div>
{attachments.length > 0 && (
<div className="mt-3 space-y-2">
{attachments.map((att, idx) => (
<div key={idx} className="flex items-center justify-between bg-slate-50 p-2 rounded border border-slate-200">
<div className="flex items-center gap-2 truncate">
{att.fileType.includes('image') ? <ImageIcon className="w-4 h-4 text-blue-500"/> : att.fileType.includes('video') ? <Film className="w-4 h-4 text-purple-500"/> : <FileIcon className="w-4 h-4 text-slate-500"/>}
<span className="text-xs truncate max-w-[200px]">{att.fileName}</span>
</div>
<button type="button" onClick={() => removeAttachment(idx)} className="text-red-500 hover:bg-red-50 p-1 rounded"><X className="w-4 h-4"/></button>
</div>
))}
</div>
)}
</div>
<div className="pt-2">
<button type="submit" disabled={submitting} className="w-full bg-blue-600 text-white py-3 rounded-lg font-bold hover:bg-blue-700 transition-colors flex justify-center items-center gap-2">
{submitting ? 'Invio in corso...' : 'Invia Segnalazione'}
</button>
</div>
</form>
</div>
</div>
)}
{/* VIEW DETAILS MODAL */}
{viewTicket && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
<div className="bg-white rounded-xl shadow-xl w-full max-w-2xl p-6 animate-in fade-in zoom-in duration-200 max-h-[90vh] overflow-y-auto">
<div className="flex justify-between items-start mb-4">
<div>
<h3 className="font-bold text-xl text-slate-800">{viewTicket.title}</h3>
<p className="text-sm text-slate-500">{new Date(viewTicket.createdAt).toLocaleString()} {getCategoryLabel(viewTicket.category)}</p>
</div>
<button onClick={() => setViewTicket(null)}><X className="w-6 h-6 text-slate-400 hover:text-slate-600"/></button>
</div>
<div className="flex gap-2 mb-6">
<div className={`px-3 py-1 rounded-lg text-sm font-bold uppercase ${getStatusColor(viewTicket.status)}`}>
{viewTicket.status.replace('_', ' ')}
</div>
<div className={`px-3 py-1 rounded-lg text-sm font-bold uppercase ${getPriorityColor(viewTicket.priority)}`}>
{viewTicket.priority}
</div>
</div>
<div className="bg-slate-50 p-4 rounded-xl border border-slate-200 mb-6 text-slate-700 whitespace-pre-wrap leading-relaxed">
{viewTicket.description}
</div>
{/* Attachments */}
{viewTicket.attachments && viewTicket.attachments.length > 0 && (
<div className="mb-6">
<h4 className="font-bold text-sm text-slate-800 mb-2 flex items-center gap-2"><Paperclip className="w-4 h-4"/> Allegati</h4>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
{viewTicket.attachments.map(att => (
<button
key={att.id}
onClick={() => openAttachment(viewTicket.id, att.id)}
className="flex flex-col items-center justify-center p-3 bg-white border border-slate-200 rounded-lg hover:border-blue-400 hover:shadow-sm transition-all text-center"
>
{att.fileType.includes('image') ? <ImageIcon className="w-6 h-6 text-blue-500 mb-1"/> : att.fileType.includes('video') ? <Film className="w-6 h-6 text-purple-500 mb-1"/> : <FileIcon className="w-6 h-6 text-slate-500 mb-1"/>}
<span className="text-[10px] text-slate-600 truncate w-full">{att.fileName}</span>
</button>
))}
</div>
</div>
)}
{/* Admin Actions */}
{isAdmin && (
<div className="border-t border-slate-100 pt-4">
<h4 className="font-bold text-sm text-slate-500 uppercase mb-3">Gestione Admin</h4>
<div className="flex flex-wrap gap-2">
{viewTicket.status !== TicketStatus.IN_PROGRESS && (
<button onClick={() => handleStatusUpdate(TicketStatus.IN_PROGRESS)} className="px-4 py-2 bg-yellow-100 text-yellow-700 rounded-lg font-bold text-sm hover:bg-yellow-200">Prendi in Carico</button>
)}
{viewTicket.status !== TicketStatus.RESOLVED && (
<button onClick={() => handleStatusUpdate(TicketStatus.RESOLVED)} className="px-4 py-2 bg-green-100 text-green-700 rounded-lg font-bold text-sm hover:bg-green-200">Segna Risolto</button>
)}
{viewTicket.status !== TicketStatus.CLOSED && (
<button onClick={() => handleStatusUpdate(TicketStatus.CLOSED)} className="px-4 py-2 bg-slate-200 text-slate-700 rounded-lg font-bold text-sm hover:bg-slate-300">Chiudi</button>
)}
<button onClick={() => handleDeleteTicket(viewTicket.id)} className="ml-auto px-4 py-2 text-red-600 font-medium text-sm hover:bg-red-50 rounded-lg">Elimina</button>
</div>
</div>
)}
{!isAdmin && viewTicket.status === TicketStatus.OPEN && (
<div className="border-t border-slate-100 pt-4 flex justify-end">
<button onClick={() => handleDeleteTicket(viewTicket.id)} className="px-4 py-2 text-red-600 font-medium text-sm hover:bg-red-50 rounded-lg">Elimina Segnalazione</button>
</div>
)}
</div>
</div>
)}
</div>
);
};

View File

@@ -1,7 +1 @@
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY . .
EXPOSE 3001
CMD ["node", "server.js"]
<13><><EFBFBD>^

View File

@@ -60,6 +60,7 @@ const initDb = async () => {
console.log(`Database connected successfully using ${DB_CLIENT}.`);
const TIMESTAMP_TYPE = 'TIMESTAMP';
const LONG_TEXT_TYPE = DB_CLIENT === 'postgres' ? 'TEXT' : 'LONGTEXT'; // For base64 files
// 0. Settings Table (Global App Settings)
await connection.query(`
@@ -82,21 +83,26 @@ const initDb = async () => {
zip_code VARCHAR(20),
notes TEXT,
iban VARCHAR(50),
paypal_client_id VARCHAR(255),
default_monthly_quota DECIMAL(10, 2) DEFAULT 100.00,
image VARCHAR(255),
created_at ${TIMESTAMP_TYPE} DEFAULT CURRENT_TIMESTAMP
)
`);
// Migration for condos: Add new address fields
// Migration for condos: Add new address fields and paypal_client_id
try {
let hasCity = false;
let hasPayPal = false;
if (DB_CLIENT === 'postgres') {
const [cols] = await connection.query("SELECT column_name FROM information_schema.columns WHERE table_name='condos'");
hasCity = cols.some(c => c.column_name === 'city');
hasPayPal = cols.some(c => c.column_name === 'paypal_client_id');
} else {
const [cols] = await connection.query("SHOW COLUMNS FROM condos");
hasCity = cols.some(c => c.Field === 'city');
hasPayPal = cols.some(c => c.Field === 'paypal_client_id');
}
if (!hasCity) {
@@ -107,6 +113,12 @@ const initDb = async () => {
await connection.query("ALTER TABLE condos ADD COLUMN zip_code VARCHAR(20)");
await connection.query("ALTER TABLE condos ADD COLUMN notes TEXT");
}
if (!hasPayPal) {
console.log('Migrating: Adding PayPal fields to condos...');
await connection.query("ALTER TABLE condos ADD COLUMN paypal_client_id VARCHAR(255)");
}
} catch(e) { console.warn("Condos migration warning:", e.message); }
@@ -255,6 +267,37 @@ const initDb = async () => {
)
`);
// 8. Tickets Table (Segnalazioni)
await connection.query(`
CREATE TABLE IF NOT EXISTS tickets (
id VARCHAR(36) PRIMARY KEY,
condo_id VARCHAR(36) NOT NULL,
user_id VARCHAR(36) NOT NULL,
title VARCHAR(255) NOT NULL,
description TEXT,
status VARCHAR(20) DEFAULT 'OPEN',
priority VARCHAR(20) DEFAULT 'MEDIUM',
category VARCHAR(20) DEFAULT 'OTHER',
created_at ${TIMESTAMP_TYPE} DEFAULT CURRENT_TIMESTAMP,
updated_at ${TIMESTAMP_TYPE} DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (condo_id) REFERENCES condos(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
`);
// 9. Ticket Attachments Table
await connection.query(`
CREATE TABLE IF NOT EXISTS ticket_attachments (
id VARCHAR(36) PRIMARY KEY,
ticket_id VARCHAR(36) NOT NULL,
file_name VARCHAR(255) NOT NULL,
file_type VARCHAR(100),
data ${LONG_TEXT_TYPE}, -- Base64 encoded file
created_at ${TIMESTAMP_TYPE} DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (ticket_id) REFERENCES tickets(id) ON DELETE CASCADE
)
`);
// --- SEEDING ---
const [rows] = await connection.query('SELECT * FROM settings WHERE id = 1');
if (rows.length === 0) {

View File

@@ -13,30 +13,41 @@ const PORT = process.env.PORT || 3001;
const JWT_SECRET = process.env.JWT_SECRET || 'dev_secret_key_123';
app.use(cors());
app.use(bodyParser.json());
// Increased limit to support base64 file uploads for tickets
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
// --- EMAIL & SCHEDULER (Same as before) ---
async function sendEmailToUsers(subject, body) {
try {
// --- EMAIL HELPERS ---
async function getTransporter() {
const [settings] = await pool.query('SELECT smtp_config FROM settings WHERE id = 1');
if (!settings.length || !settings[0].smtp_config) return;
if (!settings.length || !settings[0].smtp_config) return null;
const config = settings[0].smtp_config;
if (!config.host || !config.user || !config.pass) return;
if (!config.host || !config.user || !config.pass) return null;
const transporter = nodemailer.createTransport({
host: config.host,
port: config.port,
secure: config.secure,
auth: { user: config.user, pass: config.pass },
});
return {
transporter: nodemailer.createTransport({
host: config.host,
port: config.port,
secure: config.secure,
auth: { user: config.user, pass: config.pass },
}),
from: config.fromEmail || config.user
};
}
async function sendEmailToUsers(subject, body) {
try {
const setup = await getTransporter();
if (!setup) return;
const [users] = await pool.query('SELECT email FROM users WHERE receive_alerts = TRUE AND email IS NOT NULL AND email != ""');
if (users.length === 0) return;
const bccList = users.map(u => u.email).join(',');
await transporter.sendMail({
from: config.fromEmail || config.user,
await setup.transporter.sendMail({
from: setup.from,
bcc: bccList,
subject: subject,
text: body,
@@ -44,6 +55,21 @@ async function sendEmailToUsers(subject, body) {
} catch (error) { console.error('Email error:', error.message); }
}
async function sendDirectEmail(to, subject, body) {
try {
const setup = await getTransporter();
if (!setup) return;
await setup.transporter.sendMail({
from: setup.from,
to: to,
subject: subject,
text: body
});
console.log(`Direct email sent to ${to}`);
} catch (error) { console.error('Direct Email error:', error.message); }
}
// --- MIDDLEWARE ---
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
@@ -153,28 +179,29 @@ app.get('/api/condos', authenticateToken, async (req, res) => {
zipCode: r.zip_code,
notes: r.notes,
iban: r.iban,
paypalClientId: r.paypal_client_id, // PayPal
defaultMonthlyQuota: parseFloat(r.default_monthly_quota),
image: r.image
})));
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.post('/api/condos', authenticateToken, requireAdmin, async (req, res) => {
const { name, address, streetNumber, city, province, zipCode, notes, defaultMonthlyQuota } = req.body;
const { name, address, streetNumber, city, province, zipCode, notes, defaultMonthlyQuota, paypalClientId } = req.body;
const id = uuidv4();
try {
await pool.query(
'INSERT INTO condos (id, name, address, street_number, city, province, zip_code, notes, default_monthly_quota) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
[id, name, address, streetNumber, city, province, zipCode, notes, defaultMonthlyQuota]
'INSERT INTO condos (id, name, address, street_number, city, province, zip_code, notes, default_monthly_quota, paypal_client_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[id, name, address, streetNumber, city, province, zipCode, notes, defaultMonthlyQuota, paypalClientId]
);
res.json({ id, name, address, streetNumber, city, province, zipCode, notes, defaultMonthlyQuota });
res.json({ id, name, address, streetNumber, city, province, zipCode, notes, defaultMonthlyQuota, paypalClientId });
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.put('/api/condos/:id', authenticateToken, requireAdmin, async (req, res) => {
const { name, address, streetNumber, city, province, zipCode, notes, defaultMonthlyQuota } = req.body;
const { name, address, streetNumber, city, province, zipCode, notes, defaultMonthlyQuota, paypalClientId } = req.body;
try {
await pool.query(
'UPDATE condos SET name = ?, address = ?, street_number = ?, city = ?, province = ?, zip_code = ?, notes = ?, default_monthly_quota = ? WHERE id = ?',
[name, address, streetNumber, city, province, zipCode, notes, defaultMonthlyQuota, req.params.id]
'UPDATE condos SET name = ?, address = ?, street_number = ?, city = ?, province = ?, zip_code = ?, notes = ?, default_monthly_quota = ?, paypal_client_id = ? WHERE id = ?',
[name, address, streetNumber, city, province, zipCode, notes, defaultMonthlyQuota, paypalClientId, req.params.id]
);
res.json({ success: true });
} catch (e) { res.status(500).json({ error: e.message }); }
@@ -335,9 +362,20 @@ app.get('/api/payments', authenticateToken, async (req, res) => {
} catch (e) { res.status(500).json({ error: e.message }); }
});
function mapPaymentRow(r) { return { id: r.id, familyId: r.family_id, amount: parseFloat(r.amount), datePaid: r.date_paid, forMonth: r.for_month, forYear: r.for_year, notes: r.notes }; }
app.post('/api/payments', authenticateToken, async (req, res) => {
const { familyId, amount, datePaid, forMonth, forYear, notes } = req.body;
if (req.user.role !== 'admin') return res.status(403).json({message: "Only admins can record payments"});
// Security Check:
// Admin can post for anyone.
// Regular users can only post for their own family (e.g. PayPal automated callback)
const isPrivileged = req.user.role === 'admin' || req.user.role === 'poweruser';
if (!isPrivileged) {
if (familyId !== req.user.familyId) {
return res.status(403).json({message: "Forbidden: You can only record payments for your own family."});
}
}
const id = uuidv4();
try {
await pool.query('INSERT INTO payments (id, family_id, amount, date_paid, for_month, for_year, notes) VALUES (?, ?, ?, ?, ?, ?, ?)', [id, familyId, amount, new Date(datePaid), forMonth, forYear, notes]);
@@ -431,6 +469,197 @@ app.delete('/api/alerts/:id', authenticateToken, requireAdmin, async (req, res)
} catch (e) { res.status(500).json({ error: e.message }); }
});
// --- TICKETS (SEGNALAZIONI) ---
app.get('/api/tickets', authenticateToken, async (req, res) => {
const { condoId } = req.query;
const userId = req.user.id;
const isAdmin = req.user.role === 'admin' || req.user.role === 'poweruser';
try {
let query = `
SELECT t.*, u.name as user_name, u.email as user_email
FROM tickets t
JOIN users u ON t.user_id = u.id
WHERE t.condo_id = ?
`;
let params = [condoId];
// If not admin, restrict to own tickets
if (!isAdmin) {
query += ' AND t.user_id = ?';
params.push(userId);
}
query += ' ORDER BY t.created_at DESC';
const [rows] = await pool.query(query, params);
// Fetch attachments for these tickets
const ticketIds = rows.map(r => r.id);
let attachmentsMap = {};
if (ticketIds.length > 0) {
const placeholders = ticketIds.map(() => '?').join(',');
// Exclude 'data' column to keep listing light
const [attRows] = await pool.query(`SELECT id, ticket_id, file_name, file_type FROM ticket_attachments WHERE ticket_id IN (${placeholders})`, ticketIds);
attRows.forEach(a => {
if (!attachmentsMap[a.ticket_id]) attachmentsMap[a.ticket_id] = [];
attachmentsMap[a.ticket_id].push({ id: a.id, fileName: a.file_name, fileType: a.file_type });
});
}
const result = rows.map(r => ({
id: r.id,
condoId: r.condo_id,
userId: r.user_id,
title: r.title,
description: r.description,
status: r.status,
priority: r.priority,
category: r.category,
createdAt: r.created_at,
updatedAt: r.updated_at,
userName: r.user_name,
userEmail: r.user_email,
attachments: attachmentsMap[r.id] || []
}));
res.json(result);
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.get('/api/tickets/:id/attachments/:attachmentId', authenticateToken, async (req, res) => {
// Serve file content
try {
const [rows] = await pool.query('SELECT * FROM ticket_attachments WHERE id = ? AND ticket_id = ?', [req.params.attachmentId, req.params.id]);
if (rows.length === 0) return res.status(404).json({ message: 'File not found' });
const file = rows[0];
res.json({
id: file.id,
fileName: file.file_name,
fileType: file.file_type,
data: file.data
});
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.post('/api/tickets', authenticateToken, async (req, res) => {
const { condoId, title, description, category, priority, attachments } = req.body;
const userId = req.user.id;
const ticketId = uuidv4();
// Begin transaction
const connection = await pool.getConnection();
try {
await connection.beginTransaction();
await connection.query(
'INSERT INTO tickets (id, condo_id, user_id, title, description, category, priority, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
[ticketId, condoId, userId, title, description, category, priority || 'MEDIUM', 'OPEN']
);
if (attachments && Array.isArray(attachments)) {
for (const att of attachments) {
const attId = uuidv4();
await connection.query(
'INSERT INTO ticket_attachments (id, ticket_id, file_name, file_type, data) VALUES (?, ?, ?, ?, ?)',
[attId, ticketId, att.fileName, att.fileType, att.data]
);
}
}
await connection.commit();
// --- EMAIL NOTIFICATION TO ADMINS ---
// Find Admins/PowerUsers for this condo (or global) who want alerts
const [admins] = await connection.query(`
SELECT u.email FROM users u
LEFT JOIN families f ON u.family_id = f.id
WHERE (u.role = 'admin' OR u.role = 'poweruser')
AND (f.condo_id = ? OR u.family_id IS NULL)
AND u.receive_alerts = TRUE
`, [condoId]);
const adminEmails = admins.map(a => a.email).filter(e => e);
if (adminEmails.length > 0) {
// Fetch user name for clearer email
const [uRows] = await connection.query('SELECT name FROM users WHERE id = ?', [userId]);
const userName = uRows[0]?.name || 'Un condomino';
const subject = `Nuova Segnalazione: ${title}`;
const body = `Salve,\n\n${userName} ha aperto una nuova segnalazione.\n\nOggetto: ${title}\nCategoria: ${category}\nPriorità: ${priority || 'MEDIUM'}\n\nDescrizione:\n${description}\n\nAccedi alla piattaforma per gestire il ticket.`;
// Loop to send individually or use BCC
for(const email of adminEmails) {
sendDirectEmail(email, subject, body);
}
}
res.json({ success: true, id: ticketId });
} catch (e) {
await connection.rollback();
res.status(500).json({ error: e.message });
} finally {
connection.release();
}
});
app.put('/api/tickets/:id', authenticateToken, async (req, res) => {
const { status, priority } = req.body;
const isAdmin = req.user.role === 'admin' || req.user.role === 'poweruser';
// Only admins/powerusers can change status/priority for now
if (!isAdmin) return res.status(403).json({ message: 'Forbidden' });
try {
await pool.query(
'UPDATE tickets SET status = ?, priority = ? WHERE id = ?',
[status, priority, req.params.id]
);
// --- EMAIL NOTIFICATION TO USER ---
const [tRows] = await pool.query('SELECT t.title, t.user_id, u.email, u.receive_alerts FROM tickets t JOIN users u ON t.user_id = u.id WHERE t.id = ?', [req.params.id]);
if (tRows.length > 0) {
const ticket = tRows[0];
if (ticket.email && ticket.receive_alerts) {
const subject = `Aggiornamento Ticket: ${ticket.title}`;
const body = `Salve,\n\nIl tuo ticket "${ticket.title}" è stato aggiornato.\n\nNuovo Stato: ${status}\nPriorità: ${priority}\n\nAccedi alla piattaforma per i dettagli.`;
sendDirectEmail(ticket.email, subject, body);
}
}
res.json({ success: true });
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.delete('/api/tickets/:id', authenticateToken, async (req, res) => {
// Only delete own ticket if open, or admin can delete any
const isAdmin = req.user.role === 'admin' || req.user.role === 'poweruser';
const userId = req.user.id;
try {
let query = 'DELETE FROM tickets WHERE id = ?';
let params = [req.params.id];
if (!isAdmin) {
query += ' AND user_id = ? AND status = "OPEN"'; // Users can only delete their own OPEN tickets
params.push(userId);
}
const [result] = await pool.query(query, params);
if (result.affectedRows === 0) {
return res.status(403).json({ message: 'Cannot delete ticket (Permission denied or not found)' });
}
res.json({ success: true });
} catch (e) { res.status(500).json({ error: e.message }); }
});
initDb().then(() => {
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);

View File

@@ -1,5 +1,5 @@
import { Family, Payment, AppSettings, User, AlertDefinition, Condo, Notice, NoticeRead } from '../types';
import { Family, Payment, AppSettings, User, AlertDefinition, Condo, Notice, NoticeRead, Ticket, TicketAttachment } from '../types';
// --- CONFIGURATION TOGGLE ---
const FORCE_LOCAL_DB = false;
@@ -288,6 +288,39 @@ export const CondoService = {
await request(`/alerts/${id}`, { method: 'DELETE' });
},
// --- TICKETS ---
getTickets: async (condoId?: string): Promise<Ticket[]> => {
let url = '/tickets';
const activeId = condoId || CondoService.getActiveCondoId();
if (activeId) url += `?condoId=${activeId}`;
return request<Ticket[]>(url);
},
createTicket: async (data: Partial<Ticket> & { attachments?: { fileName: string, fileType: string, data: string }[] }) => {
const activeId = CondoService.getActiveCondoId();
if(!activeId) throw new Error("No active condo");
return request('/tickets', {
method: 'POST',
body: JSON.stringify({ ...data, condoId: activeId })
});
},
updateTicket: async (id: string, data: { status: string, priority: string }) => {
return request(`/tickets/${id}`, {
method: 'PUT',
body: JSON.stringify(data)
});
},
deleteTicket: async (id: string) => {
await request(`/tickets/${id}`, { method: 'DELETE' });
},
getTicketAttachment: async (ticketId: string, attachmentId: string): Promise<TicketAttachment> => {
return request<TicketAttachment>(`/tickets/${ticketId}/attachments/${attachmentId}`);
},
// --- SEEDING ---
seedPayments: () => {
// No-op in remote mode

View File

@@ -9,6 +9,7 @@ export interface Condo {
zipCode?: string; // CAP
notes?: string; // Note
iban?: string;
paypalClientId?: string; // PayPal Client ID for receiving payments
defaultMonthlyQuota: number;
image?: string; // Optional placeholder for logo
}
@@ -108,3 +109,51 @@ export interface AuthResponse {
token: string;
user: User;
}
// --- TICKETS ---
export enum TicketStatus {
OPEN = 'OPEN',
IN_PROGRESS = 'IN_PROGRESS',
RESOLVED = 'RESOLVED',
CLOSED = 'CLOSED'
}
export enum TicketPriority {
LOW = 'LOW',
MEDIUM = 'MEDIUM',
HIGH = 'HIGH',
URGENT = 'URGENT'
}
export enum TicketCategory {
MAINTENANCE = 'MAINTENANCE', // Manutenzione
ADMINISTRATIVE = 'ADMINISTRATIVE', // Amministrativa
NOISE = 'NOISE', // Disturbo/Rumori
CLEANING = 'CLEANING', // Pulizie
OTHER = 'OTHER' // Altro
}
export interface TicketAttachment {
id: string;
ticketId: string;
fileName: string;
fileType: string; // MIME type
data: string; // Base64 Data URI
}
export interface Ticket {
id: string;
condoId: string;
userId: string;
title: string;
description: string;
status: TicketStatus;
priority: TicketPriority;
category: TicketCategory;
createdAt: string;
updatedAt: string;
attachments?: TicketAttachment[];
userName?: string; // Joined field
userEmail?: string; // Joined field
}