Spaces:
Running
Running
File size: 15,887 Bytes
77db408 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | # Manufacturing ERP Intelligence Platform - User Guide
## Overview
This web application is a Manufacturing ERP intelligence platform that provides analytics for inventory management, revenue tracking, and service/freight analysis. It integrates data from Visma (an ERP system) and presents it through an interactive dashboard.
### Key Features
- **Inventory Analytics**: Stock valuation, dead stock identification, capital lock-up analysis
- **Revenue Analytics**: Margin calculations, trend analysis, product rankings
- **Service & Freight Analytics**: Service revenue breakdown, freight geography analysis
- **Multi-currency Support**: Switch between SEK, EUR, and USD using the currency buttons in the top-right header. Rates are fetched live from open.er-api.com once per day and cached. If the live fetch fails, hardcoded fallback rates are used automatically
- **BOM Cost Export**: Download cost breakdown CSVs from the Inventory page (list mode) or any item's detail drawer (tree mode)
- **Real-time Data Import**: Import data from Visma CSV files
## System Architecture
### Backend (FastAPI)
- Python FastAPI server with SQLite database
- Imports data from Visma CSV files (articles, BOM, customers, invoices)
- Provides REST API endpoints for frontend consumption
### Frontend (Next.js)
- React-based dashboard with interactive charts and tables
- Three main views: Inventory, Revenue, Service & Freight
- Currency toggle for multi-currency support
## Getting Started
### Prerequisites
- Python 3.x with virtual environment
- Node.js 18+ and npm
### Quick Start (Recommended β Docker)
The easiest way to start both services is via Docker Compose from the project root:
```bash
docker compose up --build
# or with the PowerShell helper:
.\run.ps1 dev
```
This single command will:
- Build and start the **FastAPI backend** at `http://localhost:8000` with hot-reload (restarts on `.py` file changes)
- Build and start the **Next.js frontend** at `http://localhost:3000` with hot-reload (updates in browser on `.tsx` file changes)
- Gate frontend startup on the backend health check passing (`GET /health`)
> **Note:** Uses `docker-compose.override.yml` which Docker auto-merges in dev mode. For a production-equivalent local run: `docker compose -f docker-compose.yml up --build`
### Quick Start (Alternative β Local, no Docker)
```bash
node run-dev.js
```
This single command will:
- Start the **FastAPI backend** at `http://127.0.0.1:8000` (uses `.venv\Scripts\python.exe` on Windows)
- Start the **Next.js frontend** at `http://localhost:3000`
- Handle graceful shutdown of both servers on `Ctrl+C`
> **Note:** The script auto-detects the OS and uses the appropriate commands for Windows (`npm.cmd`, `.venv\Scripts\python.exe`) or Linux/macOS (`npm`, `python`).
### Manual Start (Step by Step)
#### Starting the Backend
1. Navigate to the backend directory:
```bash
cd backend
```
2. Activate the virtual environment (if using one):
```bash
# Windows
.venv\Scripts\activate
```
3. Install dependencies:
```bash
pip install -r requirements.txt
```
4. Start the FastAPI server:
```bash
uvicorn main:app --reload
```
The backend will be available at: `http://127.0.0.1:8000`
#### Starting the Frontend
1. Navigate to the frontend directory:
```bash
cd frontend
```
2. Install dependencies:
```bash
npm install
```
3. Start the development server:
```bash
npm run dev
```
The frontend will be available at: `http://localhost:3000`
### OneDrive Environment - Known Issue
When the project is located inside a OneDrive-synced folder (paths containing special characters like `&`), `npm install` may fail with:
```
Error: Cannot find module 'C:\Users\...\OneDrive\napi-postinstall\lib\cli.js'
```
**Cause:** The default `cmd.exe` shell used by npm to run postinstall scripts cannot resolve paths correctly within OneDrive directories that contain special characters.
**Fix:** The file `frontend/.npmrc` is already configured to use PowerShell instead:
```ini
script-shell=C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe
```
If `npm install` still fails after a fresh clone, ensure this `.npmrc` file exists in the `frontend/` directory. If it was deleted or not tracked by Git, recreate it with the content above.
**If the problem persists:**
1. Delete `node_modules` and `package-lock.json`:
```powershell
Remove-Item -Recurse -Force frontend\node_modules
Remove-Item -Force frontend\package-lock.json
```
2. Reinstall:
```powershell
cd frontend
npm install
```
## Data Import
### Importing Visma Data
The system can import data from Visma CSV files through the API endpoints. You can use the following endpoints:
#### Import Articles, BOM, and Customers
```bash
POST /api/import/visma
```
Parameters:
- `author`: Name of the person performing the import
- `articles_file`: CSV file with article master data
- `bom_file`: CSV file with Bill of Materials data
- `customers_file`: CSV file with customer data
#### Import Invoices
```bash
POST /api/import/invoices
```
Parameters:
- `author`: Name of the person performing the import
- `headers_file`: CSV file with invoice headers
- `lines_file`: CSV file with invoice lines
### CSV File Requirements
#### Articles CSV
Required headers: `SKU`, `Name`, `Stock_Qty`, `Standard_Price`, `Last_Purchase_Price`, `Min_Order_Qty`
#### BOM CSV
Required headers: `Parent_SKU`, `Child_SKU`, `Qty_Used`
#### Customers CSV
Required headers: `Customer_ID`, `Name`, `Country`, `Currency_Code`
#### Invoice Headers CSV
Required headers: `Invoice_Number`, `Invoice_Date`, `Customer_ID`, `Total_Excl_VAT_FX`, `Currency_Code`
#### Invoice Lines CSV
Required headers: `Invoice_Number`, `SKU`, `Qty_Delivered`, `Revenue_SEK_Final`
## Dashboard Navigation
### Main Views
The dashboard has three main views accessible via the tabs at the top:
#### 1. Inventory View
- **Stock Value**: Total inventory valuation in selected currency
- **Dead Stock Value**: Value of items with no sales in >12 months
- **Zero Cost SKUs**: Active items with missing cost data
- **Negative Disposable**: Items where backorders exceed on-hand stock
- **Stock Composition**: Pie chart showing inventory value by article group
- **Stock Viability**: Pie chart showing active vs dead stock
- **Capital Lock-up**: Table of high-value items with no recent sales
- **Expensive BOMs**: List of most costly assembly structures
#### 2. Revenue View
- **Product Revenue**: Total revenue from product sales
- **Margin Metrics**: Three margin calculations (Visma snapshot, FIFO/LPP, Average)
- **Revenue Trend**: Monthly revenue and margin chart
- **Performance Rankings**: Top/bottom performers by margin
- **Margin Comparison**: Detailed margin analysis for top products
#### 3. Service & Freight View
- **Invoiced Freight**: Freight charged to customers on invoices (accounts 3520β3590, incl. header-level freight). Shown beside Net Sales, never inside it.
- **Freight Cost (GL 57xx)**: What carriers and customs charge us, from the ledger (5700/5710/5720, available from 2026; "β" under customer/project filters).
- **Net Freight Result**: Invoiced freight β freight cost.
- **Service Revenue**: Revenue from labor and installation services
- **Freight Gap**: Reconciled difference between invoice totals
- **Service Category Breakdown**: Revenue by service type and month
- **Freight Geography**: Distribution of invoiced freight by region
### Currency Switcher
The **SEK / EUR / USD** button group is located in the top-right of the global header bar and is visible on all pages.
- Clicking a currency button immediately converts all displayed financial values on the current page.
- Your selection is saved in the browser and restored on your next visit.
- Exchange rates are fetched automatically from the internet when you open the application. If the rate fetch succeeds, values reflect the day's live rates. If it fails (no network, API down), the system falls back silently to built-in approximate rates.
- The rates do not update mid-session; reload the page to pick up a fresh rate if needed.
- To inspect the current rates or diagnose conversion issues, call `GET /api/exchange-rates` directly β the `source` field will show `"cache"`, `"live"`, or `"fallback"`.
### Export Costs (BOM Cost CSV)
**From the Inventory & BOMs page:** An **Export Costs** button appears above the item list. Clicking it downloads a CSV of cost data for all items currently visible (respecting the active view tab, search, category filter, and Clean View toggle).
**From an item's detail drawer:** Open any item by clicking it in the inventory list. The detail drawer contains an **Export BOM Costs** button that downloads a tree-structured CSV showing the full BOM cost breakdown for that item, with parent/child relationships and path columns.
The exported CSV uses semicolon (`;`) as delimiter and includes columns: `Level`, `Parent_SKU`, `SKU`, `Name`, `Type`, `Category`, `Qty`, `Estimated_Total_Cost`, `Line_Cost`, `Cost_Source`, `Path`. See [`docs/data_schemas.md`](data_schemas.md) for the full column reference.
### Modal Windows
The following modals are accessible from the Inventory & BOMs page:
| Modal | How to open | Purpose |
| :--- | :--- | :--- |
| **Create Item** | "New Item" button (top of inventory list) | Add a new article manually |
| **Stock Movement** | "Record Movement" action on an item | Log a stock in/out event with quantity and cost |
| **Item Detail Drawer** | Click any item row | View full item details, BOM tree, cost breakdown, and export |
| **Visma Import** | "Import Visma" button | Upload Articles, BOM, and Customers CSVs |
| **Invoice Import** | "Import Invoices" button | Upload Invoice Headers and Lines CSVs |
### Data Refresh
The dashboard data is fetched from the backend API. To refresh the data:
1. Reload the page
2. The system will fetch the latest analytics from the backend
## Key Metrics Explained
### Inventory Metrics
- **Stock Value (SEK)**: Total inventory value at current stock valuation
- **Dead Stock**: Items with no sales movement in >12 months
- **Zero Cost Articles**: Items missing cost data (kalkylpris)
- **Negative Disposable**: Stock shortages (reserved >available)
### Revenue Metrics
- **Visma Snapshot Margin**: Margin as recorded in Visma at invoice time
- **Replacement Margin (LPP)**: Margin using current Last Purchase Price
- **Margin %**: Profitability percentage
- **Product Invoice Count**: Number of invoices containing product lines
### Service & Freight Metrics
- **Invoiced Freight**: Shipping and handling charged to customers (not part of Net Sales)
- **Freight Cost / Net Freight Result**: Carrier cost from the ledger (GL 57xx) and invoiced β cost
- **Service Revenue**: Revenue from installation, labor, and other services
- **Freight Gap**: Difference between total invoice amount and gross goods value
## Troubleshooting
### Common Issues
#### Backend Connection Error
- Ensure the backend is running on `http://127.0.0.1:8000`
- Check CORS configuration in the backend
- Verify no firewall is blocking the connection
#### `npm install` Fails on OneDrive Paths
- See the [OneDrive Environment - Known Issue](#onedrive-environment---known-issue) section above
- Ensure `frontend/.npmrc` exists with `script-shell` pointing to PowerShell
- As a last resort, use `npm install --ignore-scripts` followed by `npm rebuild`
#### Import Errors
- Verify CSV file headers match required format
- Check for duplicate file uploads (system prevents duplicates)
- Ensure CSV files use semicolon (`;`) as delimiter
#### Currency Conversion Issues
- Rates are fetched live from open.er-api.com on app load and cached for the day.
- If rates appear incorrect, reload the page to trigger a fresh fetch.
- Hardcoded fallback rates (`EUR β 0.088, USD β 0.095`) are used automatically if the internet fetch fails β no user action required.
- The rate source can be inspected by calling `GET /api/exchange-rates` directly; the `source` field will be `"cache"`, `"live"`, or `"fallback"`.
#### Data Not Updating
- Clear browser cache and reload
- Check backend logs for errors
- Verify data was successfully imported
## API Endpoints
### Inventory Endpoints
- `GET /api/items` - Retrieve items with pagination
- `GET /api/items/{item_id}` - Get specific item details
- `POST /api/items` - Create new item
- `PUT /api/items/{item_id}` - Update item
- `POST /api/items/{item_id}/movement` - Record stock movement
### Analytics Endpoints
- `GET /api/dashboard/analytics` - Get all dashboard analytics
- `GET /api/events` - Get system activity log
### Import Endpoints
- `POST /api/import/visma` - Import Visma data (articles, BOM, customers)
- `POST /api/import/invoices` - Import invoice data
### Export Endpoints
- `GET /api/export/analytics/bom-costs` - BOM cost CSV (list or tree mode)
- `GET /api/export/analytics/revenue` - Revenue rankings CSV
- `GET /api/export/analytics/inventory` - Capital lock-up CSV
- `GET /api/export/analytics/customers` - Customer revenue CSV
### Utility Endpoints
- `GET /api/exchange-rates` - Current SEK-based exchange rates (cached daily)
## Development Notes
### Project Structure
```
001 - Gateway ERP/
βββ docker-compose.yml # Production compose (no hot-reload)
βββ docker-compose.override.yml # Dev overlay β auto-merged by Docker Compose
βββ run.ps1 # PowerShell helper (up / dev / down / clean)
βββ run-dev.js # Local launcher without Docker (backend + frontend)
βββ backend/
β βββ main.py # FastAPI app β mounts all routers + /health endpoint
β βββ models.py # SQLAlchemy models (includes ExchangeRateCache)
β βββ schemas.py # Pydantic schemas (ItemSchema with snapshot_cost/variance)
β βββ crud.py # CRUD operations and BOM cost enrichment
β βββ database.py # DB connection
β βββ helpers.py # Shared utilities
β βββ routers/ # Modular endpoint groups (items, imports, dashboard, exports, exchange_rates, analysis, customers)
β βββ requirements.txt # Python dependencies (incl. watchfiles for fast reload)
β βββ data/
β βββ inventory.db # SQLite file (in Docker: /app/data/inventory.db on named volume)
βββ frontend/
β βββ .npmrc # npm config (PowerShell script-shell fix for OneDrive paths)
β βββ package.json # Node.js dependencies
β βββ src/
β βββ app/ # Next.js pages (page.tsx, layout.tsx, ClientLayout.tsx, items/, customers/, analysis/)
β βββ components/ # UI components (analytics/, items/, AlertBar, ConfirmDialog, GlobalCurrencySwitcher, Toast, ErrorBoundary, ExecutiveSummary, ...)
β βββ contexts/ # React contexts (CurrencyContext, HeaderSlotContext, UserContext)
β βββ hooks/ # Custom hooks (useCurrencyConversion, useDatePicker)
β βββ lib/ # API base URL (api.ts)
β βββ utils/ # Formatters (CCY_RATES, fmtMoney, fmtNum, GROUP_COLORS)
βββ docs/ # Technical documentation
βββ etl/ # ETL pipeline scripts for Visma data extraction
```
### Data Flow
1. CSV files from Visma are imported via API endpoints
2. Data is stored in SQLite database
3. Frontend fetches analytics via `/api/dashboard/analytics`
4. Dashboard renders interactive charts and tables
## Support and Feedback
For issues or feature requests, please check the system documentation or contact the development team.
---
*This guide reflects the feature set as of commit b8b0ddc (2026-04).* |