erp_be/BACKEND_TASKS.md
2026-06-17 11:30:11 +05:30

7.7 KiB
Raw Blame History

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.json with 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.js with dotenv/config setup 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
  • Use PascalCase models, snake_case fields, @@map to 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 env
  • src/config/logger.js — Winston + daily rotate; redact sensitive keys
  • src/config/morgan.js — HTTP logs into Winston with request ID + user
  • src/config/prisma.js — singleton client with query/error logging
  • src/config/swagger.js — OpenAPI 3.0 from route JSDoc
  • src/utils/ — ApiError, ApiResponse, asyncHandler, encryption, auditLog, pagination, generateCode
  • src/middlewares/ — requestId, error, validate, rateLimiter, auth, rbac, upload
  • src/app.js — Helmet, CORS, HPP, compression, rate limit, routes, Swagger, 404, error handler
  • src/server.js — graceful shutdown, BigInt JSON serializer, unhandled rejection/exception handlers
  • Verify GET /health responds

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:

  • auth module scaffold (login, refresh, logout) implemented
  • masters/uom module 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 (authenticateauthorizevalidate → 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: Bearer header
  • Refresh tokens: opaque, SHA-256 hashed in DB, rotated on each refresh
  • bcrypt password hashing (BCRYPT_SALT_ROUNDS=12)
  • Account lockout after MAX_LOGIN_ATTEMPTS failures
  • 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/login and /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/reject
  • X-Request-Id on 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); response meta: { page, limit, total }
  • Filtering: ?status=...&search=... per module
  • Sorting: ?sort=-created_at (- = descending)
  • IDs: BigInt serialized 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 @swagger JSDoc blocks to every route file
  • Dockerfile (Node 20 Alpine)
  • docker-compose.yml (API + Postgres 15)
  • Verify docker-compose up boots API + Postgres
  • Run npm audit in CI

10. Future Development Guidelines

When adding a new module or endpoint:

  1. Add Prisma model with common columns + soft delete
  2. Add module/permissions to seed (if new domain)
  3. Create the four-file HMVC module (five if multi-table transactions)
  4. Register routes in src/routes/v1/index.js
  5. Apply middleware chain: authenticateauthorize(MODULE, action)validate(schema) → controller
  6. Call auditLog() in service for all mutations
  7. Use nextDocumentNumber() for auto-generated codes
  8. Encrypt PII at service layer with blind index for search
  9. Add Swagger JSDoc + Jest tests
  10. 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.