Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ПЗ_23-ИСТ-1-1_Какушкина_Ольга_Витальевна

.pdf
Скачиваний:
0
Добавлен:
23.06.2025
Размер:
2.84 Mб
Скачать

FooterComponent,

ButtonComponent,

RegistrationComponent,

CommonModule,

HttpClientModule ],

templateUrl: './main-page.component.html', styleUrls: ['./main-page.component.scss'], providers: [SectionService,TeacherService ]

})

export class MainPageComponent implements OnInit { sections: Section[] = [];

teachers: Teacher[] = [];

constructor(

private sectionService: SectionService, private teacherService: TeacherService

) {}

ngOnInit() { this.loadSections(); this.loadTeachers();

}

loadSections() { this.sectionService.getSections().subscribe(sections => {

this.sections = sections; // Загружаем обновленные секции

});

}

loadTeachers() { this.teacherService.getTeachers().subscribe({

next: (teachers) => { this.teachers = teachers;

},

error: (err) => {

console.error('Ошибка при загрузке преподавателей:', err); },

});

}

getTeacherNameById(teacherId: string): string {

const teacher = this.teachers.find((t) => t.id === teacherId);

return teacher ? `${teacher.firstName} ${teacher.lastName}` : 'Неизвестный преподаватель';

}

}

Student-page.component.ts

 

Лист

НГТУ-(23-ИСТ-1-1)-КР

 

61

 

Изм. Лист

№ докум.

Подпись Дата

import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common';

import { HttpClientModule } from "@angular/common/http";

import { HeaderComponent } from '../../shared/header/header.component'; import { FooterComponent } from '../../shared/footer/footer.component'; import { AuthService } from '../../services/auth.service';

import { FormsModule } from '@angular/forms'; import { DataService } from '../../services/data.service'; import { Student } from '../../models/student.model';

import { TeacherService } from '../../services/teacher.service'; import { StudentService } from '../../services/student.service'; import { SectionService } from '../../services/section.service';

@Component({

selector: 'app-student-page', standalone: true,

imports: [HeaderComponent, FooterComponent, HttpClientModule, CommonModule, FormsModule],

templateUrl: './student-page.component.html', styleUrls: ['./student-page.component.scss'],

providers: [AuthService, DataService, TeacherService, StudentService, SectionService] })

export class StudentPageComponent implements OnInit { student: Student | null = null;

newPassword: string = ''; updatedEmail: string = ''; isEditingEmail: boolean = false;

instituteName: string | undefined; sectionName: string | undefined; sectionDetails: any;

constructor(

private studentService: StudentService, private sectionService: SectionService

) {}

ngOnInit() {

const storedStudent = localStorage.getItem('student'); if (storedStudent) {

this.student = JSON.parse(storedStudent); this.loadInstituteAndSectionNames();

} else {

console.error('Данные студента не найдены.');

}

}

private loadInstituteAndSectionNames() { if (this.student) {

this.sectionService.getInstituteById(this.student.institute).subscribe( (response: { name: string }) => {

НГТУ-(23-ИСТ-1-1)-КР

Изм. Лист

№ докум.

Подпись Дата

Лист

62

this.instituteName = response.name; },

(error: any) => {

console.error('Ошибка при получении института:', error); this.instituteName = 'Не удалось загрузить институт. Попробуйте позже.';

}

);

// Получаем данные секции по ID this.sectionService.getSectionById(this.student.section).subscribe(

(response: any) => { // Убедитесь, что вы используете нужный тип this.sectionDetails = response;

this.sectionName = response.title; },

(error: any) => {

console.error('Ошибка при загрузке секции:', error); this.sectionDetails = null;

this.sectionName = 'Ошибка загрузки секции. Попробуйте позже.';

}

);

}

}

