Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

65 Commits

Folders and files

Repository files navigation

πŸ—οΈ Controfferta Backend

Node.js TypeScript Express MongoDB Redis Vitest Docker

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.


πŸ“‘ Table of Contents


πŸš€ Core Business Capabilities

How a lead is sold

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
Loading
  1. Anyone can POST /api/v1/leads/create. No account is created.
  2. An admin moves the lead from pending to accepted or rejected, and later from accepted to closed.
  3. GET /api/v1/leads lists accepted leads. Contact details stay off this feed.
  4. A provider unlocks a lead with POST /api/v1/lead-accesses/unlock. The charge is the category's current creditCost. The access row keeps the amount that was actually taken.
  5. 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.

1. Multi-Role Authentication & Access Control (RBAC)

  • Roles are client, provider, admin, and super admin.
  • Public signup accepts client and provider. A super admin creates admin accounts. The process seeds one super admin from SUPER_ADMIN_EMAIL and SUPER_ADMIN_PASSWORD when none exists.
  • Access and refresh JWTs. Passwords are hashed with bcrypt. Email verification and password reset go out through the mail queue.

2. Lead Marketplace

  • Anyone can submit a project request. No account is created.
  • An admin moves a lead from pending to accepted or rejected, and later from accepted to closed.
  • 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.

3. Lead Unlock

  • 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, and completed.
  • Closing or rejecting a lead leaves existing unlock rows in place.

4. Credits, Packages, and Stripe

  • 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.creditBalance and 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.welcomeCreditAmount credits. When that setting has not been saved, the grant is 15. A stored 0 turns 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.completed and checkout.session.async_payment_succeeded when payment_status is paid. A stripeEvent row stops the same Stripe event from being applied twice.

5. Site Content and Support

  • 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.

6. Real-Time Chat and Notifications

  • Socket.IO on the same HTTP server, authenticated with the JWT.
  • Chat rooms, live messages, and in-app notifications pushed to user:${userId}.

7. Media Upload and Cleanup

  • 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.

πŸ›  Technology Stack

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

πŸ› System Architecture

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.


πŸ“‚ Directory Layout

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

πŸ“‹ Prerequisites

  • 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.


⚑ Getting Started

1. Clone the Repository

git clone https://github.com/Rahad-Ullah/controfferta-backend.git
cd controfferta-backend

2. Install Dependencies

npm install

βš™οΈ Environment Configuration

Copy .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_name

Forward Stripe events to the raw webhook while developing payments:

stripe listen --forward-to localhost:5001/webhooks/stripe

Put the signing secret it prints into STRIPE_WEBHOOK_SECRET.


πŸƒ Running the Application

Development Mode

Runs src/dev-server.ts with hot reload via ts-node-dev. It listens on PORT_DEV.

npm run dev

Production Build & Run

Compiles TypeScript into dist/ and starts src/server.ts on PORT.

npm run build
npm start

On 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.

Running with Docker

# Development server
docker compose --profile dev up --build

# Production server
docker compose --profile prod up -d --build

🧩 Scaffolding New Modules

npm 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.


πŸ§ͺ Testing & Quality Assurance

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

πŸ”’ Real-Time Events

Socket.IO authenticates the handshake with the JWT middleware.

  • connection: joins user:${userId} and marks the user online.
  • room:join / room:leave: enters or leaves chat:${chatId}. The user must be a participant.
  • getMessage and getChatList: emitted when a message is saved.
  • getNotification: emitted to user:${userId} when a notification is created.
  • disconnect: marks the user offline when no other socket for that user remains.

πŸ”„ Background Workers & Cleanup Jobs

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.

πŸ“ Commit & Release Workflow

Commits follow Conventional Commits through Commitizen. Releases are cut by Semantic Release.

Commitizen CLI

git add .
npm run commit

The 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.

CI/CD

  • test.yml: ESLint and Vitest coverage on every pull request and on pushes to main and master. 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 on main.

πŸ‘¨β€πŸ’» Developer

Built with ❀️ by Rahad Ullah

"Turning complex problems into elegant, efficient solutions."

GitHub Portfolio


Happy Coding πŸš€

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages