Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

296 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RikiPath.Backend — EF Core Migration & Database Safety Standards

Mentor homework attachments

Configure Supabase:Url, Supabase:Bucket, Supabase:ServiceRoleKey and Supabase:VerificationBucket on the backend. The private bucket can be named rikipath-private-documents; set Supabase__VerificationBucket=rikipath-private-documents in environments without local appsettings. A server-side service/secret key is required. When this configured bucket is missing, the storage service creates it as private on first use and verifies that it remains private. It will reject an existing public bucket. Do not put the secret key in frontend configuration.

Mentors upload JPG, PNG, PDF or DOCX (10 MB per file) with POST /api/homework/draft-files. The response contains a short-lived signed previewUrl and an owner-bound draft token. GET /api/homework/draft-files/preview-content returns a read-only Word preview; GET /api/homework/draft-files/preview streams the original for images and PDFs. Pass promptDraftTokens and answerDraftTokens to POST /api/homework/cohorts/{cohortId}/with-files when assigning. The existing multipart file fields still work for older clients. The assignment, attachments and learner notifications are saved together; answer keys are visible only to the Mentor/Admin.

Class lifecycle with direct transitions

Scheduled dates remain planning and conflict-check inputs. Authorized Mentors can close enrollment after at least one confirmed enrollment, start the next valid session, mark attendance, and end it without waiting for scheduled time. No mode flag, environment switch or special time control is used. PayOS verification and financial expiry remain unchanged. Existing automatic enrollment-deadline processing remains active.

Legacy minimum-enrollment/preparation fields remain in stored policy revisions for compatibility but are no longer operational timing gates or editable controls. Effective proposal preview values are zero; checkout hold minutes and all financial policy fields remain active.

  • Mentor endpoints: POST /api/study-courses/cohorts/{cohortId}/close-enrollment, POST /api/study-courses/cohorts/{cohortId}/sessions/{sessionId}/start and /end. Session IDs come from the cohort API, not individual learner attendance IDs. Capabilities in the API drive Web controls. Ownership, class/schedule locks, sequence, one live session per Mentor and outbox idempotency are enforced.
  • Migration 20261129090000_PersistClassSessionLifecycle adds nullable Status, ActualStartedAtUtc, ActualEndedAtUtc to StudyCohortSessions; existing scheduled dates and relationships are preserved. Completed backfill requires final attendance for every current confirmed enrollment. Cancelled cohorts backfill remaining sessions as Cancelled. Ambiguous, partially attended or rescheduled legacy histories retain null; actual timestamps are never invented. Review unresolved history individually before advancing past those sessions. New sessions start as Scheduled.
  • When the Mentor explicitly ends the final required valid session, the class lock protects automatic class/enrollment completion and review eligibility. All required sessions and roster attendance must be completed; no Admin confirmation, homework completion, feedback, review or complaint is required. No background time-skip operation writes attendance or completes classes.
  • Direct attendance does not require Meeting joins. A started class session permits early room access, direct attendance and homework. Absent and ExcusedAbsent are valid final attendance; no attendance/grade is generated automatically. Homework due dates and submission policies remain independent.
  • Before release, verify build/analyzers and offline model parity; rehearse this migration on clean and representative isolated QA databases with a verified backup. No migration is applied by startup. Server migration, restart and deployment each require separate approval. Export lifecycle evidence before any approved rollback because Down removes the new fields.

Admin-created cohorts and mentor invitations

  • Admin creates a draft class and its future session times through POST /api/study-courses/cohorts; POST /api/study-courses/cohorts/mentor-candidates returns verified mentors qualified for the plan level and free in every selected slot. The database stores each mentor offer in StudyCohortMentorInvitations, preserving decline, acceptance and reassignment history. POST /api/study-courses/cohorts/{cohortId}/mentor-invitations can invite the next eligible mentor after a decline.
  • The invited mentor can list their offers at GET /api/study-courses/cohort-mentor-invitations, then accept or decline. Decline requires a reason. Acceptance rechecks teaching level and schedule conflicts, approves the cohort session slots and changes the cohort from Draft to Published; learners can discover and enroll only after that transition. Admin receives outbox notifications for acceptance, decline and mentor change requests.
  • FE flow: call POST /api/study-courses/cohorts/mentor-candidates with { "planId": 1, "sessions": [{ "startsAtUtc": "2027-01-01T02:00:00Z", "endsAtUtc": "2027-01-01T03:00:00Z" }] } (provide every session required by the plan). Then call POST /api/study-courses/cohorts with the same planId and sessions, plus name, chosen mentorId and a new idempotencyKey UUID. The response gives cohortId and invitationId. Mentor lists invitations and calls POST /api/study-courses/cohort-mentor-invitations/{invitationId}/accept or /decline with { "reason": "..." }. The invitation response includes its status, session times and cohortRevisionAtInvite; after a decline, Admin selects another mentor and calls POST /api/study-courses/cohorts/{cohortId}/mentor-invitations with mentorId, reason, a new UUID and the current expectedCohortRevision. A changed class schedule invalidates an outstanding invitation; Admin must cancel and resend it.
  • For an active cohort, mentor schedule changes go to POST /api/study-courses/cohorts/{cohortId}/mentor-change-requests; Admin invites a replacement and the new mentor must accept before future sessions move. Learners request a class transfer through the existing /{courseId}/transfer-requests workflow; Admin chooses/approves the destination and the learner's enrollment is moved in one transaction. Per-session learner/mentor changes to group classes are rejected.
  • Mentor-authored teaching proposal submission/open-enrollment and Admin proposal approval endpoints return 409 MENTOR_SELF_SCHEDULING_CLOSED. StudyCohortMentorInvitations is added by migration 20261201081546_AddAdminCohortMentorInvitations; it is additive and its Down refuses to discard invitation history. Do not apply it to Shared Supabase from a feature branch; follow the isolated QA and release preflight above.
  • Migration 20261201132000_MakeCohortsPlanless stores the learner-facing StudyCohort.Level, backfills level and missing class tuition from historical plans, removes StudyCohorts.PlanId, and makes StudyCourses.PlanId nullable for direct class enrollment. Historical course orders retain their existing plan references and payment snapshots. Its Down refuses rollback because a new class cannot be mapped back to a plan. The Admin sets class tuition directly; learner enrollment pays that exact class price through PayOS. Review the generated SQL and rehearse on an isolated database before deployment; startup never applies this migration.
  • Migration 20261201135156_RepairCohortInvitationRevision repairs a database where the invitation migration is recorded as applied but StudyCohortMentorInvitations.CohortRevisionAtInvite is absent. It adds the required integer column only when the invitation table is empty, verifies its type and nullability, and leaves correct databases unchanged. A populated incomplete table requires manual review because the original invite-time revision cannot be reconstructed safely. The read-only preflight checks this column when the original migration is marked applied. Rehearse and obtain the normal shared database approval before applying the repair; the migration is never applied at startup.
  • The operator will review each Stage through the UI after deployment. Full automated end-to-end acceptance is not a prerequisite for this handoff. Migration rehearsal already succeeded on a clean isolated database (25 migrations, including idempotent replay) and a restored local-data clone (76 to 77 history rows); existing class, enrollment, schedule and attendance fingerprints were preserved. The clone's 22 unresolved historical sessions retained null lifecycle status and actual timestamps. Server identity/history and backup/restore still require preflight before an approved server migration.

ZIP tài liệu chuẩn bị theo cấp độ

  • Admin quản lý ZIP dùng chung cho từng cấp JLPT N5–N2 qua GET /api/admin/level-preparation-zips và GET/PUT /api/admin/level-preparation-zips/{level} (PUT nhận multipart file). Tệp nằm trong bucket Supabase private ở level-preparation/{level}/materials.zip; API danh sách chỉ trả trạng thái có ZIP, không công khai URL.
  • Khi tạo lớp, Backend kiểm tra ZIP của level đã tồn tại và trả 409 COHORT_PREPARATION_ZIP_REQUIRED nếu thiếu. Form tạo lớp không tải ZIP lên. GET /api/study-courses/cohorts/{cohortId}/preparation-zip giữ kiểm tra quyền cũ rồi ký URL ngắn hạn của ZIP theo level. Thay ZIP cấp độ áp dụng ngay cho mọi lớp cùng cấp; ZIP riêng của lớp cũ chỉ được dùng khi cấp độ chưa có ZIP chung.
  • Không thay đổi entity, schema hay migration cho luồng này.

Admin AI configuration

  • GET /api/admin/ai-configuration returns the active models, provider endpoints, timeouts, token limits and per-user quotas. It reports whether each provider key is set, but never returns a key.
  • PUT /api/admin/ai-configuration saves the complete editable configuration. Send the revision returned by GET as expectedRevision; the OpenAI key can be supplied in settings.OpenAI.ApiKey alongside BaseUrl, all six feature models, timeout and token limits, as in the server configuration shape. OpenRouter accepts openRouterApiKey and Gemini accepts up to two geminiApiKeys. Empty key fields keep existing keys. Use the matching clear...ApiKey flag to remove one. The API accepts Admin only, validates provider URLs and limits, rejects stale revisions with 409, protects keys with ASP.NET Data Protection and records non-secret before/after values in AdminAuditLogs.
  • AI clients read the live configuration from an in-process cache and refresh it from the database every 15 seconds. The instance that saves a change applies it immediately. Until the first database configuration exists, settings fall back to appsettings/environment values.
  • Migration 20261201143534_AddAdminAiRuntimeConfiguration creates the singleton AiRuntimeConfigurations row store on the first Admin save. Startup never applies this migration. Back up and retain the ASP.NET Data Protection key ring across restarts (and share it between API instances); configure AiConfiguration:DataProtectionKeysPath to a persistent path when the deployment does not retain the default key directory. Losing the key ring prevents decryption of saved provider keys.

Core Safety Rules

  1. Never run migrations against an unverified database target.
    • Always verify the resolved Host and Database via tools/verify-migration-readiness.ps1 before running dotnet ef database update.
    • Keep Local, QA (127.0.0.1:55439), Staging, and Production / Shared Supabase strictly separated.
    • AppDbContextDesignTimeFactory blocks unapproved database update / database drop commands targeting remote Supabase hosts (*.supabase.co, *.supabase.com) unless RIKIPATH_ALLOW_REMOTE_DB_MIGRATION=true (or -- --allow-remote-database) is explicitly provided after review.
  2. Never store credentials in source code, scripts, logs, or reports.
    • Supply connection strings via environment variables (AppSettings__ConnectionStrings__DefaultConnection / ConnectionStrings__DefaultConnection), User Secrets, or CI secret stores. Never print secrets in preflight or CI logs.
  3. Every domain entity / Fluent configuration change requires a reviewed migration (zero drift).
    • CI & pre-merge must verify clean compilation (dotnet build RikiPath.Backend.slnx) and offline migration parity via ./tools/verify-migration-readiness.ps1 -SkipDatabaseCheck (HasPendingModelChanges() == false, zero duplicate IDs, matching .Designer.cs files).
  4. Never arbitrarily rewrite, delete, or squash previously deployed migrations, nor mix independent branches directly on shared DBs.
    • Do not run dotnet ef database update from unmerged feature branches against Shared Supabase.
    • Every migration requires an explicit PR owner; cross-branch migrations must be integrated into the canonical branch before shared deployment.
  5. No destructive migration without an approved data-migration strategy, and no blind history tampering.
    • Never insert rows into "__EFMigrationsHistory" unless schema columns, constraints, and indexes are structurally verified (ReconcileSharedMigrationHistory.sql).
    • Never assume Down() is lossless on production data.
  6. Always rehearse on an isolated QA clone (127.0.0.1:55439) first.
    • Verify database identity, pre-check, reconciliation, pending migrations, schema parity, idempotency, existing data preservation, and Backend API smoke checks before requesting backup & shared deployment approval.
  7. One migration writer per shared database.
    • Require the Migration governance pull-request check and a named migration owner in branch protection; never use a feature-branch connection string to mutate Shared Supabase.
    • Before an approved release, the owner records the exact source SHA, read-only history/schema fingerprint, tested backup, a team-wide write freeze, and the deployment window. Re-run the fingerprint under the freeze; any change invalidates approval and requires a new QA clone.
    • Keep the remote migration override disabled outside that approved window. CI and routine Web API startup must not run schema migrations.

Automated Read-Only Tooling & Release Package

  • Fresh empty database initialization (local / isolated Docker PostgreSQL only — never integrated into VPS deployment):

    Brand-new empty local/Docker PostgreSQL databases can initialize cleanly using the fail-closed local bootstrap script (existing databases upgrade via standard reviewed EF Core migrations after preflight verification):

    .\tools\bootstrap-fresh-database.ps1 -ConnectionString "Host=localhost;Port=5432;Database=rikipath_fresh;Username=postgres;Password=..."
    Or on Linux / Docker:
    ./tools/bootstrap-fresh-database.sh --appsettings /path/to/appsettings.json
  • Offline CI build & migration checks:
    dotnet build RikiPath.Backend.slnx -c Release
    .\tools\verify-migration-readiness.ps1 -SkipDatabaseCheck -NoBuild
  • Live target read-only preflight:
    .\tools\verify-migration-readiness.ps1
  • Full Deployment, Post-Deployment & Rollback Runbook: See Docs/MigrationReleaseReadiness.md.
  • Security, Code Quality, CI/CD & Branch Protection Standards: See Docs/BACKEND_SECURITY_AND_ENGINEERING_STANDARDS.md.

