Skip to content

Repository files navigation

InsightOS

AI-powered business management dashboard for small businesses — manage inventory, track sales, record expenses, and get intelligent insights.

InsightOSNodeReactMongoDBTests


Overview

InsightOS is a full-stack business analytics platform built for small business owners who want to move beyond spreadsheets. It combines inventory management, sales tracking, expense monitoring, and AI-driven insights into a single modern dashboard.

The AI assistant (powered by Groq) analyzes your real business data and provides actionable recommendations — from identifying your top-selling products to spotting expense trends.

Supported languages: English & Bengali


Key Features

📦 Inventory Management

  • Product CRUD with name, category, price, and stock tracking
  • Low stock alerts with configurable thresholds
  • Search and category-based filtering
  • Paginated product listings + paginated low-stock endpoint

💰 Sales Tracking

  • Record sales with automatic total calculation
  • Atomic stock management via MongoDB transactions
  • Sales analytics: revenue, quantity, top products, daily trends
  • Filter by date range and product

📉 Expense Monitoring

  • Track expenses across 8 categories (rent, salary, utilities, marketing, supplies, transport, maintenance, other)
  • Expense summaries with category breakdown and daily trends
  • Filter by category and date range

🤖 AI Business Assistant

  • Chat with an AI that has access to your real business data
  • Get insights on revenue, expenses, profit margins, and inventory
  • Multi-turn conversation support with streaming responses
  • Powered by Groq (fast inference via Llama 4 Scout)
  • Optional Google Search grounding for real-time data

📊 Dashboard

  • Consolidated dashboard API endpoint (GET /api/dashboard)
  • Real-time revenue, expense, and profit metrics
  • Revenue & expense trend charts
  • Top products ranking & category breakdown
  • Recent sales & expenses at a glance
  • Low stock product alerts

👤 User Management

  • Avatar upload with automatic file cleanup
  • Email verification flow
  • Password reset (forgot/reset)
  • Admin user listing endpoint
  • Destructive action confirmation ({ "confirm": true })

🛡️ Security

  • JWT authentication with dual httpOnly cookies (access + refresh tokens)
  • Role-based authorization (user/admin)
  • Rate limiting (1000 req/hr general, 60 req/hr for AI)
  • NoSQL injection sanitization
  • Helmet security headers
  • CSRF protection via sameSite: strict cookies
  • Password validation (uppercase, lowercase, number, special character)

🌐 User Experience

  • Dark mode / Light mode toggle
  • English & Bengali language support
  • Smooth animations (Framer Motion)
  • Responsive design
  • Fully accessible (ARIA labels, semantic HTML, keyboard navigation)
  • Configurable currency formatting (VITE_CURRENCY_CODE / VITE_CURRENCY_LOCALE)

Tech Stack

Backend

TechnologyPurpose
Node.js + Express 5Server framework
MongoDB + Mongoose 9Database & ODM
Groq AIBusiness insights
JWT + bcryptAuthentication & security
Zod 4Request validation
MulterFile uploads
PinoLogging
NodemailerEmail sending (verification, password reset)
VitestTesting framework

Frontend

TechnologyPurpose
React 19UI library
Vite 8Build tool
Tailwind CSS 4Styling
TanStack React Query 5Data fetching & caching
Zustand 5State management
React Hook Form + ZodForms & validation
RechartsData visualization
Framer MotionAnimations
AxiosHTTP client (with cookie-based auth)
Vitest + jsdomFrontend testing

Getting Started

Prerequisites

  • Node.js 20+ and pnpm (or npm)
  • MongoDB instance (local or MongoDB Atlas)
  • Groq API key (from Groq Console) — optional for AI features

Installation

git clone https://github.com/yourusername/InsightOS.git
cd InsightOS

Backend Setup

cd backend
pnpm install

Create a .env file in backend/:

PORT=5000MONGODB_URI=mongodb+srv://<username>:<password>@cluster.mongodb.net/insightosJWT_ACCESS_SECRET=your-access-secret-hereJWT_REFRESH_SECRET=your-refresh-secret-hereAI_PROVIDER=groqAI_MODEL=llama-4-scoutGROQ_API_KEY=gsk_your-groq-api-keyAI_WEB_SEARCH=disabledCORS_ORIGIN=http://localhost:5173SMTP_HOST=smtp.gmail.comSMTP_PORT=587SMTP_USER=your-email@gmail.comSMTP_PASS=your-app-passwordEMAIL_FROM=noreply@insightos.appAPP_URL=http://localhost:5173NODE_ENV=development

Start the development server:

pnpm dev

Backend runs at http://localhost:5000

Frontend Setup

cd frontend
pnpm install

Create a .env file in frontend/:

VITE_API_URL=http://localhost:5000VITE_CURRENCY_CODE=USDVITE_CURRENCY_LOCALE=en-US

Start the dev server:

pnpm dev

Frontend runs at http://localhost:5173


Running Tests

Backend (46 tests)

cd backend
pnpm test

Frontend (30 tests)

cd frontend
pnpm test

Total: 76 tests across 8 test files


API Endpoints

Authentication

MethodEndpointAuthDescription
POST/api/auth/registerRegister new account
POST/api/auth/loginLogin
POST/api/auth/refreshRefresh access token (cookie)
POST/api/auth/logoutJWTLogout
GET/api/auth/meJWTGet current user
PATCH/api/auth/meJWTUpdate profile
POST/api/auth/me/avatarJWTUpload avatar
DELETE/api/auth/me/avatarJWTDelete avatar
POST/api/auth/send-verificationJWTSend email verification link
GET/api/auth/verify-email?token=xxxVerify email
POST/api/auth/forgot-passwordSend password reset email
POST/api/auth/reset-passwordReset password with token
GET/api/auth/usersAdminList all users

Dashboard

MethodEndpointAuthDescription
GET/api/dashboardJWTConsolidated dashboard data

Products

MethodEndpointAuthDescription
POST/api/productsJWTCreate product
GET/api/productsJWTList products (paginated, filterable)
GET/api/products/low-stockJWTGet low stock items (paginated)
GET/api/products/:idJWTGet product
PATCH/api/products/:idJWTUpdate product
DELETE/api/products/:idJWTDelete product

Sales

MethodEndpointAuthDescription
POST/api/salesJWTRecord sale (with stock decrement)
GET/api/salesJWTList sales (paginated, filterable)
GET/api/sales/analyticsJWTGet sales analytics
GET/api/sales/:idJWTGet sale

Expenses

MethodEndpointAuthDescription
POST/api/expensesJWTCreate expense
GET/api/expensesJWTList expenses (paginated, filterable)
GET/api/expenses/summaryJWTGet expense summary
GET/api/expenses/:idJWTGet expense
PATCH/api/expenses/:idJWTUpdate expense
DELETE/api/expenses/:idJWTDelete expense

AI Assistant

MethodEndpointAuthRate LimitDescription
POST/api/ai/chatJWT60/hrSend chat message
POST/api/ai/chat/streamJWT60/hrStreaming chat (SSE)
GET/api/ai/conversationsJWTList conversations
GET/api/ai/conversations/:idJWTGet conversation with messages
DELETE/api/ai/conversations/:idJWTDelete conversation

User Account

MethodEndpointAuthDescription
DELETE/api/user/dataJWTClear all business data (requires { "confirm": true })
DELETE/api/user/accountJWTDelete account (requires { "confirm": true })

System

MethodEndpointAuthDescription
GET/healthHealth check
GET/api-docsSwagger API documentation

Database Models

User

FieldTypeDetails
nameStringRequired, max 50 chars
emailStringRequired, unique, lowercase
passwordStringHashed (bcrypt 12 rounds), select: false
roleStringuser or admin
refreshTokenStringStored for refresh flow
avatarStringFile path to uploaded avatar
isVerifiedBooleanEmail verification status
verificationTokenStringEmail verification token
verificationTokenExpiresDateVerification token expiry
resetPasswordTokenStringPassword reset token
resetPasswordExpiresDateReset token expiry

Product

FieldTypeDetails
userIdObjectIdRef: User (indexed)
nameStringRequired, max 100 chars
categoryStringRequired
priceNumberMin 0
stockNumberMin 0, default 0
lowStockThresholdNumberDefault 10

Sale

FieldTypeDetails
userIdObjectIdRef: User (indexed)
productIdObjectIdRef: Product
quantityNumberMin 1
unitPriceNumberProduct price at time of sale
totalAmountNumberAuto-calculated
noteStringMax 200 chars
saleDateDateIndexed

Expense

FieldTypeDetails
userIdObjectIdRef: User (indexed)
titleStringRequired, max 100 chars
amountNumberMin 0
categoryStringEnum: rent, salary, utilities, marketing, supplies, transport, maintenance, other
noteStringMax 200 chars
dateDateIndexed

AIConversation

FieldTypeDetails
userIdObjectIdRef: User (indexed)
titleStringAuto-generated from first message
messagesArrayEmbedded: { role, content, timestamp }

Project Structure

