A production-grade REST API and real-time server for Controfferta.it, the Italian marketplace that matches private clients with verified companies in renovations, solar, plants, windows, and roofing.
A visitor submits a project request. An admin accepts it onto the public lead feed, without the visitor's contact details. A provider company spends credits to unlock that contact. Providers buy credits with Stripe. The domain model is in docs/erd.md.
- Core Business Capabilities
- How a lead is sold
- Technology Stack
- System Architecture
- Directory Layout
- Prerequisites
- Getting Started
- Environment Configuration
- Running the Application
- API Documentation (OpenAPI / Swagger)
- CORS and cookies
- Scaffolding New Modules
- Testing & Quality Assurance
- Real-Time Events
- Background Workers & Cleanup Jobs
- Commit & Release Workflow
flowchart LR
visitor[Visitor] -->|public submit| lead[Lead]
admin[Admin] -->|accept| lead
lead -->|accepted, contact hidden| feed[Public feed]
provider[Provider] -->|spend credits| access[Lead access]
feed --> access
provider -->|Checkout| stripe[Stripe]
stripe -->|paid webhook| ledger[Credit ledger]
ledger --> provider
- Anyone can
POST /api/v1/leads/create. No account is created. - An admin moves the lead from
pendingtoacceptedorrejected, and later fromacceptedtoclosed. GET /api/v1/leadslists accepted leads. Contact details stay off this feed.- A provider unlocks a lead with
POST /api/v1/lead-accesses/unlock. The charge is the category's currentcreditCost. The access row keeps the amount that was actually taken. - Credits arrive as a welcome grant, a paid package purchase, or an admin adjustment. Every change is a ledger row in the same database transaction as the balance update.
- Roles are client, provider, admin, and super admin.
- Public signup accepts
clientandprovider. A super admin creates admin accounts. The process seeds one super admin fromSUPER_ADMIN_EMAILandSUPER_ADMIN_PASSWORDwhen none exists. - Access and refresh JWTs. Passwords are hashed with bcrypt. Email verification and password reset go out through the mail queue.
- Anyone can submit a project request. No account is created.
- An admin moves a lead from
pendingtoacceptedorrejected, and later fromacceptedtoclosed. - The public feed lists accepted leads and can be searched by the project address. Contact details stay off the feed.
- Staff can read any lead, including contact. A provider can read an accepted lead, still without contact, until they unlock it.
- A provider spends credits to unlock one lead. The charge is the category's current
creditCost. - The access row stores the credits actually taken, so a later price change does not rewrite it.
- After unlock, the provider moves the job through
unlocked,contacted,in_progress, andcompleted. - Closing or rejecting a lead leaves existing unlock rows in place.
- Package prices, purchase totals, and transaction amounts are stored in euros. Stripe is charged in cents: the Price is created with
price * 100, and the webhook divides Stripe amounts by 100 before saving them. Provider.creditBalanceand ledger amounts are whole credits. A positive row adds credits. A negative row spends them. The balance cannot go below zero.- A new provider receives
Setting.welcomeCreditAmountcredits. When that setting has not been saved, the grant is 15. A stored0turns the grant off. - Credits are posted only when the action is final: welcome on registration, purchase when Stripe reports the checkout paid, unlock when a lead is opened, and adjustment when an admin changes a balance. Starting checkout does not grant credits. A failed, expired, or repeated paid event does not grant them again.
- Paid fulfillment runs on
checkout.session.completedandcheckout.session.async_payment_succeededwhenpayment_statusispaid. AstripeEventrow stops the same Stripe event from being applied twice.
- Public FAQ, blog posts, platform reviews, terms of service, and privacy policy.
- One platform settings document: welcome credits, contact details, a map point, and social links.
- Anyone can send a support message. Admins set status and priority.
- Socket.IO on the same HTTP server, authenticated with the JWT.
- Chat rooms, live messages, and in-app notifications pushed to
user:${userId}.
- Authenticated uploads go to AWS S3.
- A new upload is tracked in the Redis sorted set
unlinked_media_uploads. - A BullMQ job runs every 6 hours and deletes files that are still unlinked after 6 hours.
| Category | Technologies |
|---|---|
| Runtime & Language | Node.js (v20+; the Docker image is v22), TypeScript (v5.5+) in CommonJS mode |
| Web Framework | Express 4.x with CORS and express-rate-limit |
| Primary Database | MongoDB via Mongoose 8.x |
| Caching & In-Memory Store | Redis via ioredis 6.x |
| Job Queue & Workers | BullMQ 6.x for email, notifications, and media cleanup |
| Validation | Zod 3.23+ with strict request schemas |
| API Documentation | Swagger UI & OpenAPI 3.0 via @asteasolutions/zod-to-openapi |
| Third-Party Services | Stripe (Checkout & Webhooks), AWS S3 (@aws-sdk/client-s3), Nodemailer |
| Real-Time | Socket.IO 4.x |
| Testing | Vitest 3.x, Supertest 7.x, mongodb-memory-server 11.x, @vitest/coverage-v8 |
| DevOps & CI/CD | Docker, GitHub Actions, Semantic Release, Commitizen |
The project keeps the Express app separate from the process that opens ports and connections:
ββββββββββββββββββββββββ
β HTTP Requests β
ββββββββββββ¬ββββββββββββ
β
βΌ
ββββββββββββββββββββββββ
β src/app.ts β βββ Pure Express (routes, middleware,
ββββββββββββ¬ββββββββββββ errors; no listeners or DB connects)
β
βββββββββββββββββββ΄ββββββββββββββββββ
βΌ βΌ
ββββββββββββββββββββββββ ββββββββββββββββββββββββ
β src/server.ts β β tests/integration β
β src/dev-server.ts β β (Supertest) β
ββββββββββββββββββββββββ€ ββββββββββββββββββββββββ€
β β’ MongoDB Connect β β β’ In-Memory MongoDB β
β β’ Super admin seed β β β’ Zero Port Binding β
β β’ BullMQ Workers β β β’ Stripe, S3, Redis, β
β β’ Socket.IO Listener β β and SMTP mocked β
β β’ app.listen() β ββββββββββββββββββββββββ
ββββββββββββββββββββββββ
A protected request runs auth(...), then validateRequest(schema), then a thin controller. The service throws ApiError for expected failures.
Success responses look like this:
{
"success": true,
"message": "Lead unlocked successfully",
"statusCode": 201,
"data": {}
}List routes add pagination. Validation failures return 400 with success: false and errorMessages. A missing token is 401. The wrong role is 403.
POST /webhooks/stripe is registered with express.raw before the JSON parser, so Stripe can verify the signature. The handler answers 200 after it accepts the event.
Domain features live under src/app/modules/<moduleName>:
src/
βββ app/
β βββ loaders/ # BullMQ workers setup
β βββ middlewares/ # auth, socketAuth, validation, uploads, rate limit, errors
β βββ modules/
β β βββ admin/ # Admin accounts, created by a super admin
β β βββ auth/ # Login, refresh, email verification, password reset
β β βββ blog/ # Category articles, published after admin review
β β βββ category/ # Service categories and the credit cost of an unlock
β β βββ chat/ # Chat threads
β β βββ creditLedger/ # Every credit balance change
β β βββ creditPackage/ # Credit packages and their Stripe Prices
β β βββ creditPurchase/ # Checkout sessions started by a provider
β β βββ disclaimer/ # Terms of service and privacy policy
β β βββ faq/ # Public frequently asked questions
β β βββ lead/ # Project requests and the public feed
β β βββ leadAccess/ # A provider's unlock of one lead
β β βββ mediaUpload/ # S3 uploads and unlinked-file tracking
β β βββ message/ # Chat messages
β β βββ notification/ # In-app notifications and the notification worker
β β βββ platformReview/ # Reviews of the platform
β β βββ setting/ # The single site settings document
β β βββ stripeEvent/ # Webhook idempotency records
β β βββ support/ # Public contact messages
β β βββ transaction/ # Payment records, amounts in euros
β β βββ user/ # Accounts, roles, and provider signup
β β βββ wallet/ # Template payout routes, not used for credits
β βββ webhooks/
β βββ stripe/ # Raw body, signature check, and credit fulfillment
βββ api-docs/ # OpenAPI registry
βββ config/ # Env, Redis, Stripe, S3
βββ DB/ # Super admin seed
βββ helpers/ # JWT, mail, sockets
βββ routes/ # Mounts every router under /api/v1
βββ scripts/ # create-module.ts
βββ shared/ # catchAsync, sendResponse, logger
βββ app.ts # Express app, no port and no database connection
βββ dev-server.ts # Local entry, listens on PORT_DEV
βββ server.ts # Production entry, listens on PORT
- Node.js v20 or newer. The Docker image uses Node 22.
- npm
- MongoDB as a replica set (even a single node). Registration and other writes use transactions.
- Redis v6 or newer, for BullMQ and rate limits
- Docker & Docker Compose, optional, for the containerized server
Stripe, S3, and SMTP can stay on test credentials until those paths are exercised.
git clone https://github.com/Rahad-Ullah/controfferta-backend.git
cd controfferta-backendnpm installCopy .env.example to .env and replace every placeholder. Do not commit .env.
# -------------------- Server Configuration --------------------
SERVER_NAME=Controfferta
NODE_ENV=development
PORT=5000 # Production port (npm start)
PORT_DEV=5001 # Development port (npm run dev)
IP_ADDRESS=127.0.0.1
FRONTEND_URL=http://localhost:3000
DASHBOARD_URL=http://localhost:3001
BACKEND_URL=http://localhost:5001
CORS_EXTRA_ORIGINS= # optional comma-separated extra CORS origins
MEDIA_SERVER_URL=http://localhost:5001
LOGO_URL=
# -------------------- Database & Cache --------------------
DATABASE_URL=mongodb://127.0.0.1:27017/controfferta
REDIS_URL=redis://127.0.0.1:6379
# -------------------- Security & Tokens --------------------
BCRYPT_SALT_ROUNDS=12
CRYPTO_SECRET=your_32_character_crypto_secret_key
JWT_SECRET=your_super_secret_jwt_access_key
JWT_EXPIRE_IN=1d
JWT_REFRESH_SECRET=your_super_secret_jwt_refresh_key
JWT_REFRESH_EXPIRE_IN=7d
# -------------------- Email (SMTP) --------------------
EMAIL_FROM=info@controfferta.it
EMAIL_REPLY_TO=info@controfferta.it
EMAIL_USER=your_smtp_username
EMAIL_PASS=your_smtp_password
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
# -------------------- Super Admin Credentials --------------------
SUPER_ADMIN_EMAIL=super.admin@controfferta.it
SUPER_ADMIN_PASSWORD=your_super_admin_password
# -------------------- Stripe Payments --------------------
STRIPE_API_VERSION=2024-06-20
STRIPE_PUBLIC_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
# -------------------- AWS S3 Storage --------------------
AWS_REGION=eu-south-1
AWS_ACCESS_KEY_ID=your_aws_access_key
AWS_SECRET_ACCESS_KEY=your_aws_secret_key
S3_BUCKET_NAME=your_bucket_nameForward Stripe events to the raw webhook while developing payments:
stripe listen --forward-to localhost:5001/webhooks/stripePut the signing secret it prints into STRIPE_WEBHOOK_SECRET.
Runs src/dev-server.ts with hot reload via ts-node-dev. It listens on PORT_DEV.
npm run devCompiles TypeScript into dist/ and starts src/server.ts on PORT.
npm run build
npm startOn boot the process connects to MongoDB, seeds the super admin when that role is missing, opens Socket.IO on the same HTTP server, and starts the BullMQ workers.
# Development server
docker compose --profile dev up --build
# Production server
docker compose --profile prod up -d --buildnpm run cm <name>The script writes src/app/modules/<camelName>/ with the interface, model, validation, constants, service, controller, and route. Register the router in src/routes/index.ts, add a register<Name>Docs() call in src/api-docs/openapi.ts, and check the collection against docs/erd.md.
Tests are integration-first. The plan is in docs/testing-strategy.md.
- In-memory MongoDB: HTTP tests call the Express app through Supertest. Nothing binds a port.
- Isolated state: collections are cleared between tests in
tests/setup.ts. - Mocks: BullMQ, Redis, Nodemailer, AWS S3, and Stripe are stubbed under
tests/mocks/.
| Task | Command | Description |
|---|---|---|
| Run All Tests | npm test |
Vitest, once |
| One File | npx vitest run tests/integration/lead.test.ts |
A single area |
| Typecheck | npx tsc --noEmit |
TypeScript with no emit |
| Watch Mode | npm run test:watch |
Vitest in watch mode |
| Coverage Report | npm run test:coverage |
Writes the coverage/ report |
| Check Linting | npm run lint:check |
ESLint on src |
| Fix Linting | npm run lint:fix |
ESLint autofix |
| Prettier Format | npm run prettier:fix |
Formats the repo |
Socket.IO authenticates the handshake with the JWT middleware.
connection: joinsuser:${userId}and marks the user online.room:join/room:leave: enters or leaveschat:${chatId}. The user must be a participant.getMessageandgetChatList: emitted when a message is saved.getNotification: emitted touser:${userId}when a notification is created.disconnect: marks the user offline when no other socket for that user remains.
Workers start from src/app/loaders/bullmq.loader.ts:
- Email: Nodemailer sends run on the email queue, so request handlers do not wait on SMTP.
- Notifications: a worker delivers notification jobs.
- Unlinked media: uploads are scored in the Redis sorted set
unlinked_media_uploads. Linking a file removes it from the set. A repeatable job (0 */6 * * *) deletes S3 objects that are still unlinked after 6 hours.
Commits follow Conventional Commits through Commitizen. Releases are cut by Semantic Release.
git add .
npm run commitThe prompts use:
feat(scope): a new feature or endpoint.fix(scope): a bug fix.test(scope): tests.refactor(scope): a behavior-preserving change.perf(scope): a performance change.docs(scope): documentation.chore(scope): tooling, dependencies, or config.
test.yml: ESLint and Vitest coverage on every pull request and on pushes tomainandmaster. The job uses Node 20.docker-publish.yml: builds the image and pushes it to GitHub Container Registry.release.yml: Semantic Release versions the repo and publishes the GitHub Release from Conventional Commits onmain.
Built with β€οΈ by Rahad Ullah
"Turning complex problems into elegant, efficient solutions."