327 lines
11 KiB
Markdown
327 lines
11 KiB
Markdown
# SpurrinAI Backend
|
||
|
||
Welcome to the SpurrinAI Backend! This guide is designed for **beginners** and experienced developers alike. If you’re new to backend development, APIs, or deploying web services, don’t 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. It’s 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 (What’s 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 don’t 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 don’t hard-code them in your code.
|
||
|
||
---
|
||
|
||
## Project Structure
|
||
|
||
Here’s what the main folders and files do:
|
||
```
|
||
project-root/
|
||
├── 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/ # Extra documentation
|
||
├── logs/ # Where logs are saved
|
||
├── scripts/ # Helper scripts
|
||
├── tests/ # Automated tests
|
||
└── uploads/ # Where uploaded files go (PDFs, images)
|
||
```
|
||
|
||
---
|
||
|
||
## Step-by-Step Setup
|
||
|
||
### Node.js Backend
|
||
|
||
1. **Install Node.js and npm**
|
||
- Download from [nodejs.org](https://nodejs.org/)
|
||
- Check with:
|
||
```bash
|
||
node -v
|
||
npm -v
|
||
```
|
||
- You need Node.js 14+ and npm 6+
|
||
|
||
2. **Clone the repository**
|
||
```bash
|
||
git clone <repo_url>
|
||
cd spurrinai-backend
|
||
```
|
||
|
||
3. **Install Node.js dependencies**
|
||
```bash
|
||
npm install
|
||
```
|
||
- This downloads all the code libraries the backend needs.
|
||
|
||
4. **Set up your environment variables**
|
||
```bash
|
||
cp .env.example .env
|
||
# Open .env in a text editor and fill in your settings (DB password, etc.)
|
||
```
|
||
- Never share your .env file publicly!
|
||
|
||
5. **Run the setup script**
|
||
```bash
|
||
npm run setup
|
||
```
|
||
- This may create database tables or do other first-time setup.
|
||
|
||
### Python Service (for AI/PDF)
|
||
|
||
Some features (like PDF processing and AI Q&A) need a separate Python service. Here’s how to set it up:
|
||
|
||
1. **Install Python 3**
|
||
- Download from [python.org](https://www.python.org/downloads/)
|
||
- Check with:
|
||
```bash
|
||
python3 --version
|
||
```
|
||
|
||
2. **Create a virtual environment** (keeps dependencies isolated)
|
||
```bash
|
||
python3 -m venv venv
|
||
```
|
||
|
||
3. **Activate the virtual environment**
|
||
- On Linux/macOS:
|
||
```bash
|
||
source venv/bin/activate
|
||
```
|
||
- On Windows:
|
||
```bash
|
||
venv\Scripts\activate
|
||
```
|
||
|
||
4. **Install Python dependencies**
|
||
```bash
|
||
pip install -r requirements.txt
|
||
```
|
||
|
||
---
|
||
|
||
## 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 Node.js backend**
|
||
```bash
|
||
pm2 start src/app.js --name spurrinai-backend
|
||
```
|
||
|
||
3. **Start the Python service**
|
||
```bash
|
||
pm2 start chat.py --interpreter venv/bin/python --name=python-file
|
||
```
|
||
- This tells PM2 to use your Python virtual environment.
|
||
|
||
4. **Check everything is running**
|
||
```bash
|
||
pm2 list
|
||
pm2 logs
|
||
```
|
||
|
||
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. Here’s 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. You’ll 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 (What’s 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 don’t 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.), you’ll use migrations. Here’s how:
|
||
|
||
- **Create a new migration:**
|
||
```bash
|
||
npm run migrate:create
|
||
```
|
||
- **Run all migrations:**
|
||
```bash
|
||
npm run migrate
|
||
```
|
||
- **Run migrations up:**
|
||
```bash
|
||
npm run migrate:up
|
||
```
|
||
- **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
|
||
All rights reserved by Tech4biz Solutions |