Files
cmc_frontend/src/lib/facultyData.ts
2025-10-09 20:05:39 +05:30

237 lines
7.4 KiB
TypeScript

// lib/facultyData.ts
export interface TeamMember {
id: number;
professorId: string;
name: string;
firstName: string;
lastName: string;
position: string;
designation: string;
image: string;
profileUrl?: string;
phone: string;
email: string;
experience: string;
description: string;
specialty: string;
certification: string;
training: string;
workDays: string[];
skills: Skill[];
awards: Award[];
status?: string;
department?: string;
officeLocation?: string;
joinDate?: string;
category: string;
}
export interface Skill {
name: string;
level?: number;
}
export interface Award {
title: string;
year: string;
description: string;
image: string;
}
export interface FacultyApiResponse {
content: TeamMember[];
last: boolean;
first: boolean;
totalElements: number;
size: number;
numberOfElements: number;
number: number;
empty: boolean;
}
// API service class
export class FacultyService {
private static baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8080';
static async getAllFaculty(): Promise<TeamMember[]> {
try {
const response = await fetch(`${this.baseUrl}/professor?size=100`, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: FacultyApiResponse = await response.json();
return this.transformProfessorsToTeamMembers(data.content);
} catch (error) {
console.error('Error fetching faculty data:', error);
return this.getFallbackData();
}
}
static async getFacultyById(id: number): Promise<TeamMember | null> {
try {
// Find by array index from getAllFaculty for now
// In production, you might want a direct API call
const allFaculty = await this.getAllFaculty();
return allFaculty.find(member => member.id === id) || null;
} catch (error) {
console.error('Error fetching faculty member:', error);
return null;
}
}
static async getFacultyByProfessorId(professorId: string): Promise<TeamMember | null> {
try {
const response = await fetch(`${this.baseUrl}/professor/${professorId}`, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const professor = await response.json();
const transformed = this.transformProfessorsToTeamMembers([professor]);
return transformed[0] || null;
} catch (error) {
console.error('Error fetching professor by ID:', error);
return null;
}
}
static async getFacultyByCategory(category: string): Promise<TeamMember[]> {
try {
const allFaculty = await this.getAllFaculty();
return allFaculty.filter(member => member.category === category);
} catch (error) {
console.error('Error fetching faculty by category:', error);
return [];
}
}
// Helper method to check if an image URL is accessible
static async checkImageExists(imageUrl: string): Promise<boolean> {
try {
const response = await fetch(imageUrl, { method: 'HEAD' });
return response.ok;
} catch (error) {
return false;
}
}
// Helper method to get a working image URL with fallback
static async getWorkingImageUrl(originalUrl: string, fallbackUrl: string = '/images/default-avatar.jpg'): Promise<string> {
const isAccessible = await this.checkImageExists(originalUrl);
return isAccessible ? originalUrl : fallbackUrl;
}
private static transformProfessorsToTeamMembers(professors: any[]): TeamMember[] {
return professors.map((prof, index) => {
// Create proper image URL - remove /api from baseUrl for images
const imageBaseUrl = this.baseUrl;
let imageUrl = '/images/default-avatar.jpg'; // Default fallback
if (prof.profileImageUrl) {
// If it's already a full URL, use it as is
if (prof.profileImageUrl.startsWith('http')) {
imageUrl = prof.profileImageUrl;
} else {
// If it's a relative URL, construct the full URL
imageUrl = `${imageBaseUrl}${prof.profileImageUrl}`;
}
}
return {
id: index + 1, // Generate sequential ID for UI
professorId: prof.professorId,
name: prof.name || `${prof.firstName} ${prof.lastName}`,
firstName: prof.firstName,
lastName: prof.lastName,
position: prof.position || 'Faculty Member',
designation: prof.designation || prof.position || 'Faculty Member',
image: imageUrl,
profileUrl: `/faculty/${index + 1}`,
phone: prof.phone || 'Not available',
email: prof.email,
experience: prof.experience || 'Not specified',
description: prof.description || `${prof.firstName} ${prof.lastName} is a dedicated member of our faculty.`,
specialty: prof.specialty || prof.department || 'General Medicine',
certification: prof.certification || 'Medical certification details not available',
training: prof.training || 'Professional training details not available',
workDays: prof.workDays || ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
skills: prof.skills?.map((skill: any) => ({
name: skill.name,
level: skill.level
})) || [
{ name: 'Clinical Practice', level: 90 },
{ name: 'Research', level: 85 },
{ name: 'Teaching', level: 88 }
],
awards: prof.awards?.map((award: any) => ({
title: award.title,
year: award.year,
description: award.description,
image: award.imageUrl || '/images/award-icon.png'
})) || [
{
title: 'Excellence in Medical Practice',
year: new Date().getFullYear().toString(),
description: 'Recognized for outstanding contribution to medical practice and patient care.',
image: '/images/award-icon.png'
}
],
status: prof.status,
department: prof.department,
officeLocation: prof.officeLocation,
joinDate: prof.joinDate,
category: prof.category || 'FACULTY'
};
});
}
private static getFallbackData(): TeamMember[] {
return [
{
id: 1,
professorId: 'fallback-1',
name: "Loading Faculty Data...",
firstName: "Loading",
lastName: "Data",
position: "Please wait while we fetch the latest faculty information",
designation: "System Message",
image: "/images/default-avatar.jpg",
phone: "Not available",
email: "support@institution.edu",
experience: "N/A",
description: "Faculty data is currently being loaded from the server.",
specialty: "N/A",
certification: "N/A",
training: "N/A",
workDays: [],
skills: [],
awards: [],
category: 'FACULTY'
}
];
}
}
// Helper function to get team members (for backward compatibility)
export const getTeamMembers = async (): Promise<TeamMember[]> => {
return await FacultyService.getAllFaculty();
};
// Helper function to get team member by ID
export const getTeamMemberById = async (id: number): Promise<TeamMember | null> => {
return await FacultyService.getFacultyById(id);
};