diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..0178151 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,58 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project + +APLP Backend — backend for **aplp-web** (Adaptive Personal Learning Platform, learner-facing app). Java 21, Spring Boot 3.5 (parent pin: `spring-boot-starter-parent` 4.1.0), Maven, modular monolith with Clean Architecture layers, DDD-oriented, vertical-slice per business module. + +## Commands + +```bash +docker compose up -d db # start Postgres (see docker-compose.yml for port) +./mvnw spring-boot:run # run app, dev profile, port 8080 +./mvnw test # run tests (H2, Postgres-compatible mode) +./mvnw test -Dtest=AuthFlowIntegrationTest # run a single test class +./mvnw package # build jar +curl http://localhost:8080/actuator/health # liveness/readiness check +``` + +No lint/format command is configured in `pom.xml`. + +## Architecture + +Request flow: `Controller → Application/Service (use case) → Domain → Persistence → DB`. Dependencies point inward only (API → Application → Domain); persistence implements repository interfaces defined in domain. + +Each business module is a vertical slice under `src/main/java/aplp/backend/web//`: + +``` +/ +├── api/controller/ # REST controllers +├── application/ +│ ├── dtos/ # request/response DTOs +│ ├── mappers/ # manual DTO <-> domain mapping (no MapStruct despite it being on the classpath) +│ └── services/ # use case orchestration, @Transactional +├── domain/ +│ ├── entities/ # domain model — in practice these ARE the JPA entities (@Entity, jakarta.persistence.* live here directly, not layered out into a separate persistence model) +│ ├── exceptions/ # DomainException-style, mapped to HTTP in GlobalExceptionHandler +│ └── repositories/ # repository interfaces (impl lives in infrastructure/persistence) +└── infrastructure/persistence/ # Spring Data JPA repos + Repository interface implementations +``` + +Note: `docs/ARCHITECTURE.md`, `docs/CONVENTIONS.md`, `docs/MODULES.md` describe the intended design (package `com.aplp.backend`, a `persistence` layer with entities split from domain model). The actual code uses base package `aplp.backend.web` and puts JPA entities directly in `domain/entities`, with only repository *implementations* in `infrastructure/persistence`. Follow the existing code pattern (`identity`, `learner` modules), not the docs, when in doubt — the docs are aspirational/Phase 0 drafts and known to be stale on this point. + +Modules present today: `common` (shared infra — no business logic), `identity` (auth: register/login/refresh/logout, JWT), `learner` (learner profile). Planned modules (`content`, `learning`, `assessment`, `progress`, `adaptive`, `recommendation`, `assistance`, `subscription`, `notification`) are documented in `docs/MODULES.md` but not yet implemented. Modules must only talk to each other through public interfaces — no reaching into another module's internals. + +`common/` holds: `GlobalExceptionHandler` (exception → HTTP mapping), JWT (`JwtTokenProvider`, `JwtAuthenticationFilter`, `SecurityConfig`), `RequestIdFilter` (`X-Request-Id`), CORS config. + +Depends on an external artifact `aplp.backend:core` (separate Maven module, not in this repo tree). + +## Database + +PostgreSQL in dev/prod (docker-compose), H2 in Postgres-compatible mode for tests (`src/test/resources/application-test.yml`). Flyway migrations in `src/main/resources/db/migration` (`ddl-auto=validate` — entities must match migrations exactly, migrations are the source of truth). Write migrations portable across Postgres and H2. + +## Conventions worth knowing + +- Error responses go through a global `ErrorCode` enum (in `common/api`) + `GlobalExceptionHandler`; add new codes there for new failure cases. +- DTO mapping is manual (static mapper methods), not MapStruct, despite mapstruct being a dependency. +- Domain exceptions extend the project's `DomainException` and get mapped to HTTP status in the API layer, not thrown as raw HTTP errors from domain/application code. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..2329e3a --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,116 @@ +# APLP Backend — Architecture + +| | | +| --- | --- | +| **Module** | `aplp.backend.spring` | +| **Role** | Backend cho **aplp-web** (learner application) | +| **Status** | Draft | + +--- + +## 1. Architectural Direction + +Backend theo **Modular Monolith**, kết hợp: + +``` +Modular Monolith ++ Clean Architecture 4 Layers ++ DDD-oriented ++ Vertical Slice / Business Module +``` + +Nguyên tắc nền tảng: + +> **Business behavior first, database second.** + +> **Modular Monolith first; extract service chỉ khi có demonstrated need.** + +## 2. Request Flow + +``` +Controller (API layer) + ↓ +Application / Service (use case) + ↓ +Domain (business rules / model) + ↓ +Persistence (repository) + ↓ +Database +``` + +## 3. Clean Architecture — 4 Layers + +Mỗi business module có 4 layer rõ ràng: + +| Layer | Trách nhiệm | Should NOT do | +| --- | --- | --- | +| **Interface/API** | HTTP entry point, DTO request/response, validation cơ bản, tách biệt khỏi domain | Chứa business logic | +| **Application** | Use case orchestration, transactions, authorization | Chứa domain business rules | +| **Domain** | Entities, value objects, business rules, domain services | Phụ thuộc DB/HTTP | +| **Persistence** | Repository implementation, mapping, DB access | Chứa business rules | + +**Dependency rule:** chỉ phụ thuộc từ ngoài vào trong (API → Application → Domain); Persistence implement interface do Domain/Application định nghĩa. + +## 4. Modular Monolith + +- Code tổ chức theo **business module** (vertical slice), không theo technical layer toàn cục. +- Mỗi module đóng gói `interface + application + domain + persistence` cho một business capability. +- Module giao tiếp qua public API/interface; **không** import nội bộ module khác. +- Module registry/config ở application root. + +### Module Boundary + +``` +com.aplp.backend +└── (vd: identity, learner, content, learning, assessment, adaptive, ...) + ├── api (controller, dto) + ├── application (use case, service) + ├── domain (model, domain service, rules, repository interface) + └── persistence (repository impl, entity mapping, jpa) +``` + +## 5. DDD Orientation + +- **Aggregate** là ranh giới bảo toàn bất biến (invariant) trong cùng transaction. +- **Value Objects** dùng cho khái niệm không có identity riêng (Score, Money, MasteryLevel). +- **Domain Event** (optional, temporal) dùng khi cần tách rời side-effect giữa modules — **không** lạm dụng cho tất cả luồng. +- **Repository interface** ở domain, implementation ở persistence. + +## 6. Database + +- Relational database: **PostgreSQL** (chosen). Dev chạy qua `docker-compose` (port 5433); test dùng H2 (PostgreSQL mode). +- Migrations: **Flyway** (chosen) tại `src/main/resources/db/migration`. `spring.jpa.hibernate.ddl-auto=validate`. +- Schema phản ánh domain model, không thiết kế "database-first". + +## 7. Cross-Cutting Concerns + +- **Security / AuthN**: xử lý ở API/boundary layer (Phase 0). +- **Validation**: input validation ở API; business invariant validation ở domain. +- **Logging & Observability**: structured logging, common config (Phase 9 mở rộng metrics/tracing). +- **Errors**: exception mapping, đồng nhất response format. + +## 8. Deferred (tránh dùng khi chưa có justification) + +- Microservices split +- API Gateway +- Kafka / Event-driven +- Redis +- Elasticsearch +- CQRS / Event Sourcing + +## 9. Deployment + +- **Docker first** (containerize backend). +- **Kubernetes later** khi có nhu cầu scale/ops. + +## 10. Open Questions (backend-specific) + +| ID | Question | Impact | Proposed Direction | Status | +| --- | --- | --- | --- | --- | +| ARC-001 | Spring Boot version nào cho foundation? | Setup | Dùng phiên bản ổn định mới nhất hỗ trợ Java LTS | **Resolved**: Spring Boot 3.5.16 + Java 21 (Maven) | +| ARC-002 | JWT hay session cho authentication? | Security | JWT stateless + refresh flow | **Resolved**: JWT (access + rotating refresh, refresh token hash lưu DB) | +| ARC-003 | DB: PostgreSQL vs MySQL? | Setup | PostgreSQL | **Resolved**: PostgreSQL 17 (docker-compose) | +| ARC-004 | Migration: Flyway vs Liquibase? | Setup | Flyway | **Resolved**: Flyway | +| ARC-005 | Content đọc từ LMS qua API hay shared read model? | Module boundary | API/read model của LMS | Open (Phase 2) | +| ARC-006 | Transaction boundary giữa module nào cần được phân tách? | Data consistency | Ghi rõ trong từng use case | Open | \ No newline at end of file diff --git a/docs/CONVENTIONS.md b/docs/CONVENTIONS.md new file mode 100644 index 0000000..77a502e --- /dev/null +++ b/docs/CONVENTIONS.md @@ -0,0 +1,91 @@ +# APLP Backend — Conventions + +| | | +| --- | --- | +| **Status** | Draft | + +## 1. Naming & Package + +- Base package: `com.aplp.backend` +- Mỗi module: `com.aplp.backend..` với layer = `api | application | domain | persistence` (xem `ARCHITECTURE.md`). +- Tên class theo responsibility: + - Controller: `XxxController` + - Use case: `XxxUseCase` hoặc `XxxService` + - Request/Response DTO: `XxxRequest`, `XxxResponse` + - Aggregate/Root: tên domain concept (vd `Learner`, `Course`) + - Repository interface: `XxxRepository` (định nghĩa ở domain) + +## 2. Layer Rules + +| Layer | Được phép | Cấm | +| --- | --- | --- | +| `api` | AuthN/authorization (framework), input validation, DTO mapping | Business rules | +| `application` | Orchestrate use case, transaction, call domain/persistence | Nhúng business rules riêng | +| `domain` | Business logic, invariants, domain services, repository interface | Spring/JPA/HTTP dependencies | +| `persistence` | Repository impl, JPA entities, mappers | Business logic | + +- **Domain không import Spring/JPA/HTTP.** +- Persistence entities tách biệt (hoặc mappers) khỏi domain model nếu cần. + +## 3. Transaction + +- Transaction mở ở **Application** layer (`@Transactional` trên use case/service). +- Không ném transaction qua domain khi chỉ để đọc. +- Repository phương thức read nên read-only transaction khi cần. + +## 4. Validation + +- **Input/API validation** ở `api` layer (bean validation trên DTO). +- **Business invariant** trong `domain` (domain exception). +- Response lỗi dùng format đồng nhất (vd `ApiError` với code + message). + +## 5. Errors & Exceptions + +- `DomainException` cho lỗi business; mapping sang HTTP status ở `api` layer. +- Error response nhất quán: `code`, `message`, `details` (tuỳ thỏa thuận). +- Kèm `traceId`/requestId để dễ debug (Phase 0). +- Error code dùng **global enum `ErrorCode`** ở `common/api` (kèm HTTP status); mở rộng bằng cách thêm hằng số khi có module mới. + +## 6. DTO Mapping + +- Không để JPA entity lọt ra ngoài `persistence`/`api` response. +- **Mapping thủ công** (static method) trong repository impl / DTO factory — quyết định ở Phase 0 (không dùng MapStruct cho giai đoạn này; thêm khi có justification). + +## 7. Repository + +- Interface repository của module ở `domain`; implementation ở `persistence`. +- Chỉ expose các method cần thiết cho use case, không leek Query/spec toàn module. +- Query đặc thù (search, aggregation) nằm trong repository implementation. + +## 8. Domain Events (khi cần) + +- Dùng để tách rời side-effect giữa module (vd assessment hoàn thành → cập nhật adaptive state). +- Không lạm dụng: nếu đồng bộ đơn giản và cùng transaction, gọi trực tiếp qua interface. +- Nếu dùng Spring events: publish ở application layer, không trong domain. + +## 9. Config & Secrets + +- Cấu hình theo environment (`application.yml`, profile dev/prod). +- **Không commit secret/key vào repo.** Dùng env vars hoặc bí quyết quản lý (vault) khi có. +- Không log secret/token/password. + +## 10. Testing + +- Unit test cho `domain` + `application`. +- Test repository/persistence khi cần. +- Integration test cho API layer. +- Quyết định framework/test DB ở Phase 0. + +## 11. Code Style + +- Java theo tiêu chuẩn project (indent 4 spaces — xác nhận khi setup). +- Code của backend **không comment thừa**; tên rõ nghĩa. +- `@author`/metadata không bắt buộc. + +## 12. Open Questions + +| ID | Question | Status | +| --- | --- | --- | +| CON-001 | Dùng MapStruct hay mapping thủ công? | **Resolved**: thủ công (Phase 0) | +| CON-002 | Error code convention (enum per module vs global)? | **Resolved**: global `ErrorCode` trong `common/api` | +| CON-003 | JPA entities tách hay dùng chung domain model? | **Resolved**: tách riêng (`*JpaEntity` trong `persistence`, domain model trong `domain`) | \ No newline at end of file diff --git a/docs/MODULES.md b/docs/MODULES.md new file mode 100644 index 0000000..c490599 --- /dev/null +++ b/docs/MODULES.md @@ -0,0 +1,82 @@ +# APLP Backend — Modules + +| | | +| --- | --- | +| **Status** | Draft (Candidate) | + +Danh sách business module của backend `aplp.backend.spring`, ánh xạ từ từng phase trong `APLP-Project-Phases.md`. + +| Module | Phase | Type | Mô tả | +| --- | --- | --- | --- | +| `identity` | 0 ✅ | Generic | AuthN, user credential, session/token, identity provider hook. Nếu dùng IdP: không quản lý password khi không cần. | +| `learner` | 1 | Supporting (cân nhắc Core) | Learner profile, learning preferences, learning goals, mapping với identity. | +| `content` | 2 | Supporting | Content read model (course/module/lesson/activity từ LMS), catalog, enrollment/selection, publication status. | +| `learning` | 3 | Core | Learning experience: start/resume/continue, lesson completion, navigation, activity records, progress. | +| `assessment` | 4 | Supporting | Question, attempt, answer, evaluation, scoring, assessment result. | +| `progress` | 4 | Supporting | Learning progress computation & history (tách khỏi assessment để không lẫn). | +| `adaptive` | 5 | **Core** | Learner state, knowledge/skill state, mastery, prerequisite, adaptation decision, next activity. | +| `recommendation` | 6 | Core (defer) | Recommendation generation, personalized path. `Proposed`: có thể là decision/result. | +| `assistance` | 7 | Supporting | Hint, explanation, Q&A, feedback (AI integration) — phải qua domain validation. | +| `subscription` | 8 | Supporting | Plan, entitlement, usage limit, notification, account. Deferred tới productization. | +| `notification` | 8 | Generic | Notification delivery. | +| `common` | 0 ✅ | Infrastructure | Shared code: error handling, security config, base patterns, DTO conventions. | + +> Lưu ý: `common` chỉ chứa infrastructure/shared plumbing, **không** chứa business logic của module khác. + +## Phân loại bounded context + +| Type | Modules | +| --- | --- | +| Core Domain | `learning`, `adaptive`, `recommendation` (recommendation defer) | +| Supporting Domain | `learner`, `content`, `assessment`, `progress`, `assistance`, `subscription` | +| Generic Domain | `identity`, `notification`, `configuration`/`common` | + +## Cấu trúc thư mục gợi ý + +```text +src/main/java/com/aplp/backend/ +├── common/ # infrastructure & shared +├── identity/ +│ ├── api/ +│ ├── application/ +│ ├── domain/ +│ └── persistence/ +├── learner/ +├── content/ +├── learning/ +├── assessment/ +├── progress/ +├── adaptive/ +├── recommendation/ +├── assistance/ +└── subscription/ +``` + +## Quy tắc module + +1. Module A **chỉ** giao tiếp với module B qua public interface/API của B. +2. Không share DB table trực tiếp giữa module; dùng repository/read model. +3. Cross-module side-effect dùng domain event/callback nếu cần rõ ràng, không hard-code import. +4. Mỗi module phải đứng độc lập được về compile (dependency hướng trong ra ngoài). + +## Khởi tạo theo phase + +- **Phase 0 (done)**: `common`, `identity` (minimal), `learner` (basic profile). +- **Phase 2**: `content`. +- **Phase 3**: `learning`. +- **Phase 4**: `assessment`, `progress`. +- **Phase 5**: `adaptive`. +- **Phase 6**: `recommendation`. +- **Phase 7**: `assistance`. +- **Phase 8**: `subscription`, `notification`. + +> Ghi chú Phase 0: `learner` chỉ có basic profile (display name + mapping user identity). Preferences/goals thuộc Phase 1. + +## Open Questions + +| ID | Question | Impact | Status | +| --- | --- | --- | --- | +| MOD-001 | `progress` tách riêng hay gộp vào `learning`? | Module boundary | Open | +| MOD-002 | `assessment` module độc lập hay trong `learning`? | Cohesion | Open | +| MOD-003 | Cách chia sẻ content model giữa `content` và `learning` (snapshot vs reference)? | Consistency | Open | +| MOD-004 | `recommendation` có cần là module riêng hay chỉ service trong `adaptive`? | Boundary | Open | \ No newline at end of file diff --git a/docs/SETUP.md b/docs/SETUP.md new file mode 100644 index 0000000..fe21320 --- /dev/null +++ b/docs/SETUP.md @@ -0,0 +1,100 @@ +# APLP Backend — Setup + +| | | +| --- | --- | +| **Status** | Implemented (Phase 0 — Foundation) | +| **Stack** | Java 21 (LTS) · Maven · Spring Boot 3.5 · PostgreSQL · Flyway · H2 (test) | + +## 1. Prerequisites + +- JDK 21+ (build chạy được trên JDK 25; target release 21) +- Maven (hoặc dùng `./mvnw`) +- Docker (database local) + +## 2. Cấu trúc dự án + +```text +aplp.backend.spring/ +├── GOAL.md +├── APLP-Project-Phases.md +├── README.md +├── docs/ +├── pom.xml +├── mvnw +├── Dockerfile +├── docker-compose.yml # PostgreSQL local (port 5432) +└── src/ + ├── main/java/com/aplp/backend/ + │ ├── AplpBackendApplication.java + │ ├── common/ # infra: api (errors), security (JWT), web (requestId), config + │ ├── identity/ # api / application / domain / persistence + │ └── learner/ # api / application / domain / persistence + ├── main/resources/ + │ ├── application.yml # base config + │ ├── application-dev.yml # Postgres local + │ ├── application-prod.yml # Postgres via env vars + │ └── db/migration/ # Flyway migrations + └── test/... +``` + +## 3. Chạy local (dev) + +```bash +# 1. Start database +docker compose up -d db + +# 2. Chạy app (dev profile, port 8080) +./mvnw spring-boot:run + +# 3. Kiểm tra +curl http://localhost:8080/actuator/health +# => {"status":"UP","groups":["liveness","readiness"]} +``` + +Flyway tự migrate schema khi app khởi động (`ddl-auto: validate` để kiểm tra entity khớp schema). + +## 4. Verification + +```bash +./mvnw test # integration test với H2 (PostgreSQL mode) +./mvnw package # build jar +``` + +## 5. Endpoints (Phase 0) + +| Method | Path | Auth | Mô tả | +| --- | --- | --- | --- | +| POST | `/api/v1/auth/register` | Public | Đăng ký + cấp token | +| POST | `/api/v1/auth/login` | Public | Đăng nhập | +| POST | `/api/v1/auth/refresh` | Public | Refresh access token (rotate refresh token) | +| POST | `/api/v1/auth/logout` | Bearer | Thu hồi refresh token | +| GET | `/api/v1/learners/me` | Bearer | Xem learner profile (UC-0.2) | +| PATCH | `/api/v1/learners/me` | Bearer | Cập nhật display name | +| GET | `/actuator/health` | Public | Health/liveness/readiness | + +## 6. Environment Variables + +| Var | Mô tả | Default (dev) | +| --- | --- |--------------------------------------------| +| `DB_URL` | JDBC url | `jdbc:postgresql://localhost:5432/aplp` | +| `DB_USERNAME` | db user | `postgres` | +| `DB_PASSWORD` | db password | `Pa55w0rd` | +| `DB_PORT` | host port map | `5432` | +| `JWT_SECRET` | Base64 secret (HS256, ≥ 32 bytes) | dev-only default — **phải set khi deploy** | +| `JWT_ACCESS_TTL` | Access token TTL | `15m` | +| `JWT_REFRESH_TTL` | Refresh token TTL | `30d` | +| `CORS_ALLOWED_ORIGINS` | Allowed origins | `http://localhost:5173` | +| `SERVER_PORT` | App port | `8080` | + +> Dev default secret chỉ dùng cho local. **Không commit secret thật**; set `JWT_SECRET` trong môi trường không phải dev. + +## 7. Test Database + +Integration test dùng H2 in-memory (PostgreSQL mode) tại `src/test/resources/application-test.yml`. Migration viết portable (chạy được trên cả Postgres và H2). + +## 8. Docker + +```bash +docker build -t aplp-backend . +docker run -p 8080:8080 -e JWT_SECRET=... -e DB_URL=... aplp-backend +```