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
100 changes: 96 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 and type for all users by querying activity collections.
* Uses optimized approach: 5 total queries instead of per-user queries.
* @returns Map<userId, {date: Date, type: string}> - Last action info per user
*/
getUsersLastAction = async (): Promise<Map<string, { date: Date; type: string }>> => {
const lastActionMap = new Map<string, { date: Date; type: string }>()

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

// 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, 'Observation')
})

// 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, 'Training')
})

// 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, 'Conference Plan')
updateIfNewer(userId, modified, 'Conference Plan')
})

// 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, 'Action Plan')
updateIfNewer(userId, modified, 'Action Plan')
})

// 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, 'Email')
updateIfNewer(senderId, modified, 'Email')
updateIfNewer(recipientId, created, 'Email')
updateIfNewer(recipientId, modified, 'Email')
})

return lastActionMap
}

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

// 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 @@ -4791,6 +4880,7 @@ class Firebase {
}
}
}
const lastActionData = lastActionMap.get(doc.id)
result.push({
id: doc.id,
firstName: data.firstName || '',
Expand All @@ -4800,6 +4890,8 @@ class Firebase {
program: programName,
archived: data.archived || false,
lastLogin: data.lastLogin ? data.lastLogin.toDate() : null,
lastAction: lastActionData?.date || null,
lastActionType: lastActionData?.type || '',
})
})