InsightOS/
├── backend/
│ ├── src/
│ │ ├── __tests__/ # Backend tests (4 files, 46 tests)
│ │ ├── config/ # Environment, DB, AI, Swagger config
│ │ ├── constants/ # Shared constants (expense categories)
│ │ ├── middleware/ # Auth, error handling, upload, validate
│ │ ├── modules/ # Feature modules
│ │ │ ├── ai/ # AI chat & conversations
│ │ │ ├── auth/ # Authentication & user management
│ │ │ ├── dashboard/ # Dashboard data aggregation
│ │ │ ├── expense/ # Expense tracking
│ │ │ ├── product/ # Product inventory
│ │ │ ├── sales/ # Sales recording & analytics
│ │ │ └── user/ # Account management
│ │ ├── routes/ # Central route registry
│ │ ├── services/ # Shared services (email, businessData)
│ │ └── utils/ # Error classes, tokens, logger
│ ├── uploads/avatars/ # User avatar storage
│ ├── vitest.config.js
│ └── package.json
│
├── frontend/
│ ├── src/
│ │ ├── __tests__/ # Frontend tests (4 files, 30 tests)
│ │ ├── api/ # Axios config & API modules
│ │ ├── components/ # Reusable UI components
│ │ │ ├── charts/ # Recharts visualizations
│ │ │ ├── layout/ # Sidebar, Topbar, AppLayout, Footer
│ │ │ └── ui/ # Button, Card, Modal, Table, Input...
│ │ ├── context/ # Language context (i18n)
│ │ ├── hooks/ # React Query hooks
│ │ ├── lib/ # Translations, motion variants
│ │ ├── pages/ # Route pages
│ │ ├── store/ # Zustand stores
│ │ └── utils/ # Helpers (cn, config, format)
│ ├── vite.config.js
│ └── package.json
│
├── plan.md # Improvement plan (Bengali)
├── পরিবর্তনের-সারসংক্ষেপ.md # Change summary (Bengali)
└── README.md

Architecture

The backend follows a modular architecture with clean separation of concerns:

Controller → Service → Repository → Model
  • Controller — Handles HTTP requests/responses
  • Service — Business logic and orchestration
  • Repository — Database queries and data access
  • Model — Mongoose schema definitions

Each module (auth, product, sales, expense, ai, user, dashboard) is self-contained with its own controllers, services, repositories, models, and validation schemas. Cross-module dependencies are handled through shared services (services/businessData.service.js, services/email.service.js).

Authentication Flow

Login → JWT (15min) + Refresh Token (7d)
↓
Both stored as httpOnly cookies (sameSite: strict)
↓
API calls automatically send cookies → authenticateToken middleware reads cookie
↓
On 401 → axios interceptor calls /auth/refresh → new accessToken cookie set

Environment Variables

Backend (backend/.env)

VariableRequiredDefaultDescription
MONGODB_URIYesMongoDB connection string
JWT_ACCESS_SECRETYesAccess token secret
JWT_REFRESH_SECRETYesRefresh token secret
GROQ_API_KEYNoGroq API key (for AI features)
PORTNo5000Server port
NODE_ENVNodevelopmentEnvironment mode
AI_PROVIDERNogroqAI provider
AI_MODELNollama-4-scoutAI model name
AI_WEB_SEARCHNodisabledWeb search support (varies by provider)
CORS_ORIGINNohttp://localhost:5173Frontend origin
SMTP_HOSTNosmtp.gmail.comSMTP server
SMTP_PORTNo587SMTP port
SMTP_USERNoSMTP username
SMTP_PASSNoSMTP password
EMAIL_FROMNonoreply@insightos.appSender email
APP_URLNohttp://localhost:5173Frontend URL for email links

Frontend (frontend/.env)

VariableRequiredDefaultDescription
VITE_API_URLNohttp://localhost:5000Backend API URL
VITE_CURRENCY_CODENoUSDCurrency code (e.g. USD, BDT, EUR)
VITE_CURRENCY_LOCALENoen-USLocale for formatting (e.g. en-US, bn-BD)

Testing

SuiteFilesTestsCommand
Backend (unit)446cd backend && pnpm test
Frontend (unit)430cd frontend && pnpm test
Total876

Backend coverage

  • Utility classes (ApiError, ApiResponse, asyncHandler)
  • JWT token generation & verification
  • Validation middleware (Zod body/query)
  • All Zod schemas (auth, product, sale, expense)

Frontend coverage

  • Zustand auth store state management
  • Currency formatting (configurable locale)
  • Date formatting & relative time
  • Tailwind classname merging (cn utility)

License

This project is licensed under the MIT License.


Built with care for small business owners who deserve better tools.

About

AI-powered business management dashboard inventory, sales, expenses, and intelligent insights in one place.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages