From f4a4dc158af7f27874c1ca41aed48fdd8b9615c7 Mon Sep 17 00:00:00 2001 From: M Fari Madyan Date: Tue, 13 Oct 2026 07:35:16 +0700 Subject: [PATCH 1/5] chore(backend): configure database defaults, add csv gem, and generate schema --- backend/.gitignore | 3 + backend/Gemfile | 3 + backend/Gemfile.lock | 3 + backend/config/database.yml | 4 +- backend/db/schema.rb | 270 ++++++++++++++++++++++++++++++++++++ 5 files changed, 281 insertions(+), 2 deletions(-) create mode 100644 backend/db/schema.rb diff --git a/backend/.gitignore b/backend/.gitignore index e30bb69..b709bae 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -31,3 +31,6 @@ # Ignore key files for decrypting credentials and more. /config/*.key +# RSpec runtime files +/spec/examples.txt + diff --git a/backend/Gemfile b/backend/Gemfile index 47b9e08..e9a7cd6 100644 --- a/backend/Gemfile +++ b/backend/Gemfile @@ -23,6 +23,9 @@ gem "rack-cors" # Redis client for cache and Action Cable gem "redis", "~> 5.1" +# CSV gem (bundled gem in Ruby 3.4+) +gem "csv" + # Roo for reading Excel (.xlsx, .xls) files gem "roo", "~> 2.10" diff --git a/backend/Gemfile.lock b/backend/Gemfile.lock index 43738e1..25baeed 100644 --- a/backend/Gemfile.lock +++ b/backend/Gemfile.lock @@ -90,6 +90,7 @@ GEM concurrent-ruby (1.3.8) connection_pool (3.0.2) crass (1.0.7) + csv (3.3.6) database_cleaner-active_record (2.2.2) activerecord (>= 5.a) database_cleaner-core (~> 2.0) @@ -339,6 +340,7 @@ DEPENDENCIES bcrypt (~> 3.1.7) bootsnap caxlsx (~> 4.2) + csv database_cleaner-active_record debug factory_bot_rails @@ -378,6 +380,7 @@ CHECKSUMS concurrent-ruby (1.3.8) sha256=b2f1be836e968ccc78ccfce277ea79c72a88633f22306782c16ff23fb415d1e1 connection_pool (3.0.2) sha256=33fff5ba71a12d2aa26cb72b1db8bba2a1a01823559fb01d29eb74c286e62e0a crass (1.0.7) sha256=94868719948664c89ddcaf0a37c65048413dfcb1c869470a5f7a7ceb5390b295 + csv (3.3.6) sha256=aba61e7e507a66f03d45cb1f3c4b6359861c3504038b422962875dce099e4456 database_cleaner-active_record (2.2.2) sha256=88296b9f3088c31f7c0d4fcec10f68e4b71c96698043916de59b04debec10388 database_cleaner-core (2.1.0) sha256=b2875266d9b26b716e8b669c883e01c5250839f6f2ec56422b5e79aa97fb6927 date (3.6.0) sha256=18ac945c4e24ebd93534f8eab8c2fd8c5604b3e977105b3798d62a1e8d27b580 diff --git a/backend/config/database.yml b/backend/config/database.yml index df5fdd9..c16d76c 100644 --- a/backend/config/database.yml +++ b/backend/config/database.yml @@ -6,11 +6,11 @@ default: &default development: <<: *default - url: <%= ENV.fetch("DATABASE_URL") { "postgresql://postgres:postgres@localhost:5432/elearning" } %> + url: <%= ENV.fetch("DATABASE_URL") { "postgresql://postgres:postgres@localhost:5435/elearning" } %> test: <<: *default - url: <%= ENV.fetch("DATABASE_URL") { "postgresql://postgres:postgres@localhost:5432/elearning_test" } %> + url: <%= ENV.fetch("DATABASE_URL") { "postgresql://postgres:postgres@localhost:5435/elearning_test" } %> production: <<: *default diff --git a/backend/db/schema.rb b/backend/db/schema.rb new file mode 100644 index 0000000..7968e3c --- /dev/null +++ b/backend/db/schema.rb @@ -0,0 +1,270 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema[8.1].define(version: 2026_10_09_000001) do + # These are extensions that must be enabled in order to support this database + enable_extension "pg_catalog.plpgsql" + + create_table "announcements", force: :cascade do |t| + t.string "title", null: false + t.text "content", null: false + t.string "target", default: "all", null: false + t.boolean "published", default: true, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "assignment_discussions", force: :cascade do |t| + t.bigint "assignment_id", null: false + t.bigint "user_id", null: false + t.bigint "parent_id" + t.text "message", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["assignment_id"], name: "index_assignment_discussions_on_assignment_id" + t.index ["parent_id"], name: "index_assignment_discussions_on_parent_id" + t.index ["user_id"], name: "index_assignment_discussions_on_user_id" + end + + create_table "assignment_submissions", force: :cascade do |t| + t.bigint "assignment_id", null: false + t.bigint "student_id", null: false + t.string "file_path" + t.text "notes" + t.decimal "score", precision: 5, scale: 2 + t.text "feedback" + t.string "status", default: "submitted", null: false + t.datetime "submitted_at", null: false + t.datetime "graded_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["assignment_id", "student_id"], name: "index_assignment_submissions_on_assignment_id_and_student_id", unique: true + t.index ["assignment_id"], name: "index_assignment_submissions_on_assignment_id" + t.index ["student_id"], name: "index_assignment_submissions_on_student_id" + end + + create_table "assignments", force: :cascade do |t| + t.bigint "teacher_id", null: false + t.bigint "subject_id", null: false + t.bigint "classroom_id", null: false + t.string "title", null: false + t.text "description" + t.text "instructions" + t.integer "max_score", default: 100, null: false + t.datetime "due_date", null: false + t.boolean "allow_late_submission", default: false, null: false + t.string "status", default: "published", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["classroom_id"], name: "index_assignments_on_classroom_id" + t.index ["subject_id"], name: "index_assignments_on_subject_id" + t.index ["teacher_id"], name: "index_assignments_on_teacher_id" + end + + create_table "classrooms", force: :cascade do |t| + t.string "name", null: false + t.integer "level", default: 10, null: false + t.integer "capacity", default: 36, null: false + t.string "academic_year", default: "2025/2026", null: false + t.bigint "homeroom_teacher_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["homeroom_teacher_id"], name: "index_classrooms_on_homeroom_teacher_id" + t.index ["name"], name: "index_classrooms_on_name" + end + + create_table "exam_answers", force: :cascade do |t| + t.bigint "exam_attempt_id", null: false + t.bigint "question_id", null: false + t.text "student_answer" + t.boolean "is_correct" + t.decimal "points_awarded", precision: 5, scale: 2, default: "0.0" + t.datetime "graded_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["exam_attempt_id", "question_id"], name: "index_exam_answers_on_exam_attempt_id_and_question_id", unique: true + t.index ["exam_attempt_id"], name: "index_exam_answers_on_exam_attempt_id" + t.index ["question_id"], name: "index_exam_answers_on_question_id" + end + + create_table "exam_attempts", force: :cascade do |t| + t.bigint "examination_id", null: false + t.bigint "student_id", null: false + t.string "status", default: "in_progress", null: false + t.decimal "score", precision: 5, scale: 2 + t.boolean "passed" + t.integer "violations_count", default: 0, null: false + t.datetime "started_at", null: false + t.datetime "finished_at" + t.integer "remaining_seconds" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["examination_id"], name: "index_exam_attempts_on_examination_id" + t.index ["student_id"], name: "index_exam_attempts_on_student_id" + end + + create_table "examinations", force: :cascade do |t| + t.bigint "teacher_id", null: false + t.bigint "subject_id", null: false + t.bigint "classroom_id", null: false + t.string "title", null: false + t.text "description" + t.string "exam_type", default: "quiz", null: false + t.integer "duration_minutes", default: 60, null: false + t.decimal "passing_score", precision: 5, scale: 2, default: "75.0", null: false + t.datetime "start_at" + t.datetime "end_at" + t.boolean "shuffle_questions", default: false, null: false + t.boolean "shuffle_options", default: false, null: false + t.boolean "show_result", default: true, null: false + t.boolean "allow_retry", default: false, null: false + t.string "status", default: "draft", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["classroom_id"], name: "index_examinations_on_classroom_id" + t.index ["subject_id"], name: "index_examinations_on_subject_id" + t.index ["teacher_id"], name: "index_examinations_on_teacher_id" + end + + create_table "learning_materials", force: :cascade do |t| + t.bigint "teacher_id", null: false + t.bigint "subject_id", null: false + t.bigint "classroom_id" + t.string "title", null: false + t.text "description" + t.string "material_type", default: "document", null: false + t.text "content" + t.string "file_url" + t.string "file_path" + t.boolean "published", default: true, null: false + t.integer "total_views", default: 0, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["classroom_id"], name: "index_learning_materials_on_classroom_id" + t.index ["subject_id"], name: "index_learning_materials_on_subject_id" + t.index ["teacher_id"], name: "index_learning_materials_on_teacher_id" + end + + create_table "material_views", force: :cascade do |t| + t.bigint "learning_material_id", null: false + t.bigint "student_id", null: false + t.datetime "viewed_at", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["learning_material_id", "student_id"], name: "index_material_views_on_learning_material_id_and_student_id", unique: true + t.index ["learning_material_id"], name: "index_material_views_on_learning_material_id" + t.index ["student_id"], name: "index_material_views_on_student_id" + end + + create_table "questions", force: :cascade do |t| + t.bigint "examination_id", null: false + t.text "question_text", null: false + t.string "question_type", default: "multiple_choice", null: false + t.jsonb "options", default: [] + t.integer "points", default: 10, null: false + t.string "difficulty", default: "medium", null: false + t.string "correct_answer" + t.text "explanation" + t.string "image_path" + t.string "audio_path" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["examination_id"], name: "index_questions_on_examination_id" + end + + create_table "students", force: :cascade do |t| + t.bigint "user_id", null: false + t.bigint "classroom_id" + t.string "nis", null: false + t.string "nisn" + t.string "name", null: false + t.string "email", null: false + t.string "phone" + t.string "gender", default: "M", null: false + t.date "birth_date" + t.text "address" + t.string "photo" + t.boolean "active", default: true, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["classroom_id"], name: "index_students_on_classroom_id" + t.index ["nis"], name: "index_students_on_nis", unique: true + t.index ["user_id"], name: "index_students_on_user_id", unique: true + end + + create_table "subjects", force: :cascade do |t| + t.string "name", null: false + t.string "code", null: false + t.text "description" + t.bigint "teacher_id" + t.integer "credits", default: 3, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["code"], name: "index_subjects_on_code", unique: true + t.index ["teacher_id"], name: "index_subjects_on_teacher_id" + end + + create_table "teachers", force: :cascade do |t| + t.bigint "user_id", null: false + t.string "nip", null: false + t.string "name", null: false + t.string "email", null: false + t.string "phone" + t.text "address" + t.string "photo" + t.boolean "active", default: true, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["nip"], name: "index_teachers_on_nip", unique: true + t.index ["user_id"], name: "index_teachers_on_user_id", unique: true + end + + create_table "users", force: :cascade do |t| + t.string "name", null: false + t.string "email", null: false + t.string "password_digest", null: false + t.string "role", default: "ROLE_STUDENT", null: false + t.boolean "active", default: true, null: false + t.bigint "impersonated_by_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["email"], name: "index_users_on_email", unique: true + t.index ["role"], name: "index_users_on_role" + end + + add_foreign_key "assignment_discussions", "assignment_discussions", column: "parent_id" + add_foreign_key "assignment_discussions", "assignments" + add_foreign_key "assignment_discussions", "users" + add_foreign_key "assignment_submissions", "assignments" + add_foreign_key "assignment_submissions", "students" + add_foreign_key "assignments", "classrooms" + add_foreign_key "assignments", "subjects" + add_foreign_key "assignments", "teachers" + add_foreign_key "classrooms", "teachers", column: "homeroom_teacher_id" + add_foreign_key "exam_answers", "exam_attempts" + add_foreign_key "exam_answers", "questions" + add_foreign_key "exam_attempts", "examinations" + add_foreign_key "exam_attempts", "students" + add_foreign_key "examinations", "classrooms" + add_foreign_key "examinations", "subjects" + add_foreign_key "examinations", "teachers" + add_foreign_key "learning_materials", "classrooms" + add_foreign_key "learning_materials", "subjects" + add_foreign_key "learning_materials", "teachers" + add_foreign_key "material_views", "learning_materials" + add_foreign_key "material_views", "students" + add_foreign_key "questions", "examinations" + add_foreign_key "students", "classrooms" + add_foreign_key "students", "users" + add_foreign_key "subjects", "teachers" + add_foreign_key "teachers", "users" +end From e2bdf1548036f9be3c228764d1e5bee5d834c996 Mon Sep 17 00:00:00 2001 From: M Fari Madyan Date: Tue, 13 Oct 2026 07:35:22 +0700 Subject: [PATCH 2/5] feat(backend): implement repository pattern, use cases, and result monad --- .../app/controllers/api/v1/base_controller.rb | 8 +++ .../app/repositories/assignment_repository.rb | 18 +++++ backend/app/repositories/base_repository.rb | 38 +++++++++++ .../app/repositories/classroom_repository.rb | 9 +++ .../repositories/exam_attempt_repository.rb | 15 +++++ .../repositories/examination_repository.rb | 18 +++++ backend/app/repositories/user_repository.rb | 13 ++++ .../use_cases/assignments/grade_assignment.rb | 18 +++++ .../assignments/submit_assignment.rb | 25 +++++++ .../app/use_cases/auth/authenticate_user.rb | 31 +++++++++ .../app/use_cases/auth/register_student.rb | 49 ++++++++++++++ .../app/use_cases/exams/save_exam_answer.rb | 25 +++++++ .../app/use_cases/exams/start_exam_attempt.rb | 66 +++++++++++++++++++ .../use_cases/exams/submit_exam_attempt.rb | 59 +++++++++++++++++ backend/app/use_cases/use_case_result.rb | 27 ++++++++ 15 files changed, 419 insertions(+) create mode 100644 backend/app/repositories/assignment_repository.rb create mode 100644 backend/app/repositories/base_repository.rb create mode 100644 backend/app/repositories/classroom_repository.rb create mode 100644 backend/app/repositories/exam_attempt_repository.rb create mode 100644 backend/app/repositories/examination_repository.rb create mode 100644 backend/app/repositories/user_repository.rb create mode 100644 backend/app/use_cases/assignments/grade_assignment.rb create mode 100644 backend/app/use_cases/assignments/submit_assignment.rb create mode 100644 backend/app/use_cases/auth/authenticate_user.rb create mode 100644 backend/app/use_cases/auth/register_student.rb create mode 100644 backend/app/use_cases/exams/save_exam_answer.rb create mode 100644 backend/app/use_cases/exams/start_exam_attempt.rb create mode 100644 backend/app/use_cases/exams/submit_exam_attempt.rb create mode 100644 backend/app/use_cases/use_case_result.rb diff --git a/backend/app/controllers/api/v1/base_controller.rb b/backend/app/controllers/api/v1/base_controller.rb index df8f048..d19d717 100644 --- a/backend/app/controllers/api/v1/base_controller.rb +++ b/backend/app/controllers/api/v1/base_controller.rb @@ -37,6 +37,14 @@ def require_student! render_error("Forbidden: Student access required", status: :forbidden) unless @current_user&.student? || @current_user&.admin? end + def handle_result(result, message: "Success") + if result.success? + json_response(data: result.data, message: message, status: result.status) + else + render_error(result.error, status: result.status, errors: result.errors) + end + end + def json_response(data: nil, message: "Success", status: :ok, errors: nil) camelized_data = camelize_keys(data.as_json) diff --git a/backend/app/repositories/assignment_repository.rb b/backend/app/repositories/assignment_repository.rb new file mode 100644 index 0000000..66e241e --- /dev/null +++ b/backend/app/repositories/assignment_repository.rb @@ -0,0 +1,18 @@ +class AssignmentRepository < BaseRepository + def initialize + super(Assignment) + end + + def list_for_user(user) + scope = model_class.includes(:teacher, :subject, :classroom).order(due_date: :asc) + student = user.student + + if user.teacher? + scope.where(teacher_id: user.teacher&.id) + elsif student + scope.where(classroom_id: student.classroom_id, status: 'published') + else + scope + end + end +end diff --git a/backend/app/repositories/base_repository.rb b/backend/app/repositories/base_repository.rb new file mode 100644 index 0000000..b49ff5e --- /dev/null +++ b/backend/app/repositories/base_repository.rb @@ -0,0 +1,38 @@ +class BaseRepository + attr_reader :model_class + + def initialize(model_class) + @model_class = model_class + end + + def all + model_class.all + end + + def find(id) + model_class.find(id) + end + + def find_by(conditions) + model_class.find_by(conditions) + end + + def create!(attributes) + model_class.create!(attributes) + end + + def update!(id, attributes) + record = find(id) + record.update!(attributes) + record + end + + def delete!(id) + record = find(id) + record.destroy! + end + + def count + model_class.count + end +end diff --git a/backend/app/repositories/classroom_repository.rb b/backend/app/repositories/classroom_repository.rb new file mode 100644 index 0000000..46550c0 --- /dev/null +++ b/backend/app/repositories/classroom_repository.rb @@ -0,0 +1,9 @@ +class ClassroomRepository < BaseRepository + def initialize + super(Classroom) + end + + def list_with_homeroom + model_class.includes(:homeroom_teacher).order(:level, :name) + end +end diff --git a/backend/app/repositories/exam_attempt_repository.rb b/backend/app/repositories/exam_attempt_repository.rb new file mode 100644 index 0000000..a59e9db --- /dev/null +++ b/backend/app/repositories/exam_attempt_repository.rb @@ -0,0 +1,15 @@ +class ExamAttemptRepository < BaseRepository + def initialize + super(ExamAttempt) + end + + def find_or_initialize_for(exam, student) + model_class.find_or_initialize_by(examination: exam, student: student) + end + + def attempts_map_for_student(student_id) + return {} unless student_id + + model_class.where(student_id: student_id).index_by(&:examination_id) + end +end diff --git a/backend/app/repositories/examination_repository.rb b/backend/app/repositories/examination_repository.rb new file mode 100644 index 0000000..34be003 --- /dev/null +++ b/backend/app/repositories/examination_repository.rb @@ -0,0 +1,18 @@ +class ExaminationRepository < BaseRepository + def initialize + super(Examination) + end + + def list_for_user(user) + scope = model_class.includes(:teacher, :subject, :classroom, :questions).order(start_at: :desc) + student = user.student + + if user.teacher? + scope.where(teacher_id: user.teacher&.id) + elsif student + scope.where(classroom_id: student.classroom_id, status: 'published') + else + scope + end + end +end diff --git a/backend/app/repositories/user_repository.rb b/backend/app/repositories/user_repository.rb new file mode 100644 index 0000000..fa25d9d --- /dev/null +++ b/backend/app/repositories/user_repository.rb @@ -0,0 +1,13 @@ +class UserRepository < BaseRepository + def initialize + super(User) + end + + def find_by_email(email) + model_class.find_by(email: email) + end + + def find_admin + model_class.find_by(role: 'ROLE_ADMIN') + end +end diff --git a/backend/app/use_cases/assignments/grade_assignment.rb b/backend/app/use_cases/assignments/grade_assignment.rb new file mode 100644 index 0000000..658c12b --- /dev/null +++ b/backend/app/use_cases/assignments/grade_assignment.rb @@ -0,0 +1,18 @@ +module Assignments + class GradeAssignment + def call(submission_id:, score:, feedback: nil) + sub = AssignmentSubmission.find(submission_id) + sub.update!( + score: score, + feedback: feedback, + status: 'graded' + ) + + UseCaseResult.success(sub) + rescue ActiveRecord::RecordNotFound => e + UseCaseResult.failure(e.message, status: :not_found) + rescue ActiveRecord::RecordInvalid => e + UseCaseResult.failure(e.message, status: :unprocessable_entity) + end + end +end diff --git a/backend/app/use_cases/assignments/submit_assignment.rb b/backend/app/use_cases/assignments/submit_assignment.rb new file mode 100644 index 0000000..3c6a0fe --- /dev/null +++ b/backend/app/use_cases/assignments/submit_assignment.rb @@ -0,0 +1,25 @@ +module Assignments + class SubmitAssignment + def initialize(assignment_repo: AssignmentRepository.new) + @assignment_repo = assignment_repo + end + + def call(assignment_id:, student:, file_path: nil, notes: nil) + return UseCaseResult.failure("Student record not found", status: :forbidden) unless student + + assignment = @assignment_repo.find(assignment_id) + sub = AssignmentSubmission.find_or_initialize_by(assignment: assignment, student: student) + sub.file_path = file_path if file_path.present? + sub.notes = notes if notes.present? + sub.submitted_at = Time.current + sub.status = Time.current > assignment.due_date ? 'late' : 'submitted' + sub.save! + + UseCaseResult.success(sub) + rescue ActiveRecord::RecordNotFound => e + UseCaseResult.failure(e.message, status: :not_found) + rescue ActiveRecord::RecordInvalid => e + UseCaseResult.failure(e.message, status: :unprocessable_entity) + end + end +end diff --git a/backend/app/use_cases/auth/authenticate_user.rb b/backend/app/use_cases/auth/authenticate_user.rb new file mode 100644 index 0000000..099dd77 --- /dev/null +++ b/backend/app/use_cases/auth/authenticate_user.rb @@ -0,0 +1,31 @@ +module Auth + class AuthenticateUser + def initialize(user_repo: UserRepository.new) + @user_repo = user_repo + end + + def call(email:, password:) + user = @user_repo.find_by_email(email) + + unless user&.authenticate(password) + return UseCaseResult.failure("Invalid email or password", status: :unauthorized) + end + + token = JsonWebToken.encode(user_id: user.id) + payload = { + accessToken: token, + refreshToken: token, + tokenType: "Bearer", + userId: user.id, + name: user.name, + email: user.email, + roles: [user.role], + active: user.active, + impersonatedBy: user.impersonated_by_id, + token: token + } + + UseCaseResult.success(payload) + end + end +end diff --git a/backend/app/use_cases/auth/register_student.rb b/backend/app/use_cases/auth/register_student.rb new file mode 100644 index 0000000..f1b62ef --- /dev/null +++ b/backend/app/use_cases/auth/register_student.rb @@ -0,0 +1,49 @@ +module Auth + class RegisterStudent + def initialize(user_repo: UserRepository.new) + @user_repo = user_repo + end + + def call(name:, email:, password:, nis: nil, gender: 'M') + user = nil + ActiveRecord::Base.transaction do + user = User.create!( + name: name, + email: email, + password: password, + role: 'ROLE_STUDENT', + active: true + ) + + nis_code = nis.presence || "NIS#{Time.current.to_i % 1000000}" + Student.create!( + user: user, + name: user.name, + email: user.email, + nis: nis_code, + gender: gender.presence || 'M', + active: true + ) + end + + token = JsonWebToken.encode(user_id: user.id) + payload = { + accessToken: token, + refreshToken: token, + tokenType: "Bearer", + userId: user.id, + name: user.name, + email: user.email, + roles: [user.role], + active: user.active, + token: token + } + + UseCaseResult.success(payload, status: :created) + rescue ActiveRecord::RecordInvalid => e + UseCaseResult.failure(e.message, status: :unprocessable_entity, errors: e.record.errors.as_json) + rescue StandardError => e + UseCaseResult.failure(e.message, status: :bad_request) + end + end +end diff --git a/backend/app/use_cases/exams/save_exam_answer.rb b/backend/app/use_cases/exams/save_exam_answer.rb new file mode 100644 index 0000000..c49f4d0 --- /dev/null +++ b/backend/app/use_cases/exams/save_exam_answer.rb @@ -0,0 +1,25 @@ +module Exams + class SaveExamAnswer + def initialize(attempt_repo: ExamAttemptRepository.new) + @attempt_repo = attempt_repo + end + + def call(attempt_id:, question_id:, answer:) + attempt = @attempt_repo.find(attempt_id) + if attempt.status != 'in_progress' + return UseCaseResult.failure("Attempt is already submitted or inactive", status: :bad_request) + end + + question = Question.find(question_id) + ans = ExamAnswer.find_or_initialize_by(exam_attempt: attempt, question: question) + ans.student_answer = answer.to_s + ans.save! + + UseCaseResult.success(nil) + rescue ActiveRecord::RecordNotFound => e + UseCaseResult.failure(e.message, status: :not_found) + rescue ActiveRecord::RecordInvalid => e + UseCaseResult.failure(e.message, status: :unprocessable_entity) + end + end +end diff --git a/backend/app/use_cases/exams/start_exam_attempt.rb b/backend/app/use_cases/exams/start_exam_attempt.rb new file mode 100644 index 0000000..c8df95f --- /dev/null +++ b/backend/app/use_cases/exams/start_exam_attempt.rb @@ -0,0 +1,66 @@ +module Exams + class StartExamAttempt + def initialize( + exam_repo: ExaminationRepository.new, + attempt_repo: ExamAttemptRepository.new + ) + @exam_repo = exam_repo + @attempt_repo = attempt_repo + end + + def call(exam_id:, student:) + return UseCaseResult.failure("Student record not found", status: :forbidden) unless student + + exam = @exam_repo.find(exam_id) + attempt = @attempt_repo.find_or_initialize_for(exam, student) + + if attempt.new_record? || (exam.allow_retry && attempt.status == 'completed') + attempt.status = 'in_progress' + attempt.started_at = Time.current + attempt.remaining_seconds = exam.duration_minutes * 60 + attempt.violations_count = 0 + attempt.save! + end + + questions = exam.questions.order(:id).to_a + questions = questions.shuffle if exam.shuffle_questions + + existing_answers = ExamAnswer.where(exam_attempt: attempt).index_by(&:question_id) + + questions_payload = questions.map do |q| + options = q.options || [] + options = options.shuffle if exam.shuffle_options + { + id: q.id, + examinationId: q.examination_id, + questionText: q.question_text, + questionType: q.question_type, + options: options, + points: q.points, + difficulty: q.difficulty, + studentAnswer: existing_answers[q.id]&.student_answer, + imagePath: q.image_path, + audioPath: q.audio_path + } + end + + elapsed = (Time.current - attempt.started_at).to_i + remaining = [exam.duration_minutes * 60 - elapsed, 0].max + + response_data = { + attemptId: attempt.id, + examId: exam.id, + examTitle: exam.title, + durationMinutes: exam.duration_minutes, + remainingSeconds: remaining, + startedAt: attempt.started_at.iso8601, + totalQuestions: questions.size, + questions: questions_payload + } + + UseCaseResult.success(response_data) + rescue ActiveRecord::RecordNotFound => e + UseCaseResult.failure(e.message, status: :not_found) + end + end +end diff --git a/backend/app/use_cases/exams/submit_exam_attempt.rb b/backend/app/use_cases/exams/submit_exam_attempt.rb new file mode 100644 index 0000000..f98a8d3 --- /dev/null +++ b/backend/app/use_cases/exams/submit_exam_attempt.rb @@ -0,0 +1,59 @@ +module Exams + class SubmitExamAttempt + def initialize(attempt_repo: ExamAttemptRepository.new) + @attempt_repo = attempt_repo + end + + def call(attempt_id:) + attempt = @attempt_repo.find(attempt_id) + exam = attempt.examination + + questions = exam.questions.index_by(&:id) + answers = attempt.exam_answers.includes(:question) + + total_points = questions.values.sum(&:points) + earned_points = 0.0 + has_essay = false + + answers.each do |ans| + q = ans.question + next unless q + + if q.question_type == 'multiple_choice' || q.question_type == 'true_false' + is_correct = ans.student_answer.to_s.strip.downcase == q.correct_answer.to_s.strip.downcase + ans.update!( + is_correct: is_correct, + points_awarded: is_correct ? q.points : 0.0, + graded_at: Time.current + ) + earned_points += q.points if is_correct + elsif q.question_type == 'essay' + has_essay = true + end + end + + score_pct = total_points > 0 ? (earned_points / total_points * 100.0).round(2) : 0.0 + passed = score_pct >= exam.passing_score + + attempt.update!( + score: score_pct, + passed: passed, + finished_at: Time.current, + status: has_essay ? 'needs_grading' : 'completed', + remaining_seconds: 0 + ) + + payload = { + score: attempt.score, + passed: attempt.passed, + status: attempt.status, + totalQuestions: questions.size, + answeredCount: answers.size + } + + UseCaseResult.success(payload) + rescue ActiveRecord::RecordNotFound => e + UseCaseResult.failure(e.message, status: :not_found) + end + end +end diff --git a/backend/app/use_cases/use_case_result.rb b/backend/app/use_cases/use_case_result.rb new file mode 100644 index 0000000..cee0bc9 --- /dev/null +++ b/backend/app/use_cases/use_case_result.rb @@ -0,0 +1,27 @@ +class UseCaseResult + attr_reader :data, :error, :errors, :status + + def initialize(success:, data: nil, error: nil, errors: nil, status: :ok) + @success = success + @data = data + @error = error + @errors = errors + @status = status + end + + def success? + @success + end + + def failure? + !@success + end + + def self.success(data = nil, status: :ok) + new(success: true, data: data, status: status) + end + + def self.failure(error, status: :bad_request, errors: nil) + new(success: false, error: error, errors: errors, status: status) + end +end From 511962030c0ed621fc7cd77162e02352c99cb59b Mon Sep 17 00:00:00 2001 From: M Fari Madyan Date: Tue, 13 Oct 2026 07:35:29 +0700 Subject: [PATCH 3/5] refactor(backend): streamline api controllers with use cases and add test specs --- .../api/v1/assignments_controller.rb | 111 +++++++------ .../app/controllers/api/v1/auth_controller.rb | 60 +++---- .../api/v1/classrooms_controller.rb | 12 +- .../api/v1/exam_runner_controller.rb | 155 +++++------------- .../api/v1/examinations_controller.rb | 23 +-- .../spec/repositories/user_repository_spec.rb | 23 +++ .../use_cases/auth/authenticate_user_spec.rb | 25 +++ 7 files changed, 199 insertions(+), 210 deletions(-) create mode 100644 backend/spec/repositories/user_repository_spec.rb create mode 100644 backend/spec/use_cases/auth/authenticate_user_spec.rb diff --git a/backend/app/controllers/api/v1/assignments_controller.rb b/backend/app/controllers/api/v1/assignments_controller.rb index fce3c4d..5163043 100644 --- a/backend/app/controllers/api/v1/assignments_controller.rb +++ b/backend/app/controllers/api/v1/assignments_controller.rb @@ -4,15 +4,8 @@ class AssignmentsController < BaseController before_action :set_assignment, only: [:show, :update, :destroy, :submit, :submissions, :discussions, :create_discussion] def index - scope = Assignment.includes(:teacher, :subject, :classroom).order(due_date: :asc) + scope = assignment_repository.list_for_user(current_user) student = current_user.student - - if current_user.teacher? - scope = scope.where(teacher_id: current_user.teacher&.id) - elsif student - scope = scope.where(classroom_id: student.classroom_id, status: 'published') - end - submissions_map = student ? AssignmentSubmission.where(student_id: student.id).index_by(&:assignment_id) : {} data = scope.map { |a| assignment_payload(a, submissions_map[a.id]) } @@ -30,7 +23,7 @@ def create return if performed? teacher = current_user.teacher || Teacher.first - assignment = Assignment.create!( + assignment = assignment_repository.create!( teacher: teacher, subject_id: params[:subjectId], classroom_id: params[:classroomId], @@ -69,7 +62,7 @@ def destroy require_teacher! return if performed? - @assignment.destroy! + assignment_repository.delete!(@assignment.id) json_response(data: nil, message: "Assignment deleted successfully") end @@ -77,17 +70,18 @@ def submit require_student! return if performed? - student = current_user.student - return render_error("Student record not found") unless student - - sub = AssignmentSubmission.find_or_initialize_by(assignment: @assignment, student: student) - sub.file_path = params[:filePath] if params[:filePath].present? - sub.notes = params[:notes] if params[:notes].present? - sub.submitted_at = Time.current - sub.status = Time.current > @assignment.due_date ? 'late' : 'submitted' - sub.save! + result = submit_assignment_use_case.call( + assignment_id: @assignment.id, + student: current_user.student, + file_path: params[:filePath], + notes: params[:notes] + ) - json_response(data: submission_payload(sub), message: "Assignment submitted successfully") + if result.success? + json_response(data: submission_payload(result.data), message: "Assignment submitted successfully") + else + render_error(result.error, status: result.status, errors: result.errors) + end end def submissions @@ -103,14 +97,17 @@ def grade_submission require_teacher! return if performed? - sub = AssignmentSubmission.find(params[:submission_id]) - sub.update!( + result = grade_assignment_use_case.call( + submission_id: params[:submission_id], score: params[:score], - feedback: params[:feedback], - graded_at: Time.current, - status: 'graded' + feedback: params[:feedback] ) - json_response(data: submission_payload(sub), message: "Submission graded successfully") + + if result.success? + json_response(data: submission_payload(result.data), message: "Submission graded successfully") + else + render_error(result.error, status: result.status, errors: result.errors) + end end def discussions @@ -132,31 +129,43 @@ def create_discussion private + def assignment_repository + @assignment_repository ||= AssignmentRepository.new + end + + def submit_assignment_use_case + @submit_assignment_use_case ||= Assignments::SubmitAssignment.new( + assignment_repo: assignment_repository + ) + end + + def grade_assignment_use_case + @grade_assignment_use_case ||= Assignments::GradeAssignment.new + end + def set_assignment - @assignment = Assignment.find(params[:id]) + @assignment = assignment_repository.find(params[:id]) end def assignment_payload(a, submission = nil) { id: a.id, - teacherId: a.teacher_id, - teacherName: a.teacher&.name, + title: a.title, + description: a.description, + instructions: a.instructions, subjectId: a.subject_id, subjectName: a.subject&.name, classroomId: a.classroom_id, classroomName: a.classroom&.name, - title: a.title, - description: a.description, - instructions: a.instructions, + teacherId: a.teacher_id, + teacherName: a.teacher&.name, maxScore: a.max_score, dueDate: a.due_date&.iso8601, allowLateSubmission: a.allow_late_submission, status: a.status, - createdAt: a.created_at&.iso8601, - hasSubmitted: submission.present?, - studentScore: submission&.score, - studentSubmissionStatus: submission&.status, - studentSubmittedAt: submission&.submitted_at&.iso8601 + submissionsCount: a.submissions.count, + submission: submission ? submission_payload(submission) : nil, + createdAt: a.created_at&.iso8601 } end @@ -165,29 +174,27 @@ def submission_payload(s) id: s.id, assignmentId: s.assignment_id, studentId: s.student_id, - studentName: s.student.name, - studentNis: s.student.nis, + studentName: s.student&.name, + nis: s.student&.nis, filePath: s.file_path, notes: s.notes, + submittedAt: s.submitted_at&.iso8601, score: s.score, feedback: s.feedback, - status: s.status, - submittedAt: s.submitted_at&.iso8601, - gradedAt: s.graded_at&.iso8601 + status: s.status } end - def discussion_payload(c, all_comments) - replies = all_comments.select { |r| r.parent_id == c.id }.map { |r| discussion_payload(r, all_comments) } + def discussion_payload(comment, all_comments) + replies = all_comments.select { |c| c.parent_id == comment.id } { - id: c.id, - assignmentId: c.assignment_id, - userId: c.user_id, - userName: c.user.name, - userRole: c.user.role, - message: c.message, - createdAt: c.created_at&.iso8601, - replies: replies + id: comment.id, + userId: comment.user_id, + userName: comment.user&.name, + userRole: comment.user&.role, + message: comment.message, + createdAt: comment.created_at&.iso8601, + replies: replies.map { |r| discussion_payload(r, all_comments) } } end end diff --git a/backend/app/controllers/api/v1/auth_controller.rb b/backend/app/controllers/api/v1/auth_controller.rb index 9796de4..744f2cb 100644 --- a/backend/app/controllers/api/v1/auth_controller.rb +++ b/backend/app/controllers/api/v1/auth_controller.rb @@ -4,40 +4,22 @@ class AuthController < BaseController skip_before_action :authenticate_user!, only: [:login, :register] def login - user = User.find_by(email: params[:email]) - if user&.authenticate(params[:password]) - token = JsonWebToken.encode(user_id: user.id) - json_response(data: build_auth_payload(user, token), message: "Login successful") - else - render_error("Invalid email or password", status: :unauthorized) - end + result = authenticate_user_use_case.call( + email: params[:email], + password: params[:password] + ) + handle_result(result, message: "Login successful") end def register - User.transaction do - user = User.create!( - name: params[:name], - email: params[:email], - password: params[:password], - role: 'ROLE_STUDENT', - active: true - ) - - nis = params[:nis].presence || "NIS#{Time.current.to_i % 1000000}" - Student.create!( - user: user, - name: user.name, - email: user.email, - nis: nis, - gender: params[:gender].presence || 'M', - active: true - ) - - token = JsonWebToken.encode(user_id: user.id) - json_response(data: build_auth_payload(user, token), message: "Registration successful", status: :created) - end - rescue ActiveRecord::RecordInvalid => e - render_error(e.message, status: :unprocessable_entity) + result = register_student_use_case.call( + name: params[:name], + email: params[:email], + password: params[:password], + nis: params[:nis], + gender: params[:gender] + ) + handle_result(result, message: "Registration successful") end def me @@ -57,14 +39,14 @@ def impersonate require_admin! return if performed? - target_user = User.find(params[:user_id]) + target_user = user_repository.find(params[:user_id]) token = JsonWebToken.encode(user_id: target_user.id) payload = build_auth_payload(target_user, token, impersonated_by: current_user.id) json_response(data: payload, message: "Impersonation started successfully") end def stop_impersonate - admin_user = User.find_by(role: 'ROLE_ADMIN') || current_user + admin_user = user_repository.find_admin || current_user token = JsonWebToken.encode(user_id: admin_user.id) payload = build_auth_payload(admin_user, token) json_response(data: payload, message: "Returned to admin session") @@ -72,6 +54,18 @@ def stop_impersonate private + def user_repository + @user_repository ||= UserRepository.new + end + + def authenticate_user_use_case + @authenticate_user_use_case ||= Auth::AuthenticateUser.new(user_repo: user_repository) + end + + def register_student_use_case + @register_student_use_case ||= Auth::RegisterStudent.new(user_repo: user_repository) + end + def build_auth_payload(user, token, impersonated_by: nil) { accessToken: token, diff --git a/backend/app/controllers/api/v1/classrooms_controller.rb b/backend/app/controllers/api/v1/classrooms_controller.rb index e1a2721..80fa0e3 100644 --- a/backend/app/controllers/api/v1/classrooms_controller.rb +++ b/backend/app/controllers/api/v1/classrooms_controller.rb @@ -4,7 +4,7 @@ class ClassroomsController < BaseController before_action :set_classroom, only: [:show, :update, :destroy] def index - classrooms = Classroom.includes(:homeroom_teacher).order(:level, :name) + classrooms = classroom_repository.list_with_homeroom data = classrooms.map { |c| classroom_payload(c) } json_response(data: data) end @@ -17,7 +17,7 @@ def create require_admin! return if performed? - classroom = Classroom.create!(classroom_params) + classroom = classroom_repository.create!(classroom_params) json_response(data: classroom_payload(classroom), message: "Classroom created successfully", status: :created) end @@ -33,14 +33,18 @@ def destroy require_admin! return if performed? - @classroom.destroy! + classroom_repository.delete!(@classroom.id) json_response(data: nil, message: "Classroom deleted successfully") end private + def classroom_repository + @classroom_repository ||= ClassroomRepository.new + end + def set_classroom - @classroom = Classroom.find(params[:id]) + @classroom = classroom_repository.find(params[:id]) end def classroom_params diff --git a/backend/app/controllers/api/v1/exam_runner_controller.rb b/backend/app/controllers/api/v1/exam_runner_controller.rb index 969829b..9189c51 100644 --- a/backend/app/controllers/api/v1/exam_runner_controller.rb +++ b/backend/app/controllers/api/v1/exam_runner_controller.rb @@ -5,80 +5,30 @@ def start require_student! return if performed? - student = current_user.student - return render_error("Student record not found") unless student - - exam = Examination.find(params[:id]) - attempt = ExamAttempt.find_or_initialize_by(examination: exam, student: student) - - if attempt.new_record? || (exam.allow_retry && attempt.status == 'completed') - attempt.status = 'in_progress' - attempt.started_at = Time.current - attempt.remaining_seconds = exam.duration_minutes * 60 - attempt.violations_count = 0 - attempt.save! - end - - questions = exam.questions.order(:id).to_a - questions = questions.shuffle if exam.shuffle_questions - - # Fetch existing student answers if attempt was in progress - existing_answers = ExamAnswer.where(exam_attempt: attempt).index_by(&:question_id) - - questions_payload = questions.map do |q| - options = q.options || [] - options = options.shuffle if exam.shuffle_options - { - id: q.id, - examinationId: q.examination_id, - questionText: q.question_text, - questionType: q.question_type, - options: options, - points: q.points, - difficulty: q.difficulty, - studentAnswer: existing_answers[q.id]&.student_answer, - imagePath: q.image_path, - audioPath: q.audio_path - } - end - - elapsed = (Time.current - attempt.started_at).to_i - remaining = [exam.duration_minutes * 60 - elapsed, 0].max - - response_data = { - attemptId: attempt.id, - examId: exam.id, - examTitle: exam.title, - durationMinutes: exam.duration_minutes, - remainingSeconds: remaining, - startedAt: attempt.started_at.iso8601, - totalQuestions: questions.size, - questions: questions_payload - } - - json_response(data: response_data) + result = start_exam_attempt_use_case.call( + exam_id: params[:id], + student: current_user.student + ) + handle_result(result) end def answer require_student! return if performed? - attempt = ExamAttempt.find(params[:attempt_id]) - return render_error("Attempt is already submitted") if attempt.status != 'in_progress' - - question = Question.find(params[:questionId]) - ans = ExamAnswer.find_or_initialize_by(exam_attempt: attempt, question: question) - ans.student_answer = params[:answer].to_s - ans.save! - - json_response(data: nil, message: "Answer saved") + result = save_exam_answer_use_case.call( + attempt_id: params[:attempt_id], + question_id: params[:questionId], + answer: params[:answer] + ) + handle_result(result, message: "Answer saved") end def violation require_student! return if performed? - attempt = ExamAttempt.find(params[:attempt_id]) + attempt = exam_attempt_repository.find(params[:attempt_id]) attempt.increment!(:violations_count) json_response(data: { violations: attempt.violations_count }, message: "Violation recorded") end @@ -87,59 +37,15 @@ def submit require_student! return if performed? - attempt = ExamAttempt.find(params[:attempt_id]) - exam = attempt.examination - - # Calculate scores automatically - questions = exam.questions.index_by(&:id) - answers = attempt.exam_answers.includes(:question) - - total_points = questions.values.sum(&:points) - earned_points = 0.0 - has_essay = false - - answers.each do |ans| - q = ans.question - next unless q - - if q.question_type == 'multiple_choice' || q.question_type == 'true_false' - is_correct = ans.student_answer.to_s.strip.downcase == q.correct_answer.to_s.strip.downcase - ans.update!( - is_correct: is_correct, - points_awarded: is_correct ? q.points : 0.0, - graded_at: Time.current - ) - earned_points += q.points if is_correct - elsif q.question_type == 'essay' - has_essay = true - end - end - - score_pct = total_points > 0 ? (earned_points / total_points * 100.0).round(2) : 0.0 - passed = score_pct >= exam.passing_score - - attempt.update!( - score: score_pct, - passed: passed, - finished_at: Time.current, - status: has_essay ? 'needs_grading' : 'completed', - remaining_seconds: 0 - ) - - json_response(data: { - score: attempt.score, - passed: attempt.passed, - status: attempt.status, - totalQuestions: questions.size, - answeredCount: answers.size - }, message: "Exam submitted successfully") + result = submit_exam_attempt_use_case.call(attempt_id: params[:attempt_id]) + handle_result(result, message: "Exam submitted successfully") end def grade_essay require_teacher! return if performed? - attempt = ExamAttempt.find(params[:attempt_id]) + attempt = exam_attempt_repository.find(params[:attempt_id]) ans = attempt.exam_answers.find(params[:answer_id]) points = params[:pointsAwarded].to_f @@ -168,7 +74,7 @@ def monitor require_teacher! return if performed? - exam = Examination.find(params[:id]) + exam = examination_repository.find(params[:id]) attempts = exam.exam_attempts.includes(student: :classroom).order(started_at: :desc) total_q = exam.questions.count @@ -191,6 +97,35 @@ def monitor json_response(data: data) end + + private + + def examination_repository + @examination_repository ||= ExaminationRepository.new + end + + def exam_attempt_repository + @exam_attempt_repository ||= ExamAttemptRepository.new + end + + def start_exam_attempt_use_case + @start_exam_attempt_use_case ||= Exams::StartExamAttempt.new( + exam_repo: examination_repository, + attempt_repo: exam_attempt_repository + ) + end + + def save_exam_answer_use_case + @save_exam_answer_use_case ||= Exams::SaveExamAnswer.new( + attempt_repo: exam_attempt_repository + ) + end + + def submit_exam_attempt_use_case + @submit_exam_attempt_use_case ||= Exams::SubmitExamAttempt.new( + attempt_repo: exam_attempt_repository + ) + end end end end diff --git a/backend/app/controllers/api/v1/examinations_controller.rb b/backend/app/controllers/api/v1/examinations_controller.rb index bf1d96c..a5a3db8 100644 --- a/backend/app/controllers/api/v1/examinations_controller.rb +++ b/backend/app/controllers/api/v1/examinations_controller.rb @@ -4,16 +4,9 @@ class ExaminationsController < BaseController before_action :set_exam, only: [:show, :update, :destroy, :update_status, :questions, :create_question, :import_questions_excel] def index - scope = Examination.includes(:teacher, :subject, :classroom, :questions).order(start_at: :desc) + scope = examination_repository.list_for_user(current_user) student = current_user.student - - if current_user.teacher? - scope = scope.where(teacher_id: current_user.teacher&.id) - elsif student - scope = scope.where(classroom_id: student.classroom_id, status: 'published') - end - - attempts_map = student ? ExamAttempt.where(student_id: student.id).index_by(&:examination_id) : {} + attempts_map = exam_attempt_repository.attempts_map_for_student(student&.id) data = scope.map { |e| exam_payload(e, attempts_map[e.id]) } json_response(data: data) @@ -21,7 +14,7 @@ def index def show student = current_user.student - attempt = student ? ExamAttempt.find_by(examination: @exam, student: student) : nil + attempt = student ? exam_attempt_repository.find_by(examination: @exam, student: student) : nil json_response(data: exam_payload(@exam, attempt)) end @@ -187,8 +180,16 @@ def import_questions_excel private + def examination_repository + @examination_repository ||= ExaminationRepository.new + end + + def exam_attempt_repository + @exam_attempt_repository ||= ExamAttemptRepository.new + end + def set_exam - @exam = Examination.find(params[:id]) + @exam = examination_repository.find(params[:id]) end def exam_payload(e, attempt = nil) diff --git a/backend/spec/repositories/user_repository_spec.rb b/backend/spec/repositories/user_repository_spec.rb new file mode 100644 index 0000000..e55cb92 --- /dev/null +++ b/backend/spec/repositories/user_repository_spec.rb @@ -0,0 +1,23 @@ +require 'rails_helper' + +RSpec.describe UserRepository, type: :model do + let(:repo) { described_class.new } + let!(:user) { User.create!(name: 'Admin Test', email: 'admin@repo-test.com', password: 'password123', role: 'ROLE_ADMIN') } + + describe '#find_by_email' do + it 'finds user by email' do + found = repo.find_by_email('admin@repo-test.com') + expect(found).to eq(user) + end + + it 'returns nil for unknown email' do + expect(repo.find_by_email('unknown@email.com')).to be_nil + end + end + + describe '#find_admin' do + it 'returns an admin user' do + expect(repo.find_admin).to eq(user) + end + end +end diff --git a/backend/spec/use_cases/auth/authenticate_user_spec.rb b/backend/spec/use_cases/auth/authenticate_user_spec.rb new file mode 100644 index 0000000..6964bf4 --- /dev/null +++ b/backend/spec/use_cases/auth/authenticate_user_spec.rb @@ -0,0 +1,25 @@ +require 'rails_helper' + +RSpec.describe Auth::AuthenticateUser do + let(:use_case) { described_class.new } + let!(:user) { User.create!(name: 'Teacher One', email: 'teacher@usecase-test.com', password: 'password123', role: 'ROLE_TEACHER') } + + describe '#call' do + it 'returns success with token payload on valid credentials' do + result = use_case.call(email: 'teacher@usecase-test.com', password: 'password123') + + expect(result).to be_success + expect(result.data[:accessToken]).to be_present + expect(result.data[:userId]).to eq(user.id) + expect(result.data[:roles]).to include('ROLE_TEACHER') + end + + it 'returns unauthorized failure on incorrect password' do + result = use_case.call(email: 'teacher@usecase-test.com', password: 'wrongpassword') + + expect(result).to be_failure + expect(result.status).to eq(:unauthorized) + expect(result.error).to eq("Invalid email or password") + end + end +end From a0209e7db12bd18f2d7fa1320f954b95dcf9650f Mon Sep 17 00:00:00 2001 From: M Fari Madyan Date: Tue, 13 Oct 2026 07:35:39 +0700 Subject: [PATCH 4/5] feat(frontend): introduce typed api service layer and optimize component lifecycles --- frontend/src/pages/admin/Classrooms.tsx | 20 ++-- frontend/src/pages/exams/ExamMonitor.tsx | 52 ++++----- frontend/src/pages/exams/ExamRunner.tsx | 65 ++++++------ frontend/src/services/announcementService.ts | 23 ++++ frontend/src/services/assignmentService.ts | 53 ++++++++++ frontend/src/services/authService.ts | 29 +++++ frontend/src/services/classroomService.ts | 36 +++++++ frontend/src/services/examService.ts | 105 +++++++++++++++++++ frontend/src/services/gradeService.ts | 9 ++ frontend/src/services/index.ts | 10 ++ frontend/src/services/materialService.ts | 37 +++++++ frontend/src/services/studentService.ts | 54 ++++++++++ frontend/src/services/subjectService.ts | 36 +++++++ frontend/src/services/teacherService.ts | 37 +++++++ frontend/src/store/authStore.ts | 13 +-- 15 files changed, 505 insertions(+), 74 deletions(-) create mode 100644 frontend/src/services/announcementService.ts create mode 100644 frontend/src/services/assignmentService.ts create mode 100644 frontend/src/services/authService.ts create mode 100644 frontend/src/services/classroomService.ts create mode 100644 frontend/src/services/examService.ts create mode 100644 frontend/src/services/gradeService.ts create mode 100644 frontend/src/services/index.ts create mode 100644 frontend/src/services/materialService.ts create mode 100644 frontend/src/services/studentService.ts create mode 100644 frontend/src/services/subjectService.ts create mode 100644 frontend/src/services/teacherService.ts diff --git a/frontend/src/pages/admin/Classrooms.tsx b/frontend/src/pages/admin/Classrooms.tsx index f1b4d87..9361eea 100644 --- a/frontend/src/pages/admin/Classrooms.tsx +++ b/frontend/src/pages/admin/Classrooms.tsx @@ -1,6 +1,6 @@ import React, { useEffect, useState } from 'react'; -import api from '../../api/client'; -import type { Classroom, Teacher, ApiResponse } from '../../types'; +import { classroomService, teacherService } from '../../services'; +import type { Classroom, Teacher } from '../../types'; import { Plus, Trash2, Edit2, GraduationCap, X } from 'lucide-react'; export const Classrooms: React.FC = () => { @@ -21,12 +21,12 @@ export const Classrooms: React.FC = () => { const loadData = async () => { try { setLoading(true); - const [crRes, tRes] = await Promise.all([ - api.get>('/classrooms'), - api.get>('/teachers'), + const [crData, tData] = await Promise.all([ + classroomService.getAll(), + teacherService.getAll(), ]); - setClassrooms(crRes.data.data); - setTeachers(tRes.data.data); + setClassrooms(crData); + setTeachers(tData); } catch (e) { console.error(e); } finally { @@ -73,9 +73,9 @@ export const Classrooms: React.FC = () => { }; if (editingClassroom) { - await api.put(`/classrooms/${editingClassroom.id}`, payload); + await classroomService.update(editingClassroom.id, payload); } else { - await api.post('/classrooms', payload); + await classroomService.create(payload); } setModalOpen(false); @@ -87,7 +87,7 @@ export const Classrooms: React.FC = () => { const handleDelete = async (id: number) => { if (confirm('Are you sure you want to delete this classroom?')) { - await api.delete(`/classrooms/${id}`); + await classroomService.delete(id); loadData(); } }; diff --git a/frontend/src/pages/exams/ExamMonitor.tsx b/frontend/src/pages/exams/ExamMonitor.tsx index 4ca7a52..39977a3 100644 --- a/frontend/src/pages/exams/ExamMonitor.tsx +++ b/frontend/src/pages/exams/ExamMonitor.tsx @@ -1,9 +1,9 @@ -import React, { useEffect, useState, useRef } from 'react'; +import React, { useEffect, useState, useRef, useCallback } from 'react'; import { useParams, Link } from 'react-router-dom'; import { Client } from '@stomp/stompjs'; import SockJS from 'sockjs-client'; -import api from '../../api/client'; -import type { Exam, ExamMonitorItem, ApiResponse } from '../../types'; +import { examService } from '../../services'; +import type { Exam, ExamMonitorItem } from '../../types'; import { ArrowLeft, MonitorPlay, @@ -24,21 +24,37 @@ export const ExamMonitor: React.FC = () => { const stompClientRef = useRef(null); - const loadData = async () => { + const loadData = useCallback(async () => { + if (!id) return; try { setLoading(true); - const [eRes, mRes] = await Promise.all([ - api.get>(`/exams/${id}`), - api.get>(`/exams/${id}/monitor`), + const [eData, mData] = await Promise.all([ + examService.getById(Number(id)), + examService.getMonitorData(Number(id)), ]); - setExam(eRes.data.data); - setAttempts(mRes.data.data); + setExam(eData); + setAttempts(mData); } catch (e) { console.error(e); } finally { setLoading(false); } - }; + }, [id]); + + const handleRealtimeEvent = useCallback((event: any) => { + if (!id) return; + const { eventType, data } = event; + + if (eventType === 'VIOLATION_REPORTED') { + setRecentAlert(`🚨 VIOLATION: Student ${data.studentName} flagged for ${data.reason}!`); + setTimeout(() => setRecentAlert(null), 6000); + } + + // Refresh telemetry table + examService.getMonitorData(Number(id)) + .then((items) => setAttempts(items)) + .catch(() => {}); + }, [id]); useEffect(() => { if (!id) return; @@ -75,21 +91,7 @@ export const ExamMonitor: React.FC = () => { stompClientRef.current.deactivate(); } }; - }, [id]); - - const handleRealtimeEvent = (event: any) => { - const { eventType, data } = event; - - if (eventType === 'VIOLATION_REPORTED') { - setRecentAlert(`🚨 VIOLATION: Student ${data.studentName} flagged for ${data.reason}!`); - setTimeout(() => setRecentAlert(null), 6000); - } - - // Refresh telemetry table - api.get>(`/exams/${id}/monitor`) - .then((r) => setAttempts(r.data.data)) - .catch(() => {}); - }; + }, [id, loadData, handleRealtimeEvent]); const activeCount = attempts.filter((a) => a.status === 'in_progress').length; const completedCount = attempts.filter((a) => a.status === 'completed' || a.status === 'submitted').length; diff --git a/frontend/src/pages/exams/ExamRunner.tsx b/frontend/src/pages/exams/ExamRunner.tsx index 189573f..9d36d12 100644 --- a/frontend/src/pages/exams/ExamRunner.tsx +++ b/frontend/src/pages/exams/ExamRunner.tsx @@ -1,7 +1,7 @@ -import React, { useEffect, useState, useRef } from 'react'; +import React, { useEffect, useState, useRef, useCallback } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; -import api from '../../api/client'; -import type { ExamStartResponse, ApiResponse } from '../../types'; +import { examService } from '../../services'; +import type { ExamStartResponse } from '../../types'; import { Clock, AlertTriangle, @@ -29,16 +29,39 @@ export const ExamRunner: React.FC = () => { // Submit / Finish states const [submitConfirmOpen, setSubmitConfirmOpen] = useState(false); - const [submittedResult, setSubmittedResult] = useState(null); + const [submittedResult, setSubmittedResult] = useState<{ + score: number; + passed: boolean; + status: string; + totalQuestions: number; + answeredCount: number; + } | null>(null); const attemptIdRef = useRef(null); + const handleSubmitExam = useCallback(async () => { + const attemptId = attemptIdRef.current; + if (!attemptId) return; + + try { + setLoading(true); + const res = await examService.submitExam(attemptId); + setSubmittedResult(res); + setSubmitConfirmOpen(false); + } catch (err: any) { + alert(err.response?.data?.message || 'Failed to submit exam'); + } finally { + setLoading(false); + } + }, []); + useEffect(() => { + if (!id) return; + const startExam = async () => { try { setLoading(true); - const res = await api.post>(`/exams/${id}/start`); - const data = res.data.data; + const data = await examService.startExam(Number(id)); setSession(data); attemptIdRef.current = data.attemptId; setSecondsLeft(data.remainingSeconds); @@ -65,10 +88,8 @@ export const ExamRunner: React.FC = () => { useEffect(() => { const handleVisibilityChange = () => { if (document.hidden && attemptIdRef.current && !submittedResult) { - api.post(`/exams/attempts/${attemptIdRef.current}/violation`, { - reason: 'TAB_SWITCH_OR_MINIMIZED', - }).then((res) => { - const count = res.data.data.violations; + examService.recordViolation(attemptIdRef.current).then((res) => { + const count = res.violations; setViolations(count); if (count >= 5) { alert('Maximum security violations reached (5). Your exam is being automatically submitted.'); @@ -89,7 +110,7 @@ export const ExamRunner: React.FC = () => { document.removeEventListener('visibilitychange', handleVisibilityChange); document.removeEventListener('contextmenu', handleContextMenu); }; - }, [submittedResult]); + }, [submittedResult, handleSubmitExam]); // Timer Countdown useEffect(() => { @@ -107,7 +128,7 @@ export const ExamRunner: React.FC = () => { }, 1000); return () => clearInterval(timer); - }, [secondsLeft, submittedResult]); + }, [secondsLeft, submittedResult, handleSubmitExam]); const handleSelectOption = async (questionId: number, value: string) => { setAnswers((prev) => ({ ...prev, [questionId]: value })); @@ -115,10 +136,7 @@ export const ExamRunner: React.FC = () => { if (session?.attemptId) { setSaving(true); try { - await api.post(`/exams/attempts/${session.attemptId}/answer`, { - questionId, - answerText: value, - }); + await examService.saveAnswer(session.attemptId, questionId, value); } catch (e) { console.error('Failed to autosave answer', e); } finally { @@ -127,21 +145,6 @@ export const ExamRunner: React.FC = () => { } }; - const handleSubmitExam = async () => { - if (!session?.attemptId) return; - - try { - setLoading(true); - const res = await api.post(`/exams/attempts/${session.attemptId}/submit`); - setSubmittedResult(res.data.data); - setSubmitConfirmOpen(false); - } catch (err: any) { - alert(err.response?.data?.message || 'Failed to submit exam'); - } finally { - setLoading(false); - } - }; - const formatTime = (secs: number) => { const h = Math.floor(secs / 3600); const m = Math.floor((secs % 3600) / 60); diff --git a/frontend/src/services/announcementService.ts b/frontend/src/services/announcementService.ts new file mode 100644 index 0000000..67affd5 --- /dev/null +++ b/frontend/src/services/announcementService.ts @@ -0,0 +1,23 @@ +import api from '../api/client'; +import type { Announcement, ApiResponse } from '../types'; + +export const announcementService = { + async getAll(): Promise { + const res = await api.get>('/announcements'); + return res.data.data; + }, + + async create(data: { title: string; content: string; target: string; published: boolean }): Promise { + const res = await api.post>('/announcements', data); + return res.data.data; + }, + + async update(id: number, data: Partial): Promise { + const res = await api.put>(`/announcements/${id}`, data); + return res.data.data; + }, + + async delete(id: number): Promise { + await api.delete(`/announcements/${id}`); + }, +}; diff --git a/frontend/src/services/assignmentService.ts b/frontend/src/services/assignmentService.ts new file mode 100644 index 0000000..ea972a7 --- /dev/null +++ b/frontend/src/services/assignmentService.ts @@ -0,0 +1,53 @@ +import api from '../api/client'; +import type { ApiResponse, Assignment, Discussion, Submission } from '../types'; + +export const assignmentService = { + async getAll(): Promise { + const res = await api.get>('/assignments'); + return res.data.data; + }, + + async getById(id: number): Promise { + const res = await api.get>(`/assignments/${id}`); + return res.data.data; + }, + + async create(data: Partial): Promise { + const res = await api.post>('/assignments', data); + return res.data.data; + }, + + async update(id: number, data: Partial): Promise { + const res = await api.put>(`/assignments/${id}`, data); + return res.data.data; + }, + + async delete(id: number): Promise { + await api.delete(`/assignments/${id}`); + }, + + async submit(assignmentId: number, data: { filePath?: string; notes?: string }): Promise { + const res = await api.post>(`/assignments/${assignmentId}/submit`, data); + return res.data.data; + }, + + async getSubmissions(assignmentId: number): Promise { + const res = await api.get>(`/assignments/${assignmentId}/submissions`); + return res.data.data; + }, + + async gradeSubmission(submissionId: number, data: { score: number; feedback?: string }): Promise { + const res = await api.post>(`/assignments/submissions/${submissionId}/grade`, data); + return res.data.data; + }, + + async getDiscussions(assignmentId: number): Promise { + const res = await api.get>(`/assignments/${assignmentId}/discussions`); + return res.data.data; + }, + + async createDiscussion(assignmentId: number, data: { parentId?: number | null; message: string }): Promise { + const res = await api.post>(`/assignments/${assignmentId}/discussions`, data); + return res.data.data; + }, +}; diff --git a/frontend/src/services/authService.ts b/frontend/src/services/authService.ts new file mode 100644 index 0000000..0264704 --- /dev/null +++ b/frontend/src/services/authService.ts @@ -0,0 +1,29 @@ +import api from '../api/client'; +import type { ApiResponse, AuthResponse, User } from '../types'; + +export const authService = { + async login(email: string, password: string):Promise { + const res = await api.post>('/auth/login', { email, password }); + return res.data.data; + }, + + async register(data: { name: string; email: string; password: string; nis?: string; gender?: string }): Promise { + const res = await api.post>('/auth/register', data); + return res.data.data; + }, + + async getProfile(): Promise { + const res = await api.get>('/auth/me'); + return res.data.data; + }, + + async impersonate(userId: number): Promise { + const res = await api.post>(`/admin/impersonate/${userId}`); + return res.data.data; + }, + + async stopImpersonate(): Promise { + const res = await api.post>('/admin/stop-impersonate'); + return res.data.data; + }, +}; diff --git a/frontend/src/services/classroomService.ts b/frontend/src/services/classroomService.ts new file mode 100644 index 0000000..6c6e6dc --- /dev/null +++ b/frontend/src/services/classroomService.ts @@ -0,0 +1,36 @@ +import api from '../api/client'; +import type { ApiResponse, Classroom } from '../types'; + +export interface ClassroomInput { + name: string; + level: number; + capacity: number; + academicYear: string; + homeroomTeacherId?: number | null; +} + +export const classroomService = { + async getAll(): Promise { + const res = await api.get>('/classrooms'); + return res.data.data; + }, + + async getById(id: number): Promise { + const res = await api.get>(`/classrooms/${id}`); + return res.data.data; + }, + + async create(data: ClassroomInput): Promise { + const res = await api.post>('/classrooms', data); + return res.data.data; + }, + + async update(id: number, data: ClassroomInput): Promise { + const res = await api.put>(`/classrooms/${id}`, data); + return res.data.data; + }, + + async delete(id: number): Promise { + await api.delete(`/classrooms/${id}`); + }, +}; diff --git a/frontend/src/services/examService.ts b/frontend/src/services/examService.ts new file mode 100644 index 0000000..0ef8d5a --- /dev/null +++ b/frontend/src/services/examService.ts @@ -0,0 +1,105 @@ +import api from '../api/client'; +import type { ApiResponse, Exam, ExamMonitorItem, ExamStartResponse, Question } from '../types'; + +export const examService = { + async getAll(): Promise { + const res = await api.get>('/exams'); + return res.data.data; + }, + + async getById(id: number): Promise { + const res = await api.get>(`/exams/${id}`); + return res.data.data; + }, + + async create(data: Partial): Promise { + const res = await api.post>('/exams', data); + return res.data.data; + }, + + async update(id: number, data: Partial): Promise { + const res = await api.put>(`/exams/${id}`, data); + return res.data.data; + }, + + async delete(id: number): Promise { + await api.delete(`/exams/${id}`); + }, + + async updateStatus(id: number, status: string): Promise { + const res = await api.patch>(`/exams/${id}/status`, { status }); + return res.data.data; + }, + + async getQuestions(id: number): Promise { + const res = await api.get>(`/exams/${id}/questions`); + return res.data.data; + }, + + async createQuestion(examId: number, data: Partial): Promise { + const res = await api.post>(`/exams/${examId}/questions`, data); + return res.data.data; + }, + + async updateQuestion(examId: number, questionId: number, data: Partial): Promise { + const res = await api.put>(`/exams/${examId}/questions/${questionId}`, data); + return res.data.data; + }, + + async deleteQuestion(examId: number, questionId: number): Promise { + await api.delete(`/exams/${examId}/questions/${questionId}`); + }, + + async importQuestionsExcel(examId: number, file: File): Promise<{ count: number }> { + const formData = new FormData(); + formData.append('file', file); + const res = await api.post>(`/exams/${examId}/questions/import-excel`, formData, { + headers: { 'Content-Type': 'multipart/form-data' }, + }); + return res.data.data; + }, + + // CBT Exam Runner + async startExam(examId: number): Promise { + const res = await api.post>(`/exams/${examId}/start`); + return res.data.data; + }, + + async saveAnswer(attemptId: number, questionId: number, answer: string): Promise { + await api.post(`/exams/attempts/${attemptId}/answer`, { questionId, answer }); + }, + + async recordViolation(attemptId: number): Promise<{ violations: number }> { + const res = await api.post>(`/exams/attempts/${attemptId}/violation`); + return res.data.data; + }, + + async submitExam(attemptId: number): Promise<{ + score: number; + passed: boolean; + status: string; + totalQuestions: number; + answeredCount: number; + }> { + const res = await api.post>(`/exams/attempts/${attemptId}/submit`); + return res.data.data; + }, + + async gradeEssay(attemptId: number, answerId: number, pointsAwarded: number, isCorrect: boolean): Promise { + await api.post(`/exams/attempts/${attemptId}/answers/${answerId}/grade-essay`, { + pointsAwarded, + isCorrect, + }); + }, + + async getMonitorData(examId: number): Promise { + const res = await api.get>(`/exams/${examId}/monitor`); + return res.data.data; + }, +}; diff --git a/frontend/src/services/gradeService.ts b/frontend/src/services/gradeService.ts new file mode 100644 index 0000000..441a409 --- /dev/null +++ b/frontend/src/services/gradeService.ts @@ -0,0 +1,9 @@ +import api from '../api/client'; +import type { ApiResponse, GradeReportResponse } from '../types'; + +export const gradeService = { + async getStudentGrades(): Promise { + const res = await api.get>('/student/grades'); + return res.data.data; + }, +}; diff --git a/frontend/src/services/index.ts b/frontend/src/services/index.ts new file mode 100644 index 0000000..c2b2406 --- /dev/null +++ b/frontend/src/services/index.ts @@ -0,0 +1,10 @@ +export * from './authService'; +export * from './classroomService'; +export * from './subjectService'; +export * from './teacherService'; +export * from './studentService'; +export * from './examService'; +export * from './assignmentService'; +export * from './materialService'; +export * from './announcementService'; +export * from './gradeService'; diff --git a/frontend/src/services/materialService.ts b/frontend/src/services/materialService.ts new file mode 100644 index 0000000..547d63f --- /dev/null +++ b/frontend/src/services/materialService.ts @@ -0,0 +1,37 @@ +import api from '../api/client'; +import type { ApiResponse, LearningMaterial } from '../types'; + +export const materialService = { + async getAll(): Promise { + const res = await api.get>('/materials'); + return res.data.data; + }, + + async getById(id: number): Promise { + const res = await api.get>(`/materials/${id}`); + return res.data.data; + }, + + async create(data: Partial): Promise { + const res = await api.post>('/materials', data); + return res.data.data; + }, + + async update(id: number, data: Partial): Promise { + const res = await api.put>(`/materials/${id}`, data); + return res.data.data; + }, + + async delete(id: number): Promise { + await api.delete(`/materials/${id}`); + }, + + async recordView(materialId: number): Promise { + await api.post(`/materials/${materialId}/views`); + }, + + async getViewers(materialId: number): Promise<{ studentId: number; studentName: string; viewedAt: string }[]> { + const res = await api.get>(`/materials/${materialId}/viewers`); + return res.data.data; + }, +}; diff --git a/frontend/src/services/studentService.ts b/frontend/src/services/studentService.ts new file mode 100644 index 0000000..b82ff96 --- /dev/null +++ b/frontend/src/services/studentService.ts @@ -0,0 +1,54 @@ +import api from '../api/client'; +import type { ApiResponse, Student, StudentExamCard } from '../types'; + +export interface StudentInput { + name: string; + email: string; + nis: string; + nisn?: string; + gender: 'M' | 'F'; + classroomId?: number | null; + phone?: string; + address?: string; + password?: string; +} + +export const studentService = { + async getAll(): Promise { + const res = await api.get>('/students'); + return res.data.data; + }, + + async getById(id: number): Promise { + const res = await api.get>(`/students/${id}`); + return res.data.data; + }, + + async create(data: StudentInput): Promise { + const res = await api.post>('/students', data); + return res.data.data; + }, + + async update(id: number, data: Partial): Promise { + const res = await api.put>(`/students/${id}`, data); + return res.data.data; + }, + + async delete(id: number): Promise { + await api.delete(`/students/${id}`); + }, + + async getExamCards(): Promise { + const res = await api.get>('/students/exam-cards'); + return res.data.data; + }, + + async importExcel(file: File): Promise<{ count: number }> { + const formData = new FormData(); + formData.append('file', file); + const res = await api.post>('/students/import-excel', formData, { + headers: { 'Content-Type': 'multipart/form-data' }, + }); + return res.data.data; + }, +}; diff --git a/frontend/src/services/subjectService.ts b/frontend/src/services/subjectService.ts new file mode 100644 index 0000000..77e35d0 --- /dev/null +++ b/frontend/src/services/subjectService.ts @@ -0,0 +1,36 @@ +import api from '../api/client'; +import type { ApiResponse, Subject } from '../types'; + +export interface SubjectInput { + name: string; + code: string; + description?: string; + credits: number; + teacherId?: number | null; +} + +export const subjectService = { + async getAll(): Promise { + const res = await api.get>('/subjects'); + return res.data.data; + }, + + async getById(id: number): Promise { + const res = await api.get>(`/subjects/${id}`); + return res.data.data; + }, + + async create(data: SubjectInput): Promise { + const res = await api.post>('/subjects', data); + return res.data.data; + }, + + async update(id: number, data: SubjectInput): Promise { + const res = await api.put>(`/subjects/${id}`, data); + return res.data.data; + }, + + async delete(id: number): Promise { + await api.delete(`/subjects/${id}`); + }, +}; diff --git a/frontend/src/services/teacherService.ts b/frontend/src/services/teacherService.ts new file mode 100644 index 0000000..c1da1b6 --- /dev/null +++ b/frontend/src/services/teacherService.ts @@ -0,0 +1,37 @@ +import api from '../api/client'; +import type { ApiResponse, Teacher } from '../types'; + +export interface TeacherInput { + name: string; + email: string; + nip: string; + phone?: string; + address?: string; + password?: string; +} + +export const teacherService = { + async getAll(): Promise { + const res = await api.get>('/teachers'); + return res.data.data; + }, + + async getById(id: number): Promise { + const res = await api.get>(`/teachers/${id}`); + return res.data.data; + }, + + async create(data: TeacherInput): Promise { + const res = await api.post>('/teachers', data); + return res.data.data; + }, + + async update(id: number, data: Partial): Promise { + const res = await api.put>(`/teachers/${id}`, data); + return res.data.data; + }, + + async delete(id: number): Promise { + await api.delete(`/teachers/${id}`); + }, +}; diff --git a/frontend/src/store/authStore.ts b/frontend/src/store/authStore.ts index b63559e..120e906 100644 --- a/frontend/src/store/authStore.ts +++ b/frontend/src/store/authStore.ts @@ -1,6 +1,6 @@ import { create } from 'zustand'; -import api from '../api/client'; -import type { User, AuthResponse, ApiResponse } from '../types'; +import { authService } from '../services'; +import type { User } from '../types'; interface AuthState { user: User | null; @@ -41,8 +41,7 @@ export const useAuthStore = create((set) => ({ login: async (email: string, password: string) => { set({ isLoading: true }); try { - const response = await api.post>('/auth/login', { email, password }); - const data = response.data.data; + const data = await authService.login(email, password); const user: User = { id: data.userId, @@ -71,8 +70,7 @@ export const useAuthStore = create((set) => ({ }, impersonate: async (userId: number) => { - const response = await api.post>(`/admin/impersonate/${userId}`); - const data = response.data.data; + const data = await authService.impersonate(userId); const user: User = { id: data.userId, @@ -91,8 +89,7 @@ export const useAuthStore = create((set) => ({ }, stopImpersonate: async () => { - const response = await api.post>('/admin/stop-impersonate'); - const data = response.data.data; + const data = await authService.stopImpersonate(); const user: User = { id: data.userId, From c9fde4c28f6944852c82824f2c038016d1166058 Mon Sep 17 00:00:00 2001 From: M Fari Madyan Date: Tue, 13 Oct 2026 07:47:39 +0700 Subject: [PATCH 5/5] test(backend): isolate test suite with DatabaseCleaner truncation and resilient fixtures --- backend/spec/rails_helper.rb | 5 +++++ backend/spec/repositories/user_repository_spec.rb | 4 +++- backend/spec/requests/api/v1/auth_spec.rb | 10 +++++++++- backend/spec/requests/api/v1/classrooms_spec.rb | 9 ++++++--- 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/backend/spec/rails_helper.rb b/backend/spec/rails_helper.rb index abb56a4..fee638f 100644 --- a/backend/spec/rails_helper.rb +++ b/backend/spec/rails_helper.rb @@ -2,6 +2,7 @@ require_relative '../config/environment' abort("The Rails environment is running in production mode!") if Rails.env.production? require 'rspec/rails' +require 'database_cleaner/active_record' begin ActiveRecord::Migration.maintain_test_schema! @@ -14,6 +15,10 @@ config.infer_spec_type_from_file_location! config.filter_rails_from_backtrace! + config.before(:suite) do + DatabaseCleaner.clean_with(:truncation) + end + def auth_headers_for(user) token = JsonWebToken.encode(user_id: user.id) { 'Authorization' => "Bearer #{token}" } diff --git a/backend/spec/repositories/user_repository_spec.rb b/backend/spec/repositories/user_repository_spec.rb index e55cb92..16afdd5 100644 --- a/backend/spec/repositories/user_repository_spec.rb +++ b/backend/spec/repositories/user_repository_spec.rb @@ -17,7 +17,9 @@ describe '#find_admin' do it 'returns an admin user' do - expect(repo.find_admin).to eq(user) + admin = repo.find_admin + expect(admin).to be_present + expect(admin.role).to eq('ROLE_ADMIN') end end end diff --git a/backend/spec/requests/api/v1/auth_spec.rb b/backend/spec/requests/api/v1/auth_spec.rb index 0ce2422..abe9d27 100644 --- a/backend/spec/requests/api/v1/auth_spec.rb +++ b/backend/spec/requests/api/v1/auth_spec.rb @@ -1,7 +1,15 @@ require 'rails_helper' RSpec.describe 'Api::V1::Auth', type: :request do - let!(:user) { User.create!(name: 'Admin Test', email: 'admin@elearning.test', password: 'password123', role: 'ROLE_ADMIN') } + let!(:user) do + existing = User.find_by(email: 'admin@elearning.test') + if existing + existing.update!(password: 'password123') + existing + else + User.create!(name: 'Admin Test', email: 'admin@elearning.test', password: 'password123', role: 'ROLE_ADMIN') + end + end describe 'POST /api/v1/auth/login' do it 'returns JWT access token on valid credentials' do diff --git a/backend/spec/requests/api/v1/classrooms_spec.rb b/backend/spec/requests/api/v1/classrooms_spec.rb index 7f1a39b..af56e95 100644 --- a/backend/spec/requests/api/v1/classrooms_spec.rb +++ b/backend/spec/requests/api/v1/classrooms_spec.rb @@ -1,8 +1,11 @@ require 'rails_helper' RSpec.describe 'Api::V1::Classrooms', type: :request do - let!(:admin) { User.create!(name: 'Admin', email: 'admin@elearning.test', password: 'password123', role: 'ROLE_ADMIN') } - let!(:classroom) { Classroom.create!(name: '10-A', level: 10, capacity: 36, academic_year: '2025/2026') } + let!(:admin) do + User.find_by(email: 'admin@elearning.test') || + User.create!(name: 'Admin', email: 'admin@elearning.test', password: 'password123', role: 'ROLE_ADMIN') + end + let!(:classroom) { Classroom.find_by(name: '10-A') || Classroom.create!(name: '10-A', level: 10, capacity: 36, academic_year: '2025/2026') } describe 'GET /api/v1/classrooms' do it 'returns list of classrooms' do @@ -12,7 +15,7 @@ body = JSON.parse(response.body) expect(body['success']).to be true expect(body['data']).to be_an(Array) - expect(body['data'].first['name']).to eq('10-A') + expect(body['data'].any? { |c| c['name'] == '10-A' }).to be true end end