Final documentation and code updates: reorganized debug scripts and implementation documents to documentation directory

This commit is contained in:
Quality App Developer
2026-02-10 13:21:58 +02:00
parent e53e3acc8e
commit bb8cd011f5
5 changed files with 204 additions and 2 deletions

View File

@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""
Script to generate test FG scan data for quality reports testing
Run inside container: docker exec quality_app_v2 python /app/test_fg_data.py
"""
import pymysql
from datetime import datetime, timedelta
import random
import os
# Database configuration from environment
db_config = {
'host': os.getenv('DB_HOST', 'mariadb'),
'user': os.getenv('DB_USER', 'quality_user'),
'password': os.getenv('DB_PASSWORD', 'quality_pass'),
'database': os.getenv('DB_NAME', 'quality_db'),
'port': int(os.getenv('DB_PORT', 3306))
}
def generate_test_scans():
"""Generate realistic test FG scan data"""
try:
db = pymysql.connect(**db_config)
cursor = db.cursor()
# Create table if not exists
cursor.execute("""
CREATE TABLE IF NOT EXISTS scanfg_orders (
Id INT AUTO_INCREMENT PRIMARY KEY,
operator_code VARCHAR(4) NOT NULL,
CP_full_code VARCHAR(15) NOT NULL,
OC1_code VARCHAR(4) NOT NULL,
OC2_code VARCHAR(4) NOT NULL,
quality_code TINYINT(3) NOT NULL,
date DATE NOT NULL,
time TIME NOT NULL,
approved_quantity INT DEFAULT 0,
rejected_quantity INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_cp (CP_full_code),
INDEX idx_date (date),
INDEX idx_operator (operator_code),
UNIQUE KEY unique_cp_date (CP_full_code, date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
""")
db.commit()
print("✓ Table 'scanfg_orders' ready")
# Sample data
operators = ['OP01', 'OP02', 'OP03', 'OP04']
cp_codes = [f'CP{str(i).zfill(8)}-{str(j).zfill(4)}' for i in range(1, 6) for j in range(1, 4)]
oc1_codes = ['OC01', 'OC02', 'OC03', 'OC04']
oc2_codes = ['OC10', 'OC20', 'OC30', 'OC40']
defect_codes = ['000', '001', '002', '003', '004', '005'] # 000 = approved, others = defects
# Generate scans for last 10 days
scans_created = 0
for days_back in range(10):
date = (datetime.now() - timedelta(days=days_back)).date()
# Generate 20-50 scans per day
num_scans = random.randint(20, 50)
for _ in range(num_scans):
hour = random.randint(6, 18)
minute = random.randint(0, 59)
second = random.randint(0, 59)
time = f'{hour:02d}:{minute:02d}:{second:02d}'
operator = random.choice(operators)
cp_code = random.choice(cp_codes)
oc1_code = random.choice(oc1_codes)
oc2_code = random.choice(oc2_codes)
# 90% approved, 10% rejected
defect_code = random.choice(['000'] * 9 + ['001', '002', '003', '004', '005'])
try:
insert_query = """
INSERT INTO scanfg_orders
(operator_code, CP_full_code, OC1_code, OC2_code, quality_code, date, time)
VALUES (%s, %s, %s, %s, %s, %s, %s)
"""
cursor.execute(insert_query, (operator, cp_code, oc1_code, oc2_code, defect_code, date, time))
scans_created += 1
except Exception:
# Skip duplicate entries
pass
db.commit()
print(f"✓ Generated {scans_created} test scans")
# Show summary
cursor.execute("""
SELECT COUNT(*) as total,
SUM(CASE WHEN quality_code = '000' THEN 1 ELSE 0 END) as approved,
SUM(CASE WHEN quality_code != '000' THEN 1 ELSE 0 END) as rejected
FROM scanfg_orders
""")
result = cursor.fetchone()
print(f"\nDatabase Summary:")
print(f" Total Scans: {result[0]}")
print(f" Approved: {result[1] or 0}")
print(f" Rejected: {result[2] or 0}")
print(f" Approval Rate: {((result[1] or 0) / (result[0] or 1) * 100):.1f}%")
# Show sample by date
cursor.execute("""
SELECT date, COUNT(*) as count,
SUM(CASE WHEN quality_code = '000' THEN 1 ELSE 0 END) as approved
FROM scanfg_orders
GROUP BY date
ORDER BY date DESC
LIMIT 10
""")
print(f"\nScans by Date (Last 10 Days):")
print(f" {'Date':<12} {'Total':<8} {'Approved':<10} {'Rate':<8}")
print(f" {'-'*40}")
for row in cursor.fetchall():
date_str = str(row[0])
total = row[1]
approved = row[2] or 0
rate = (approved / total * 100) if total > 0 else 0
print(f" {date_str:<12} {total:<8} {approved:<10} {rate:.1f}%")
cursor.close()
db.close()
print("\n✅ Test data generation completed successfully!")
except Exception as e:
print(f"❌ Error: {e}")
raise
if __name__ == '__main__':
generate_test_scans()

View File

@@ -0,0 +1,162 @@
#!/usr/bin/env python3
"""
Test script for PDF generation functionality
Tests both single label and batch PDF generation
"""
import json
import requests
import sys
# Configuration
BASE_URL = "http://localhost:8080"
LOGIN_URL = f"{BASE_URL}/login"
SINGLE_PDF_URL = f"{BASE_URL}/labels/api/generate-pdf"
BATCH_PDF_URL = f"{BASE_URL}/labels/api/generate-pdf/1/true"
# Test credentials
TEST_USERNAME = "admin"
TEST_PASSWORD = "admin123"
def test_pdf_generation():
"""Test PDF generation endpoints"""
session = requests.Session()
# Step 1: Login
print("=" * 70)
print("Step 1: Logging in...")
print("=" * 70)
login_data = {
'username': TEST_USERNAME,
'password': TEST_PASSWORD
}
response = session.post(LOGIN_URL, data=login_data)
if response.status_code not in [200, 302]: # Accept both OK and redirect
print(f"❌ Login failed with status {response.status_code}")
print(f"Response: {response.text[:200]}")
return False
print(f"✓ Login successful (status: {response.status_code})")
# Step 2: Test Single Label PDF Generation
print("\n" + "=" * 70)
print("Step 2: Testing Single Label PDF Generation...")
print("=" * 70)
order_data = {
"id": 1,
"comanda_productie": "CP00000711",
"cod_articol": "ART001",
"descr_com_prod": "Memory Foam Pillow - Premium Quality",
"cantitate": 5,
"com_achiz_client": "PO2026001",
"nr_linie_com_client": "001",
"customer_name": "ACME Corporation",
"customer_article_number": "ACME-MFP-001",
"data_livrara": "2026-02-11",
"dimensiune": "Standard (50x70cm)",
"piece_number": 1,
"total_pieces": 5
}
response = session.post(
SINGLE_PDF_URL,
json=order_data,
headers={'Content-Type': 'application/json'}
)
if response.status_code == 200:
if response.headers.get('Content-Type') == 'application/pdf':
print(f"✓ Single label PDF generated successfully")
print(f" Content-Type: {response.headers.get('Content-Type')}")
print(f" PDF Size: {len(response.content)} bytes")
# Save to file for manual inspection
with open('/tmp/test_label_single.pdf', 'wb') as f:
f.write(response.content)
print(f" Saved to: /tmp/test_label_single.pdf")
else:
print(f"❌ Invalid content type: {response.headers.get('Content-Type')}")
print(f"Response: {response.text[:200]}")
return False
else:
print(f"❌ Single PDF generation failed with status {response.status_code}")
print(f"Response: {response.text[:200]}")
return False
# Step 3: Test Batch PDF Generation
print("\n" + "=" * 70)
print("Step 3: Testing Batch PDF Generation...")
print("=" * 70)
response = session.post(BATCH_PDF_URL)
if response.status_code == 200:
if response.headers.get('Content-Type') == 'application/pdf':
print(f"✓ Batch PDF generated successfully")
print(f" Content-Type: {response.headers.get('Content-Type')}")
print(f" PDF Size: {len(response.content)} bytes")
# Save to file for manual inspection
with open('/tmp/test_label_batch.pdf', 'wb') as f:
f.write(response.content)
print(f" Saved to: /tmp/test_label_batch.pdf")
else:
print(f"❌ Invalid content type: {response.headers.get('Content-Type')}")
print(f"Response: {response.text[:200]}")
return False
else:
print(f"❌ Batch PDF generation failed with status {response.status_code}")
print(f"Response: {response.text[:200]}")
return False
# Step 4: Verify order marked as printed
print("\n" + "=" * 70)
print("Step 4: Verifying order status...")
print("=" * 70)
# Check if order is marked as printed
import pymysql
try:
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='quality_user',
password='quality_secure_password_2026',
database='quality_db'
)
cursor = conn.cursor()
cursor.execute("SELECT id, comanda_productie, printed_labels FROM order_for_labels WHERE id = 1")
row = cursor.fetchone()
cursor.close()
conn.close()
if row:
order_id, cp_code, printed_status = row
print(f"Order ID: {order_id}, CP Code: {cp_code}")
if printed_status == 1:
print(f"✓ Order marked as printed (printed_labels = {printed_status})")
else:
print(f"⚠ Order NOT marked as printed (printed_labels = {printed_status})")
else:
print("⚠ Order not found in database")
except Exception as e:
print(f"⚠ Could not verify order status: {e}")
print("\n" + "=" * 70)
print("✓ All PDF generation tests completed successfully!")
print("=" * 70)
return True
if __name__ == '__main__':
try:
success = test_pdf_generation()
sys.exit(0 if success else 1)
except Exception as e:
print(f"\n❌ Unexpected error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)