Back to Projects

YNM Safety — CRM & Price Engine

Full-stack CRM and quotation management system built for YNM Safety Pvt Ltd combining Price Engine (4 quotation types: MBCB, Signages, Paint, Price List with PDF export, HSN/SAC codes, digital signatures, merge-quotes), complete CRM (Accounts & Sub-Accounts, Contacts, Leads, Tasks with timers/chat, Activities, Dashboard with leaderboard/streaks), AI features (RAG Chat, Query Engine, Task Assist, Daily Insights, Pricing Analysis powered by Google Gemini), and Admin Tools (rate approvals, monitoring dashboards). Built with Next.js 16 (App Router), React 18, TypeScript 5.9, Supabase PostgreSQL (RLS, real-time subscriptions), 160+ RESTful API endpoints, 103 components, 22 hooks, 30+ AI modules, 6 calculation modules.

Next.js 16React 18TypeScript 5.9SupabasePostgreSQLTailwind CSS 3.4Framer MotionRechartsGoogle GeminijsPDFDockerGitHub ActionsGCP Cloud RunGCP Secret ManagerRedis (optional)Makefile

Role

Full-stack engineer

Team

Solo

Company/Organization

YNM Safety

The Problem

YNM Safety needed automated quotation generation for complex road safety products (MBCB crash barriers, reflective signages, thermoplastic...

CRM data was scattered across different systems (spreadsheets, emails, manual notes) with no unified interface for customer lifecycle management,...

Sales team lacked real-time insights into customer interactions, quotation status, lead follow-ups, task completion rates, and performance...

No intelligent assistance for pricing decisionssales team couldn't easily query business data in natural language, get AI-powered task...

Historical pricing decisions and quotation records were difficult to reference and analyze for consistency, making it hard to maintain pricing...

Required secure deployment with role-based access control (10+ roles: Admin, Sales Manager, Sales Rep, etc.) to ensure proper authorization,...

Needed ability to merge multiple quotations into single document for clients requesting combined quotes across product categories (e.g., MBCB +...

The Solution

Built a comprehensive Next.js 16 application with App Router serving as the central business platform for YNM Safety.

Price Engine (4 Quotation Types with PDF Export)

MBCB Quotations — Metal Beam Crash Barriers with three types (W-Beam, Thrie Beam, Double W-Beam). Formula-based calculations for posts (spacing,...

Signages Quotations — Reflective signboards with MS angle/pipe structural options, board types (plain/printed), digital printing specifications,...

Paint Quotations — Thermoplastic road-marking paints with material types (hot-applied thermoplastic, cold plastic), color options, quantity,...

Price List Quotations — Multi-line quotations from configurable price catalogs. Select multiple products with quantities, apply discounts,...

All quotations generate professional PDFs via jsPDF with: - Company logo and letterhead - HSN/SAC codes for tax compliance - Digital signatures...

Merge Quotes

— Combine multiple quotations (e.g., MBCB + Signages + Paint) into single PDF document for clients requesting comprehensive quotes.

Complete CRM System

Accounts & Sub-Accounts — Hierarchical account management with parent-child relationships. Engagement scoring based on interactions (tasks...

Contacts — Contact management linked to accounts. Store name, email, phone, designation, decision-making authority, communication preferences....

Leads — Lead tracking with follow-up scheduling, lead scoring (based on engagement, budget, timeline), conversion tracking, and historical...

Tasks — Task management with built-in timers (track time spent), in-app chat (team collaboration on tasks), PDF attachments (upload relevant...

Activities — Comprehensive activity logging for all interactions: calls, emails, meetings, quotes sent, tasks completed. Filterable timeline...

Dashboard — Real-time analytics with:

- Targets — Sales targets vs actuals with progress bars

- Leaderboard — Top performers by quotes sent, deals closed, revenue

- Streak Tracking — Daily login streaks, task completion streaks to motivate team

- Charts — Revenue trends (Recharts), lead funnel, conversion rates, quote acceptance rates

- KPIs — Pipeline value, average deal size, win rate, sales cycle length

AI-Powered Features (Google Gemini)

RAG Chat — Intelligent assistant with business context and database knowledge. Trained on company data (products, pricing, clients, past quotes)....

Query Engine — Natural language to database query conversion. Sales team can ask "Show me all leads from last month with budget > 5 lakhs" and...

Task Assist — AI-powered task recommendations based on lead stage, time since last contact, upcoming deadlines. Suggests next best actions like...

Daily Insights — Automated coaching and performance analysis delivered daily. Analyzes sales rep performance, identifies bottlenecks (e.g., long...

Pricing Analysis — AI-driven pricing recommendations based on historical data, competitor analysis (if available), product margins. Suggests...

Admin Tools

Rate Approvals — Admin workflow for approving custom pricing rates that deviate from standard pricing. Sales reps submit quote with custom rates...

Monitoring Dashboards — System health, API usage, user activity, error logs. Admin visibility into platform performance.

Automated Workflows — Background jobs (cron) for: daily insights generation, lead scoring updates, overdue task reminders, engagement score...

Backend Architecture (160+ RESTful API Endpoints)

Organized by domain with service-layer architecture:

`/api/auth/*`Login, session management, role verification (10+ roles)

`/api/accounts/*`Account CRUD, sub-accounts, engagement scoring

`/api/contacts/*`Contact management linked to accounts

`/api/crm/leads/*`Lead tracking, follow-ups, scoring

`/api/crm/tasks/*`Task management, timers, chat, attachments

`/api/activities/*`Activity logging and reporting

`/api/quotes/*`Quotation CRUD (MBCB, Signages, Paint, Price List), PDF generation, merge-quotes

`/api/ai/*`RAG chat, query engine, task assist, daily insights, pricing analysis

`/api/admin/*`Rate approvals, user management, monitoring

`/api/cron/*`Scheduled jobs authenticated with CRON_SECRET

`/api/health`Liveness probe for Cloud Run

`/api/verify-keys`Configuration check (Supabase, Gemini, Google Maps)

Database & Real-time (Supabase)

PostgreSQL with Supabase for relational data storage

Row Level Security (RLS) — Database-level access control without middleware. Each table has RLS policies based on user roles.

Real-time subscriptions — Live updates for dashboard metrics, new leads, task assignments. UI updates automatically when data changes.

Auto-generated TypeScript types — Supabase CLI generates types (src/types/) for type-safe database queries.

Formula-Based Pricing Engine

6 calculation modules in lib/calculations/ directory

Deterministic TypeScript functions for predictable, auditable calculations

MBCB: post spacing, concrete volume, beam length, spacer count

Signages: area calculation, material costs, labor estimation

Paint: coverage per liter, road length, material quantity

Price List: line item totals, discounts, GST, final amount

CI/CD (GitHub Actions)

Workflow in .github/workflows/ci.yml runs on every push and PR to main/master/develop:

Lint (parallel) — ESLint rules for code quality

Type Check (parallel) — tsc --noEmit for TypeScript errors

Build (after lint + type-check pass) — Production build verification

Concurrency control: if you push again while checks run, previous run auto-cancels.

Local CI check: `make ci` runs lint + type-check + build (mirrors GitHub Actions).

Makefile Automation (13 commands)

`make dev`Start development server (localhost:3000)

`make install`Clean install dependencies (npm ci)

`make lint`Run ESLint

`make typecheck`Run TypeScript type checking

`make build`Type-check and build for production

`make ci`Run lint + type-check + build

`make docker-build`Build Docker image locally

`make docker-run`Build and run container on port 3000

`make deploy PROJECT_ID=<id>`Deploy via Cloud Build to Cloud Run

`make logs PROJECT_ID=<id>`Tail Cloud Run logs

`make status PROJECT_ID=<id>`Show Cloud Run service status

`make secrets PROJECT_ID=<id>`List project secrets in Secret Manager

`make clean`Remove .next/ and node_modules/

Deployment Options

Vercel (recommended) — Import repo, set root directory, add environment variables (NEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_ANON_KEY,...

GCP Cloud Run — cloudbuild.yaml builds Docker image and deploys. Secrets stored in GCP Secret Manager with crm-pe- prefix (crm-pe-supabase-url,...

Docker standalone — Build with --build-arg for public env vars, run with -e for private env vars.

Security Best Practices

.gitignore blocks .env.local, .env.production, .env.development, *.key, *.pem, credentials.json, service-account*.json

.dockerignore prevents secrets from being copied into Docker images

.gcloudignore prevents secrets from being uploaded to GCP

.env.example template with placeholder values (safe to commit) for local setup

Real secrets set in deployment platform (Vercel Environment Variables or GCP Secret Manager)

No hardcoded secrets anywhere in source code

Optional Features

Redis caching — Optional REDIS_URL for caching frequently accessed data. App works without Redis (caching disabled).

Design Decisions

Chose Next.js 16 with App Router for modern React patterns (Server Components by default), unified API routes, SSR/SSG optimization, and excellent...

Used formula-based pricing calculations over ML modelsdeterministic TypeScript functions are auditable, predictable, debuggable, and don't require...

Built 160+ RESTful API endpoints organized by domain (auth, accounts, contacts, leads, tasks, activities, quotes, ai, admin, cron) with service-layer...

Selected Supabase for PostgreSQLmanaged database with Row Level Security (database-level access control without middleware), real-time subscriptions...

Implemented Row Level Security (RLS) policies in Supabasedatabase-level access control based on user roles ensures data security without additional...

Chose Google Gemini for AI features (RAG, query engine, insights)cost-effective, good quality for business use cases, streaming support for chat....

Built custom CRM instead of integrating Salesforce/HubSpotmaintains full control over data models, avoids vendor lock-in, eliminates monthly...

Added gamification (leaderboards, streaks, targets) to Dashboarddrives sales team adoption and engagement through competition and achievement...

Implemented merge-quotes featureallows combining multiple quotations (MBCB + Signages + Paint) into single PDF, addressing client need for...

Used jsPDF for PDF generation instead of external PDF servicesno API costs, works offline, full control over layout, includes HSN/SAC codes and...

Added in-app chat for tasksteam collaboration on task context without switching to external chat apps like Slack/Teams. Chat history persists with...

Implemented task timerstrack time spent on each task for productivity analysis and accurate billing/costing.

Made Redis optionalapp builds and runs without Redis (caching disabled). REDIS_URL enables caching for performance boost but not required for...

Added verify-keys endpointquickly check if Supabase, Gemini, and Google Maps APIs are configured correctly without diving into code. Useful for...

Used GitHub Actions with concurrency controlif you push again while CI runs, previous run auto-cancels to save CI minutes and get faster feedback.

Created Makefile for project automationsingle commands (`make dev`, `make ci`, `make deploy`) simplify development workflow and ensure consistency...

Separated environment configuration.env.example template for local setup, real secrets in platform dashboards (Vercel/GCP). Never commit .env.local...

Implemented 10+ role-based access controlAdmin, Sales Manager, Sales Rep, etc. with different permissions for quotes, rate approvals, admin tools,...

Tradeoffs & Constraints

Chose formula-based pricing over AI/ML pricing modelsmore predictable, auditable, and debuggable for business trust, but less adaptive to dynamic...

Built extensive API surface (160+ endpoints)comprehensive feature coverage but requires careful versioning, documentation, and maintenance. Trade...

Supabase with Row Level Securitydatabase-level access control is elegant and performant, but RLS policies can be complex to debug. PostgreSQL logs...

Real-time Supabase subscriptionsgreat UX with live dashboard updates, but increases Supabase connection usage and costs. Each active subscription...

Google Gemini for AI featurescost-effective (~$0.002/call) and good quality, but less capable than GPT-4 for complex reasoning. Trade cost for...

GCP Cloud Run deploymentexcellent auto-scaling and pay-per-use pricing, but cold starts (1-2 seconds) for first request after idle period....

jsPDF for PDF generationfull control and no API costs, but limited to client-side rendering. For very complex PDFs (hundreds of pages), server-side...

Custom CRM instead of Salesforce/HubSpotfull control and no monthly fees, but requires ongoing maintenance and feature development. Trade vendor...

Redis optional for cachingapp works without it, but performance boost from caching is significant for frequently accessed data (price catalogs,...

In-app task chatconvenient for team collaboration, but not as feature-rich as dedicated chat apps (no threads, no reactions, no file sharing beyond...

Next.js 16 App Routermodern React patterns and performance, but learning curve for team familiar with Pages Router. Migration from Pages Router to...

TypeScript 5.9type safety reduces runtime errors and improves developer experience, but adds compile time and requires type definitions for all...

Would improve: Add offline mode for field sales (service workers, local storage), implement demand forecasting based on historical quote data, add...

Outcome & Impact

Production business platform live at www.crm-ynmsafety.com serving as the central system for YNM Safety's sales operations, CRM, and quotation...

Comprehensive backend with 160+ RESTful API endpoints organized by domain: /api/auth/* (login, session, roles), /api/accounts/* (CRUD, sub-accounts,...

Price Engine with 4 quotation types: MBCB (W-Beam, Thrie Beam, Double W-Beam with post & spacer calculations), Signages (reflective signboards with...

Merge-quotes feature combines multiple quotations (e.g., MBCB + Signages + Paint) into single PDF document for clients requesting comprehensive...

Complete CRM system: Hierarchical Accounts & Sub-Accounts with engagement scoring based on interactions, Contacts linked to accounts with...

Real-time Dashboard with analytics: Sales targets vs actuals with progress bars, leaderboard showing top performers by quotes sent/deals...

AI-powered features by Google Gemini: RAG Chat (intelligent assistant with business context and database knowledge, answers questions like 'What was...

Admin Tools: Rate approval workflow (sales reps submit custom pricing → admin reviews → approve/reject with notes), monitoring dashboards (system...

Formula-based pricing engine with 6 calculation modules in lib/calculations/deterministic TypeScript functions for predictable, auditable...

Supabase PostgreSQL with Row Level Security (RLS)database-level access control based on user roles (10+ roles: Admin, Sales Manager, Sales Rep,...

Optional Redis caching via REDIS_URLapp works without Redis (caching disabled), but Redis provides significant performance boost for frequently...

GitHub Actions CI/CD: .github/workflows/ci.yml runs lint + type-check + build on every push and PR to main/master/develop with concurrency control...

Makefile automation with 13 commands: make dev (start dev server), make install (clean install), make lint (ESLint), make typecheck (tsc), make build...

Secure deployment with no secrets in repository: .gitignore blocks .env.local/.env.production, *.key, *.pem, credentials.json, service-account*.json;...

Flexible deployment options: Vercel (recommendedimport repo, set env vars, deploy), GCP Cloud Run (cloudbuild.yaml builds Docker and deploys,...

Health and verification endpoints: GET /api/health for Cloud Run liveness probe, GET /api/verify-keys to check Supabase/Gemini/Maps configuration...

Frontend architecture: 103 React components (ui primitives in components/ui/, CRM-specific in components/crm/, forms, modals), 22 custom hooks...

Project structure: app/ (Next.js App Router with api/ and page routes), components/ (React components), hooks/ (custom hooks), contexts/ (Context...

Comprehensive documentation in README: Table of contents, overview, features, tech stack, project structure, getting started (prerequisites,...

Proprietary licenseprivate software for YNM Safety Pvt Ltd with all rights reserved.

Tech Stack

Core: Next.js 16 (App Router), React 18, TypeScript 5.9

Backend: 160+ RESTful API endpoints with service-layer architecture

Database: Supabase (PostgreSQL) with Row Level Security (RLS) and real-time subscriptions

UI: Tailwind CSS 3.4 (utility-first styling), Framer Motion (animations), Recharts (data visualization)

AI: Google Gemini (RAG Chat, Query Engine, Task Assist, Daily Insights, Pricing Analysis)

Documents: jsPDF for PDF generation (quotations with HSN/SAC codes, digital signatures)

Caching: Redis (optionalapp works without it, REDIS_URL enables caching)

CI/CD: GitHub Actions (lint, type-check, build with concurrency control)

Deployment: Docker (multi-stage build), Vercel (recommended), GCP Cloud Run (with Secret Manager)

Automation: Makefile (13 commands for dev/build/deploy workflows)

Architecture: 103 components, 22 hooks, 30+ AI modules, 6 calculation modules, 55+ utils, 10+ roles

Back to Projects