Expand Down
25 changes: 18 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 @@ -108,15 +109,23 @@ class AllUsersTable extends React.Component<Props, State> {

formatDate = (d: Date | null) => d ? d.toLocaleString([], { dateStyle: 'short', timeStyle: 'short' }) : 'Never'

formatLastAction = (user: Types.User) => {
if (!user.lastAction) return 'Never'
const date = user.lastAction.toLocaleString([], { dateStyle: 'short', timeStyle: 'short' })
return user.lastActionType ? `${user.lastActionType} - ${date}` : date
}

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', 'Action Type']
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)),
escape(u.lastActionType || '')
].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 +188,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 +214,7 @@ class AllUsersTable extends React.Component<Props, State> {
</Tooltip>
</TableCell>
<TableCell>{this.formatDate(user.lastLogin)}</TableCell>
<TableCell>{this.formatLastAction(user)}</TableCell>
<TableCell onClick={e => e.stopPropagation()} style={{ textAlign: 'center' }}>
<Tooltip title="Edit user">
<IconButton size="small" onClick={() => this.props.onUserClick?.(user)}>
Expand Down
2 changes: 2 additions & 0 deletions src/constants/Types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,8 @@ export interface User {
id: string
}>,
lastLogin?: Date,
lastAction?: Date,
lastActionType?: string,
email?: string,
school?: string,
program?: string,
Expand Down
2 changes: 1 addition & 1 deletion src/views/protected/AdminViews/AllUsersPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class AllUsersPage extends React.Component<Props, State> {
handleUserClick = (user: Types.User) => {
this.setState({
selected: user, firstName: user.firstName, lastName: user.lastName,
email: user.email, editOpen: true,
email: user.email || '', editOpen: true,
})
}

Expand Down
128 changes: 122 additions & 6 deletions src/views/protected/UsersViews/UsersPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import AppBar from "../../../components/AppBar";
import Grid from "@material-ui/core/Grid";
import { Dialog, DialogTitle, DialogContent, DialogActions, Button, TextField, Typography } from "@material-ui/core";
import FirebaseContext from "../../../components/Firebase/FirebaseContext";
import { coachLoaded, Role } from '../../../state/actions/coach'
import { connect } from 'react-redux';
Expand Down Expand Up @@ -112,6 +113,12 @@ interface State {
sendToSites: Array<Object>
allUsers: Types.User[]
allUsersLoading: boolean
editDialogOpen: boolean
archiveDialogOpen: boolean
selectedUser: Types.User | null
editFirstName: string
editLastName: string
editEmail: string
}

function checkCurrent(item: string) {
Expand Down Expand Up @@ -142,7 +149,13 @@ class UsersPage extends React.Component<Props, State> {
propFilter: [],
sendToSites: [],
allUsers: [],
allUsersLoading: true
allUsersLoading: true,
editDialogOpen: false,
archiveDialogOpen: false,
selectedUser: null,
editFirstName: '',
editLastName: '',
editEmail: ''
}
}

Expand Down Expand Up @@ -569,17 +582,53 @@ class UsersPage extends React.Component<Props, State> {
}

handleAllUserClick = (user: Types.User) => {
// Could open edit dialog - for now just log
console.log('User clicked:', user)
this.setState({
selectedUser: user,
editFirstName: user.firstName,
editLastName: user.lastName,
editEmail: user.email || '',
editDialogOpen: true
})
}

handleEditSave = async () => {
const { selectedUser, editFirstName, editLastName, editEmail } = this.state
if (!selectedUser || !editFirstName.trim() || !editLastName.trim()) {
alert('Name is required')
return
}

await this.context.editUserName(selectedUser.id, editFirstName, editLastName, editEmail, selectedUser.role)
this.setState(s => ({
allUsers: s.allUsers.map(u => u.id === selectedUser.id
? { ...u, firstName: editFirstName, lastName: editLastName, email: editEmail }
: u
),
editDialogOpen: false,
selectedUser: null
}))
}

handleAllUserArchive = async (user: Types.User) => {
await this.context.db.collection('users').doc(user.id).update({ archived: !user.archived })
handleArchiveFromEdit = () => {
this.setState({ editDialogOpen: false, archiveDialogOpen: true })
}

handleArchiveConfirm = async () => {
const { selectedUser } = this.state
if (!selectedUser) return

await this.context.db.collection('users').doc(selectedUser.id).update({ archived: !selectedUser.archived })
this.setState(s => ({
allUsers: s.allUsers.map(u => u.id === user.id ? { ...u, archived: !user.archived } : u)
allUsers: s.allUsers.map(u => u.id === selectedUser.id ? { ...u, archived: !selectedUser.archived } : u),
archiveDialogOpen: false,
selectedUser: null
}))
}

handleAllUserArchive = (user: Types.User) => {
this.setState({ selectedUser: user, archiveDialogOpen: true })
}

static propTypes = {
classes: PropTypes.exact({
root: PropTypes.string,
Expand Down Expand Up @@ -735,6 +784,73 @@ class UsersPage extends React.Component<Props, State> {
</Grid>
</Grid>
</div>

{/* Edit User Dialog */}
<Dialog open={this.state.editDialogOpen} onClose={() => this.setState({ editDialogOpen: false })} maxWidth="sm" fullWidth>
<DialogTitle>Edit User</DialogTitle>
<DialogContent>
<Grid container spacing={2} style={{ marginTop: 8 }}>
<Grid item xs={6}>
<TextField
fullWidth
label="First Name"
variant="outlined"
value={this.state.editFirstName}
onChange={e => this.setState({ editFirstName: e.target.value })}
/>
</Grid>
<Grid item xs={6}>
<TextField
fullWidth
label="Last Name"
variant="outlined"
value={this.state.editLastName}
onChange={e => this.setState({ editLastName: e.target.value })}
/>
</Grid>
<Grid item xs={12}>
<TextField
fullWidth
label="Email"
variant="outlined"
value={this.state.editEmail}
onChange={e => this.setState({ editEmail: e.target.value })}
/>
</Grid>
</Grid>
</DialogContent>
<DialogActions>
<Button
onClick={this.handleArchiveFromEdit}
color={this.state.selectedUser?.archived ? 'primary' : 'secondary'}
>
{this.state.selectedUser?.archived ? 'Unarchive' : 'Archive'}
</Button>
<div style={{ flex: 1 }} />
<Button onClick={() => this.setState({ editDialogOpen: false })}>Cancel</Button>
<Button onClick={this.handleEditSave} color="primary" variant="contained">Save</Button>
</DialogActions>
</Dialog>

{/* Archive Confirmation Dialog */}
<Dialog open={this.state.archiveDialogOpen} onClose={() => this.setState({ archiveDialogOpen: false })}>
<DialogTitle>{this.state.selectedUser?.archived ? 'Unarchive' : 'Archive'} User</DialogTitle>
<DialogContent>
<Typography>
Are you sure you want to {this.state.selectedUser?.archived ? 'unarchive' : 'archive'} {this.state.selectedUser?.firstName} {this.state.selectedUser?.lastName}?
</Typography>
</DialogContent>
<DialogActions>
<Button onClick={() => this.setState({ archiveDialogOpen: false })}>Cancel</Button>
<Button
onClick={this.handleArchiveConfirm}
color={this.state.selectedUser?.archived ? 'primary' : 'secondary'}
variant="contained"
>
{this.state.selectedUser?.archived ? 'Unarchive' : 'Archive'}
</Button>
</DialogActions>
</Dialog>
</div>
);
}
Expand Down
Loading