feat: FASE 7 - Polish & Testing (security, i18n, test suite, docs)

Security hardening: CORS lockdown, rate limiting middleware con sliding
window e eviction IP stale, security headers (CSP, HSTS, X-Frame-Options),
session cookie hardening, filename sanitization upload.

i18n completion: internazionalizzati barcode.js e csv-export.js con bridge
window.BARCODE_I18N/CSV_I18N, aggiornati .po IT/EN con 27 nuove stringhe.

Tablet UX: touch target 44px per dispositivi coarse pointer.

Test suite: 101 test totali (76 server + 25 client), copertura completa
di tutti i router API, autenticazione, ruoli, CRUD, SPC, file upload,
security integration. Infrastruttura SQLite async in-memory con fixtures.

Fix critici: MissingGreenlet in recipe_service (selectinload eager),
route ordering tasks.py, auth_service bcrypt diretto, Measurement.id
Integer per SQLite.

Documentazione: API.md (riferimento completo 40+ endpoint),
DEPLOYMENT.md (guida produzione con Docker/Nginx/SSL),
USER_GUIDE.md (manuale utente per ruolo).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Adriano
2026-02-07 17:10:24 +01:00
parent 26e5b9343d
commit dd2ebf863a
46 changed files with 6322 additions and 90 deletions
+1455
View File
File diff suppressed because it is too large Load Diff
+819
View File
@@ -0,0 +1,819 @@
# TieMeasureFlow Deployment Guide
This guide covers deploying TieMeasureFlow in development, staging, and production environments.
## Table of Contents
1. [Prerequisites](#prerequisites)
2. [Environment Setup](#environment-setup)
3. [Database Setup](#database-setup)
4. [Server Deployment](#server-deployment)
5. [Client Deployment](#client-deployment)
6. [Production Deployment](#production-deployment)
7. [Docker Deployment](#docker-deployment)
8. [SSL/HTTPS](#ssltls)
9. [Backup Strategy](#backup-strategy)
10. [Troubleshooting](#troubleshooting)
## Prerequisites
### System Requirements
- **OS**: Linux, macOS, or Windows
- **Python**: 3.11 or higher
- **MySQL**: 8.0 or higher
- **Node.js**: 16+ (optional, for Tailwind CSS compilation)
- **Disk Space**: 500 MB minimum
- **RAM**: 2 GB minimum
### Software Installation
#### Linux/macOS
```bash
# Python 3.11+
python3 --version
# MySQL 8.0
mysql --version
# Node.js (optional)
node --version
npm --version
```
#### Windows
Download and install:
- [Python 3.11+](https://www.python.org/downloads/)
- [MySQL Community Server](https://dev.mysql.com/downloads/mysql/)
- [Node.js](https://nodejs.org/) (optional)
---
## Environment Setup
### 1. Clone Repository
```bash
git clone <repository-url>
cd TieMeasureFlow
```
### 2. Create .env File
Copy the example and customize for your environment:
```bash
cp .env.example .env
```
### 3. Configure .env
Edit `.env` with your settings:
```env
# =====================================================================
# DATABASE
# =====================================================================
DB_HOST=localhost
DB_PORT=3306
DB_NAME=tiemeasureflow
DB_USER=tmflow
DB_PASSWORD=change_me_in_production
# =====================================================================
# SERVER (FastAPI)
# =====================================================================
SERVER_HOST=0.0.0.0
SERVER_PORT=8000
SERVER_SECRET_KEY=change-this-to-a-random-secret-key-with-32-chars
# =====================================================================
# CLIENT (Flask)
# =====================================================================
CLIENT_HOST=0.0.0.0
CLIENT_PORT=5000
# =====================================================================
# CORS
# =====================================================================
SERVER_CORS_ORIGINS=http://localhost:5000,http://127.0.0.1:5000
# =====================================================================
# FILE UPLOAD
# =====================================================================
UPLOAD_DIR=uploads
MAX_UPLOAD_SIZE_MB=50
# =====================================================================
# RATE LIMITING
# =====================================================================
RATE_LIMIT_LOGIN=5
RATE_LIMIT_GENERAL=100
# =====================================================================
# SSL/HTTPS (Production only)
# =====================================================================
SSL_CERTFILE=
SSL_KEYFILE=
```
### Environment Variables Reference
| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| `DB_HOST` | string | localhost | MySQL server hostname |
| `DB_PORT` | int | 3306 | MySQL server port |
| `DB_NAME` | string | tiemeasureflow | Database name |
| `DB_USER` | string | tmflow | Database user |
| `DB_PASSWORD` | string | change_me_in_production | Database password **[CHANGE IN PROD]** |
| `SERVER_HOST` | string | 0.0.0.0 | API server bind address |
| `SERVER_PORT` | int | 8000 | API server port |
| `SERVER_SECRET_KEY` | string | change-this-to... | Secret key for sessions **[CHANGE IN PROD]** |
| `CLIENT_HOST` | string | 0.0.0.0 | Flask client bind address |
| `CLIENT_PORT` | int | 5000 | Flask client port |
| `SERVER_CORS_ORIGINS` | string | http://localhost:5000 | Comma-separated CORS origins |
| `UPLOAD_DIR` | string | uploads | Directory for file uploads |
| `MAX_UPLOAD_SIZE_MB` | int | 50 | Maximum upload file size in MB |
| `RATE_LIMIT_LOGIN` | int | 5 | Login requests per minute |
| `RATE_LIMIT_GENERAL` | int | 100 | General requests per minute |
| `SSL_CERTFILE` | string | (empty) | Path to SSL certificate (production) |
| `SSL_KEYFILE` | string | (empty) | Path to SSL private key (production) |
---
## Database Setup
### 1. Create MySQL Database and User
```bash
mysql -u root -p
```
```sql
-- Create database
CREATE DATABASE tiemeasureflow CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Create user
CREATE USER 'tmflow'@'localhost' IDENTIFIED BY 'secure_password_here';
-- Grant permissions
GRANT ALL PRIVILEGES ON tiemeasureflow.* TO 'tmflow'@'localhost';
FLUSH PRIVILEGES;
-- Exit
EXIT;
```
### 2. Run Database Migrations
```bash
cd server
pip install -r requirements.txt
alembic upgrade head
```
This creates all required tables:
- `users` - System users
- `recipes` - Measurement recipes
- `recipe_versions` - Immutable recipe versions
- `recipe_tasks` - Tasks within recipes
- `recipe_subtasks` - Subtasks within tasks (individual measurements)
- `measurements` - Recorded measurements
- `access_logs` - API access audit trail
- `system_settings` - Configuration key-value pairs
- `recipe_version_audit` - Recipe change history
### 3. Create Initial Admin User (Optional)
Use the Flask client to create the first admin user, or run:
```bash
cd server
python -c "
from database import init_db, SessionLocal
from services.auth_service import create_user
import asyncio
async def init():
await init_db()
async with SessionLocal() as db:
await create_user(
db,
username='admin',
password='change_me_first_login',
display_name='Admin',
email='admin@example.com',
roles=['Maker', 'MeasurementTec', 'Metrologist'],
is_admin=True
)
await db.commit()
print('Admin user created: admin / change_me_first_login')
asyncio.run(init())
"
```
---
## Server Deployment
### Development Server
```bash
cd server
pip install -r requirements.txt
uvicorn main:app --reload --host 0.0.0.0 --port 8000
```
Runs at `http://0.0.0.0:8000`
API Documentation:
- Swagger UI: `http://localhost:8000/docs`
- ReDoc: `http://localhost:8000/redoc`
### Production Server (Gunicorn + Uvicorn)
Install Gunicorn:
```bash
pip install gunicorn
```
Start server:
```bash
cd server
gunicorn main:app \
--workers 4 \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8000 \
--access-logfile /var/log/tiemeasureflow/access.log \
--error-logfile /var/log/tiemeasureflow/error.log \
--log-level info
```
### Production Server (Waitress - Windows)
Install Waitress:
```bash
pip install waitress
```
Start server:
```bash
cd server
waitress-serve --host=0.0.0.0 --port=8000 main:app
```
### systemd Service (Linux)
Create `/etc/systemd/system/tiemeasureflow-api.service`:
```ini
[Unit]
Description=TieMeasureFlow API Server
After=network.target mysql.service
[Service]
Type=notify
User=tiemeasureflow
WorkingDirectory=/opt/tiemeasureflow/server
Environment="PATH=/opt/tiemeasureflow/venv/bin"
ExecStart=/opt/tiemeasureflow/venv/bin/gunicorn main:app \
--workers 4 \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8000
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.target
```
Enable and start:
```bash
sudo systemctl daemon-reload
sudo systemctl enable tiemeasureflow-api.service
sudo systemctl start tiemeasureflow-api.service
sudo systemctl status tiemeasureflow-api.service
```
View logs:
```bash
sudo journalctl -u tiemeasureflow-api -f
```
---
## Client Deployment
### Development Server
```bash
cd client
pip install -r requirements.txt
flask run --host 0.0.0.0 --port 5000
```
Runs at `http://0.0.0.0:5000`
### Compile Tailwind CSS (Optional)
```bash
cd client
npx tailwindcss -i static/css/input.css -o static/css/tailwind.css --watch
```
### Production Server (Gunicorn)
```bash
pip install gunicorn
cd client
gunicorn --workers 4 --bind 0.0.0.0:5000 app:app
```
### systemd Service (Linux)
Create `/etc/systemd/system/tiemeasureflow-web.service`:
```ini
[Unit]
Description=TieMeasureFlow Web Client
After=network.target tiemeasureflow-api.service
[Service]
Type=notify
User=tiemeasureflow
WorkingDirectory=/opt/tiemeasureflow/client
Environment="PATH=/opt/tiemeasureflow/venv/bin"
Environment="FLASK_ENV=production"
ExecStart=/opt/tiemeasureflow/venv/bin/gunicorn \
--workers 4 \
--bind 0.0.0.0:5000 \
app:app
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.target
```
---
## Production Deployment
### Security Checklist
- [ ] Change all default passwords in `.env`
- [ ] Generate random `SERVER_SECRET_KEY` (32+ characters)
- [ ] Set CORS origins to actual client domains
- [ ] Enable SSL/HTTPS (see SSL/TLS section)
- [ ] Configure firewall rules
- [ ] Set up regular database backups
- [ ] Configure log rotation
- [ ] Use strong database credentials
- [ ] Restrict file upload sizes
- [ ] Keep dependencies updated
### Recommended Architecture
```
┌─────────────────┐
│ Nginx Proxy │ (Port 80/443)
└────────┬────────┘
┌────┴────┐
│ │
┌───▼──┐ ┌───▼──┐
│API │ │Web │
│:8000 │ │:5000 │
└──────┘ └──────┘
│ │
└────┬─────┘
┌────▼────┐
│ MySQL │
│ :3306 │
└─────────┘
```
### Nginx Configuration
Create `/etc/nginx/sites-available/tiemeasureflow`:
```nginx
upstream tiemeasureflow_api {
server 127.0.0.1:8000;
}
upstream tiemeasureflow_web {
server 127.0.0.1:5000;
}
server {
listen 80;
server_name yourdomain.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com;
ssl_certificate /etc/ssl/certs/yourdomain.com.crt;
ssl_certificate_key /etc/ssl/private/yourdomain.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
client_max_body_size 50M;
# API
location /api/ {
proxy_pass http://tiemeasureflow_api;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Web Client
location / {
proxy_pass http://tiemeasureflow_web;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Static files (optional caching)
location /static/ {
proxy_pass http://tiemeasureflow_web;
expires 1d;
add_header Cache-Control "public, immutable";
}
}
```
Enable and test:
```bash
sudo ln -s /etc/nginx/sites-available/tiemeasureflow /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```
---
## Docker Deployment
### Docker Compose (Complete Stack)
The project includes a `docker-compose.yml` for easy deployment:
```bash
# Build images
docker-compose build
# Start services
docker-compose up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down
```
### Manual Docker Build
#### API Server
```dockerfile
FROM python:3.11-slim
WORKDIR /app/server
COPY server/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY server/ .
COPY .env ..
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
```
Build and run:
```bash
docker build -f server/Dockerfile -t tiemeasureflow-api .
docker run -p 8000:8000 --env-file .env tiemeasureflow-api
```
#### Web Client
```dockerfile
FROM python:3.11-slim
WORKDIR /app/client
COPY client/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY client/ .
COPY .env ..
EXPOSE 5000
CMD ["gunicorn", "--workers", "4", "--bind", "0.0.0.0:5000", "app:app"]
```
Build and run:
```bash
docker build -f client/Dockerfile -t tiemeasureflow-web .
docker run -p 5000:5000 --env-file .env tiemeasureflow-web
```
---
## SSL/TLS
### Self-Signed Certificate (Development)
```bash
openssl req -x509 -newkey rsa:4096 -keyout server.key -out server.crt -days 365 -nodes
```
### Let's Encrypt (Production)
```bash
sudo apt install certbot python3-certbot-nginx
sudo certbot certonly --nginx -d yourdomain.com
```
### Configure in .env
```env
SSL_CERTFILE=/etc/ssl/certs/yourdomain.com.crt
SSL_KEYFILE=/etc/ssl/private/yourdomain.com.key
```
### Start Server with SSL
```bash
cd server
gunicorn main:app \
--workers 4 \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8443 \
--certfile /etc/ssl/certs/yourdomain.com.crt \
--keyfile /etc/ssl/private/yourdomain.com.key
```
---
## Backup Strategy
### Daily Database Backups
Create backup script `/opt/tiemeasureflow/backup.sh`:
```bash
#!/bin/bash
BACKUP_DIR="/opt/tiemeasureflow/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
DB_NAME="tiemeasureflow"
DB_USER="tmflow"
mkdir -p $BACKUP_DIR
# MySQL dump
mysqldump -u $DB_USER -p$MYSQL_PASSWORD $DB_NAME \
| gzip > $BACKUP_DIR/db_$TIMESTAMP.sql.gz
# Keep only last 30 days
find $BACKUP_DIR -name "db_*.sql.gz" -mtime +30 -delete
# Upload to S3 (optional)
# aws s3 cp $BACKUP_DIR/db_$TIMESTAMP.sql.gz s3://your-bucket/backups/
echo "Backup completed: $BACKUP_DIR/db_$TIMESTAMP.sql.gz"
```
Schedule with crontab:
```bash
crontab -e
```
Add line:
```cron
0 2 * * * /opt/tiemeasureflow/backup.sh >> /var/log/tiemeasureflow/backup.log 2>&1
```
### Restore from Backup
```bash
# Decompress
gunzip < backups/db_20250207_020000.sql.gz | \
mysql -u tmflow -p tiemeasureflow
```
---
## Troubleshooting
### Database Connection Failed
```
sqlalchemy.exc.OperationalError: (asyncmy.errors.ProgrammingError) (2003, "Can't connect to MySQL server...")
```
**Check:**
```bash
# Verify MySQL is running
mysql -u tmflow -p -e "SELECT 1"
# Check .env variables
grep DB_ .env
# Test connection string
cd server && python -c "from config import settings; print(settings.database_url)"
```
### Port Already in Use
```
OSError: [Errno 48] Address already in use
```
**Solution:**
```bash
# Find process on port 8000
lsof -i :8000
kill -9 <PID>
# Or use different port
uvicorn main:app --port 8001
```
### Import Errors
```
ModuleNotFoundError: No module named 'fastapi'
```
**Solution:**
```bash
cd server
pip install -r requirements.txt
```
### File Upload Not Working
```
/app/server/uploads: Permission denied
```
**Solution:**
```bash
# Create uploads directory with correct permissions
mkdir -p server/uploads
chmod 755 server/uploads
```
### Migrations Failed
```
alembic.util.exc.CommandError: Can't locate revision identified by...
```
**Solution:**
```bash
cd server
# Check migration status
alembic current
# Reset migrations (CAUTION - deletes data)
alembic downgrade base
alembic upgrade head
```
### API Key Not Working
```
detail: "Invalid API key"
```
**Solution:**
```bash
# Regenerate API key for user (admin endpoint)
curl -X POST http://localhost:8000/api/users/1/regenerate-key \
-H "X-API-Key: admin_token"
```
---
## Performance Tuning
### MySQL
Edit `/etc/mysql/mysql.conf.d/mysqld.cnf`:
```ini
[mysqld]
# Connection pool
max_connections = 100
# Buffer sizes
innodb_buffer_pool_size = 256M
innodb_log_file_size = 100M
# Query optimization
query_cache_size = 0
query_cache_type = 0
# Logging
slow_query_log = 1
long_query_time = 2
```
Restart:
```bash
sudo systemctl restart mysql
```
### Application Workers
Increase Gunicorn workers (rule: 2 * CPU_cores + 1):
```bash
gunicorn --workers 9 ... # For 4-core system
```
### Nginx Caching
Add to nginx config:
```nginx
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m max_size=1g inactive=60m;
location /api/statistics/ {
proxy_cache api_cache;
proxy_cache_valid 200 10m;
add_header X-Cache-Status $upstream_cache_status;
}
```
---
## Monitoring & Logging
### Application Logs
```bash
# API server
tail -f /var/log/tiemeasureflow/api_error.log
# Web client
tail -f /var/log/tiemeasureflow/web_error.log
# System
journalctl -u tiemeasureflow-api -f
```
### Health Check Endpoint
```bash
curl http://localhost:8000/api/health
```
Response:
```json
{
"status": "ok",
"service": "TieMeasureFlow API",
"version": "0.1.0"
}
```
### Database Connection Pooling
Monitor with:
```bash
# MySQL connections
mysql -e "SHOW PROCESSLIST;" | grep tiemeasureflow
```
+693
View File
@@ -0,0 +1,693 @@
# TieMeasureFlow User Guide
Welcome to TieMeasureFlow - a comprehensive measurement task management system designed for precision measurement workflows with caliper measurements, barcode tracking, and statistical process control.
## Table of Contents
1. [System Overview](#system-overview)
2. [Getting Started](#getting-started)
3. [User Roles](#user-roles)
4. [Maker Workflow](#maker-workflow)
5. [MeasurementTec Workflow](#measurementtec-workflow)
6. [Metrologist Workflow](#metrologist-workflow)
7. [Admin Workflow](#admin-workflow)
8. [UI Features](#ui-features)
9. [Keyboard Shortcuts](#keyboard-shortcuts)
10. [Tips & Tricks](#tips--tricks)
## System Overview
### What is TieMeasureFlow?
TieMeasureFlow is a web-based measurement management system that enables teams to:
- **Create measurement recipes** - Define measurement procedures with tasks, subtasks, and tolerance specifications
- **Execute measurements** - Record measurements using USB calipers or manual input with automatic pass/fail determination
- **Track traceability** - Associate measurements with lot numbers, serial numbers, and operators
- **Analyze quality** - Generate SPC (Statistical Process Control) charts, capability indices, and quality reports
- **Export data** - Download measurements as CSV or generate PDF reports with configurable formatting
### Key Concepts
| Concept | Description |
|---------|-------------|
| **Recipe** | Master document that defines a set of measurements to perform |
| **Version** | Immutable snapshot of a recipe. Editing creates a new version; old measurements stay linked to original |
| **Task** | Logical group of related subtasks (e.g., "Measure external dimensions") |
| **Subtask** | Individual measurement point with tolerance limits (UTL/UWL/LWL/LTL) |
| **Measurement** | Individual recorded value with automatic pass/fail/warning status |
| **Lot/Serial** | Traceability fields linking measurements to physical parts |
### Architecture
```
TieMeasureFlow
├── Server (FastAPI on port 8000)
│ ├── Authentication & Authorization
│ ├── Recipe versioning & management
│ ├── Measurement storage & analysis
│ └── Statistical calculations
└── Client (Flask on port 5000)
├── Maker: Recipe editor
├── MeasurementTec: Measurement entry
├── Metrologist: SPC dashboard
└── Admin: User management
```
---
## Getting Started
### Login
1. Open `http://localhost:5000` (or your configured client URL)
2. Enter **username** and **password**
3. Click **Login**
You are now logged in and redirected to your role's dashboard.
### Change Language
Click the **language selector** (top-right) to switch between:
- **Italian (Italiano)** - Default
- **English** - Full UI and data labels translated
Language preference is saved to your profile.
### Change Theme
Click the **theme toggle** (sun/moon icon, top-right) to switch between:
- **Light Mode** - White background, dark text
- **Dark Mode** - Dark background, light text
Theme preference is saved to your profile.
### Profile Settings
1. Click your **username** (top-right)
2. Select **Profile** or **Settings**
3. Update:
- Display name
- Email
- Language preference
- Theme preference
4. Click **Save**
---
## User Roles
TieMeasureFlow has four primary roles. Users can have multiple roles simultaneously.
### Maker
**Purpose:** Create and maintain measurement procedures
**Permissions:**
- Create new recipes
- Edit recipe structure (tasks, subtasks, tolerances)
- Add measurement points and annotations
- Upload images/PDFs for reference
- View recipe history and versions
- Manage recipe access
**Access:**
- Menu: **Maker** → Recipe Management
- Can see: All recipes and their versions
**Typical Tasks:**
- Define new measurement procedures
- Set tolerance limits (UTL/UWL/LWL/LTL)
- Create visual annotations on images
- Document measurement instructions
---
### MeasurementTec
**Purpose:** Execute measurements in the field/lab
**Permissions:**
- Select recipes to measure
- Record individual measurements
- Use USB caliper for automated input
- Scan barcodes for lot/serial tracking
- View assigned measurement tasks
- Export measurements to CSV
**Access:**
- Menu: **Measure** → Task Execution
- Can see: Published recipes only
**Typical Tasks:**
- Open a recipe via barcode or search
- Follow task instructions
- Record measurements (manual or USB caliper)
- Scan lot and serial numbers
- Monitor real-time pass/fail status
---
### Metrologist
**Purpose:** Analyze measurements and generate quality reports
**Permissions:**
- View all measurements across recipes
- Access SPC statistics and control charts
- View capability indices (Cp, Cpk, Pp, Ppk)
- Generate PDF reports
- Export measurements and charts
- Filter data by recipe, date, operator, lot
**Access:**
- Menu: **Statistics** → SPC Dashboard
- Can see: All measurements and statistics
**Typical Tasks:**
- Monitor process capability
- Generate control charts
- Investigate out-of-control conditions
- Export data for analysis
- Create quality reports
---
### Admin
**Purpose:** System administration and user management
**Permissions:**
- Create/edit/delete users
- Assign roles to users
- Regenerate user API keys
- Configure system settings
- Upload company logo
- Manage CSV export settings
**Access:**
- Menu: **Admin** → User Management
- Can see: All users and system settings
**Typical Tasks:**
- Onboard new users
- Reset lost API keys
- Configure locale/format settings
- Upload company branding
- Manage system access
---
## Maker Workflow
### Create a New Recipe
1. Navigate to **Maker****Recipe Management**
2. Click **New Recipe**
3. Enter details:
- **Code**: Unique identifier (e.g., `RECIPE_MOTOR_001`)
- **Name**: Human-readable name
- **Description**: Purpose and context
4. Click **Create Recipe**
5. Recipe v1 is created and ready for editing
### Add Tasks and Subtasks
1. Open a recipe
2. Click **Add Task**
3. Enter task details:
- **Title**: e.g., "Measure external dimensions"
- **Directive**: Step-by-step instructions
- **Description**: Additional context
- **File Type**: Select if using images/PDFs
4. Click **Add Subtask** for each measurement point
5. For each subtask:
- **Marker #**: Unique number within task (e.g., 1, 2, 3)
- **Description**: What is being measured
- **Measurement Type**: `length`, `angle`, `diameter`, etc.
- **Nominal**: Target value
- **UTL**: Upper Tolerance Limit (hard limit)
- **UWL**: Upper Warning Limit (warning zone)
- **LWL**: Lower Warning Limit (warning zone)
- **LTL**: Lower Tolerance Limit (hard limit)
- **Unit**: `mm`, `inch`, `degree`, etc.
**Tolerance Example:**
```
LTL: 9.5 mm (FAIL below this)
LWL: 9.8 mm (WARNING below this)
Nominal: 10.0 mm
UWL: 10.2 mm (WARNING above this)
UTL: 10.5 mm (FAIL above this)
```
### Add Annotations & Images
1. Open a task
2. Click **Upload Image** to add reference photo
3. Click **Annotate** to add visual markers
4. In the annotation editor:
- **Marker Tool**: Click to place numbered points
- **Text Tool**: Add labels
- **Draw Tool**: Add circles/lines
5. Save annotations
### Manage Versions
When you edit a recipe (add/remove tasks, change tolerances), a **new version** is created automatically. This ensures:
- Measurements remain linked to the version they were recorded against
- You can compare results across versions
- Historical record is preserved
**Version Management:**
1. Open recipe
2. Click **Versions** tab
3. View all versions with:
- Version number and date
- Who made changes
- Change notes
- Measurement count
4. Click version to view its structure
**Warning:** If a version has existing measurements, you cannot edit it directly. Create a new version to make changes.
---
## MeasurementTec Workflow
### Select a Recipe
**Method 1: Search**
1. Navigate to **Measure****Select Recipe**
2. Type recipe name or code in search box
3. Click recipe from results
**Method 2: Barcode Scan**
1. Navigate to **Measure****Select Recipe**
2. Scan recipe barcode
3. Recipe loads automatically
### Enter Lot & Serial Information
After selecting recipe:
1. **Lot Number**: Scan or type batch identifier
2. **Serial Number**: Scan or type part identifier
3. Click **Continue**
This information is recorded with every measurement for traceability.
### Perform Measurements
For each task:
1. **Read Instructions** - Display shows task directive and reference image
2. **Locate Measurement Points** - Find marked positions on the part
3. **Record Measurement**:
**Option A: USB Caliper**
- Connect USB caliper to tablet/computer
- Place part in caliper
- Press measurement button on caliper
- System automatically records value
- Move to next measurement point
**Option B: Manual Entry**
- Type measured value in input field
- Value field accepts decimals and negative numbers
- Press Enter or click Next
4. **Monitor Pass/Fail Status**:
- **GREEN/Pass**: Value within LWL-UWL
- **YELLOW/Warning**: Value within LTL-LWL or UWL-UTL
- **RED/Fail**: Value outside LTL or UTL
5. **Submit Measurements** - Click Submit when all tasks complete
### Keyboard Shortcuts
| Shortcut | Action |
|----------|--------|
| `Tab` | Move to next measurement field |
| `Shift+Tab` | Move to previous field |
| `Enter` | Submit measurement and move to next |
| `Esc` | Cancel current task |
| `Ctrl+Z` | Undo last measurement |
### USB Caliper Auto-Detection
TieMeasureFlow automatically detects USB caliper input. To use:
1. Connect caliper via USB
2. Open measurement form
3. Focus on measurement input field
4. Press measurement button on caliper
5. Value appears in field automatically
**Note:** System distinguishes caliper input (rapid <30ms intervals, 3+ keystrokes) from human typing (>100ms intervals).
---
## Metrologist Workflow
### Access SPC Dashboard
1. Navigate to **Statistics****SPC Dashboard**
2. Dashboard loads with recipe list
### Select Data to Analyze
1. **Recipe**: Select from dropdown (required)
2. **Version**: Leave blank for all versions, or select specific version
3. **Subtask**: Select specific measurement point, or leave blank for summary
4. **Date Range**: Optional - filter by measurement date
5. **Operator**: Optional - filter by who performed measurement
6. **Lot/Serial**: Optional - filter by part traceability
Click **Apply Filters**
### View Summary Statistics
Card displays:
- **Total Measurements**: Count
- **Pass %**: Percentage passing all limits
- **Warning %**: Percentage in warning zone
- **Fail %**: Percentage outside limits
Use for quick quality assessment.
### Analyze Control Chart
The **control chart** displays:
- **Individual Points**: Each measurement value
- **Center Line**: Mean (average) value
- **UCL/LCL**: Upper/Lower Control Limits
- **Red Markers**: Out-of-control points
**What to Look For:**
- Points outside UCL or LCL → Process out of control
- Trend (6+ consecutive rising/falling) → Process drift
- All points on one side of center → Bias
- Regular oscillation → Calibration problem
### Check Process Capability
**Capability Indices** tell you if the process can consistently meet specifications:
| Index | What It Means | Target |
|-------|---------------|--------|
| **Cp** | Process capability (theoretical) | > 1.33 |
| **Cpk** | Process capability (actual, accounting for centering) | > 1.33 |
| **Pp** | Process performance (single sample) | > 1.67 |
| **Ppk** | Process performance (accounting for centering) | > 1.67 |
**Interpretation:**
- **Cpk > 1.67**: Excellent - process is capable
- **Cpk 1.33-1.67**: Good - process is acceptable
- **Cpk < 1.33**: Poor - process needs improvement
### View Histogram
The **histogram** shows:
- **Bars**: Distribution of measured values across bins
- **Curve**: Theoretical normal distribution overlay
- **Limits**: Vertical lines for LTL/LWL/UWL/UTL
**What to Look For:**
- Normal bell curve → Process is well-behaved
- Bimodal (two peaks) → Two different populations mixing
- Skewed distribution → Process bias
- Values outside limits → Specification violations
### Generate Reports
#### SPC Report (PDF)
1. Select filters (recipe, subtask, date range)
2. Click **Export SPC Report**
3. PDF downloads with:
- Control chart graph
- Histogram with curve
- Capability statistics
- Summary table
#### Measurements Report (PDF)
1. Select filters (optional subtask filter)
2. Click **Export Measurements Report**
3. PDF downloads with:
- Complete measurement table
- Pass/fail status
- Lot/serial information
- Operator name and date
#### CSV Export
1. Click **Export Data** button
2. CSV downloads with all filtered measurements
3. Columns: ID, subtask, version, operator, value, pass/fail, deviation, lot, serial, date
4. Delimiter and decimal format per system settings
---
## Admin Workflow
### User Management
#### Create User
1. Navigate to **Admin****User Management**
2. Click **Add User**
3. Enter:
- **Username**: Login identifier (must be unique)
- **Password**: Initial password (user can change after login)
- **Display Name**: Full name for display
- **Email**: Contact email
- **Roles**: Check one or more:
- Maker
- MeasurementTec
- Metrologist
- **Admin**: Check if user manages other users
4. Click **Create User**
5. Confirm user was created and notify them to change password
#### Edit User
1. Navigate to **Admin****User Management**
2. Click user row to edit
3. Update fields (all optional):
- Display name
- Email
- Roles
- Admin status
- Active status
4. Click **Save**
#### Deactivate User
1. Navigate to **Admin****User Management**
2. Click user row
3. Click **Deactivate User**
4. Confirm - user is soft-deleted (can be reactivated)
5. User's API key is cleared, login no longer works
#### Reset API Key
If user loses their API key:
1. Navigate to **Admin****User Management**
2. Click user row
3. Click **Regenerate API Key**
4. New key is generated and displayed
5. Provide new key to user (display once only)
### System Settings
#### Configure CSV Export
1. Navigate to **Admin****Settings**
2. Update:
- **CSV Delimiter**: `,` (comma) or `;` (semicolon)
- **CSV Decimal Separator**: `.` (period) or `,` (comma)
3. Click **Save**
4. All future CSV exports use these settings
**Example:**
- European format: Delimiter `;`, Decimal `,`
- US/UK format: Delimiter `,`, Decimal `.`
#### Upload Company Logo
1. Navigate to **Admin****Settings**
2. Click **Upload Logo**
3. Select image file (JPEG, PNG, GIF, WebP, SVG, max 50 MB)
4. Click **Upload**
5. Logo appears in header of all pages
---
## UI Features
### Navigation
**Top Navigation Bar:**
- Logo/company branding (left)
- Main menu: Measure, Maker, Statistics, Admin (center)
- Language selector, Theme toggle, User menu (right)
**Breadcrumbs:** Show current page hierarchy
**Search:** Available on list pages to filter by name/code
### Responsive Design
- **Desktop (1024px+)**: Full layout with sidebar
- **Tablet (768px+)**: Sidebar collapses to hamburger menu
- **Mobile (< 768px)**: Touch-optimized layout
### Data Tables
- **Sortable columns**: Click header to sort ascending/descending
- **Pagination**: Navigate between pages
- **Filters**: Narrow results by multiple criteria
- **Export**: Download as CSV
### Forms
- **Auto-save**: Some fields auto-save when you leave the field
- **Validation**: Error messages shown inline
- **Tooltips**: Hover over `?` icons for field help
- **Progress indicators**: Multi-step forms show progress
### Modal Dialogs
- Confirmation for destructive actions
- Forms for data entry
- Information displays
- Close with X button or Cancel
---
## Tips & Tricks
### Maker Best Practices
1. **Use Clear Naming**: Task and subtask names should describe exactly what is measured
2. **Document Units**: Always specify units (mm, inches, degrees) in subtask description
3. **Set Realistic Tolerances**: Ensure UTL/LTL are achievable with your equipment
4. **Version Control**: Add meaningful change notes when creating new versions
5. **Use Annotations**: Visual markers help operators find exact measurement points
6. **Test First**: Do a test measurement before rollout to ensure tolerances are reasonable
### MeasurementTec Best Practices
1. **Barcode Scanning**: Scan lot/serial barcodes rather than typing to avoid errors
2. **Consistent Operator**: Use consistent technique - caliper orientation, pressure, etc.
3. **Check Zero**: Zero your caliper at start of shift
4. **Monitor Warnings**: Watch for warning zone measurements - may indicate drift
5. **Document Deviations**: If you encounter fails, note the cause in observations
6. **Batch Together**: Group measurements from same lot for statistical significance
### Metrologist Best Practices
1. **Regular Reviews**: Check control charts daily for out-of-control conditions
2. **Trend Analysis**: Look beyond individual points - watch for sustained trends
3. **Root Cause**: When investigating failures, cross-reference by operator and time
4. **Baseline**: Establish baseline capability when process starts
5. **Update Limits**: Periodically review if specification limits are appropriate
6. **Archive Reports**: Keep dated PDF reports for audit trail
### Performance Tips
1. **Filter Early**: Use date range and version filters to speed up statistics queries
2. **Batch Operations**: Enter multiple measurements at once rather than one-by-one
3. **Cache Data**: Browser caches filter selections - reuse recent filters
4. **Offline Mode**: Some tablet deployments support offline measurement entry, synced later
5. **Export Over Display**: For large datasets (>1000 measurements), export to CSV and analyze in Excel
### Troubleshooting
**"Recipe not found" when scanning barcode**
- Verify barcode matches recipe code
- Check recipe is active (not deactivated)
- Try searching by name instead
**USB Caliper not working**
- Check USB cable connection
- Try removing and re-inserting caliper
- Check browser console for permission errors
- Use manual entry as backup
**Measurements seem wrong**
- Verify subtask is correct marker number
- Check caliper zero before starting
- Look for outliers - may indicate operator error
- Export data and check in spreadsheet
**Cannot edit recipe**
- Recipe may have existing measurements
- Create new version first
- Check if you have Maker role
**Export file encoding issues**
- If Excel shows garbled characters, check CSV settings
- Try semicolon delimiter with comma decimal separator for European locales
- File is UTF-8 encoded; ensure Excel opens with UTF-8 encoding
---
## Getting Help
### Online Resources
- **API Documentation**: `http://localhost:8000/docs`
- **Project Guide**: See `DEPLOYMENT.md` and `API.md`
- **Database Structure**: See schema in Alembic migrations
### Contact Support
- **System Admin**: For user account issues
- **Maker Manager**: For recipe structure and tolerance questions
- **Quality Engineer**: For SPC interpretation and reporting
---
## Keyboard & Accessibility
### Keyboard Navigation
- `Tab`: Navigate between fields
- `Shift+Tab`: Navigate backwards
- `Enter`: Submit forms
- `Escape`: Close modals/cancel operations
- `Alt+M`: Jump to main menu
- `Alt+S`: Jump to search
### Screen Reader Support
- All UI elements have proper ARIA labels
- Forms announce validation errors
- Tables have accessible headers
- Images have alt text
### High Contrast Mode
Enabled automatically for operating systems with high contrast settings
---
## Version History
**TieMeasureFlow v0.1.0**
Released: February 2025
**Features:**
- Recipe versioning with copy-on-write
- USB caliper integration
- SPC statistics and control charts
- PDF report generation
- Multi-language support (IT/EN)
- Light/Dark theme