feat: Add targeted notices to Condopay
Implements the ability to send notices to specific families within a condominium, rather than broadcasting to all. This includes: - Updating the `Notice` type with `targetFamilyIds`. - Adding a `target_families` JSON column to the `notices` table in the database, with a migration for existing installations. - Modifying the API to handle the new `targetFamilyIds` field during notice creation and retrieval. - Updating the UI to allow users to select specific families for notices.
This commit is contained in:
BIN
.dockerignore
BIN
.dockerignore
Binary file not shown.
@@ -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, CreditCard, ToggleLeft, ToggleRight, LayoutGrid, PieChart } 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, ToggleLeft, ToggleRight, LayoutGrid, PieChart, Users } from 'lucide-react';
|
||||
|
||||
export const SettingsPage: React.FC = () => {
|
||||
const currentUser = CondoService.getCurrentUser();
|
||||
@@ -96,6 +96,7 @@ export const SettingsPage: React.FC = () => {
|
||||
const [notices, setNotices] = useState<Notice[]>([]);
|
||||
const [showNoticeModal, setShowNoticeModal] = useState(false);
|
||||
const [editingNotice, setEditingNotice] = useState<Notice | null>(null);
|
||||
const [noticeTargetMode, setNoticeTargetMode] = useState<'all' | 'specific'>('all');
|
||||
const [noticeForm, setNoticeForm] = useState<{
|
||||
title: string;
|
||||
content: string;
|
||||
@@ -103,13 +104,15 @@ export const SettingsPage: React.FC = () => {
|
||||
link: string;
|
||||
condoId: string;
|
||||
active: boolean;
|
||||
targetFamilyIds: string[];
|
||||
}>({
|
||||
title: '',
|
||||
content: '',
|
||||
type: 'info',
|
||||
link: '',
|
||||
condoId: '',
|
||||
active: true
|
||||
active: true,
|
||||
targetFamilyIds: []
|
||||
});
|
||||
const [noticeReadStats, setNoticeReadStats] = useState<Record<string, NoticeRead[]>>({});
|
||||
|
||||
@@ -421,12 +424,23 @@ export const SettingsPage: React.FC = () => {
|
||||
// --- Notice Handlers ---
|
||||
const openAddNoticeModal = () => {
|
||||
setEditingNotice(null);
|
||||
setNoticeForm({ title: '', content: '', type: 'info', link: '', condoId: activeCondo?.id || '', active: true });
|
||||
setNoticeTargetMode('all');
|
||||
setNoticeForm({ title: '', content: '', type: 'info', link: '', condoId: activeCondo?.id || '', active: true, targetFamilyIds: [] });
|
||||
setShowNoticeModal(true);
|
||||
};
|
||||
const openEditNoticeModal = (n: Notice) => {
|
||||
setEditingNotice(n);
|
||||
setNoticeForm({ title: n.title, content: n.content, type: n.type, link: n.link || '', condoId: n.condoId, active: n.active });
|
||||
const isTargeted = n.targetFamilyIds && n.targetFamilyIds.length > 0;
|
||||
setNoticeTargetMode(isTargeted ? 'specific' : 'all');
|
||||
setNoticeForm({
|
||||
title: n.title,
|
||||
content: n.content,
|
||||
type: n.type,
|
||||
link: n.link || '',
|
||||
condoId: n.condoId,
|
||||
active: n.active,
|
||||
targetFamilyIds: n.targetFamilyIds || []
|
||||
});
|
||||
setShowNoticeModal(true);
|
||||
};
|
||||
const handleNoticeSubmit = async (e: React.FormEvent) => {
|
||||
@@ -435,6 +449,7 @@ export const SettingsPage: React.FC = () => {
|
||||
const payload: Notice = {
|
||||
id: editingNotice ? editingNotice.id : '',
|
||||
...noticeForm,
|
||||
targetFamilyIds: noticeTargetMode === 'all' ? [] : noticeForm.targetFamilyIds,
|
||||
date: editingNotice ? editingNotice.date : new Date().toISOString()
|
||||
};
|
||||
await CondoService.saveNotice(payload);
|
||||
@@ -457,6 +472,17 @@ export const SettingsPage: React.FC = () => {
|
||||
} catch(e) { console.error(e); }
|
||||
};
|
||||
|
||||
const toggleNoticeFamilyTarget = (familyId: string) => {
|
||||
setNoticeForm(prev => {
|
||||
const current = prev.targetFamilyIds;
|
||||
if (current.includes(familyId)) {
|
||||
return { ...prev, targetFamilyIds: current.filter(id => id !== familyId) };
|
||||
} else {
|
||||
return { ...prev, targetFamilyIds: [...current, familyId] };
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const openReadDetails = (noticeId: string) => {
|
||||
setSelectedNoticeId(noticeId);
|
||||
setShowReadDetailsModal(true);
|
||||
@@ -841,7 +867,9 @@ export const SettingsPage: React.FC = () => {
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4">
|
||||
{notices.map(notice => (
|
||||
{notices.map(notice => {
|
||||
const isTargeted = notice.targetFamilyIds && notice.targetFamilyIds.length > 0;
|
||||
return (
|
||||
<div key={notice.id} className={`bg-white p-5 rounded-xl border shadow-sm relative transition-all ${notice.active ? 'border-slate-200' : 'border-slate-100 opacity-60 bg-slate-50'}`}>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-start gap-3">
|
||||
@@ -849,10 +877,22 @@ export const SettingsPage: React.FC = () => {
|
||||
{notice.type === 'warning' ? <AlertTriangle className="w-5 h-5"/> : notice.type === 'maintenance' ? <Hammer className="w-5 h-5"/> : notice.type === 'event' ? <Calendar className="w-5 h-5"/> : <Info className="w-5 h-5"/>}
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-bold text-slate-800">{notice.title}</h4>
|
||||
<h4 className="font-bold text-slate-800 flex items-center gap-2">
|
||||
{notice.title}
|
||||
{isTargeted && (
|
||||
<span className="text-[10px] bg-slate-100 text-slate-500 border border-slate-200 px-2 py-0.5 rounded-full uppercase flex items-center gap-1">
|
||||
<Users className="w-3 h-3" /> Privato
|
||||
</span>
|
||||
)}
|
||||
</h4>
|
||||
<p className="text-xs text-slate-400 font-medium uppercase tracking-wide mb-1">{getCondoName(notice.condoId)} • {new Date(notice.date).toLocaleDateString()}</p>
|
||||
<p className="text-sm text-slate-600 line-clamp-2">{notice.content}</p>
|
||||
{notice.link && <a href={notice.link} className="text-xs text-blue-600 underline mt-1 flex items-center gap-1"><LinkIcon className="w-3 h-3"/> Allegato</a>}
|
||||
{isTargeted && (
|
||||
<p className="text-[10px] text-slate-400 mt-2">
|
||||
Visibile a: {notice.targetFamilyIds!.length} famiglie
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-3">
|
||||
@@ -881,7 +921,8 @@ export const SettingsPage: React.FC = () => {
|
||||
<button onClick={() => handleDeleteNotice(notice.id)} className="text-sm text-red-600 font-medium px-3 py-1 hover:bg-red-50 rounded">Elimina</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
{notices.length === 0 && <div className="text-center p-8 text-slate-400">Nessun avviso pubblicato.</div>}
|
||||
</div>
|
||||
</div>
|
||||
@@ -1017,12 +1058,13 @@ export const SettingsPage: React.FC = () => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* NOTICE MODAL (Existing) */}
|
||||
{/* NOTICE MODAL (Updated with Target Selector) */}
|
||||
{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">
|
||||
<h3 className="font-bold text-lg mb-4 text-slate-800">{editingNotice ? 'Modifica Avviso' : 'Nuovo Avviso'}</h3>
|
||||
<form onSubmit={handleNoticeSubmit} className="space-y-4">
|
||||
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 animate-in fade-in zoom-in duration-200 flex flex-col max-h-[90vh]">
|
||||
<h3 className="font-bold text-lg mb-4 text-slate-800 flex-shrink-0">{editingNotice ? 'Modifica Avviso' : 'Nuovo Avviso'}</h3>
|
||||
<div className="overflow-y-auto flex-1 pr-2">
|
||||
<form id="noticeForm" onSubmit={handleNoticeSubmit} className="space-y-4">
|
||||
<input className="w-full border p-2.5 rounded-lg text-slate-700" placeholder="Titolo" value={noticeForm.title} onChange={e => setNoticeForm({...noticeForm, title: e.target.value})} required />
|
||||
<textarea className="w-full border p-2.5 rounded-lg text-slate-700 h-24" placeholder="Contenuto avviso..." value={noticeForm.content} onChange={e => setNoticeForm({...noticeForm, content: e.target.value})} required />
|
||||
|
||||
@@ -1045,17 +1087,68 @@ export const SettingsPage: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-xs text-slate-500 font-bold uppercase mb-2 block">A chi è rivolto?</label>
|
||||
<div className="flex gap-4 mb-3">
|
||||
<label className="flex items-center gap-2 text-sm text-slate-700 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="targetMode"
|
||||
value="all"
|
||||
checked={noticeTargetMode === 'all'}
|
||||
onChange={() => setNoticeTargetMode('all')}
|
||||
className="w-4 h-4 text-blue-600"
|
||||
/>
|
||||
Tutti i condomini
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm text-slate-700 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="targetMode"
|
||||
value="specific"
|
||||
checked={noticeTargetMode === 'specific'}
|
||||
onChange={() => setNoticeTargetMode('specific')}
|
||||
className="w-4 h-4 text-blue-600"
|
||||
/>
|
||||
Seleziona Famiglie
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Family Selector */}
|
||||
{noticeTargetMode === 'specific' && (
|
||||
<div className="border border-slate-200 rounded-lg p-2 max-h-40 overflow-y-auto bg-slate-50">
|
||||
{families.length === 0 ? (
|
||||
<p className="text-xs text-slate-400 text-center py-2">Nessuna famiglia disponibile.</p>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{families.map(fam => (
|
||||
<label key={fam.id} className="flex items-center gap-2 p-1.5 hover:bg-white rounded cursor-pointer transition-colors">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={noticeForm.targetFamilyIds.includes(fam.id)}
|
||||
onChange={() => toggleNoticeFamilyTarget(fam.id)}
|
||||
className="w-4 h-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
|
||||
/>
|
||||
<span className="text-sm text-slate-700">{fam.name} <span className="text-slate-400 text-xs">(Int. {fam.unitNumber})</span></span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-xs text-slate-500 font-bold uppercase mb-1 block">Link Esterno (Opzionale)</label>
|
||||
<input className="w-full border p-2.5 rounded-lg text-slate-700" placeholder="https://..." value={noticeForm.link} onChange={e => setNoticeForm({...noticeForm, link: e.target.value})} />
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-2">
|
||||
<button type="button" onClick={() => setShowNoticeModal(false)} className="flex-1 border p-2.5 rounded-lg text-slate-600 hover:bg-slate-50">Annulla</button>
|
||||
<button type="submit" className="flex-1 bg-blue-600 text-white p-2.5 rounded-lg hover:bg-blue-700">Salva</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div className="flex gap-2 pt-4 border-t border-slate-100 flex-shrink-0">
|
||||
<button type="button" onClick={() => setShowNoticeModal(false)} className="flex-1 border p-2.5 rounded-lg text-slate-600 hover:bg-slate-50">Annulla</button>
|
||||
<button type="submit" form="noticeForm" className="flex-1 bg-blue-600 text-white p-2.5 rounded-lg hover:bg-blue-700">Salva</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
FROM node:18-alpine
|
||||
WORKDIR /app
|
||||
|
||||
# Set production environment
|
||||
ENV NODE_ENV=production
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm install --production
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 3001
|
||||
CMD ["node", "server.js"]
|
||||
|
||||
18
server/db.js
18
server/db.js
@@ -269,11 +269,29 @@ const initDb = async () => {
|
||||
link VARCHAR(255),
|
||||
date ${TIMESTAMP_TYPE} DEFAULT CURRENT_TIMESTAMP,
|
||||
active BOOLEAN DEFAULT TRUE,
|
||||
target_families JSON ${DB_CLIENT === 'postgres' ? 'NULL' : 'NULL'},
|
||||
created_at ${TIMESTAMP_TYPE} DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (condo_id) REFERENCES condos(id) ON DELETE CASCADE
|
||||
)
|
||||
`);
|
||||
|
||||
// Migration for notices: Add target_families
|
||||
try {
|
||||
let hasTargets = false;
|
||||
if (DB_CLIENT === 'postgres') {
|
||||
const [cols] = await connection.query("SELECT column_name FROM information_schema.columns WHERE table_name='notices'");
|
||||
hasTargets = cols.some(c => c.column_name === 'target_families');
|
||||
} else {
|
||||
const [cols] = await connection.query("SHOW COLUMNS FROM notices");
|
||||
hasTargets = cols.some(c => c.Field === 'target_families');
|
||||
}
|
||||
|
||||
if (!hasTargets) {
|
||||
console.log('Migrating: Adding target_families to notices...');
|
||||
await connection.query("ALTER TABLE notices ADD COLUMN target_families JSON");
|
||||
}
|
||||
} catch(e) { console.warn("Notices migration warning:", e.message); }
|
||||
|
||||
// 7. Notice Reads
|
||||
await connection.query(`
|
||||
CREATE TABLE IF NOT EXISTS notice_reads (
|
||||
|
||||
@@ -297,24 +297,45 @@ app.get('/api/notices', authenticateToken, async (req, res) => {
|
||||
}
|
||||
query += ' ORDER BY date DESC';
|
||||
const [rows] = await pool.query(query, params);
|
||||
res.json(rows.map(r => ({ id: r.id, condoId: r.condo_id, title: r.title, content: r.content, type: r.type, link: r.link, date: r.date, active: !!r.active })));
|
||||
res.json(rows.map(r => ({
|
||||
id: r.id,
|
||||
condoId: r.condo_id,
|
||||
title: r.title,
|
||||
content: r.content,
|
||||
type: r.type,
|
||||
link: r.link,
|
||||
date: r.date,
|
||||
active: !!r.active,
|
||||
targetFamilyIds: r.target_families ? (typeof r.target_families === 'string' ? JSON.parse(r.target_families) : r.target_families) : []
|
||||
})));
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.post('/api/notices', authenticateToken, requireAdmin, async (req, res) => {
|
||||
const { condoId, title, content, type, link, active } = req.body;
|
||||
const { condoId, title, content, type, link, active, targetFamilyIds } = req.body;
|
||||
const id = uuidv4();
|
||||
try {
|
||||
await pool.query('INSERT INTO notices (id, condo_id, title, content, type, link, active, date) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())', [id, condoId, title, content, type, link, active]);
|
||||
res.json({ id, condoId, title, content, type, link, active });
|
||||
const targetFamiliesJson = targetFamilyIds && targetFamilyIds.length > 0 ? JSON.stringify(targetFamilyIds) : null;
|
||||
await pool.query(
|
||||
'INSERT INTO notices (id, condo_id, title, content, type, link, active, target_families, date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())',
|
||||
[id, condoId, title, content, type, link, active, targetFamiliesJson]
|
||||
);
|
||||
res.json({ id, condoId, title, content, type, link, active, targetFamilyIds });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.put('/api/notices/:id', authenticateToken, requireAdmin, async (req, res) => {
|
||||
const { title, content, type, link, active } = req.body;
|
||||
const { title, content, type, link, active, targetFamilyIds } = req.body;
|
||||
try {
|
||||
await pool.query('UPDATE notices SET title = ?, content = ?, type = ?, link = ?, active = ? WHERE id = ?', [title, content, type, link, active, req.params.id]);
|
||||
const targetFamiliesJson = targetFamilyIds && targetFamilyIds.length > 0 ? JSON.stringify(targetFamilyIds) : null;
|
||||
await pool.query(
|
||||
'UPDATE notices SET title = ?, content = ?, type = ?, link = ?, active = ?, target_families = ? WHERE id = ?',
|
||||
[title, content, type, link, active, targetFamiliesJson, req.params.id]
|
||||
);
|
||||
res.json({ success: true });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.delete('/api/notices/:id', authenticateToken, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
await pool.query('DELETE FROM notices WHERE id = ?', [req.params.id]);
|
||||
@@ -337,13 +358,40 @@ app.get('/api/notices/:id/reads', authenticateToken, async (req, res) => {
|
||||
app.get('/api/notices/unread', authenticateToken, async (req, res) => {
|
||||
const { userId, condoId } = req.query;
|
||||
try {
|
||||
// First get user's family ID to filter targeted notices
|
||||
const [users] = await pool.query('SELECT family_id FROM users WHERE id = ?', [userId]);
|
||||
const userFamilyId = users.length > 0 ? users[0].family_id : null;
|
||||
|
||||
const [rows] = await pool.query(`
|
||||
SELECT n.* FROM notices n
|
||||
LEFT JOIN notice_reads nr ON n.id = nr.notice_id AND nr.user_id = ?
|
||||
WHERE n.condo_id = ? AND n.active = TRUE AND nr.read_at IS NULL
|
||||
ORDER BY n.date DESC
|
||||
`, [userId, condoId]);
|
||||
res.json(rows.map(r => ({ id: r.id, condoId: r.condo_id, title: r.title, content: r.content, type: r.type, link: r.link, date: r.date, active: !!r.active })));
|
||||
|
||||
// Filter in JS for simplicity across DBs (handling JSON field logic)
|
||||
const filtered = rows.filter(n => {
|
||||
if (!n.target_families) return true; // Public to all
|
||||
let targets = n.target_families;
|
||||
if (typeof targets === 'string') {
|
||||
try { targets = JSON.parse(targets); } catch(e) { return true; }
|
||||
}
|
||||
if (!Array.isArray(targets) || targets.length === 0) return true; // Empty array = Public
|
||||
|
||||
// If explicit targets are set, user MUST belong to one of the families
|
||||
return userFamilyId && targets.includes(userFamilyId);
|
||||
});
|
||||
|
||||
res.json(filtered.map(r => ({
|
||||
id: r.id,
|
||||
condoId: r.condo_id,
|
||||
title: r.title,
|
||||
content: r.content,
|
||||
type: r.type,
|
||||
link: r.link,
|
||||
date: r.date,
|
||||
active: !!r.active
|
||||
})));
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user