updated email in utlization exports and user exports added new

This commit is contained in:
Abhijit 2026-11-17 14:34:00 +05:30
parent ec761c811c
commit be209e7b76
3 changed files with 74 additions and 5 deletions

View File

@ -260,9 +260,9 @@ export function reportRoutes(server) {
const ownIds = ownCohorts.map((item) => item._id);
const run = await CohortSession.countDocuments({ cohort: { $in: ownIds }, status: { $in: ['scheduled', 'completed'] } });
const cancelledOwn = await CohortSession.countDocuments({ cohort: { $in: ownIds }, status: 'cancelled' });
items.push([`${prt.firstName} ${prt.lastName}`, used, max, Math.max(0, max - used), run, cancelledOwn]);
items.push([`${prt.firstName} ${prt.lastName}`, prt.email || '', used, max, Math.max(0, max - used), run, cancelledOwn]);
}
rows = [['PRT', 'Used', 'Max', 'Idle', 'Sessions', 'Cancelled'], ...items];
rows = [['PRT', 'Email', 'Used', 'Max', 'Idle', 'Sessions', 'Cancelled'], ...items];
} else if (type === 'vitals') {
/* Old: sessions from the current cohort only.
const patients = await listOnboardedForReports({ virtualPrtId: scopedPrt(request), diseaseType: request.query.diseaseType || undefined });

View File

@ -25,6 +25,16 @@ function isSuperRole(role) {
return role?.systemKey === 'super_admin';
}
function csvEscape(value) {
const text = value == null ? '' : String(value);
if (/[",\n]/.test(text)) return `"${text.replace(/"/g, '""')}"`;
return text;
}
function toCsv(rows) {
return rows.map((row) => row.map(csvEscape).join(',')).join('\n');
}
async function assertCanMutateTarget(actorCreds, targetUser) {
const targetRole = targetUser.role && typeof targetUser.role === 'object'
? targetUser.role
@ -73,6 +83,39 @@ export function userRoutes(server) {
},
});
server.route({
method: 'GET',
path: '/api/users/export',
options: { pre: [{ method: requirePermission('users', 'view') }] },
handler: async (request, h) => {
await writeAudit(request, { action: 'user.exported', resourceType: 'user', resourceId: '' });
const { search = '' } = request.query;
const filter = {};
if (search) {
const rx = new RegExp(String(search).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
filter.$or = [{ firstName: rx }, { lastName: rx }, { email: rx }, { phone: rx }];
}
const users = await User.find(filter).populate('role').sort({ firstName: 1, lastName: 1 });
const rows = [
['Name', 'Email', 'Phone', 'Role', 'Languages', 'Status'],
...users.map((user) => {
const dto = toUserDto(user);
return [
`${dto.firstName} ${dto.lastName}`.trim(),
dto.email || '',
dto.phone || '',
dto.role?.name || '',
(dto.languages || []).join('; '),
dto.isActive ? 'Active' : 'Inactive',
];
}),
];
return h.response(toCsv(rows))
.type('text/csv')
.header('content-disposition', 'attachment; filename="users.csv"');
},
});
server.route({
method: 'GET',
path: '/api/users/{id}',

View File

@ -50,6 +50,26 @@ export default function UsersPage() {
load().catch(() => {});
}, [page, pageSize, query]);
const downloadExport = () => {
const params = new URLSearchParams();
if (query) params.set('search', query);
const suffix = params.toString() ? `?${params}` : '';
fetch(`/api/users/export${suffix}`, { credentials: 'include' })
.then((res) => {
if (!res.ok) throw new Error('Could not export users.');
return res.blob();
})
.then((blob) => {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'users.csv';
link.click();
URL.revokeObjectURL(url);
})
.catch((err) => setError(err.message));
};
const openCreate = () => {
setEditing(null);
setForm({ ...emptyForm, role: roles.find((r) => r.systemKey === 'educator')?.id || roles[0]?.id || '' });
@ -156,6 +176,7 @@ export default function UsersPage() {
return (
<Container fluid>
<PageBreadcrumb title="Users" subtitle="Admin" />
{error && !modal ? <div className="alert alert-danger">{error}</div> : null}
<Row>
<Col>
<Card>
@ -167,9 +188,14 @@ export default function UsersPage() {
</div>
<Button type="submit" variant="light">Search</Button>
</form>
{can('users', 'add') ? (
<Button variant="success" onClick={openCreate}><TbPlus className="me-1" /> Add user</Button>
) : null}
<div className="d-flex gap-2">
{can('users', 'view') ? (
<Button type="button" variant="outline-primary" onClick={downloadExport}>Export CSV</Button>
) : null}
{can('users', 'add') ? (
<Button variant="success" onClick={openCreate}><TbPlus className="me-1" /> Add user</Button>
) : null}
</div>
</CardHeader>
<DataTable table={table} emptyMessage="No users found" />
{total > 0 && (