Add RUT registration & Validation, bulk aprove

This commit is contained in:
2025-12-28 19:57:42 -03:00
parent b91de06e29
commit f6564ec2a6
4 changed files with 214 additions and 66 deletions

View File

@@ -14,6 +14,19 @@ model User {
password String password String
role String @default("USER") // ADMIN, USER role String @default("USER") // ADMIN, USER
plates Plate[] plates Plate[]
people Person[]
}
model Person {
id Int @id @default(autoincrement())
rut String @unique
name String
status String @default("PENDING") // PENDING, APPROVED, DENIED
startDate DateTime
endDate DateTime
createdAt DateTime @default(now())
addedBy User? @relation(fields: [addedById], references: [id])
addedById Int?
} }
model Plate { model Plate {

View File

@@ -147,6 +147,76 @@ app.get('/api/recent', async (req, res) => {
} }
}); });
// Helper: RUT Validation
function validateRut(rut) {
if (!rut || !/^[0-9]+-[0-9kK]{1}$/.test(rut)) return false;
let [num, dv] = rut.split('-');
let total = 0;
let multiple = 2;
for (let i = num.length - 1; i >= 0; i--) {
total += parseInt(num.charAt(i)) * multiple;
multiple = (multiple + 1) % 8 || 2;
}
let res = 11 - (total % 11);
let finalDv = res === 11 ? '0' : res === 10 ? 'K' : res.toString();
return finalDv.toUpperCase() === dv.toUpperCase();
}
// People CRUD
app.get('/api/people', authenticateToken, async (req, res) => {
try {
const where = req.user.role === 'ADMIN' ? {} : { addedById: req.user.id };
const people = await prisma.person.findMany({
where,
include: { addedBy: { select: { username: true } } }
});
res.json(people);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.post('/api/people', authenticateToken, async (req, res) => {
const { rut, name, durationDays } = req.body;
if (!validateRut(rut)) {
return res.status(400).json({ error: 'Invalid RUT format (12345678-K)' });
}
const startDate = new Date();
const endDate = new Date();
endDate.setDate(endDate.getDate() + parseInt(durationDays || 1));
try {
const person = await prisma.person.create({
data: {
rut,
name,
startDate,
endDate,
status: 'PENDING',
addedById: req.user.id
}
});
res.json(person);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Admin: Bulk Approve People by User
app.post('/api/people/bulk-approve', authenticateToken, isAdmin, async (req, res) => {
const { userId } = req.body;
try {
await prisma.person.updateMany({
where: { addedById: parseInt(userId), status: 'PENDING' },
data: { status: 'APPROVED' }
});
res.json({ message: 'Bulk approval successful' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Detection Endpoint (from Python) // Detection Endpoint (from Python)
app.post('/api/detect', async (req, res) => { app.post('/api/detect', async (req, res) => {
const { plate_number } = req.body; const { plate_number } = req.body;

View File

@@ -10,7 +10,7 @@ function AdminDashboard({ token }) {
const [users, setUsers] = useState([]); const [users, setUsers] = useState([]);
const [plates, setPlates] = useState([]); const [plates, setPlates] = useState([]);
const [newUser, setNewUser] = useState({ username: '', password: '', role: 'USER' }); const [newUser, setNewUser] = useState({ username: '', password: '', role: 'USER' });
const [activeTab, setActiveTab] = useState('monitor'); // 'monitor' | 'plates' | 'users' const [activeTab, setActiveTab] = useState('monitor'); // 'monitor' | 'plates' | 'users' | 'visitors'
// Monitor State // Monitor State
const [detections, setDetections] = useState([]); const [detections, setDetections] = useState([]);
@@ -18,6 +18,9 @@ function AdminDashboard({ token }) {
const [viewMode, setViewMode] = useState('live'); // 'live' | 'history' const [viewMode, setViewMode] = useState('live'); // 'live' | 'history'
const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]); const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);
// Visitor State
const [activePeople, setActivePeople] = useState([]);
useEffect(() => { useEffect(() => {
fetchData(); fetchData();
@@ -38,10 +41,11 @@ function AdminDashboard({ token }) {
const fetchData = async () => { const fetchData = async () => {
try { try {
const authHeader = { headers: { Authorization: `Bearer ${token}` } }; const authHeader = { headers: { Authorization: `Bearer ${token}` } };
const [usersRes, platesRes, recentRes] = await Promise.all([ const [usersRes, platesRes, recentRes, peopleRes] = await Promise.all([
axios.get(`${API_URL}/api/auth`, authHeader).catch(err => ({ data: [] })), axios.get(`${API_URL}/api/auth`, authHeader).catch(err => ({ data: [] })),
axios.get(`${API_URL}/api/plates`, authHeader), axios.get(`${API_URL}/api/plates`, authHeader),
axios.get(`${API_URL}/api/recent`, authHeader) axios.get(`${API_URL}/api/recent`, authHeader),
axios.get(`${API_URL}/api/people`, authHeader)
]); ]);
setUsers(usersRes.data); setUsers(usersRes.data);
setPlates(platesRes.data); setPlates(platesRes.data);
@@ -50,6 +54,7 @@ function AdminDashboard({ token }) {
status: log.accessStatus, status: log.accessStatus,
timestamp: log.timestamp timestamp: log.timestamp
}))); })));
setActivePeople(peopleRes.data);
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} }
@@ -101,10 +106,23 @@ function AdminDashboard({ token }) {
} }
}; };
const handleBulkApprove = async (userId) => {
if (!confirm('Approve ALL pending visitors for this user?')) return;
try {
await axios.post(`${API_URL}/api/people/bulk-approve`, { userId }, {
headers: { Authorization: `Bearer ${token}` }
});
fetchData();
alert('All visitors approved');
} catch (err) {
alert(err.message);
}
};
const StatusBadge = ({ status }) => ( const StatusBadge = ({ status }) => (
<span className={`px-2 py-1 rounded text-xs font-bold ${status === 'GRANTED' ? 'bg-green-600 text-white' : <span className={`px-2 py-1 rounded text-xs font-bold ${status === 'GRANTED' ? 'bg-green-600 text-white' :
status === 'DENIED' ? 'bg-red-600 text-white' : status === 'DENIED' ? 'bg-red-600 text-white' :
'bg-yellow-600 text-white' 'bg-yellow-600 text-white'
}`}> }`}>
{status} {status}
</span> </span>
@@ -137,6 +155,9 @@ function AdminDashboard({ token }) {
> >
User Management User Management
</button> </button>
<button onClick={() => setActiveTab('visitors')} className={`px-4 py-2 rounded-md transition-all ${activeTab === 'visitors' ? 'bg-purple-600' : 'hover:text-purple-400'}`}>
Visitor Approvals
</button>
</div> </div>
</header> </header>

View File

@@ -10,9 +10,12 @@ function UserDashboard({ token, username }) {
const [plates, setPlates] = useState([]); const [plates, setPlates] = useState([]);
const [newPlate, setNewPlate] = useState({ number: '', owner: '' }); const [newPlate, setNewPlate] = useState({ number: '', owner: '' });
const [detections, setDetections] = useState([]); const [detections, setDetections] = useState([]);
const [people, setPeople] = useState([]);
const [newPerson, setNewPerson] = useState({ name: '', rut: '', durationDays: 1 });
useEffect(() => { useEffect(() => {
fetchPlates(); fetchPlates();
fetchPeople();
// Listen for live detections (optional, maybe user wants to see their plates detected?) // Listen for live detections (optional, maybe user wants to see their plates detected?)
// For now, let's show all global detections but emphasize this is a "Portal" // For now, let's show all global detections but emphasize this is a "Portal"
@@ -37,6 +40,17 @@ function UserDashboard({ token, username }) {
} }
}; };
const fetchPeople = async () => {
try {
const res = await axios.get(`${API_URL}/api/people`, {
headers: { Authorization: `Bearer ${token}` }
});
setPeople(res.data);
} catch (err) {
console.error(err);
}
};
const handleRegister = async (e) => { const handleRegister = async (e) => {
e.preventDefault(); e.preventDefault();
try { try {
@@ -54,76 +68,106 @@ function UserDashboard({ token, username }) {
} }
}; };
const handleRegisterPerson = async (e) => {
e.preventDefault();
try {
await axios.post(`${API_URL}/api/people`, newPerson, {
headers: { Authorization: `Bearer ${token}` }
});
setNewPerson({ name: '', rut: '', durationDays: 1 });
fetchPeople();
alert('Person registered! Waiting for admin approval.');
} catch (err) {
alert('Error: ' + (err.response?.data?.error || err.message));
}
};
return ( return (
<div className="min-h-screen bg-slate-900 text-slate-100 p-8"> <div className="min-h-screen bg-slate-900 text-slate-100 p-8">
<div className="max-w-6xl mx-auto grid grid-cols-1 lg:grid-cols-3 gap-8"> <div className="max-w-6xl mx-auto space-y-12">
{/* Register & My Plates (Full Width) */} <header>
<div className="col-span-1 lg:col-span-3 space-y-8"> <h1 className="text-3xl font-bold bg-gradient-to-r from-blue-400 to-cyan-300 bg-clip-text text-transparent mb-2">
<header> Welcome, {username}
<h1 className="text-3xl font-bold bg-gradient-to-r from-blue-400 to-cyan-300 bg-clip-text text-transparent mb-2"> </h1>
Welcome, {username} <p className="text-slate-400">Manage your vehicles and visitors.</p>
</h1> </header>
<p className="text-slate-400">Manage your vehicles and access.</p>
</header>
<div className="bg-slate-800 rounded-2xl p-6 border border-slate-700"> {/* Plates Section */}
<h2 className="text-xl font-semibold mb-6 flex items-center gap-2"> <div className="bg-slate-800 rounded-2xl p-6 border border-slate-700">
<Car className="text-blue-400" /> My Registered Plates <h2 className="text-xl font-semibold mb-6 flex items-center gap-2">
</h2> <Car className="text-blue-400" /> My Registered Plates
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
{plates.length === 0 && <p className="text-slate-500 col-span-3">No plates registered.</p>} {plates.length === 0 && <p className="text-slate-500 col-span-3">No plates registered.</p>}
{plates.map(plate => ( {plates.map(plate => (
<div key={plate.id} className="flex items-center justify-between p-4 bg-slate-900 rounded-xl border border-slate-700"> <div key={plate.id} className="flex items-center justify-between p-4 bg-slate-900 rounded-xl border border-slate-700">
<div> <div>
<div className="font-mono text-xl font-bold tracking-wider">{plate.number}</div> <div className="font-mono text-xl font-bold tracking-wider">{plate.number}</div>
<div className="text-sm text-slate-400">{plate.owner}</div> <div className="text-sm text-slate-400">{plate.owner}</div>
</div>
<div>
{plate.status === 'ALLOWED' && (
<span className="flex items-center gap-1 text-green-400 bg-green-900/30 px-3 py-1 rounded-full text-xs font-bold">
<CheckCircle size={14} /> ACTIVE
</span>
)}
{plate.status === 'PENDING' && (
<span className="flex items-center gap-1 text-yellow-400 bg-yellow-900/30 px-3 py-1 rounded-full text-xs font-bold">
<Clock size={14} /> PENDING
</span>
)}
{plate.status === 'DENIED' && (
<span className="flex items-center gap-1 text-red-400 bg-red-900/30 px-3 py-1 rounded-full text-xs font-bold">
<AlertCircle size={14} /> DENIED
</span>
)}
</div>
</div> </div>
))} <span className={`text-xs px-2 py-1 rounded font-bold ${plate.status === 'ALLOWED' ? 'bg-green-900 text-green-300' : plate.status === 'PENDING' ? 'bg-yellow-900 text-yellow-300' : 'bg-red-900 text-red-300'}`}>
</div> {plate.status}
</span>
</div>
))}
</div> </div>
<div className="bg-slate-800 rounded-2xl p-6 border border-slate-700"> <form onSubmit={handleRegister} className="flex gap-4">
<h2 className="text-xl font-semibold mb-4">Request New Access</h2> <input
<form onSubmit={handleRegister} className="flex gap-4"> className="flex-1 bg-slate-900 border border-slate-700 rounded-lg p-3 font-mono uppercase"
<input placeholder="Plate Number (e.g. ABCD12)"
className="flex-1 bg-slate-900 border border-slate-700 rounded-lg p-3 font-mono uppercase" value={newPlate.number}
placeholder="Plate Number (e.g. ABCD12)" onChange={e => setNewPlate({ ...newPlate, number: e.target.value })}
value={newPlate.number} required
onChange={e => setNewPlate({ ...newPlate, number: e.target.value })} />
required <input
/> className="flex-1 bg-slate-900 border border-slate-700 rounded-lg p-3"
<input placeholder="Owner Name"
className="flex-1 bg-slate-900 border border-slate-700 rounded-lg p-3" value={newPlate.owner}
placeholder="Owner Name" onChange={e => setNewPlate({ ...newPlate, owner: e.target.value })}
value={newPlate.owner} required
onChange={e => setNewPlate({ ...newPlate, owner: e.target.value })} />
required <button className="bg-blue-600 hover:bg-blue-500 px-6 rounded-lg font-bold transition-colors">
/> Submit
<button className="bg-blue-600 hover:bg-blue-500 px-6 rounded-lg font-bold transition-colors"> </button>
Submit </form>
</button> </div>
</form>
{/* Visitors Section */}
<div className="bg-slate-800 rounded-2xl p-6 border border-slate-700">
<h2 className="text-xl font-semibold mb-6 flex items-center gap-2">
<Users className="text-purple-400" /> My Visitors
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
{people.length === 0 && <p className="text-slate-500 col-span-3">No visitors registered.</p>}
{people.map(p => (
<div key={p.id} className="p-4 bg-slate-900 rounded-xl border border-slate-700">
<div className="flex justify-between">
<div className="font-bold">{p.name}</div>
<span className={`text-xs px-2 py-1 rounded font-bold ${p.status === 'APPROVED' ? 'bg-green-900 text-green-300' : p.status === 'PENDING' ? 'bg-yellow-900 text-yellow-300' : 'bg-red-900 text-red-300'}`}>
{p.status}
</span>
</div>
<div className="text-sm text-slate-400 font-mono mt-1">{p.rut}</div>
<div className="text-xs text-slate-500 mt-2">
Until: {new Date(p.endDate).toLocaleDateString()}
</div>
</div>
))}
</div> </div>
<form onSubmit={handleRegisterPerson} className="flex gap-4 flex-wrap">
<input className="flex-1 min-w-[200px] bg-slate-900 border border-slate-700 rounded p-3" placeholder="Full Name" value={newPerson.name} onChange={e => setNewPerson({ ...newPerson, name: e.target.value })} required />
<input className="flex-1 min-w-[150px] bg-slate-900 border border-slate-700 rounded p-3" placeholder="RUT (12345678-9)" value={newPerson.rut} onChange={e => setNewPerson({ ...newPerson, rut: e.target.value })} required />
<select className="bg-slate-900 border border-slate-700 rounded p-3" value={newPerson.durationDays} onChange={e => setNewPerson({ ...newPerson, durationDays: parseInt(e.target.value) })} required>
<option value="1">1 Day</option>
<option value="2">2 Days</option>
<option value="7">1 Week</option>
</select>
<button className="bg-purple-600 hover:bg-purple-500 px-6 rounded-lg font-bold transition-colors">Add Visitor</button>
</form>
</div> </div>
</div> </div>