readme.md

This commit is contained in:
Ubuntu 2025-07-28 14:49:18 +05:30
parent fb257a22c3
commit a18fccc427

344
readme.md
View File

@ -1,145 +1,327 @@
# SpurrinAI Backend
A Node.js backend application for SpurrinAI platform.
Welcome to the SpurrinAI Backend! This guide is designed for **beginners** and experienced developers alike. If youre new to backend development, APIs, or deploying web services, dont worry—this README will walk you through everything step by step.
---
## What is SpurrinAI Backend?
**SpurrinAI Backend** is the server-side part of the SpurrinAI platform. Its built with [Node.js](https://nodejs.org/) (JavaScript) and also uses a [Python](https://www.python.org/) service for advanced features like PDF processing and AI-powered Q&A. This backend provides:
- Secure user authentication and management for hospitals, admins, and app users
- Document upload and processing (including PDFs)
- Real-time chat and Q&A (using WebSockets)
- Analytics and feedback collection
- Integration with a Python AI service for smart answers
**Who is this for?**
- Developers who want to run, test, or contribute to SpurrinAI
---
## Table of Contents
- [What is SpurrinAI Backend?](#what-is-spurrinai-backend)
- [Key Concepts & Terms](#key-concepts--terms)
- [Project Structure](#project-structure)
- [Step-by-Step Setup](#step-by-step-setup)
- [Node.js Backend](#nodejs-backend)
- [Python Service (for AI/PDF)](#python-service-for-aipdf)
- [How to Run Everything](#how-to-run-everything)
- [API Overview (What Can You Do?)](#api-overview-what-can-you-do)
- [Authentication & Roles (How Login Works)](#authentication--roles-how-login-works)
- [Controllers, Services, and Middleware (Whats Happening Inside?)](#controllers-services-and-middleware-whats-happening-inside)
- [WebSocket Features (Real-Time Chat)](#websocket-features-real-time-chat)
- [Database Migrations (Updating the Database)](#database-migrations-updating-the-database)
- [Troubleshooting & Tips](#troubleshooting--tips)
- [Learn More](#learn-more)
- [Support](#support)
- [License](#license)
---
## Key Concepts & Terms
- **Backend**: The part of an app that runs on a server, handles data, and talks to databases and other services. Users dont see it directly.
- **API (Application Programming Interface)**: A way for different programs (like your frontend and backend) to talk to each other using HTTP requests (like GET, POST, etc.).
- **Node.js**: A popular way to run JavaScript on the server (not just in the browser).
- **Python**: Another programming language, used here for AI and PDF features.
- **PM2**: A tool that keeps your server running, restarts it if it crashes, and makes it easy to manage multiple services (Node.js and Python).
- **JWT (JSON Web Token)**: A secure way to prove who you are (used for login/authentication).
- **WebSocket**: A technology for real-time, two-way communication (like chat) between your browser and the server.
- **.env file**: A file where you put secret settings (like passwords and API keys) so you dont hard-code them in your code.
---
## Project Structure
Heres what the main folders and files do:
```
project-root/
├── src/
│ ├── app.js # App entry point
│ ├── config/ # Configuration files
│ ├── controllers/ # Route controllers with business logic
│ ├── middleware/ # Custom middleware
│ ├── migrations/ # Database migrations
│ ├── routes/ # Route definitions
│ ├── services/ # Business logic
├── src/ # All the main code
│ ├── app.js # Where the app starts
│ ├── config/ # Settings and configuration
│ ├── controllers/ # Code that handles each API request
│ ├── middleware/ # Code that runs before/after requests (security, auth, etc.)
│ ├── migrations/ # Database update scripts
│ ├── routes/ # Defines all the API endpoints
│ ├── services/ # Business logic and helpers
│ └── utils/ # Utility functions
├── docs/ # Documentation
├── logs/ # Application logs
├── scripts/ # Build and setup scripts
├── tests/ # Test files
└── uploads/ # User uploads
├── docs/ # Extra documentation
├── logs/ # Where logs are saved
├── scripts/ # Helper scripts
├── tests/ # Automated tests
└── uploads/ # Where uploaded files go (PDFs, images)
```
## Prerequisites
---
- Node.js >= 14.0.0
- MySQL >= 5.7
- npm >= 6.0.0
## Step-by-Step Setup
## Installation
### Node.js Backend
1. Clone the repository:
1. **Install Node.js and npm**
- Download from [nodejs.org](https://nodejs.org/)
- Check with:
```bash
git clone git_repository_url
cd spurrinai-backend (or respected folder )
node -v
npm -v
```
- You need Node.js 14+ and npm 6+
2. **Clone the repository**
```bash
git clone <repo_url>
cd spurrinai-backend
```
2. Install dependencies:
3. **Install Node.js dependencies**
```bash
npm install
```
- This downloads all the code libraries the backend needs.
3. Set up environment variables:
4. **Set up your environment variables**
```bash
cp .env.example .env
# Edit .env with your configuration
# Open .env in a text editor and fill in your settings (DB password, etc.)
```
- Never share your .env file publicly!
4. Run the setup script:
5. **Run the setup script**
```bash
npm run setup
```
- This may create database tables or do other first-time setup.
## Development Mode
### Python Service (for AI/PDF)
1. Start the development server with hot-reload:
```bash
npm run dev
```
# Run migrations up
```bash
npm run migrate:up
```
## Production Mode
Some features (like PDF processing and AI Q&A) need a separate Python service. Heres how to set it up:
1. Build the application:
1. **Install Python 3**
- Download from [python.org](https://www.python.org/downloads/)
- Check with:
```bash
npm run build
python3 --version
```
2. Start the production server:
2. **Create a virtual environment** (keeps dependencies isolated)
```bash
npm start
python3 -m venv venv
```
3. For production deployment, ensure:
- Set `NODE_ENV=production` in `.env`
- Configure proper database credentials
- Set up SSL/TLS certificates
- Configure proper logging
- Set up process manager (PM2 recommended)
3. **Activate the virtual environment**
- On Linux/macOS:
```bash
source venv/bin/activate
```
- On Windows:
```bash
venv\Scripts\activate
```
### Using PM2 (Recommended for Production)
4. **Install Python dependencies**
```bash
pip install -r requirements.txt
```
1. Install PM2 globally:
---
## How to Run Everything
### Using PM2 (Recommended for Beginners)
**PM2** is a process manager. It keeps your backend and Python service running, restarts them if they crash, and makes it easy to start/stop everything with simple commands.
1. **Install PM2 globally**
```bash
npm install -g pm2
```
2. Start the application with PM2:
2. **Start the Node.js backend**
```bash
pm2 start src/app.js --name spurrinai-backend
```
3. Other useful PM2 commands:
3. **Start the Python service**
```bash
# Monitor application
pm2 monit
pm2 start chat.py --interpreter venv/bin/python --name=python-file
```
- This tells PM2 to use your Python virtual environment.
# View logs
pm2 logs spurrinai-backend
# Restart application
pm2 restart spurrinai-backend
# Stop application
pm2 stop spurrinai-backend
# Flush logs
pm2 flush
# Delete all logs
pm2 flush spurrinai-backend
# Reload application with zero downtime
pm2 reload spurrinai-backend
4. **Check everything is running**
```bash
pm2 list
pm2 logs
```
## Database Migrations
5. **Other useful PM2 commands**
```bash
pm2 restart <name>
pm2 stop <name>
pm2 delete <name>
pm2 monit
```
**Tip:** If you ever reboot your server, you can run `pm2 resurrect` to bring everything back up, or use `pm2 startup` to make PM2 start on boot.
---
## API Overview (What Can You Do?)
This backend provides many features. Heres a simple summary of what each group of API endpoints does:
### Auth (Login)
- **Login**: `/api/auth/login` — Log in as an admin or hospital user. Youll get a token to use for other requests.
### Super Admins
- Manage the highest-level users (can create hospitals, manage other admins, etc.)
### Hospitals
- Create, update, and manage hospitals and their settings.
- Upload hospital logos, manage users, and more.
### Users (Hospital/Admin)
- Add, edit, or remove users from a hospital.
- Manage user profiles and passwords.
### App Users
- Register and log in as an app user (patients, clients, etc.).
- Upload ID photos, manage chat sessions, and more.
### Documents
- Upload and manage documents (PDFs, images) for hospitals and users.
### PDF Processing
- Send PDFs to the Python service for processing and Q&A extraction.
### Feedback
- Submit and view feedback between users, hospitals, and admins.
### Analytics
- Get reports and statistics about hospitals and users.
### Excel Data
- Upload and process Excel files (admin only).
### Onboarding
- Track and fetch onboarding steps for users.
### Roles
- List all available user roles.
**For a full list of endpoints and what they do, see the API Overview section above.**
---
## Authentication & Roles (How Login Works)
- **JWT-based authentication**: When you log in, you get a special token (JWT) that proves who you are. You must include this token in the `Authorization` header for most requests:
```
Authorization: Bearer <your-token-here>
```
- **Roles**: Different users have different permissions:
- `Spurrinadmin`: Top-level admin
- `Superadmin`: Hospital owner/admin
- `Admin`: Hospital staff
- `Viewer`: Read-only user
- `AppUser`: Regular app user (patient, etc.)
- The backend checks your role before letting you do certain things.
---
## Controllers, Services, and Middleware (Whats Happening Inside?)
- **Controllers**: The main logic for each API endpoint (e.g., login, upload document, etc.)
- **Services**: Helper code for things like talking to the database, generating tokens, or calling the Python AI service.
- **Middleware**: Code that runs before/after your request (checks your token, rate-limits requests, adds security headers, etc.)
**You dont need to change these to use the API, but if you want to contribute or learn, check out the `src/controllers/`, `src/services/`, and `src/middleware/` folders.**
---
## WebSocket Features (Real-Time Chat)
- **WebSocket** lets you have live, two-way chat between the app and the backend (for Q&A, chatbots, etc.).
- The backend runs a WebSocket server on port `40510` (and a secure one on `40520`).
- You need to send your JWT token when connecting.
- Used for real-time Q&A and chat sessions.
---
## Database Migrations (Updating the Database)
If you change the database structure (add tables, etc.), youll use migrations. Heres how:
- **Create a new migration:**
```bash
# Create new migration
npm run migrate:create
# Run all migrations
```
- **Run all migrations:**
```bash
npm run migrate
# Run migrations up
```
- **Run migrations up:**
```bash
npm run migrate:up
# Run migrations down
```
- **Run migrations down:**
```bash
npm run migrate:down
```
---
## Troubleshooting & Tips
- **Port already in use?**
- You might already have something running on the same port. Stop it or change the port in your `.env` file.
- **Missing dependencies?**
- Run `npm install` (Node.js) or `pip install -r requirements.txt` (Python) again.
- **.env file errors?**
- Make sure you copied `.env.example` to `.env` and filled in all the required values.
- **Database connection issues?**
- Check your DB settings in `.env`. Make sure MySQL is running and accessible.
- **Python service not working?**
- Make sure you activated your virtual environment and installed all dependencies.
- Check PM2 logs with `pm2 logs python-file`.
- **Need to reset everything?**
- You can stop all PM2 processes with `pm2 delete all` and start again.
---
## Learn More
- [Node.js Official Docs](https://nodejs.org/en/docs/)
- [Python Official Docs](https://docs.python.org/3/)
- [PM2 Documentation](https://pm2.keymetrics.io/)
- [What is a REST API? (freeCodeCamp)](https://www.freecodecamp.org/news/rest-api-tutorial/)
- [JWT Introduction](https://jwt.io/introduction)
- [WebSocket Introduction (MDN)](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API)
---
## Support
For support, please contact:
- Email: contact@tech4biz.io
- Issue Tracker: GitHub Issues
## License
UNLICENSED - All rights reserved by Tech4biz Solutions
All rights reserved by Tech4biz Solutions