Feedback, official reviews and complaints

  • Private learning feedback uses CohortLearningFeedback; the existing star-based content feedback cannot represent this workflow. Only its learner and the current class Mentor can read it or download private evidence. New feedback closes after completion; history and pending replies remain available.
  • Official class ratings require a completed, paid/partially-refunded enrollment and class, and existing attendance eligibility. Creation locks the enrollment and permits one review per enrollment. Historical rows are retained; only one eligible visible row per enrollment contributes to aggregates. Existing public-comment moderation policy is preserved.
  • Complaints reuse CohortComplaints and append-only events. Admin explicitly grants a redacted Mentor prompt and optional access to the original evidence. Supplements remain private to the learner and Admin. No grant is backfilled for historical complaints. NeedsInformation and Withdrawn extend existing statuses without rewriting history.
  • Enrollment/payment support is available from My Courses before the class workspace opens, including payments under review. It does not grant class access or reconcile/approve payment.
  • Migration 20261129110000_AddLearningFeedbackAndComplaintWorkflow depends on the existing chain including 20261129090000_PersistClassSessionLifecycle. It adds a separate feedback table and nullable complaint metadata; existing rows, subscriptions, attendance and ratings are retained. Down refuses rollback if new workflow data exists.
  • This change was reviewed statically only at the user's instruction: no build, lint, typecheck, tests, migration generation/apply, runtime API or database checks. The designer/snapshot were prepared in source and are not a verified EF-generated artifact. Do not deploy or commit migrations until build/analyzers, model-drift, migration source review, clean and populated isolated QA rehearsals pass.
  • Migration 20261130120000_AddHomeworkFiles (after 20261130013913_AlignMockQuestionSectionIndex) is additive only: HomeworkAssignmentAttachments (Mentor đề bài Prompt / đáp án AnswerKey, one row per recipient sharing a FileKey) and HomeworkSubmissionFiles (multi-file learner submissions). Existing assignments, submissions and the legacy single PrivateScanReference are untouched. Files reuse the private-verification bucket (JPG/PNG/PDF, 10 MB each, max 5 per upload); clients only see FileKey. Down drops both tables (export file metadata first; stored objects stay in the bucket). Homework submit/edit is rejected after DueAt (HOMEWORK_DEADLINE_PASSED); grading after the deadline is allowed. Prepared statically (no build, no dotnet ef): the Designer/snapshot were written in source and must be re-verified with verify-migration-readiness.ps1 before any apply.
  • Homework simplification (no new migration beyond AddHomeworkFiles): new class homework has no type; the Mentor's private đáp án text is stored in the existing AuthoredDefinitionJson (AnswerGuide, returned only to Mentor/Admin). Giao bài with files uses POST /api/homework/cohorts/{id}/with-files (uploads before any row is saved); DueAt is required. Private storage additionally accepts Word DOCX (ZIP + word/document.xml, no vbaProject.bin); legacy .doc is rejected. The private read cap is 10 MB (was 5 MB, below the 10 MB homework upload cap). Scores stay stored 0–100 and are shown 0–10; Passed is optional. Publishing accepts ExpectedRevision and returns 409 HOMEWORK_SUBMISSION_CHANGED if the learner edited meanwhile. Mentor access to class homework now follows the class's current Mentor (Cohort.MentorId), also for the sidebar counter. AI drafting reads typed text, DOCX XML, PDF text layers and OCRs only images / scanned PDF pages / image-only Word files, cached per private reference in IMemoryCache (6 h, per instance) with a per-assignment in-flight guard.
  • Deployment preflight must identify the target and migration history, verify a database plus private-evidence backup/restore, inspect pending DDL and confirm branch parity. Apply only through the separately approved deployment process. After deployment manually verify each role's ownership, duplicate requests, scoped evidence, notification delivery, terminal complaints and final-session completion. Prefer a forward correction; do not downgrade to an old app unable to understand new statuses or manually edit migration history.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages