Skip to main content

Quick Start Guide

This guide will help you set up and run the Banca Management Backend locally, configure your environment, and make your first authenticated API request.

Prerequisites

Before you begin, ensure you have the following installed:

Node.js

Version 20.x required

PostgreSQL

Version 14+ recommended

Redis

Optional for caching
The project uses Prisma ORM which requires a PostgreSQL database. For production, Supabase with transaction pooler (port 6543) is recommended.

Installation

1

Clone the repository

git clone <repository-url>
cd backend-bancas
2

Install dependencies

npm install
This will install all required packages including:
  • Express.js and middleware (cors, helmet, express-rate-limit)
  • Prisma Client and CLI
  • Authentication (jsonwebtoken, bcryptjs)
  • Validation (zod)
  • Logging (pino)
  • Testing (jest, supertest)
3

Configure environment variables

Create a .env.local file in the root directory based on .env.example:
cp .env.example .env.local
Edit .env.local with your configuration (see Environment Configuration below).
4

Set up the database

Generate Prisma Client and run migrations:
npm run prisma:generate
npm run migrate:dev
For Supabase/PgBouncer environments, use npm run migrate:deploy instead of migrate:dev as shadow database is disabled.
5

Seed initial data (optional)

npm run prisma:seed
This creates initial bancas, ventanas, users, and lottery configurations for testing.
6

Start the development server

npm run dev
The server will start on http://localhost:3000 (or the PORT specified in your .env file).

Environment Configuration

The .env.local file contains critical configuration. Here are the essential variables:

Server Configuration

NODE_ENV=development
PORT=3000
LOG_LEVEL=info
DISABLE_AUTH=false  # Set to true only for development/testing
CORS_ORIGIN=        # Comma-separated list of allowed origins

Database URLs

The system supports three database connection strings for optimal performance:
# Transaction Pooler (port 6543) - For web requests
DATABASE_URL=postgresql://user:[email protected]:6543/postgres?pgbouncer=true&connection_limit=1

# Session Pooler (port 5432) - For migrations and long operations
DIRECT_URL=postgresql://user:[email protected]:5432/postgres

# Read Replica (port 5432) - Optional, for analytics queries
DATABASE_URL_REPLICA=postgresql://postgres.PROJECT_REF-rr-REGION:[email protected]:5432/postgres
If DATABASE_URL_REPLICA is not configured, the system automatically falls back to the primary DATABASE_URL for read queries.

JWT Configuration

JWT_ACCESS_SECRET=your-super-secret-access-key-here
JWT_REFRESH_SECRET=your-super-secret-refresh-key-here
JWT_ACCESS_EXPIRES_IN=60m
JWT_REFRESH_EXPIRES_IN=7d
Generate strong, unique secrets for production! Never commit these values to version control.

Business Rules

SALES_DAILY_MAX=100000
MULTIPLIER_BASE_DEFAULT_X=90

Redis Cache (Optional)

CACHE_ENABLED=false
REDIS_URL=redis://localhost:6379
REDIS_TOKEN=
CACHE_TTL_CUTOFF=300
CACHE_TTL_RESTRICTIONS=300

Transaction Settings

TX_MAX_RETRIES=3
TX_BACKOFF_MIN_MS=250
TX_BACKOFF_MAX_MS=600

Making Your First API Request

Once the server is running, you can interact with the API. Here’s how to authenticate and make your first request.

1. Register a User

POST /api/v1/auth/register
Content-Type: application/json

{
  "username": "admin",
  "password": "SecurePass123!",
  "name": "Admin User",
  "email": "[email protected]",
  "role": "ADMIN"
}
For development, you can set DISABLE_AUTH=true in your .env.local to bypass authentication and simulate an ADMIN user.

2. Login

POST /api/v1/auth/login
Content-Type: application/json

{
  "username": "admin",
  "password": "SecurePass123!"
}
Response:
{
  "success": true,
  "data": {
    "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "user": {
      "id": "uuid-here",
      "username": "admin",
      "name": "Admin User",
      "role": "ADMIN",
      "email": "[email protected]"
    }
  }
}

3. Access Protected Endpoints

Use the accessToken from the login response in the Authorization header:
GET /api/v1/auth/me
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Response:
{
  "success": true,
  "data": {
    "id": "uuid-here",
    "username": "admin",
    "name": "Admin User",
    "role": "ADMIN",
    "email": "[email protected]",
    "ventanaId": null,
    "isActive": true
  }
}

4. Explore Available Routes

Here are some key endpoints to explore:
# Get current user
GET /api/v1/auth/me

# Refresh access token
POST /api/v1/auth/refresh

# Logout
POST /api/v1/auth/logout

Development Scripts

The project includes several useful npm scripts:
# Development
npm run dev              # Start with hot reload
npm run build            # Compile TypeScript
npm run typecheck        # Type check without emit

# Database
npm run prisma:generate  # Generate Prisma Client
npm run migrate:dev      # Run migrations (development)
npm run migrate:deploy   # Deploy migrations (production)
npm run prisma:seed      # Seed database
npm run studio           # Open Prisma Studio

# Testing
npm run test             # Run tests
npm run test:watch       # Run tests in watch mode
npm run test:coverage    # Generate coverage report

# Production
npm run start            # Start production server

Next Steps

System Architecture

Learn about the layered architecture, data models, and request flow

API Reference

Explore detailed API documentation for all endpoints

Authentication

Deep dive into JWT auth, roles, and security

Commission System

Configure hierarchical commission policies

Troubleshooting

Use npm run migrate:deploy instead of migrate:dev. Shadow database is disabled for PgBouncer compatibility.
Ensure your JWT_ACCESS_SECRET and JWT_REFRESH_SECRET are set and match between requests. Check token expiration settings.
Add your frontend origin to the CORS_ORIGIN environment variable (comma-separated for multiple origins).
For Supabase, verify you’re using the correct pooler port (6543 for transaction pooler, 5432 for session pooler). Check connection limits.
Need help? Contact the maintainer at [email protected]

Build docs developers (and LLMs) love