Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Component } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { GrantExtensionFormComponent } from './grant-extension-form.component';
import { MatDialogModule } from '@angular/material/dialog';
import { CommonModule } from '@angular/common';

@Component({
selector: 'f-grant-extension-dialog',
standalone: true,
imports: [MatDialogModule, CommonModule, GrantExtensionFormComponent],
template: `
<h2 mat-dialog-title>Grant Extension</h2>
<mat-dialog-content>
<f-grant-extension-form></f-grant-extension-form>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button (click)="close()">Close</button>
</mat-dialog-actions>
`
})
export class GrantExtensionDialogComponent {
constructor(private dialogRef: MatDialogRef<GrantExtensionDialogComponent>) {}

close(): void {
this.dialogRef.close();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<h2 mat-dialog-title>Grant Extension</h2>
<form [formGroup]="grantExtensionForm" (ngSubmit)="submitForm()">

<mat-dialog-content [formGroup]="grantExtensionForm">
<!-- Student Selection with Search -->
<div class="w-full mb-4">
<mat-form-field appearance="fill" class="w-full">
<mat-label>Search Students</mat-label>
<input matInput
[(ngModel)]="searchQuery"
(ngModelChange)="filterStudents()"
(focus)="showStudentList = true"
[ngModelOptions]="{standalone: true}"
placeholder="Type to search students...">
</mat-form-field>

<!-- Select All Option -->
<div class="flex items-center px-2 mt-0" *ngIf="showStudentList">
<mat-checkbox
#selectAllBox
[checked]="selectedStudents.length === filteredStudents.length"
(change)="toggleSelectAll()"
(mouseup)="handleCheckboxBlur()"
color="primary"
disableRipple>
Select All
</mat-checkbox>
</div>

<!-- Student List -->
<div *ngIf="showStudentList"
class="student-list-container mt-4 mb-8"
style="max-height: 200px; min-height: 100px; overflow-y: auto; border: 1px solid #e0e0e0; border-radius: 4px; padding: 8px; scrollbar-width: thin; scrollbar-color: #888 #f1f1f1;">
<div *ngFor="let student of filteredStudents"
class="flex items-center px-4 py-2 cursor-pointer transition-colors duration-200"
[class.hover:bg-gray-100]="!isStudentSelected(student.id)"
[class.bg-blue-100]="isStudentSelected(student.id)"
(click)="toggleStudent(student.id)"
(keydown)="handleStudentKeydown($event, student.id)"
tabindex="0"
role="option"
[attr.aria-selected]="isStudentSelected(student.id)">
{{ student.name }} ({{ student.id }})
</div>
</div>

<mat-error *ngIf="grantExtensionForm.get('students')?.touched && grantExtensionForm.get('students')?.invalid">
Please select at least one student.
</mat-error>
</div>

<!-- Extension Duration -->
<div class="mb-8">
<label for="extension" class="block text-xl font-semibold text-gray-900 mb-4">
Extension Duration: <strong>{{ grantExtensionForm.get('extension')?.value }}</strong> day(s)
</label>

<mat-slider
min="1"
max="30"
step="1"
tickInterval="5"
thumbLabel
class="w-full"
style="width: 100%; max-width: 600px; min-width: 300px;"
>
<input matSliderThumb formControlName="extension" />
</mat-slider>
</div>

<!-- Reason Field -->
<mat-form-field appearance="fill" class="w-full mb-4">
<mat-label>Reason</mat-label>
<textarea
matInput
formControlName="reason"
rows="4"
required
></textarea>
<mat-error *ngIf="grantExtensionForm.get('reason')?.touched && grantExtensionForm.get('reason')?.invalid">
Please provide a reason for the extension.
</mat-error>
</mat-form-field>

<!-- Notes Field (Optional) -->
<mat-form-field appearance="fill" class="w-full mb-4">
<mat-label>Additional Notes (optional)</mat-label>
<textarea matInput formControlName="notes" rows="3"></textarea>
</mat-form-field>
</mat-dialog-content>

<!-- Form Buttons -->
<mat-dialog-actions align="end">
<button mat-button type="button" (click)="close()" [disabled]="isSubmitting">Cancel</button>
<button mat-flat-button color="primary" type="submit" [disabled]="isSubmitting">
Grant Extension
</button>
</mat-dialog-actions>
</form>

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { GrantExtensionFormComponent } from './grant-extension-form.component';

describe('GrantExtensionFormComponent', () => {
let component: GrantExtensionFormComponent;
let fixture: ComponentFixture<GrantExtensionFormComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [GrantExtensionFormComponent]
})
.compileComponents();

fixture = TestBed.createComponent(GrantExtensionFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatInputModule } from '@angular/material/input';
import { MatSliderModule } from '@angular/material/slider';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ExtensionService } from 'src/app/api/services/extension.service';
import { FormsModule } from '@angular/forms';
import { MatCheckboxModule } from '@angular/material/checkbox';

@Component({
selector: 'f-grant-extension-form',
standalone: true,
imports: [
ReactiveFormsModule,
CommonModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule,
MatSliderModule,
MatButtonModule,
MatDialogModule,
FormsModule,
MatCheckboxModule
],
templateUrl: './grant-extension-form.component.html'
})
export class GrantExtensionFormComponent implements OnInit {
grantExtensionForm!: FormGroup;
isSubmitting = false;
searchQuery = '';
selectedStudents: number[] = [];
showStudentList = false;

// Temporary values will be replaced with dynamic context
unitId = 1;
taskDefinitionId = 25;

// List of test students to choose from
students = [
{ id: 1, name: 'Joe M' },
{ id: 2, name: 'Sahiru W' },
{ id: 3, name: 'Samindi M' },
{ id: 4, name: 'Student 4' },
{ id: 5, name: 'Student 5' },
{ id: 6, name: 'Student 6' },
{ id: 7, name: 'Student 7' },
{ id: 8, name: 'Student 8' },
{ id: 9, name: 'Student 9' },
{ id: 10, name: 'Student 10' },
{ id: 11, name: 'Student 11' },
{ id: 12, name: 'Student 12' },
{ id: 13, name: 'Student 13' },
{ id: 14, name: 'Student 14' },
{ id: 15, name: 'Student 15' },
{ id: 16, name: 'Student 16' },
{ id: 17, name: 'Student 17' },
{ id: 18, name: 'Student 18' },
{ id: 19, name: 'Student 19' },
{ id: 20, name: 'Student 20' }
];
filteredStudents = this.students;
Comment on lines +43 to +66
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be list of students fetched from the backend?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the note! This PR specifically focuses on the Student Search and Select UI, building on PR #330. The current test list is for demo purposes—backend integration should be handled in a follow-up PR.


constructor(
private fb: FormBuilder,
private dialogRef: MatDialogRef<GrantExtensionFormComponent>,
private snackBar: MatSnackBar,
private extensionService: ExtensionService
) {}

// Initialize the reactive form with validators for each field
ngOnInit(): void {
this.grantExtensionForm = this.fb.group({
students: [[], Validators.required],
extension: [1, [Validators.required, Validators.min(1)]],
reason: ['', Validators.required],
notes: ['']
});
}

// Filters students based on search query
filterStudents(): void {
if (!this.searchQuery) {
this.filteredStudents = this.students;
} else {
const query = this.searchQuery.toLowerCase();
this.filteredStudents = this.students.filter(student =>
student.name.toLowerCase().includes(query) ||
student.id.toString().includes(query)
);
}
}

// Toggles student selection state
toggleStudent(studentId: number): void {
const index = this.selectedStudents.indexOf(studentId);
if (index === -1) {
this.selectedStudents.push(studentId);
} else {
this.selectedStudents.splice(index, 1);
}
this.grantExtensionForm.patchValue({ students: this.selectedStudents });
}

// Handles keyboard navigation for student selection
handleStudentKeydown(event: KeyboardEvent, studentId: number): void {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
this.toggleStudent(studentId);
}
}

// Toggles selection of all filtered students
toggleSelectAll(): void {
if (this.selectedStudents.length === this.filteredStudents.length) {
this.selectedStudents = [];
} else {
this.selectedStudents = this.filteredStudents.map(student => student.id);
}
this.grantExtensionForm.patchValue({ students: this.selectedStudents });
}

// Checks if a student is selected
isStudentSelected(studentId: number): boolean {
return this.selectedStudents.includes(studentId);
}

// Safely handles blur for checkboxes
handleCheckboxBlur(): void {
// This avoids calling blur() directly on the checkbox reference
// which can cause errors when the reference isn't to a DOM element
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur();
}
}

// Handles form submission.
// Builds the payload and sends it to the backend via the ExtensionService.
// Displays a success or error message and closes the dialog on success.
submitForm(): void {
if (this.grantExtensionForm.invalid) {
this.grantExtensionForm.markAllAsTouched();
return;
}

this.isSubmitting = true;

const { students, extension, reason, notes } = this.grantExtensionForm.value;
const unitId = 1; // temporary value
const payload = {
student_ids: students,
task_definition_id: 25,
weeks_requested: extension,
comment: reason,
notes: notes,
};

this.extensionService.grantExtension(unitId, payload).subscribe({
next: () => {
this.snackBar.open('Extension granted successfully!', 'Close', { duration: 3000 });
this.dialogRef.close(true);
},
error: (error) => {
const errorMsg = error?.error?.message || 'An unexpected error occurred. Please try again.';
this.snackBar.open(`Failed to grant extension: ${errorMsg}`, 'Close', { duration: 5000 });
console.error('Grant Extension Error:', error);
},
complete: () => {
this.isSubmitting = false;
}
});
}

// Closes the dialog without submitting the form
close(): void {
this.dialogRef.close();
}
}
2 changes: 1 addition & 1 deletion src/app/api/services/authentication.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export class AuthenticationService {
remember: boolean;
},
): Observable<any> {
return this.httpClient.post(this.AUTH_URL, userCredentials).pipe(
return this.httpClient.post(this.AUTH_URL, userCredentials, { withCredentials: true }).pipe(
map((response: any) => {
// Extract relevant data from response and construct user object to store in cache.
const user: User = this.userService.cache.getOrCreate(
Expand Down
38 changes: 38 additions & 0 deletions src/app/api/services/extension.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { UserService } from 'src/app/api/models/doubtfire-model';

interface GrantExtensionPayload {
student_ids: number[];
task_definition_id: number;
weeks_requested: number;
comment: string;
notes?: string;
}

@Injectable({
providedIn: 'root'
})
export class ExtensionService {
constructor(
private http: HttpClient,
private userService: UserService
) {}

grantExtension(unitId: number, payload: GrantExtensionPayload): Observable<any> {
const authToken = this.userService.currentUser?.authenticationToken ?? '';
const username = this.userService.currentUser?.username ?? '';

const headers = new HttpHeaders({
'Auth-Token': authToken,
'Username': username
});

return this.http.post(
`/api/units/${unitId}/staff-grant-extension`,
payload,
{ headers }
);
}
}
Loading