Initial commit

This commit is contained in:
Zzzz
2026-04-27 18:40:30 +08:00
commit 2120774b05
112 changed files with 12308 additions and 0 deletions
@@ -0,0 +1,141 @@
# Database Guidelines
> MySQL data and DAO conventions for the library-management system.
---
## Overview
MySQL is the project data layer. DAO classes perform CRUD and query operations
against MySQL. Application source and schema files are not present yet, so table
and class names here are illustrative conventions for future implementation.
---
## Core Tables
Use primary keys for every table and foreign keys for cross-entity integrity.
Illustrative table names:
- `books`: book information, inventory count/status, category reference.
- `book_categories`: category names and descriptions.
- `readers`: reader profiles, borrowing eligibility, contact information.
- `borrow_records`: book-reader borrowing, return, renew, and overdue data.
- `administrators`: administrator/librarian login and profile data.
- `roles`: administrator, librarian, reader, and future role definitions.
- `permissions`: permission definitions for protected actions.
- `role_permissions`: role-to-permission mapping.
- `system_logs`: key operation logs, backup events, and exception traces.
When schema files are introduced, record the actual path, DDL style, and exact
table names here.
---
## DAO Responsibilities
- DAOs own database CRUD and query details.
- Use parameterized SQL or prepared-statement style access; never concatenate
raw request parameters into SQL.
- Keep transaction boundaries in the service layer for workflows that span
multiple DAO calls, such as borrow/return operations that also update
inventory status.
- Return entities or small query result objects to services, not HTML or
servlet response objects.
- Keep MySQL connection details in a shared configuration/helper once one
exists, for example `JdbcUtil` plus `db.properties`.
---
## Query Guidance
- Book search must support combined lookup by title, author, category, and ID.
- Statistics queries should cover borrowing rankings, inventory reports, and
overdue reports.
- Borrowing records should preserve enough dates/status fields for borrow,
return, renew, overdue calculation, and automatic collection status updates.
- Permission queries should support role-based checks for administrator,
librarian, and reader workflows.
---
## Integrity Constraints
- `books.category_id` should reference `book_categories`.
- `borrow_records.book_id` should reference `books`.
- `borrow_records.reader_id` should reference `readers`.
- Administrator-role and role-permission mapping tables should use foreign keys
to preserve authorization integrity.
- Prefer explicit status columns/enums for inventory and borrowing states, then
document the chosen values once code exists.
## Scenario: Login And Permission Scaffold Schema
### 1. Scope / Trigger
- Trigger: the initial Java Web scaffold introduced a concrete MySQL schema and
login contract.
- Schema path: `src/main/resources/db/schema.sql`.
- Example configuration path: `src/main/resources/db.properties.example`.
### 2. Signatures
- DAO signature: `UserDao.findActiveByUsername(String username)`.
- Service signature: `AuthService.authenticate(String username, String password)`.
- Permission signature: `AuthService.hasPermission(AuthenticatedUser user, Permission permission)`.
- Login tables: `roles`, `permissions`, `role_permissions`, `users`, and
`system_logs`.
### 3. Contracts
- `users.username`: unique login identifier submitted by `LoginServlet`.
- `users.password_hash`: PBKDF2 hash in
`pbkdf2_sha256$iterations$saltBase64$hashBase64` format.
- `users.role_code`: foreign key to `roles.code`; supported scaffold values
are `administrator`, `librarian`, and `reader`.
- Session state stores an `AuthenticatedUser` snapshot, role code, and
permission-code set. It must not store raw passwords or DAO result objects
with password hashes.
### 4. Validation & Error Matrix
- Missing username or password -> request returns to login JSP with
`Username and password are required.`
- Unknown user, inactive user, or hash mismatch -> request returns to login JSP
with `Invalid username or password.`
- Missing `db.properties`, JDBC failure, or unsupported role code -> request
returns a generic service-unavailable message and logs server-side details.
- Authenticated user missing a required permission -> HTTP 403 and
`WEB-INF/jsp/auth/unauthorized.jsp`.
### 5. Good/Base/Bad Cases
- Good: `admin` resolves to `administrator`, receives all scaffold
permissions, and can access `/admin/home`.
- Base: `reader` resolves to `reader`, can access `/reader/home`, and cannot
access `/admin/home`.
- Bad: a JSP reads SQL or password hashes directly from the database. Keep that
logic in DAO/service code.
### 6. Tests Required
- Compile service/DAO/entity/util classes with `javac` when Maven is
unavailable.
- Run `PermissionPolicyCheck` or equivalent assertions for administrator,
librarian, and reader permissions.
- When Maven/Tomcat dependencies are installed, run `mvn test` or
`mvn clean package` to compile Servlet and JSP integration.
### 7. Wrong vs Correct
#### Wrong
```java
// JSP or Servlet opens JDBC and checks passwords directly.
```
#### Correct
```text
login.jsp -> LoginServlet -> AuthService -> UserDao -> users/roles tables
```
@@ -0,0 +1,73 @@
# Directory Structure
> Backend directory organization for the JSP + Servlet + MySQL application.
---
## Overview
Future backend code should follow the established B/S layered architecture.
There is no application source tree yet; the paths and package names below are
illustrative conventions to use when creating the first application code.
---
## Suggested Layout
```text
src/main/java/com/mzh/library/
controller/ Servlet controllers such as BookServlet
service/ Service interfaces such as BookService
service/impl/ Business implementations such as BookServiceImpl
dao/ DAO interfaces such as BookDao
dao/impl/ MySQL DAO implementations such as BookDaoImpl
entity/ JavaBeans/entities such as Book, Reader, BorrowRecord
filter/ Authentication, authorization, encoding filters
util/ Shared utilities such as JdbcUtil or DateUtil
src/main/resources/
db.properties MySQL connection configuration when introduced
src/main/webapp/
WEB-INF/web.xml Servlet/filter mappings when annotations are not used
```
Use the package root consistently once the first code is created. If a
different root package is chosen in IDEA, update this spec in the same change.
---
## Layer Responsibilities
- `controller`: Servlet classes dispatch requests, validate parameters, call
services, choose JSP forwards or redirects, and return results.
- `service`: Business workflows including book warehousing/intake, borrowing,
returning, renewals, inventory status updates, overdue statistics, and
permission checks.
- `dao`: CRUD and query access to MySQL. DAOs should not perform presentation
rendering or multi-step business workflows.
- `entity`: Plain data objects representing books, categories, readers,
borrowing records, administrators, roles/permissions, and system logs.
- `filter`: Cross-cutting web concerns such as login checks, role guards, and
request encoding.
- `util`: Small shared helpers only after searching for existing helpers first.
---
## Naming Conventions
- Servlet controllers use names such as `BookServlet`, `ReaderServlet`,
`BorrowServlet`, and `LoginServlet`.
- Service interfaces and implementations use names such as `BookService` and
`BookServiceImpl`.
- DAO interfaces and implementations use names such as `BookDao` and
`BookDaoImpl`.
- Entity names should be singular Java nouns such as `Book`, `BookCategory`,
`Reader`, `BorrowRecord`, `Administrator`, `RolePermission`, and
`SystemLog`.
---
## Boundaries
Do not put SQL in JSPs or Servlets. Do not put HTML generation in DAOs or
services. Keep permission checks in filters/services and keep request parameter
parsing in controllers.
+54
View File
@@ -0,0 +1,54 @@
# Error Handling
> Backend error handling conventions for Servlet, service, DAO, and MySQL code.
---
## Overview
Servlet controllers are responsible for parameter validation and safe result
return. Services report business failures such as ineligible readers,
unavailable inventory, failed permission checks, and overdue-rule violations.
DAOs report database failures without leaking SQL details to JSP pages.
---
## Controller Behavior
- Validate required parameters, numeric IDs, dates, and operation names before
calling services.
- On validation failure, return to the relevant JSP with field-level messages
or redirect with a short flash-style message.
- Do not print stack traces or database details into JSP output.
- Use forwards for rendering request-scoped form errors and redirects after
successful mutating operations to avoid duplicate submissions.
---
## Service Behavior
- Centralize business rule failures in the service layer: permission denied,
reader not eligible to borrow, book not available, renewal rejected, overdue
status conflicts, and inventory update failures.
- Keep transaction rollback decisions close to multi-step workflows such as
borrow, return, renew, and book intake.
- Return clear success/failure results or throw project-specific exceptions
once the application defines an exception model.
---
## DAO Behavior
- Wrap low-level SQL/MySQL exceptions with enough context for logs, but do not
expose credentials, raw SQL with user values, or stack traces to users.
- Close JDBC resources reliably using the project helper or language construct
chosen by the first implementation.
- Let services decide whether a DAO failure should abort a transaction or map
to a user-facing message.
---
## User-Facing Results
Use concise messages suitable for JSP rendering. For protected operations,
prefer generic denial messages over exposing permission internals.
+77
View File
@@ -0,0 +1,77 @@
# Backend Development Guidelines
> Backend conventions for the JSP + Servlet + MySQL library-management system.
---
## Overview
The developer has established the backend architecture as a B/S Java web
application using JSP + Servlet, MySQL, Tomcat, and IDEA. Application source
code does not exist in this workspace yet, so package names, class names, and
table names below are illustrative project conventions for future code rather
than references to existing files.
Use a layered design:
```
JSP/CSS presentation -> Servlet controller -> Service/business -> DAO -> MySQL
```
Controllers handle request dispatch, parameter validation, and result return.
Services handle business workflows and permission checks. DAOs perform database
CRUD. MySQL stores books, categories, readers, borrowing records,
administrators, roles/permissions, and system logs.
---
## Guidelines Index
| Guide | Description | Status |
|-------|-------------|--------|
| [Directory Structure](./directory-structure.md) | Servlet, service, DAO, entity, and config organization | Project decision documented |
| [Database Guidelines](./database-guidelines.md) | MySQL tables, DAO CRUD, keys, and transactions | Project decision documented |
| [Error Handling](./error-handling.md) | Servlet validation, service failures, and safe responses | Project decision documented |
| [Quality Guidelines](./quality-guidelines.md) | Layer boundaries and review constraints | Project decision documented |
| [Logging Guidelines](./logging-guidelines.md) | System logs, key operations, and exception tracing | Project decision documented |
---
## Pre-Development Checklist
Before backend implementation, read:
- `.trellis/spec/backend/directory-structure.md`
- `.trellis/spec/backend/database-guidelines.md`
- `.trellis/spec/backend/error-handling.md`
- `.trellis/spec/backend/logging-guidelines.md`
- `.trellis/spec/backend/quality-guidelines.md`
- `.trellis/tasks/00-bootstrap-guidelines/research/project-requirements.md`
---
## Core Backend Modules
- Login and permission management for administrator, librarian, and reader
roles.
- Book information management for create, update, delete, category maintenance,
and inventory status.
- Reader information management for profiles, borrowing eligibility, and
contact information.
- Borrowing and return management for borrow, return, renew, overdue handling,
and automatic collection status updates.
- Book search and statistics for combined title, author, category, and ID
search, borrowing rankings, inventory reports, and overdue reports.
- System maintenance and logs for key operation logs, data backup support, and
exception tracing.
## Evidence
- `.trellis/tasks/00-bootstrap-guidelines/research/repo-scan.md` records that
no application source code exists yet.
- `.trellis/tasks/00-bootstrap-guidelines/research/project-requirements.md`
records the developer-provided stack, architecture, modules, and data model.
---
**Language**: All documentation should be written in **English**.
@@ -0,0 +1,53 @@
# Logging Guidelines
> Logging and system-log conventions for the library-management backend.
---
## Overview
The project requires system maintenance/log support for key operation logs, data
backup support, and exception tracing. MySQL should include a system log table,
illustratively `system_logs`, for durable audit and troubleshooting records.
---
## What to Log
Record key operations that affect security, data integrity, or inventory:
- Login success/failure and logout for administrator, librarian, and reader
roles when applicable.
- Permission changes, role changes, and denied protected operations.
- Book create, update, delete, category maintenance, and warehousing/intake.
- Borrow, return, renew, overdue handling, and automatic inventory status
updates.
- Reader profile, eligibility, and contact information changes.
- Data backup events and restore-related maintenance actions.
- Unhandled exceptions and failed database operations with safe context.
---
## System Log Fields
When the schema is introduced, `system_logs` should preserve enough information
to trace actions without exposing sensitive data. Useful fields include an ID,
operator ID, operator role, operation type, target entity/table, target ID,
result status, message, timestamp, and request IP when available.
---
## Sensitive Data
Do not log passwords, raw credentials, full request bodies, database connection
strings, or unnecessary personal data. Prefer IDs and operation summaries over
large before/after payloads.
---
## Exception Tracing
Server logs may contain technical stack traces for developers. User-facing JSP
pages should receive concise messages. Durable system logs should record the
operation, actor, failure category, and correlation details needed to locate
the server-side exception.
@@ -0,0 +1,58 @@
# Quality Guidelines
> Backend quality constraints for the JSP + Servlet + MySQL application.
---
## Overview
No application source code exists yet, but the developer has established the
backend stack and layered design. Future backend work should preserve those
decisions and update these specs with real file paths once code exists.
---
## Required Patterns
- Keep strict layer boundaries: Servlet -> Service -> DAO -> MySQL.
- Use JSP/CSS only for presentation; JSPs must not contain SQL or business
workflow logic.
- Validate request parameters in Servlet controllers before calling services.
- Enforce permission checks in filters/services for administrator, librarian,
and reader roles.
- Keep inventory status updates inside service workflows so borrow, return,
renew, overdue handling, and book intake remain consistent.
- Use primary keys and foreign keys for core entity relationships.
- Record key operations and exceptions according to the logging spec.
---
## Forbidden Patterns
- Do not introduce React, Vue, SPA routing, ORM conventions, or non-Servlet
backend frameworks unless the developer explicitly changes the stack.
- Do not place SQL in JSP files or directly in presentation helpers.
- Do not put business workflows in DAO classes.
- Do not rely on client-side validation as the only validation for protected
operations.
- Do not expose stack traces, raw SQL errors, or sensitive personal data to end
users.
---
## Checks And Testing
When Java source exists, document and run the actual compile/test commands for
the chosen IDEA/Tomcat project structure. Until then, documentation-only
changes should run Trellis validation, Python compile checks for Trellis
scripts when relevant, and placeholder scans for scaffold markers.
---
## Review Checklist
- Does the change preserve JSP + Servlet + MySQL + Tomcat assumptions?
- Are Servlet, service, DAO, and JSP responsibilities separated?
- Are book, category, reader, borrowing, administrator, permission, and log
data flows covered where relevant?
- Are role permissions and operation logs handled for protected workflows?