# ERP Backend API

Indian Manufacturing ERP Backend built with Node.js, Express.js, Sequelize ORM, and MySQL.

## Project Structure

```
backend/
├── config/           # Configuration files (database, environment)
├── controllers/      # Route controllers (business logic orchestration)
├── middlewares/      # Express middlewares (auth, error handling, validation)
├── migrations/       # Database migrations
├── models/           # Sequelize models
├── routes/           # API routes
├── services/         # Business logic layer
├── validations/      # Request validation schemas
├── utils/            # Utility functions
├── seeders/          # Database seeders
├── app.js            # Express app configuration
├── server.js         # Server entry point
└── package.json      # Dependencies

```

## Architecture

**MVC Pattern:**
- **Models**: Sequelize models (data layer)
- **Services**: Business logic layer
- **Controllers**: Request/response handling
- **Routes**: API endpoint definitions

**Key Principles:**
- Controllers contain NO business logic
- Services contain ALL business logic
- Models only define schema and relations
- All APIs protected with JWT authentication
- Role-based authorization
- Centralized error handling
- Transaction management using Sequelize

## Setup

1. Install dependencies:
```bash
npm install
```

2. Configure environment variables:
```bash
# Copy the template file
cp env.template .env
# Edit .env with your database credentials
```

**Required Environment Variables:**
- `DB_HOST` - MySQL host (default: localhost)
- `DB_PORT` - MySQL port (default: 3306)
- `DB_NAME` - Database name (default: erp_db)
- `DB_USER` - MySQL username (default: root)
- `DB_PASSWORD` - MySQL password (default: empty)
- `JWT_SECRET` - Secret key for JWT tokens (CHANGE IN PRODUCTION)
- `JWT_REFRESH_SECRET` - Secret key for refresh tokens (CHANGE IN PRODUCTION)

3. Create MySQL database:
```sql
CREATE DATABASE erp_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```

4. Run migrations:
```bash
npm run migrate
```

5. Start development server:
```bash
npm run dev
```

## Database Migrations

All 37 master tables have been migrated:

**Base Masters (6):**
- Country, State, City
- Currency, CurrencyRate
- UOM, UOMConversion
- Bank

**Organization (3):**
- Company
- Plant
- GSTIN

**Authorization (5):**
- User
- Role, Permission
- UserRole, RolePermission

**HR (3):**
- Employee
- Department, Designation

**Finance (4):**
- GLAccount
- CostCenter
- FiscalYear, FiscalPeriod

**Compliance (2):**
- TaxMaster
- TDSMaster

**Material (3):**
- Material
- MaterialPlant
- MaterialValuation

**Business Partner (4):**
- BusinessPartner
- BPAddress
- BPBank
- BPGSTIN

**Production (5):**
- BOMHeader, BOMComponent
- Routing, RoutingOperation
- WorkCenter

## API Structure

All APIs follow the pattern: `/api/v1/{resource}`

**Authentication:**
- All endpoints require JWT token (except login)
- Token format: `Authorization: Bearer {token}`

**Response Format:**
```json
{
  "success": true,
  "message": "Success message",
  "data": {},
  "meta": {}
}
```

## Environment Variables

See `.env.example` for required environment variables.

## Migration Commands

```bash
# Run all pending migrations
npm run migrate

# Undo last migration
npm run migrate:undo

# Undo all migrations
npm run migrate:undo:all
```

## Notes

- All tables use underscored naming (snake_case)
- Timestamps are automatically managed (created_at, updated_at)
- Soft deletes implemented via status fields
- Effective dating supported where applicable
- Multi-company, multi-plant, multi-GSTIN architecture

