7.7 KiB
7.7 KiB
ERP Backend — Development Tasks (Phase 1)
Reference: BACKEND_SETUP.md
Use this checklist when building or extending the backend. Follow the build order in Section 1.
1. Project Scaffold
- Create
package.jsonwith dependencies and scripts from the spec - Install dependencies (
npm install) - Add
.env.example(never commit.env) - Configure ESLint, Prettier, Husky, lint-staged
- Add
jest.config.jswithdotenv/configsetup file
2. Database & Prisma
- Define
prisma/schema.prisma:- Auth:
User,Role,Module,Permission,RolePermission,RefreshToken,PasswordResetToken - System:
AuditLog,DocumentSeries - Business: Vendor (+ sub-tables), PurchaseOrder (+ items), GRN (+ items), Asset (+ transfers), all masters
- Auth:
- Use
PascalCasemodels,snake_casefields,@@mapto plural table names - Add common columns on every business table:
is_active,created_by,updated_by,created_at,updated_at,deleted_at - Run
npx prisma migrate dev --name init - Run
npx prisma generate - Implement idempotent
prisma/seed.js(modules → permissions → roles → role_permissions → Super Admin user)
Seed requirements
| Step | Content |
|---|---|
| Modules | USERS, ROLES, MASTERS, VENDOR, PURCHASE_ORDER, GRN, ASSET |
| Permissions | Each module × view, create, edit, delete, approve, export (skip where N/A) |
| Roles | Super Admin, Admin, Purchase Manager, Store Manager, Accounts, Asset Manager |
| Bootstrap user | Super Admin, bcrypt-hashed password, status = active |
3. Core Infrastructure
src/config/env.js— Joi validation; app must refuse to boot on invalid/missing envsrc/config/logger.js— Winston + daily rotate; redact sensitive keyssrc/config/morgan.js— HTTP logs into Winston with request ID + usersrc/config/prisma.js— singleton client with query/error loggingsrc/config/swagger.js— OpenAPI 3.0 from route JSDocsrc/utils/— ApiError, ApiResponse, asyncHandler, encryption, auditLog, pagination, generateCodesrc/middlewares/— requestId, error, validate, rateLimiter, auth, rbac, uploadsrc/app.js— Helmet, CORS, HPP, compression, rate limit, routes, Swagger, 404, error handlersrc/server.js— graceful shutdown, BigInt JSON serializer, unhandled rejection/exception handlers- Verify
GET /healthresponds
4. Modules (HMVC Pattern)
Build in this order. Each module: *.routes.js → *.controller.js → *.service.js → *.validation.js (+ *.repository.js for complex modules).
| # | Module | Notes |
|---|---|---|
| 8 | auth | login, refresh, logout; rotating hashed refresh tokens; account lockout |
| 9 | masters | UOM first as template, then replicate 13 sub-masters under masters/index.js |
| 10 | vendors | CRUD + addresses/contacts/bank-details; encrypt bank account numbers |
| 11 | purchase-orders | Header + line items; repository for transactions; submit/approve/reject/amend/cancel |
| 12 | grn | Receipt + PO status recalc + asset auto-creation in one transaction |
| 13 | assets | CRUD + transfer + transfer history |
| — | users | CRUD, RBAC: USERS |
| — | roles | CRUD + permission assignment, RBAC: ROLES |
Current progress:
authmodule scaffold (login,refresh,logout) implementedmasters/uommodule implemented as template (CRUD + RBAC + validation + audit log)- Replicated masters CRUD modules:
item-categories,brands,gst-rates,payment-terms,delivery-terms,asset-categories,departments,designations,document-series - Pending masters now completed:
item-subcategories,items,warehouses,plants
Layer rules
| Layer | Responsibility |
|---|---|
| Routes | HTTP mapping + middleware chain (authenticate → authorize → validate → controller) |
| Controller | Parse request, call service, return ApiResponse — no business logic, no Prisma |
| Service | Business logic, Prisma (or repository), auditLog on every mutation |
| Repository | Multi-table prisma.$transaction only (PO, GRN, Assets) |
| Validation | Joi schemas for body/query |
5. API Routes (Phase 1)
/api/v1/auth/{login,refresh,logout}
/api/v1/users
/api/v1/roles
/api/v1/masters/{uom,item-categories,item-subcategories,items,brands,gst-rates,warehouses,payment-terms,delivery-terms,asset-categories,departments,designations,plants,document-series}
/api/v1/vendors (+ /addresses, /contacts, /bank-details)
/api/v1/purchase-orders (+ /submit, /approve, /reject, /amend, /cancel, /pdf)
/api/v1/grn (+ /cancel, /pdf)
/api/v1/assets (+ /transfer, /transfer-history)
6. Security Tasks
- JWT access tokens (15m) in
Authorization: Bearerheader - Refresh tokens: opaque, SHA-256 hashed in DB, rotated on each refresh
- bcrypt password hashing (
BCRYPT_SALT_ROUNDS=12) - Account lockout after
MAX_LOGIN_ATTEMPTSfailures authenticate+authorize(module, action)on every protected route- AES-256-GCM field encryption + HMAC blind index for searchable PII
- Rate limiting: global on
/api, stricter on/auth/loginand/auth/forgot-password - Helmet, CORS (no
*in production), HPP, compression - File uploads: MIME allow-list, random filenames, RBAC-protected download (not direct web serve)
auditLog()on every create/update/status-change/approve/rejectX-Request-Idon every request for log correlation
RBAC permission actions
view, create, edit, delete, approve, export
7. API Conventions
- Versioning:
/api/v1/... - Pagination:
?page=1&limit=20(cap limit at 100); responsemeta: { page, limit, total } - Filtering:
?status=...&search=...per module - Sorting:
?sort=-created_at(-= descending) - IDs:
BigIntserialized as strings in JSON - Dates: ISO 8601 UTC
- Soft delete: set
deleted_at, never hard-delete transactional records - Response envelope:
{ success, message, data?, meta?, errors? }
8. Testing
- Jest + Supertest against
app.js(no live server) - Separate test DB via
.env.test+prisma migrate deploy - Mirror structure:
tests/modules/<module>/<module>.test.js
Minimum Phase 1 coverage
- Auth: login, refresh, lockout
- RBAC: allowed vs forbidden
- Vendor: CRUD + status transitions
- PO: status lifecycle
- GRN: partial receipt → PO status recalculation
9. Documentation & DevOps
- Add
@swaggerJSDoc blocks to every route file Dockerfile(Node 20 Alpine)docker-compose.yml(API + Postgres 15)- Verify
docker-compose upboots API + Postgres - Run
npm auditin CI
10. Future Development Guidelines
When adding a new module or endpoint:
- Add Prisma model with common columns + soft delete
- Add module/permissions to seed (if new domain)
- Create the four-file HMVC module (five if multi-table transactions)
- Register routes in
src/routes/v1/index.js - Apply middleware chain:
authenticate→authorize(MODULE, action)→validate(schema)→ controller - Call
auditLog()in service for all mutations - Use
nextDocumentNumber()for auto-generated codes - Encrypt PII at service layer with blind index for search
- Add Swagger JSDoc + Jest tests
- Breaking API changes → new version (
/api/v2)
Complex transaction modules
Use *.repository.js with prisma.$transaction when a single operation touches multiple tables (e.g. PO header + items, GRN + PO qty update + asset creation).
Masters replication
Copy the UOM module pattern for new masters: simple name/code fields, RBAC code MASTERS, no document numbering.