updateEmail() { if (this.student) {

this.student.email = this.updatedEmail; this.studentService.updateStudentEmail(this.student).subscribe(

() => {

console.log('Email успешно обновлен'); this.isEditingEmail = false;

localStorage.setItem('student', JSON.stringify(this.student)); },

(error: any) => console.error('Ошибка при обновлении email:', error) );

}

}

updatePassword() { if (this.student) {

this.studentService.updateStudentPassword(this.student.id, this.newPassword).subscribe( () => {

console.log('Пароль успешно обновлен'); this.newPassword = '';

},

(error: any) => console.error('Ошибка при обновлении пароля:', error) );

}

}

}

Teacher-add.component.ts

НГТУ-(23-ИСТ-1-1)-КР

Изм. Лист

№ докум.

Подпись Дата

Лист

63

import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common';

import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { FormsModule } from '@angular/forms';

import { TeacherService } from '../../services/teacher.service'; import { Teacher } from '../../models/teacher.model';

import { Section } from '../../models/section.model';

import { HttpClientModule } from '@angular/common/http'; import { ReactiveFormsModule } from '@angular/forms';

import { HeaderComponent } from '../../shared/header/header.component'; import { FooterComponent } from '../../shared/footer/footer.component';

@Component({

selector: 'app-teacher-add', imports: [HttpClientModule,

ReactiveFormsModule,

CommonModule,

FormsModule,

HeaderComponent,

FooterComponent],

templateUrl: './teacher-add.component.html', styleUrl: './teacher-add.component.scss', providers:[TeacherService]

})

export class TeacherAddComponent implements OnInit { teacherForm!: FormGroup;

teachers: Teacher[] = []; sections: Section[] = []; editMode: boolean = false;

currentEditingTeacher!: Teacher | null; showPassword: boolean = false;

constructor(private fb: FormBuilder, private teacherService: TeacherService) { this.teachers = [];

}

ngOnInit(): void { this.createForm(); this.loadTeachers(); this.loadSections();

}

loadSections(): void { this.teacherService.getSections().subscribe((data: Section[]) => {

this.sections = data;

console.log('Секции загружены:', this.sections); // Выводим массив секций в консоль

});

}

togglePasswordVisibility() {

this.showPassword = !this.showPassword; // Переключение видимости пароля

НГТУ-(23-ИСТ-1-1)-КР

Изм. Лист

№ докум.

Подпись Дата

Лист

64

}

createForm() {

this.teacherForm = this.fb.group({ firstName: ['', Validators.required], lastName: ['', Validators.required],

email: ['', [Validators.required, Validators.email]],

password: ['', [Validators.minLength(6)]], // пароля нет в required, чтобы не требовать его при редактировании

experience: ['', Validators.required], university: ['', Validators.required], photoUrl: [''],

sections: [[]] });

}

loadTeachers() { this.teacherService.getTeachers().subscribe((data) => {

this.teachers = data;

this.teachers = data.map(teacher => ({ ...teacher, isEditing: false })); });

}

onSubmit() {

if (this.teacherForm.valid) {

const teacher: Teacher = this.teacherForm.value;

if (this.editMode && this.currentEditingTeacher) { // Обновляем данные преподавателя

teacher.id = this.currentEditingTeacher.id; // Сохраняем id для обновления this.teacherService.updateTeacher(teacher).subscribe(() => {

const index = this.teachers.findIndex(t => t.id === teacher.id); if (index !== -1) {

this.teachers[index] = teacher; // Обновляем данные в списке

}

this.resetForm();

});

}else {

//Добавляем нового преподавателя teacher.id = Date.now().toString();

this.teacherService.addTeacher(teacher).subscribe(newTeacher => { this.teachers.push(newTeacher);

this.resetForm();

});

}

}

}

editTeacher(teacher: Teacher) {

this.editMode = true; // Включаем режим редактирования

 

Лист

НГТУ-(23-ИСТ-1-1)-КР

 

65

 

Изм. Лист

№ докум.

Подпись Дата

this.currentEditingTeacher = teacher; // Сохраняем текущего редактируемого преподавателя

this.teacherForm.patchValue(teacher); // Заполняем форму данными преподавателя

}

resetForm() { this.teacherForm.reset(); this.editMode = false; this.currentEditingTeacher = null;

}

scrollToForm() {

const anchor = document.getElementById('form-header'); if (anchor) {

anchor.scrollIntoView({ behavior: 'smooth' });

}

}

deleteTeacher(id: string) { this.teacherService.deleteTeacher(id).subscribe(() => {

this.teachers = this.teachers.filter(teacher => teacher.id !== id); });

}

getSectionTitleById(sectionId: string): string { console.log('Ищем секцию с ID:', sectionId); // Вывод ID const section = this.sections.find(s => s.id === sectionId); return section ? section.title : 'Неизвестная секция';

}

}

Teacher-page.component.ts

import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms';

import { HttpClientModule } from "@angular/common/http";

import { HeaderComponent } from '../../shared/header/header.component'; import { FooterComponent } from '../../shared/footer/footer.component'; import { Router } from '@angular/router';

import { TeacherService } from '../../services/teacher.service'; import { Teacher } from '../../models/teacher.model';

@Component({

selector: 'app-teacher-page', standalone: true,

imports: [CommonModule, FormsModule, HeaderComponent, FooterComponent, HttpClientModule],

templateUrl: './teacher-page.component.html', styleUrls: ['./teacher-page.component.scss'],

НГТУ-(23-ИСТ-1-1)-КР

Изм. Лист

№ докум.

Подпись Дата

Лист

66

providers: [ TeacherService], })

export class TeacherPageComponent implements OnInit { currentUser!: Teacher;

updatedEmail: string = ''; updatedPassword: string = ''; selectedFile: File | null = null;

additionalInfoFields: { label: string; value: string }[] = []; newFieldLabel: string = '';

newFieldValue: string = ''; isEditingEmail: boolean = false; isEditingPassword: boolean = false; photoUrl: string | null = null; sectionNames: string[] = []; schedule: any[] = [];

constructor(

private teacherService: TeacherService, private router: Router,

) {}

ngOnInit() { this.loadCurrentUserData();

}

getSectionsNames(sectionIds: string[]) {

// Тут мы делаем запрос для каждой секции sectionIds.forEach(sectionId => {

//Преобразуем sectionId в number, если это необходимо const id = Number(sectionId);

//Если id - действительно число, можно вызвать метод if (!isNaN(id)) {

this.teacherService.getSectionById(id).subscribe( response => {

this.sectionNames.push(response.title); // Предполагается, что ответ включает

поле `title`

this.getSchedule(sectionId);

},

error => {

console.error('Ошибка при получении названия секции:', error);

}

);

} else {

console.error('Неверный ID секции:', sectionId);

}

});

}

uploadPhoto() {

if (!this.selectedFile) {

НГТУ-(23-ИСТ-1-1)-КР

Изм. Лист

№ докум.

Подпись Дата

Лист

67

return; // Не выполнять действие, если файл не выбран

}

const formData = new FormData(); formData.append('file', this.selectedFile);

// Загружаем новую фотографию this.teacherService.uploadPhoto(formData).subscribe(

(response) => {

console.log('Фотография загружена:', response); this.photoUrl = response.imageUrl;

this.currentUser.photoUrl = this.photoUrl; // Обновляем URL в объекте текущего пользователя

this.updateTeacherInfo(); // Сохраняем изменения в базе данных this.selectedFile = null; // Сброс выбора файла

},

error => {

console.error('Ошибка при загрузке фотографии:', error);

}

);

}

onFileSelected(event: any) { this.selectedFile = event.target.files[0];

}

async updateTeacherInfo() { const updatedData = {

...this.currentUser, email: this.updatedEmail,

password: this.updatedPassword, // Сохранение нового поля photoUrl: this.photoUrl,

additionalInfo: this.additionalInfoFields, };

this.teacherService.updateTeacherInfo(this.currentUser.id, updatedData).subscribe( () => {

console.log('Информация о преподавателе успешно обновлена.'); localStorage.setItem('teacher', JSON.stringify(updatedData)); this.loadCurrentUserData();

},

(error) => {

console.error('Ошибка при обновлении информации о преподавателе:', error);

}

);

}

addAdditionalField() {

if (this.newFieldLabel && this.newFieldValue) {

this.additionalInfoFields.push({ label: this.newFieldLabel, value: this.newFieldValue });

НГТУ-(23-ИСТ-1-1)-КР

Изм. Лист

№ докум.

Подпись Дата

Лист

68

this.newFieldLabel = ''; this.newFieldValue = '';

}

}

removeAdditionalField(index: number) { this.additionalInfoFields.splice(index, 1);

}

onDoubleClickEmail() { this.isEditingEmail = true;

}

onBlurEmail() { this.isEditingEmail = false; this.updateTeacherInfo();

}

onDoubleClickPassword() {

this.isEditingPassword = true; // Включаем режим редактирования console.log('Редактирование пароля включено'); // Для отладки

}

onBlurPassword() {

this.isEditingPassword = false; // Выключаем режим редактирования this.updateTeacherInfo();

console.log('Редактирование пароля завершено'); // Для отладки

}

loadCurrentUserData() {

const user = localStorage.getItem('teacher'); if (user) {

this.currentUser = JSON.parse(user); this.updatedEmail = this.currentUser.email ?? '';

this.updatedPassword = this.currentUser.password ?? ''; // Це значение должно корректно загружаться из localStorage

this.photoUrl = this.currentUser.photoUrl ?? ''; this.getSectionsNames(this.currentUser.sections);

} else {

console.error('Учитель не найден, перенаправляем на страницу входа...'); this.router.navigate(['teacher-auth-form']);

}

}

getSchedule(sectionId: string) { this.teacherService.getScheduleBySectionId(sectionId).subscribe(

(schedule) => {

this.schedule.push(schedule); // Добавляем расписание в массив

},

error => {

console.error('Ошибка при получении расписания:', error);

 

Лист

НГТУ-(23-ИСТ-1-1)-КР

 

69

 

Изм. Лист

№ докум.

Подпись Дата

}

);

}

}

Server.js

const express = require('express'); const multer = require('multer'); const cors = require('cors');

const path = require('path'); const fs = require('fs');

/// Настройки для загрузки файлов

const uploadFolder = path.join(__dirname, 'images'); if (!fs.existsSync(uploadFolder)) {

fs.mkdirSync(uploadFolder);

}

const app = express(); app.use(cors());

app.use(express.json()); // Для обработки JSON const upload = multer({ dest: uploadFolder });

//Статическая раздача файлов из папки images app.use('/images', express.static(uploadFolder));

//Роут для загрузки файлов

app.post('/upload', upload.single('file'), (req, res) => { if (req.file) {

const imageUrl = `http://localhost:3002/images/${req.file.filename}`; res.json({ imageUrl });

} else {

res.status(400).json({ message: 'Файл не загружен' });

}

});

// Считываем текущие секции из db.json const getSections = () => {

if (!fs.existsSync('C:/Users/user/SectionStud/public/db.json')) { return [];

}

const data = fs.readFileSync('C:/Users/user/SectionStud/public/db.json'); return JSON.parse(data);

};

//Записываем секции в db.json const saveSections = (sections) => {

fs.writeFileSync('C:/Users/user/SectionStud/public/db.json', JSON.stringify(sections, null, 2)); };

//Роут для создания новой секции

 

Лист

НГТУ-(23-ИСТ-1-1)-КР

 

70

 

Изм. Лист

№ докум.

Подпись Дата

Соседние файлы в предмете Курсовая