Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 93 additions & 4 deletions src/components/Firebase/Firebase.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4737,6 +4737,89 @@ class Firebase {
* Gets all users from Firestore with relevant information for admin dashboard
* @returns {Array} Array of user objects with id, name, email, role, status, and lastLogin
*/
/**
* Get last action date for all users by querying activity collections.
* Uses optimized approach: 5 total queries instead of per-user queries.
* @returns Map<userId, Date> - Last action date per user
*/
getUsersLastAction = async (): Promise<Map<string, Date>> => {
const lastActionMap = new Map<string, Date>()

const updateIfNewer = (userId: string, date: Date | null) => {
if (!date || !userId) return
const current = lastActionMap.get(userId)
if (!current || date > current) {
lastActionMap.set(userId, date)
}
}

// Helper to extract userId from /user/ID format (used in observations)
const extractUserId = (ref: string): string => {
if (!ref) return ''
return ref.startsWith('/user/') ? ref.replace('/user/', '') : ref
}

// Query all 5 collections in parallel for better performance
const [observations, knowledgeChecks, conferencePlans, actionPlans, emails] = await Promise.all([
this.db.collection('observations').get(),
this.db.collection('knowledgeChecks').get(),
this.db.collection('conferencePlans').get(),
this.db.collection('actionPlans').get(),
this.db.collection('emails').get()
])

// 1. Observations (largest collection - 20K+)
observations.docs.forEach(doc => {
const data = doc.data()
const userId = extractUserId(data.teacher)
const endDate = data.end?.toDate?.() || null
updateIfNewer(userId, endDate)
})

// 2. Knowledge Checks (6K+)
knowledgeChecks.docs.forEach(doc => {
const data = doc.data()
const userId = data.answeredBy
const timestamp = data.timestamp?.toDate?.() || null
updateIfNewer(userId, timestamp)
})

// 3. Conference Plans
conferencePlans.docs.forEach(doc => {
const data = doc.data()
const userId = data.teacher
const created = data.dateCreated?.toDate?.() || null
const modified = data.dateModified?.toDate?.() || null
updateIfNewer(userId, created)
updateIfNewer(userId, modified)
})

// 4. Action Plans
actionPlans.docs.forEach(doc => {
const data = doc.data()
const userId = data.teacher
const created = data.dateCreated?.toDate?.() || null
const modified = data.dateModified?.toDate?.() || null
updateIfNewer(userId, created)
updateIfNewer(userId, modified)
})

// 5. Emails (check both sender and recipient)
emails.docs.forEach(doc => {
const data = doc.data()
const senderId = data.user
const recipientId = data.recipientId
const created = data.dateCreated?.toDate?.() || null
const modified = data.dateModified?.toDate?.() || null
updateIfNewer(senderId, created)
updateIfNewer(senderId, modified)
updateIfNewer(recipientId, created)
updateIfNewer(recipientId, modified)
})

return lastActionMap
}

getAllUsers = async () => {
const result: Array<{
id: string
Expand All @@ -4747,17 +4830,22 @@ class Firebase {
program: string
archived: boolean
lastLogin: Date | null
lastAction: Date | null
}> = []

// Fetch all programs to build a lookup map
const programsSnapshot = await this.db.collection('programs').get()
// Fetch programs, users, and last action data in parallel
const [programsSnapshot, usersSnapshot, lastActionMap] = await Promise.all([
this.db.collection('programs').get(),
this.db.collection('users').get(),
this.getUsersLastAction()
])

// Build programs lookup map
const programsMap = new Map<string, string>()
programsSnapshot.docs.forEach(doc => {
programsMap.set(doc.id, doc.data().name || '')
})

const usersSnapshot = await this.db.collection('users').get()

usersSnapshot.docs.forEach(doc => {
const data = doc.data()
// Get first program name from user's programs array
Expand Down Expand Up @@ -4800,6 +4888,7 @@ class Firebase {
program: programName,
archived: data.archived || false,
lastLogin: data.lastLogin ? data.lastLogin.toDate() : null,
lastAction: lastActionMap.get(doc.id) || null,
})
})

Expand Down
18 changes: 11 additions & 7 deletions src/components/UsersComponents/AllUsersTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,12 @@ class AllUsersTable extends React.Component<Props, State> {
if (statusFilter) users = users.filter(u => u.archived === (statusFilter === 'archived'))

users.sort((a, b) => {
const aVal = sortField === 'lastLogin'
? (a.lastLogin?.getTime() || 0)
const isDateField = sortField === 'lastLogin' || sortField === 'lastAction'
const aVal = isDateField
? (a[sortField]?.getTime() || 0)
: String(a[sortField] || '').toLowerCase()
const bVal = sortField === 'lastLogin'
? (b.lastLogin?.getTime() || 0)
const bVal = isDateField
? (b[sortField]?.getTime() || 0)
: String(b[sortField] || '').toLowerCase()
return sortDir === 'asc' ? (aVal > bVal ? 1 : -1) : (aVal < bVal ? 1 : -1)
})
Expand All @@ -110,13 +111,14 @@ class AllUsersTable extends React.Component<Props, State> {

handleExport = () => {
const users = this.getFilteredUsers()
const headers = ['Last Name', 'First Name', 'Email', 'Role', 'Program', 'Status', 'Last Login']
const headers = ['Last Name', 'First Name', 'Email', 'Role', 'Program', 'Status', 'Last Login', 'Last Action']
const escape = (val: string) => `"${(val || '').replace(/"/g, '""')}"`
const rows = users.map(u => [
escape(u.lastName), escape(u.firstName), escape(u.email),
escape(this.formatRole(u.role)), escape(u.program || ''),
escape(u.archived ? 'Archived' : 'Active'),
escape(this.formatDate(u.lastLogin))
escape(this.formatDate(u.lastLogin)),
escape(this.formatDate(u.lastAction))
].join(','))
const csv = [headers.join(','), ...rows].join('\n')
const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })
Expand Down Expand Up @@ -179,12 +181,13 @@ class AllUsersTable extends React.Component<Props, State> {
<SortHeader field="program" label="Program" />
<SortHeader field="archived" label="Status" />
<SortHeader field="lastLogin" label="Last Login" />
<SortHeader field="lastAction" label="Last Action" />
<th style={{ padding: '4px 8px', textAlign: 'center', fontSize: '1.25rem', fontWeight: 500 }}><strong>Edit</strong></th>
</tr>
</thead>
<tbody>
{paginated.length === 0 ? (
<tr><TableCell colSpan={8} style={{ textAlign: 'center', padding: 40 }}>No users found</TableCell></tr>
<tr><TableCell colSpan={9} style={{ textAlign: 'center', padding: 40 }}>No users found</TableCell></tr>
) : paginated.map(user => (
<TableRow key={user.id}>
<TableCell>{user.lastName}</TableCell>
Expand All @@ -204,6 +207,7 @@ class AllUsersTable extends React.Component<Props, State> {
</Tooltip>
</TableCell>
<TableCell>{this.formatDate(user.lastLogin)}</TableCell>
<TableCell>{this.formatDate(user.lastAction)}</TableCell>
<TableCell onClick={e => e.stopPropagation()} style={{ textAlign: 'center' }}>
<Tooltip title="Edit user">
<IconButton size="small" onClick={() => this.props.onUserClick?.(user)}>
Expand Down
1 change: 1 addition & 0 deletions src/constants/Types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ export interface User {
id: string
}>,
lastLogin?: Date,
lastAction?: Date,
email?: string,
school?: string,
program?: string,
Expand Down
Loading