Minimata

Minimata

Minimal-Data-Dependency CRM with PostgreSQL and Prisma

CI Status License Node.js TypeScript PostgreSQL Prisma ORM React Next.js Full-Stack Minimum-Dependency CRM Neon WSL Linux Express.js JWT Password Hashing body-parser CORS express-session express-rate-limit express-validator zod Node.js Cluster helmet Authentication Authorization RBAC Middleware Swagger swagger-jsdoc swagger-ui-express ts-node ESLint Prettier nodemon cross-env dotenv morgan winston Jest Supertest ts-jest @types/jest @types/supertest PM2 CRUD KPI Tracking API Routes SSR SSG Back-End Front-End CSS/SASS GitHub


Table of Contents

Project Overview

Minimata is a robust and scalable CRM (Customer Relationship Management) system with minimal reliance on third-party tools. It leverages PostgreSQL as the database and Prisma as the (Object-Relational Mapping) ORM for efficient data interaction. The system features custom authentication, role-based access control, secure password storage, and session management, all implemented from scratch to maximize control and minimize external dependencies. Ad-ons include integration with Neon for enhanced scalability and serverless capabilities.

Core Functionalities

Directory Structure


Minimata Project Root
├── README.md                             # Project documentation
├── package.json                          # Monorepo config, root scripts
├── .env                                  # Environment variables
├── turbo.json                            # Turborepo pipeline config
├── apps/                                 # All deployable applications
│   ├── web/                              # Next.js Front-End SPA
│   │   ├── __tests__/                    # Unit/Component Tests
│   │   ├── public/                       # Static assets
│   │   ├── src/
│   │   │   ├── app/                      # Next.js app directory (routing)
│   │   │   │   ├── api/                  # Next.js API routes (replaces Express)
│   │   │   │   │   ├── auth/             # Authentication API endpoints
|   |   |   |   |   |   ├── approve/
|   |   |   |   |   |   │   └── route.ts  # Approve API (migrated from Express)
|   |   |   |   |   |   ├── me/
|   |   |   |   |   |   │   └── route.ts  # Get authenticated user info (Next.js API)
|   |   |   |   |   |   ├── new-users/
|   |   |   |   |   |       └── route.ts  # List new users (migrated from Express)
│   │   │   │   │   ├── contact/          # Contact form processing endpoint
│   │   │   │   │   ├── accounts/         # CRUD endpoints for accounts/CRM
│   │   │   │   │   └── middleware.ts     # Optional middleware for API routes
│   │   │   │   ├── contact/              # Contact page and components
│   │   │   │   ├── dashboard/            # Dashboard route (role-based)
│   │   │   │   ├── login/                # Login page
│   │   │   │   ├── register/             # Register page
│   │   │   │   ├── unauthorized/         # Unauthorized page
│   │   │   │   ├── page.tsx              # Home page
│   │   │   │   ├── layout.tsx            # App-wide layout
│   │   │   │   ├── tailwind.css           # Global styles
│   │   │   │   └── favicon.ico           # Favicon
│   │   │   ├── components/               # Shared UI components
│   │   │   ├── hooks/                    # Custom React hooks
│   │   │   ├── utils/                    # Shared utilities
│   │   │   ├── prisma/                   # Prisma client and schema
│   │   │   └── types/                    # Local types
│   │   ├── package.json                  # Next.js app dependencies
│   │   └── tsconfig.json                 # TS config for web app
├── packages/                             # Shared libraries
│   ├── ui/                               # Shared UI components (lib)
│   ├── utils/                            # Shared utilities (lib)
│   ├── types/                            # Shared TypeScript types
│   └── db/                               # Prisma client and helpers
│       ├── prisma/
│       ├── package.json
├── scripts/                              # Dev/ops scripts
├── tests/                                # End-to-end/integration tests

Key Files and Folders


Backend: src/server/


Classic React Client: client/


Next.js Front-End App: apps/web/


Types and Shared


Prisma


Other

Notes on Arcitectural Best Practices


Tools and Technologies

Backend:

Frontend:

Dev Tools:

Logging:

API & Docs:

Testing:

Deployment & Scaling:

Deployment (Exclusive Feature):

Getting Started

1. Update Packages

Update the package list and upgrade existing packages:

sudo apt update
sudo apt upgrade

2. Install Node.js and npm (or yarn)

Using nvm (Node Version Manager) is recommended for managing multiple Node.js versions:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install --lts
nvm use --lts

Alternatively, install directly:

sudo apt install nodejs npm

3. Install PostgreSQL

sudo apt install postgresql postgresql-contrib

4. Install Prisma CLI:

npm install -g prisma

5. Start PostgreSQL service

sudo service postgresql start

or via Docker:

# Create Container
docker-compose up -d

# Verify Initialization Logs
docker logs postgres_container # Look for message similar to "PostgreSQL init process complete; ready for start up."

# Access the PostgreSQL Container
docker exec -it postgres_container bash

6. Create PostgreSQL User and Database (replace your_username and your_database)

# Open PostgeSQL Database
sudo -u postgres psql

# Create Username and Password
CREATE USER your_username WITH PASSWORD 'your_password';          # Bypass if using .env

# Create Database with Owner
CREATE DATABASE your_database WITH OWNER your_username;           # Bypass if using .env

# Grant Privileges to User
GRANT ALL PRIVILEGES ON DATABASE your_database TO your_username;  # Bypass if using .env

# List Roles
\du

# List DBs
\l

# Exit PostgreSQL
\q

# Exit Docker Postgres Container
exit

7. Navigate to the project directory

If not already navigate your project directory:

cd <project_directory>

8. Install project dependencies

# Generate Default JSON Package
npm init -y

# Install dependencies
npm install # Or yarn

# Generate Secure JWT Secret
npx generate-jwt-secret --length 32
  1. Set up environment variables:

Create a .env file in the project root directory and populate it with necessary environment variables, including the PostgreSQL connection string. Ensure this file is excluded from version control (add it to .gitignore). Example:

DATABASE_URL=postgresql://your_username:your_password@localhost:5432/your_database?schema=public

JWT_SECRET=your_secure_jwt_secret

10. Generate Prisma Client and Run Migrations

# Create Prisma Directory
mkdir -p prisma

# Create Prisma Schema File (Model Definitions)
touch prisma/schema.prisma

# Generate Prisma Client
npx prisma generate

# Run Migrations
npx prisma migrate dev --name init

11. Install & Run the Development Servers

  1. Access the application: Open your web browser and navigate to http://localhost:3000 (or the port specified in your server configuration) to access the application.

Implementation

Authentication

Backend:

Frontend:

Authorization Middleware (JWT)

How it works:

  1. Import and use the middleware in your route: import { authenticateJWT } from ‘./middleware/jwt’;
  2. Protect a route: app.use(‘/api/protected’, authenticateJWT, rbac([‘admin’]));
  3. The middleware will reject requests with missing, invalid, or expired tokens.

User Interfaces

Database Schema with Prisma

Request Validation

How it works:

  1. Add validation chains (e.g., body('email').isEmail()) to route handlers.
  2. Use validationResult(req) to check for errors and return them if present.
  3. Example for /api/auth/register and /api/auth/login.

Role-Based Access Control (RBAC)

How it works:

  1. Import and use the middleware in your route: import { rbac } from './middleware/rbac';
  2. Protect a route: app.use('/admin', rbac(['admin']));
  3. Assumes req.user.roles is set by your authentication/JWT middleware.

Advanced Logging

How it works:

  1. Winston logger is defined in src/server/utils/logger.ts.
  2. Morgan is configured in src/server/server.ts to use Winston as its output stream.
  3. All errors are logged using Winston in the error-handling middleware.

Testing

API Documentation (Swagger)

How it works:

  1. Add JSDoc comments to your route files (see Swagger/OpenAPI spec for syntax).
  2. The docs are auto-generated and served at /api/docs.

Clustering & Scaling

How it works:

  1. Run the clustered server with ts-node src/server/server.cluster.ts (or compile and run the JS output).
  2. PM2 can be used to manage the cluster: pm2 start dist/server/server.cluster.js -i max (for max CPU scaling).
  3. PM2 provides monitoring, log rotation, and automatic restarts for robust production deployments.

PM2 Example Commands:

# Install PM2 globally
npm install -g pm2

# Start the clustered server with max workers
pm2 start dist/server/server.cluster.js -i max --name minimata-api

# Monitor logs and processes
pm2 logs
pm2 monit

# Reload with zero downtime
pm2 reload minimata-api

# Stop and delete
pm2 stop minimata-api
pm2 delete minimata-api

Plan of Action and Milestones

Phase 1: Core Authentication & Database Setup (Weeks 1-3)

Phase 2: CRM Core Features (Weeks 4-6)

Phase 3: Custom KPI Tracking & UI Refinements (Weeks 7-9)

Phase 4: Optimization & Future Enhancements (Weeks 10+)


This roadmap provides a structured approach to building the CRM, allowing for phased development and ensuring a robust and scalable solution while minimizing third-party dependencies.