Compare commits
4 Commits
Update-Exc
...
feature/mo
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
56b0d6d398 | ||
|
|
22d7a349a2 | ||
|
|
3afc096fd4 | ||
|
|
406219547d |
@@ -31,7 +31,7 @@ Long-term goal: evolve into a WMS, but right now focus on making this workflow r
|
||||
## Scanlook (current product summary)
|
||||
Scanlook is a web app for warehouse counting workflows built with Flask + SQLite.
|
||||
|
||||
**Current Version:** 0.14.0
|
||||
**Current Version:** 0.15.0
|
||||
|
||||
**Tech Stack:**
|
||||
- Backend: Python/Flask, raw SQL (no ORM), openpyxl (Excel file generation)
|
||||
@@ -68,7 +68,7 @@ Scanlook is a web app for warehouse counting workflows built with Flask + SQLite
|
||||
|
||||
**Long-term goal:** Modular WMS with future modules for Shipping, Receiving, Transfers, Production.
|
||||
|
||||
**Module System (v0.14.0):**
|
||||
**Module System:**
|
||||
- Modules table defines available modules (module_key used for routing)
|
||||
- UserModules table tracks per-user access
|
||||
- Home page (/home) shows module cards based on user's access
|
||||
|
||||
298
app.py
298
app.py
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
ScanLook - Inventory Management System
|
||||
ScanLook - Modular Inventory Management System
|
||||
Flask Application
|
||||
Production-Ready Release
|
||||
Production-Ready Release with Module System
|
||||
"""
|
||||
from flask import Flask, render_template, request, redirect, url_for, session, flash, jsonify, send_from_directory
|
||||
from werkzeug.security import check_password_hash
|
||||
@@ -13,21 +13,11 @@ app = Flask(__name__)
|
||||
|
||||
# Now import your custom modules
|
||||
from db import query_db, execute_db, get_db
|
||||
from blueprints.data_imports import data_imports_bp
|
||||
from blueprints.users import users_bp
|
||||
from blueprints.sessions import sessions_bp
|
||||
from blueprints.admin_locations import admin_locations_bp
|
||||
from blueprints.counting import counting_bp
|
||||
from blueprints.cons_sheets import cons_sheets_bp
|
||||
from utils import login_required
|
||||
|
||||
# Register Blueprints
|
||||
app.register_blueprint(data_imports_bp)
|
||||
# Register Core Blueprints (non-modular)
|
||||
app.register_blueprint(users_bp)
|
||||
app.register_blueprint(sessions_bp)
|
||||
app.register_blueprint(admin_locations_bp)
|
||||
app.register_blueprint(counting_bp)
|
||||
app.register_blueprint(cons_sheets_bp)
|
||||
|
||||
# V1.0: Use environment variable for production, fallback to demo key for development
|
||||
app.secret_key = os.environ.get('SCANLOOK_SECRET_KEY', 'scanlook-demo-key-replace-for-production')
|
||||
@@ -38,7 +28,7 @@ app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=1)
|
||||
|
||||
|
||||
# 1. Define the version
|
||||
APP_VERSION = '0.15.0'
|
||||
APP_VERSION = '0.17.0' # Bumped version for modular architecture
|
||||
|
||||
# 2. Inject it into all templates automatically
|
||||
@app.context_processor
|
||||
@@ -53,11 +43,17 @@ if not os.path.exists(db_path):
|
||||
init_database()
|
||||
create_default_users()
|
||||
print("Database initialized!")
|
||||
print("📦 Install modules from /admin/modules")
|
||||
|
||||
# Run migrations to apply any pending database changes
|
||||
from migrations import run_migrations
|
||||
run_migrations()
|
||||
|
||||
# Load and register active modules
|
||||
from module_manager import get_module_manager
|
||||
module_manager = get_module_manager()
|
||||
module_manager.load_active_modules(app)
|
||||
|
||||
|
||||
# ==================== ROUTES: AUTHENTICATION ====================
|
||||
|
||||
@@ -119,50 +115,245 @@ def home():
|
||||
return render_template('home.html', modules=modules)
|
||||
|
||||
|
||||
# ==================== ROUTES: DASHBOARD ====================
|
||||
# ==================== ROUTES: ADMIN DASHBOARD ====================
|
||||
|
||||
@app.route('/admin')
|
||||
@login_required
|
||||
def admin_dashboard():
|
||||
"""Main dashboard - different views for admin vs staff"""
|
||||
"""Admin dashboard - shows all available modules"""
|
||||
role = session.get('role')
|
||||
|
||||
if role in ['owner', 'admin']:
|
||||
# Admin dashboard
|
||||
show_archived = request.args.get('show_archived', '0') == '1'
|
||||
if role not in ['owner', 'admin']:
|
||||
flash('Access denied. Admin role required.', 'danger')
|
||||
return redirect(url_for('home'))
|
||||
|
||||
if show_archived:
|
||||
# Show all sessions (active and archived)
|
||||
sessions_list = query_db('''
|
||||
SELECT s.*, u.full_name as created_by_name,
|
||||
COUNT(DISTINCT lc.location_count_id) as total_locations,
|
||||
SUM(CASE WHEN lc.status = 'completed' THEN 1 ELSE 0 END) as completed_locations,
|
||||
SUM(CASE WHEN lc.status = 'in_progress' THEN 1 ELSE 0 END) as in_progress_locations
|
||||
FROM CountSessions s
|
||||
LEFT JOIN Users u ON s.created_by = u.user_id
|
||||
LEFT JOIN LocationCounts lc ON s.session_id = lc.session_id
|
||||
WHERE s.status IN ('active', 'archived')
|
||||
GROUP BY s.session_id
|
||||
ORDER BY s.status ASC, s.created_timestamp DESC
|
||||
''')
|
||||
# Get modules this user has access to
|
||||
user_id = session.get('user_id')
|
||||
modules = query_db('''
|
||||
SELECT m.module_id, m.module_name, m.module_key, m.description, m.icon
|
||||
FROM Modules m
|
||||
JOIN UserModules um ON m.module_id = um.module_id
|
||||
WHERE um.user_id = ? AND m.is_active = 1
|
||||
ORDER BY m.display_order
|
||||
''', [user_id])
|
||||
|
||||
return render_template('admin_dashboard.html', modules=modules)
|
||||
|
||||
# ==================== MODULE MANAGER UI ====================
|
||||
|
||||
@app.route('/admin/modules')
|
||||
@login_required
|
||||
def module_manager_ui():
|
||||
"""Module manager interface for admins"""
|
||||
if session.get('role') not in ['owner', 'admin']:
|
||||
flash('Access denied. Admin role required.', 'danger')
|
||||
return redirect(url_for('home'))
|
||||
|
||||
modules = module_manager.scan_available_modules()
|
||||
return render_template('module_manager.html', modules=modules)
|
||||
|
||||
|
||||
@app.route('/admin/modules/<module_key>/install', methods=['POST'])
|
||||
@login_required
|
||||
def install_module(module_key):
|
||||
"""Install a module"""
|
||||
if session.get('role') not in ['owner', 'admin']:
|
||||
return jsonify({'success': False, 'message': 'Access denied'}), 403
|
||||
|
||||
result = module_manager.install_module(module_key)
|
||||
|
||||
if result['success']:
|
||||
result['restart_required'] = True
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
@app.route('/admin/modules/<module_key>/uninstall', methods=['POST'])
|
||||
@login_required
|
||||
def uninstall_module(module_key):
|
||||
"""Uninstall a module"""
|
||||
if session.get('role') not in ['owner', 'admin']:
|
||||
return jsonify({'success': False, 'message': 'Access denied'}), 403
|
||||
|
||||
# Check if user wants to keep data
|
||||
keep_data = request.args.get('keep_data') == 'true'
|
||||
drop_tables = not keep_data
|
||||
|
||||
result = module_manager.uninstall_module(module_key, drop_tables=drop_tables)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@app.route('/admin/modules/<module_key>/activate', methods=['POST'])
|
||||
@login_required
|
||||
def activate_module(module_key):
|
||||
"""Activate a module"""
|
||||
if session.get('role') not in ['owner', 'admin']:
|
||||
return jsonify({'success': False, 'message': 'Access denied'}), 403
|
||||
|
||||
result = module_manager.activate_module(module_key)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@app.route('/admin/modules/<module_key>/deactivate', methods=['POST'])
|
||||
@login_required
|
||||
def deactivate_module(module_key):
|
||||
"""Deactivate a module"""
|
||||
if session.get('role') not in ['owner', 'admin']:
|
||||
return jsonify({'success': False, 'message': 'Access denied'}), 403
|
||||
|
||||
result = module_manager.deactivate_module(module_key)
|
||||
return jsonify(result)
|
||||
|
||||
@app.route('/admin/restart', methods=['POST'])
|
||||
@login_required
|
||||
def restart_server():
|
||||
"""Restart the Flask server"""
|
||||
if session.get('role') not in ['owner', 'admin']:
|
||||
return jsonify({'success': False, 'message': 'Access denied'}), 403
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
try:
|
||||
print("\n🔄 Server restart requested by admin...")
|
||||
|
||||
# Return response first
|
||||
response = jsonify({'success': True, 'message': 'Server restarting...'})
|
||||
|
||||
# Schedule restart after response is sent
|
||||
def restart():
|
||||
import time
|
||||
time.sleep(0.5) # Give time for response to send
|
||||
|
||||
if os.name == 'nt': # Windows
|
||||
os.execv(sys.executable, ['python'] + sys.argv)
|
||||
else: # Linux/Mac
|
||||
os.execv(sys.executable, [sys.executable] + sys.argv)
|
||||
|
||||
from threading import Thread
|
||||
Thread(target=restart).start()
|
||||
|
||||
return response
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'message': f'Restart failed: {str(e)}'})
|
||||
|
||||
|
||||
"""
|
||||
Add this route to app.py
|
||||
"""
|
||||
|
||||
@app.route('/admin/modules/upload', methods=['POST'])
|
||||
@login_required
|
||||
def upload_module():
|
||||
"""Upload and extract a module package"""
|
||||
if session.get('role') not in ['owner', 'admin']:
|
||||
return jsonify({'success': False, 'message': 'Access denied'}), 403
|
||||
|
||||
if 'module_file' not in request.files:
|
||||
return jsonify({'success': False, 'message': 'No file uploaded'})
|
||||
|
||||
file = request.files['module_file']
|
||||
|
||||
if file.filename == '':
|
||||
return jsonify({'success': False, 'message': 'No file selected'})
|
||||
|
||||
if not file.filename.endswith('.zip'):
|
||||
return jsonify({'success': False, 'message': 'File must be a ZIP archive'})
|
||||
|
||||
try:
|
||||
import zipfile
|
||||
import tempfile
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
# Create temp directory
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Save uploaded file
|
||||
zip_path = os.path.join(temp_dir, 'module.zip')
|
||||
file.save(zip_path)
|
||||
|
||||
# Extract zip
|
||||
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
||||
zip_ref.extractall(temp_dir)
|
||||
|
||||
# Find the module folder (should contain manifest.json)
|
||||
module_folder = None
|
||||
manifest_path = None
|
||||
|
||||
# Check if manifest.json is at root of zip
|
||||
if os.path.exists(os.path.join(temp_dir, 'manifest.json')):
|
||||
module_folder = temp_dir
|
||||
manifest_path = os.path.join(temp_dir, 'manifest.json')
|
||||
else:
|
||||
# Show only active sessions
|
||||
sessions_list = query_db('''
|
||||
SELECT s.*, u.full_name as created_by_name,
|
||||
COUNT(DISTINCT lc.location_count_id) as total_locations,
|
||||
SUM(CASE WHEN lc.status = 'completed' THEN 1 ELSE 0 END) as completed_locations,
|
||||
SUM(CASE WHEN lc.status = 'in_progress' THEN 1 ELSE 0 END) as in_progress_locations
|
||||
FROM CountSessions s
|
||||
LEFT JOIN Users u ON s.created_by = u.user_id
|
||||
LEFT JOIN LocationCounts lc ON s.session_id = lc.session_id
|
||||
WHERE s.status = 'active'
|
||||
GROUP BY s.session_id
|
||||
ORDER BY s.created_timestamp DESC
|
||||
''')
|
||||
# Look for manifest.json in subdirectories
|
||||
for item in os.listdir(temp_dir):
|
||||
item_path = os.path.join(temp_dir, item)
|
||||
if os.path.isdir(item_path):
|
||||
potential_manifest = os.path.join(item_path, 'manifest.json')
|
||||
if os.path.exists(potential_manifest):
|
||||
module_folder = item_path
|
||||
manifest_path = potential_manifest
|
||||
break
|
||||
|
||||
return render_template('admin_dashboard.html', sessions=sessions_list, show_archived=show_archived)
|
||||
if not manifest_path:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': 'Invalid module package: manifest.json not found'
|
||||
})
|
||||
|
||||
# Read and validate manifest
|
||||
with open(manifest_path, 'r') as f:
|
||||
manifest = json.load(f)
|
||||
|
||||
required_fields = ['module_key', 'name', 'version', 'author']
|
||||
for field in required_fields:
|
||||
if field not in manifest:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': f'Invalid manifest.json: missing required field "{field}"'
|
||||
})
|
||||
|
||||
module_key = manifest['module_key']
|
||||
|
||||
# Check if module already exists
|
||||
modules_dir = os.path.join(os.path.dirname(__file__), 'modules')
|
||||
target_path = os.path.join(modules_dir, module_key)
|
||||
|
||||
if os.path.exists(target_path):
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': f'Module "{module_key}" already exists. Please uninstall it first or use a different module key.'
|
||||
})
|
||||
|
||||
# Required files check
|
||||
required_files = ['manifest.json', '__init__.py']
|
||||
for req_file in required_files:
|
||||
if not os.path.exists(os.path.join(module_folder, req_file)):
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': f'Invalid module package: {req_file} not found'
|
||||
})
|
||||
|
||||
# Copy module to /modules directory
|
||||
shutil.copytree(module_folder, target_path)
|
||||
|
||||
print(f"✅ Module '{manifest['name']}' uploaded successfully to {target_path}")
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': f"Module '{manifest['name']}' uploaded successfully! Click Install to activate it."
|
||||
})
|
||||
|
||||
except zipfile.BadZipFile:
|
||||
return jsonify({'success': False, 'message': 'Invalid ZIP file'})
|
||||
except json.JSONDecodeError:
|
||||
return jsonify({'success': False, 'message': 'Invalid manifest.json: not valid JSON'})
|
||||
except Exception as e:
|
||||
print(f"❌ Module upload error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return jsonify({'success': False, 'message': f'Upload failed: {str(e)}'})
|
||||
|
||||
# ==================== PWA SUPPORT ROUTES ====================
|
||||
|
||||
@@ -204,6 +395,19 @@ def whatami():
|
||||
"""
|
||||
|
||||
|
||||
@app.route('/debug/routes')
|
||||
@login_required
|
||||
def list_routes():
|
||||
"""Debug: List all registered routes"""
|
||||
if session.get('role') not in ['owner', 'admin']:
|
||||
return "Access denied", 403
|
||||
|
||||
routes = []
|
||||
for rule in app.url_map.iter_rules():
|
||||
routes.append(f"{rule.endpoint}: {rule.rule}")
|
||||
|
||||
return "<br>".join(sorted(routes))
|
||||
|
||||
# ==================== RUN APPLICATION ====================
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"""
|
||||
ScanLook Database Initialization
|
||||
Creates all tables and indexes for the inventory management system
|
||||
UPDATED: Reflects post-migration schema (CURRENT baseline is now global)
|
||||
ScanLook Database Initialization - CORE ONLY
|
||||
Creates only core system tables. Module tables are created when modules are installed.
|
||||
"""
|
||||
|
||||
import sqlite3
|
||||
@@ -13,10 +12,14 @@ DB_PATH = os.path.join(os.path.dirname(__file__), 'scanlook.db')
|
||||
|
||||
|
||||
def init_database():
|
||||
"""Initialize the database with all tables and indexes"""
|
||||
"""Initialize the database with core system tables only"""
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# ============================================
|
||||
# CORE SYSTEM TABLES
|
||||
# ============================================
|
||||
|
||||
# Users Table
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS Users (
|
||||
@@ -32,145 +35,7 @@ def init_database():
|
||||
)
|
||||
''')
|
||||
|
||||
# CountSessions Table
|
||||
# NOTE: current_baseline_version removed - CURRENT is now global
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS CountSessions (
|
||||
session_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_name TEXT NOT NULL,
|
||||
session_type TEXT NOT NULL CHECK(session_type IN ('cycle_count', 'full_physical')),
|
||||
created_by INTEGER NOT NULL,
|
||||
created_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
master_baseline_timestamp DATETIME,
|
||||
current_baseline_timestamp DATETIME,
|
||||
status TEXT DEFAULT 'active' CHECK(status IN ('active', 'completed', 'archived')),
|
||||
branch TEXT DEFAULT 'Main',
|
||||
FOREIGN KEY (created_by) REFERENCES Users(user_id)
|
||||
)
|
||||
''')
|
||||
|
||||
# BaselineInventory_Master Table (Session-specific, immutable)
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS BaselineInventory_Master (
|
||||
baseline_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL,
|
||||
lot_number TEXT NOT NULL,
|
||||
item TEXT NOT NULL,
|
||||
description TEXT,
|
||||
system_location TEXT NOT NULL,
|
||||
system_bin TEXT NOT NULL,
|
||||
system_quantity REAL NOT NULL,
|
||||
uploaded_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (session_id) REFERENCES CountSessions(session_id)
|
||||
)
|
||||
''')
|
||||
|
||||
# BaselineInventory_Current Table (GLOBAL - shared across all sessions)
|
||||
# MIGRATION CHANGE: No session_id, no baseline_version, no is_deleted
|
||||
# This table is replaced entirely on each upload
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS BaselineInventory_Current (
|
||||
current_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
lot_number TEXT NOT NULL,
|
||||
item TEXT NOT NULL,
|
||||
description TEXT,
|
||||
system_location TEXT,
|
||||
system_bin TEXT NOT NULL,
|
||||
system_quantity REAL NOT NULL,
|
||||
upload_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(lot_number, system_bin)
|
||||
)
|
||||
''')
|
||||
|
||||
# LocationCounts Table
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS LocationCounts (
|
||||
location_count_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL,
|
||||
location_name TEXT NOT NULL,
|
||||
counted_by INTEGER NOT NULL,
|
||||
start_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
end_timestamp DATETIME,
|
||||
status TEXT DEFAULT 'not_started' CHECK(status IN ('not_started', 'in_progress', 'completed')),
|
||||
expected_lots_master INTEGER DEFAULT 0,
|
||||
lots_found INTEGER DEFAULT 0,
|
||||
lots_missing INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (session_id) REFERENCES CountSessions(session_id),
|
||||
FOREIGN KEY (counted_by) REFERENCES Users(user_id)
|
||||
)
|
||||
''')
|
||||
|
||||
# ScanEntries Table
|
||||
# MIGRATION CHANGE: Removed current_* columns - now fetched via JOIN
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS ScanEntries (
|
||||
entry_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL,
|
||||
location_count_id INTEGER NOT NULL,
|
||||
lot_number TEXT NOT NULL,
|
||||
item TEXT,
|
||||
description TEXT,
|
||||
scanned_location TEXT NOT NULL,
|
||||
actual_weight REAL NOT NULL,
|
||||
scanned_by INTEGER NOT NULL,
|
||||
scan_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
-- MASTER baseline comparison (immutable, set at scan time)
|
||||
master_status TEXT CHECK(master_status IN ('match', 'wrong_location', 'ghost_lot', 'missing')),
|
||||
master_expected_location TEXT,
|
||||
master_expected_weight REAL,
|
||||
master_variance_lbs REAL,
|
||||
master_variance_pct REAL,
|
||||
|
||||
-- Duplicate detection
|
||||
duplicate_status TEXT DEFAULT '00' CHECK(duplicate_status IN ('00', '01', '03', '04')),
|
||||
duplicate_info TEXT,
|
||||
|
||||
-- CURRENT baseline comparison removed - now via JOIN in queries
|
||||
-- Removed: current_status, current_system_location, current_system_weight,
|
||||
-- current_variance_lbs, current_variance_pct, current_baseline_version
|
||||
|
||||
-- Metadata
|
||||
comment TEXT,
|
||||
is_deleted INTEGER DEFAULT 0,
|
||||
deleted_by INTEGER,
|
||||
deleted_timestamp DATETIME,
|
||||
modified_timestamp DATETIME,
|
||||
|
||||
FOREIGN KEY (session_id) REFERENCES CountSessions(session_id),
|
||||
FOREIGN KEY (location_count_id) REFERENCES LocationCounts(location_count_id),
|
||||
FOREIGN KEY (scanned_by) REFERENCES Users(user_id),
|
||||
FOREIGN KEY (deleted_by) REFERENCES Users(user_id)
|
||||
)
|
||||
''')
|
||||
|
||||
# MissingLots Table
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS MissingLots (
|
||||
missing_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL,
|
||||
location_count_id INTEGER,
|
||||
lot_number TEXT NOT NULL,
|
||||
item TEXT,
|
||||
master_expected_location TEXT NOT NULL,
|
||||
master_expected_quantity REAL NOT NULL,
|
||||
current_system_location TEXT,
|
||||
current_system_quantity REAL,
|
||||
marked_by INTEGER NOT NULL,
|
||||
marked_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
found_later TEXT DEFAULT 'N' CHECK(found_later IN ('Y', 'N')),
|
||||
found_location TEXT,
|
||||
FOREIGN KEY (session_id) REFERENCES CountSessions(session_id),
|
||||
FOREIGN KEY (location_count_id) REFERENCES LocationCounts(location_count_id),
|
||||
FOREIGN KEY (marked_by) REFERENCES Users(user_id)
|
||||
)
|
||||
''')
|
||||
|
||||
# ============================================
|
||||
# MODULE SYSTEM TABLES
|
||||
# ============================================
|
||||
|
||||
# Modules Table - Available feature modules
|
||||
# Modules Table (legacy - for user permissions)
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS Modules (
|
||||
module_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
@@ -183,7 +48,7 @@ def init_database():
|
||||
)
|
||||
''')
|
||||
|
||||
# UserModules Table - Module access per user
|
||||
# UserModules Table (module access per user)
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS UserModules (
|
||||
user_module_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
@@ -198,104 +63,35 @@ def init_database():
|
||||
)
|
||||
''')
|
||||
|
||||
# ============================================
|
||||
# CONSUMPTION SHEETS MODULE TABLES
|
||||
# ============================================
|
||||
|
||||
# cons_processes - Master list of consumption sheet process types
|
||||
# Module Registry Table (new module manager system)
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS cons_processes (
|
||||
CREATE TABLE IF NOT EXISTS module_registry (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
process_key TEXT UNIQUE NOT NULL,
|
||||
process_name TEXT NOT NULL,
|
||||
template_file BLOB,
|
||||
template_filename TEXT,
|
||||
rows_per_page INTEGER DEFAULT 30,
|
||||
detail_start_row INTEGER DEFAULT 10,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
created_by INTEGER NOT NULL,
|
||||
is_active INTEGER DEFAULT 1,
|
||||
FOREIGN KEY (created_by) REFERENCES Users(user_id)
|
||||
module_key TEXT UNIQUE NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
author TEXT,
|
||||
description TEXT,
|
||||
is_installed INTEGER DEFAULT 0,
|
||||
is_active INTEGER DEFAULT 0,
|
||||
installed_at TEXT,
|
||||
config_json TEXT
|
||||
)
|
||||
''')
|
||||
|
||||
# cons_process_fields - Custom field definitions for each process
|
||||
# Schema Migrations Table (for core migrations only)
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS cons_process_fields (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
process_id INTEGER NOT NULL,
|
||||
table_type TEXT NOT NULL CHECK(table_type IN ('header', 'detail')),
|
||||
field_name TEXT NOT NULL,
|
||||
field_label TEXT NOT NULL,
|
||||
field_type TEXT NOT NULL CHECK(field_type IN ('TEXT', 'INTEGER', 'REAL', 'DATE', 'DATETIME')),
|
||||
max_length INTEGER,
|
||||
is_required INTEGER DEFAULT 0,
|
||||
is_duplicate_key INTEGER DEFAULT 0,
|
||||
is_active INTEGER DEFAULT 1,
|
||||
sort_order INTEGER DEFAULT 0,
|
||||
excel_cell TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (process_id) REFERENCES cons_processes(id)
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
''')
|
||||
|
||||
# cons_sessions - Staff scanning sessions
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS cons_sessions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
process_id INTEGER NOT NULL,
|
||||
created_by INTEGER NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
status TEXT DEFAULT 'active' CHECK(status IN ('active', 'archived')),
|
||||
FOREIGN KEY (process_id) REFERENCES cons_processes(id),
|
||||
FOREIGN KEY (created_by) REFERENCES Users(user_id)
|
||||
)
|
||||
''')
|
||||
|
||||
# Note: Header values still use flexible key-value storage
|
||||
# cons_session_header_values - Flexible storage for header field values
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS cons_session_header_values (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL,
|
||||
field_id INTEGER NOT NULL,
|
||||
field_value TEXT,
|
||||
FOREIGN KEY (session_id) REFERENCES cons_sessions(id),
|
||||
FOREIGN KEY (field_id) REFERENCES cons_process_fields(id)
|
||||
)
|
||||
''')
|
||||
|
||||
# Note: Detail tables are created dynamically per process as cons_proc_{process_key}_details
|
||||
# They include system columns (id, session_id, scanned_by, scanned_at, duplicate_status,
|
||||
# duplicate_info, comment, is_deleted) plus custom fields defined in cons_process_fields
|
||||
|
||||
# Create Indexes
|
||||
# MASTER baseline indexes
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_baseline_master_lot ON BaselineInventory_Master(session_id, lot_number)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_baseline_master_loc ON BaselineInventory_Master(session_id, system_location)')
|
||||
|
||||
# ScanEntries indexes
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_scanentries_session ON ScanEntries(session_id)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_scanentries_location ON ScanEntries(location_count_id)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_scanentries_lot ON ScanEntries(lot_number)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_scanentries_deleted ON ScanEntries(is_deleted)')
|
||||
|
||||
# LocationCounts indexes
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_location_counts ON LocationCounts(session_id, status)')
|
||||
|
||||
# Note: No indexes on BaselineInventory_Current needed - UNIQUE constraint handles lookups
|
||||
|
||||
# Consumption Sheets indexes
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_cons_process_fields_process ON cons_process_fields(process_id, table_type)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_cons_process_fields_active ON cons_process_fields(process_id, is_active)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_cons_sessions_process ON cons_sessions(process_id, status)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_cons_sessions_user ON cons_sessions(created_by, status)')
|
||||
# Note: Detail table indexes are created dynamically when process tables are created
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f"✅ Database initialized at: {DB_PATH}")
|
||||
print("📝 Schema version: Post-migration (CURRENT baseline is global)")
|
||||
print(f"✅ Core database initialized at: {DB_PATH}")
|
||||
print("📦 Module tables will be created when modules are installed")
|
||||
|
||||
|
||||
def create_default_users():
|
||||
@@ -327,52 +123,7 @@ def create_default_users():
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_default_modules():
|
||||
"""Create default modules and assign to admin users"""
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Define default modules
|
||||
default_modules = [
|
||||
('Inventory Counts', 'counting', 'Cycle counts and physical inventory', 'fa-clipboard-check', 1, 1),
|
||||
('Consumption Sheets', 'cons_sheets', 'Production consumption tracking', 'fa-clipboard-list', 1, 2),
|
||||
]
|
||||
|
||||
# Insert modules (ignore if already exist)
|
||||
for module in default_modules:
|
||||
try:
|
||||
cursor.execute('''
|
||||
INSERT INTO Modules (module_name, module_key, description, icon, is_active, display_order)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
''', module)
|
||||
except sqlite3.IntegrityError:
|
||||
pass # Module already exists
|
||||
|
||||
conn.commit()
|
||||
|
||||
# Auto-assign all modules to owner and admin users
|
||||
cursor.execute('SELECT user_id FROM Users WHERE role IN ("owner", "admin")')
|
||||
admin_users = cursor.fetchall()
|
||||
|
||||
cursor.execute('SELECT module_id FROM Modules')
|
||||
all_modules = cursor.fetchall()
|
||||
|
||||
for user in admin_users:
|
||||
for module in all_modules:
|
||||
try:
|
||||
cursor.execute('''
|
||||
INSERT INTO UserModules (user_id, module_id)
|
||||
VALUES (?, ?)
|
||||
''', (user[0], module[0]))
|
||||
except sqlite3.IntegrityError:
|
||||
pass # Assignment already exists
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print("✅ Default modules created and assigned to admin users")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
init_database()
|
||||
create_default_users()
|
||||
create_default_modules()
|
||||
|
||||
BIN
database/scanlook.db.backup_before_modular
Normal file
BIN
database/scanlook.db.backup_before_modular
Normal file
Binary file not shown.
158
migrations.py
158
migrations.py
@@ -1,12 +1,8 @@
|
||||
"""
|
||||
ScanLook Database Migration System
|
||||
ScanLook Core Database Migration System
|
||||
|
||||
Simple migration system that tracks and applies database changes.
|
||||
Each migration has a version number and an up() function.
|
||||
|
||||
Usage:
|
||||
from migrations import run_migrations
|
||||
run_migrations() # Call on app startup
|
||||
IMPORTANT: This file only contains CORE system migrations.
|
||||
Module-specific migrations are in each module's migrations.py file.
|
||||
"""
|
||||
|
||||
import sqlite3
|
||||
@@ -75,19 +71,13 @@ def table_exists(table):
|
||||
|
||||
|
||||
# ============================================
|
||||
# MIGRATIONS
|
||||
# CORE SYSTEM MIGRATIONS ONLY
|
||||
# ============================================
|
||||
# Add new migrations to this list.
|
||||
# Each migration is a tuple: (version, name, up_function)
|
||||
#
|
||||
# RULES:
|
||||
# - Never modify an existing migration
|
||||
# - Always add new migrations at the end with the next version number
|
||||
# - Check if changes are needed before applying (idempotent)
|
||||
# Module-specific migrations are handled by each module's migrations.py
|
||||
# ============================================
|
||||
|
||||
def migration_001_add_modules_tables():
|
||||
"""Add Modules and UserModules tables"""
|
||||
"""Add Modules and UserModules tables (if not created by init_db)"""
|
||||
conn = get_db()
|
||||
|
||||
if not table_exists('Modules'):
|
||||
@@ -141,132 +131,42 @@ def migration_002_add_usermodules_granted_columns():
|
||||
conn.close()
|
||||
|
||||
|
||||
def migration_003_add_default_modules():
|
||||
"""Add default modules if they don't exist"""
|
||||
def migration_003_add_module_registry():
|
||||
"""Add module_registry table for new module manager system"""
|
||||
conn = get_db()
|
||||
|
||||
# Check if modules exist
|
||||
existing = conn.execute('SELECT COUNT(*) as cnt FROM Modules').fetchone()
|
||||
|
||||
if existing['cnt'] == 0:
|
||||
if not table_exists('module_registry'):
|
||||
conn.execute('''
|
||||
INSERT INTO Modules (module_name, module_key, description, icon, is_active, display_order)
|
||||
VALUES ('Inventory Counts', 'counting', 'Cycle counts and physical inventory', 'fa-clipboard-check', 1, 1)
|
||||
CREATE TABLE module_registry (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
module_key TEXT UNIQUE NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
author TEXT,
|
||||
description TEXT,
|
||||
is_installed INTEGER DEFAULT 0,
|
||||
is_active INTEGER DEFAULT 0,
|
||||
installed_at TEXT,
|
||||
config_json TEXT
|
||||
)
|
||||
''')
|
||||
conn.execute('''
|
||||
INSERT INTO Modules (module_name, module_key, description, icon, is_active, display_order)
|
||||
VALUES ('Consumption Sheets', 'cons_sheets', 'Production consumption tracking', 'fa-clipboard-list', 1, 2)
|
||||
''')
|
||||
print(" Added default modules")
|
||||
print(" Created module_registry table")
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def migration_004_assign_modules_to_admins():
|
||||
"""Auto-assign all modules to owner and admin users"""
|
||||
conn = get_db()
|
||||
|
||||
# Get admin users
|
||||
admins = conn.execute('SELECT user_id FROM Users WHERE role IN ("owner", "admin")').fetchall()
|
||||
modules = conn.execute('SELECT module_id FROM Modules').fetchall()
|
||||
|
||||
for user in admins:
|
||||
for module in modules:
|
||||
try:
|
||||
conn.execute('''
|
||||
INSERT INTO UserModules (user_id, module_id)
|
||||
VALUES (?, ?)
|
||||
''', [user['user_id'], module['module_id']])
|
||||
except sqlite3.IntegrityError:
|
||||
pass # Already assigned
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(" Assigned modules to admin users")
|
||||
|
||||
|
||||
def migration_005_add_cons_process_fields_duplicate_key():
|
||||
"""Add is_duplicate_key column to cons_process_fields if missing"""
|
||||
conn = get_db()
|
||||
|
||||
if table_exists('cons_process_fields'):
|
||||
if not column_exists('cons_process_fields', 'is_duplicate_key'):
|
||||
conn.execute('ALTER TABLE cons_process_fields ADD COLUMN is_duplicate_key INTEGER DEFAULT 0')
|
||||
print(" Added is_duplicate_key column to cons_process_fields")
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def migration_006_add_is_deleted_to_locationcounts():
|
||||
"""Add is_deleted column to LocationCounts table"""
|
||||
conn = get_db()
|
||||
|
||||
if table_exists('LocationCounts'):
|
||||
if not column_exists('LocationCounts', 'is_deleted'):
|
||||
conn.execute('ALTER TABLE LocationCounts ADD COLUMN is_deleted INTEGER DEFAULT 0')
|
||||
print(" Added is_deleted column to LocationCounts")
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def migration_007_add_detail_end_row():
|
||||
"""Add detail_end_row column to cons_processes table"""
|
||||
conn = get_db()
|
||||
|
||||
if table_exists('cons_processes'):
|
||||
if not column_exists('cons_processes', 'detail_end_row'):
|
||||
conn.execute('ALTER TABLE cons_processes ADD COLUMN detail_end_row INTEGER')
|
||||
print(" Added detail_end_row column to cons_processes")
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def migration_008_add_page_height():
|
||||
"""Add page_height column to cons_processes table"""
|
||||
conn = get_db()
|
||||
|
||||
if table_exists('cons_processes'):
|
||||
if not column_exists('cons_processes', 'page_height'):
|
||||
conn.execute('ALTER TABLE cons_processes ADD COLUMN page_height INTEGER')
|
||||
print(" Added page_height column to cons_processes")
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def migration_009_add_print_columns():
|
||||
"""Add print_start_col and print_end_col to cons_processes"""
|
||||
conn = get_db()
|
||||
if table_exists('cons_processes'):
|
||||
if not column_exists('cons_processes', 'print_start_col'):
|
||||
conn.execute('ALTER TABLE cons_processes ADD COLUMN print_start_col TEXT DEFAULT "A"')
|
||||
print(" Added print_start_col")
|
||||
if not column_exists('cons_processes', 'print_end_col'):
|
||||
conn.execute('ALTER TABLE cons_processes ADD COLUMN print_end_col TEXT')
|
||||
print(" Added print_end_col")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
# List of all migrations in order
|
||||
# List of CORE migrations only
|
||||
MIGRATIONS = [
|
||||
(1, 'add_modules_tables', migration_001_add_modules_tables),
|
||||
(2, 'add_usermodules_granted_columns', migration_002_add_usermodules_granted_columns),
|
||||
(3, 'add_default_modules', migration_003_add_default_modules),
|
||||
(4, 'assign_modules_to_admins', migration_004_assign_modules_to_admins),
|
||||
(5, 'add_cons_process_fields_duplicate_key', migration_005_add_cons_process_fields_duplicate_key),
|
||||
(6, 'add_is_deleted_to_locationcounts', migration_006_add_is_deleted_to_locationcounts),
|
||||
(7, 'add_detail_end_row', migration_007_add_detail_end_row),
|
||||
(8, 'add_page_height', migration_008_add_page_height),
|
||||
(9, 'add_print_columns', migration_009_add_print_columns),
|
||||
(3, 'add_module_registry', migration_003_add_module_registry),
|
||||
]
|
||||
|
||||
|
||||
def run_migrations():
|
||||
"""Run all pending migrations"""
|
||||
print("🔄 Checking database migrations...")
|
||||
"""Run all pending core migrations"""
|
||||
print("🔄 Checking core database migrations...")
|
||||
|
||||
# Make sure migrations table exists
|
||||
init_migrations_table()
|
||||
@@ -278,10 +178,10 @@ def run_migrations():
|
||||
pending = [(v, n, f) for v, n, f in MIGRATIONS if v not in applied]
|
||||
|
||||
if not pending:
|
||||
print("✅ Database is up to date")
|
||||
print("✅ Core database is up to date")
|
||||
return
|
||||
|
||||
print(f"📦 Running {len(pending)} migration(s)...")
|
||||
print(f"📦 Running {len(pending)} core migration(s)...")
|
||||
|
||||
for version, name, func in pending:
|
||||
print(f"\n Migration {version}: {name}")
|
||||
@@ -293,7 +193,7 @@ def run_migrations():
|
||||
print(f" ❌ Migration {version} failed: {e}")
|
||||
raise
|
||||
|
||||
print("\n✅ All migrations complete")
|
||||
print("\n✅ All core migrations complete")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
370
module_manager.py
Normal file
370
module_manager.py
Normal file
@@ -0,0 +1,370 @@
|
||||
"""
|
||||
ScanLook Module Manager
|
||||
Handles module discovery, installation, uninstallation, and activation
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import sqlite3
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Optional
|
||||
|
||||
|
||||
MODULES_DIR = Path(__file__).parent / 'modules'
|
||||
DB_PATH = Path(__file__).parent / 'database' / 'scanlook.db'
|
||||
|
||||
|
||||
def get_db():
|
||||
"""Get database connection (standalone, no Flask context needed)"""
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
|
||||
def query_db(query, args=(), one=False):
|
||||
"""Query database and return results"""
|
||||
conn = get_db()
|
||||
cur = conn.execute(query, args)
|
||||
rv = cur.fetchall()
|
||||
conn.close()
|
||||
return (rv[0] if rv else None) if one else rv
|
||||
|
||||
|
||||
def execute_db(query, args=()):
|
||||
"""Execute database command and return lastrowid"""
|
||||
conn = get_db()
|
||||
cur = conn.execute(query, args)
|
||||
conn.commit()
|
||||
last_id = cur.lastrowid
|
||||
conn.close()
|
||||
return last_id
|
||||
|
||||
|
||||
class ModuleManager:
|
||||
"""Manages ScanLook modules"""
|
||||
|
||||
def __init__(self):
|
||||
self.modules_dir = MODULES_DIR
|
||||
self._ensure_modules_table()
|
||||
|
||||
def _ensure_modules_table(self):
|
||||
"""Ensure the module_registry table exists in the database"""
|
||||
conn = get_db()
|
||||
conn.execute('''
|
||||
CREATE TABLE IF NOT EXISTS module_registry (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
module_key TEXT UNIQUE NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
author TEXT,
|
||||
description TEXT,
|
||||
is_installed INTEGER DEFAULT 0,
|
||||
is_active INTEGER DEFAULT 0,
|
||||
installed_at TEXT,
|
||||
config_json TEXT
|
||||
)
|
||||
''')
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def scan_available_modules(self) -> List[Dict]:
|
||||
"""
|
||||
Scan the /modules directory for available modules.
|
||||
Returns list of module info dicts from manifest.json files.
|
||||
"""
|
||||
available = []
|
||||
|
||||
if not self.modules_dir.exists():
|
||||
return available
|
||||
|
||||
for item in self.modules_dir.iterdir():
|
||||
if not item.is_dir():
|
||||
continue
|
||||
|
||||
manifest_path = item / 'manifest.json'
|
||||
if not manifest_path.exists():
|
||||
continue
|
||||
|
||||
try:
|
||||
with open(manifest_path, 'r') as f:
|
||||
manifest = json.load(f)
|
||||
|
||||
# Validate required fields
|
||||
required = ['module_key', 'name', 'version', 'author', 'description']
|
||||
if not all(field in manifest for field in required):
|
||||
print(f"⚠️ Invalid manifest in {item.name}: missing required fields")
|
||||
continue
|
||||
|
||||
# Check installation status from database
|
||||
db_module = query_db(
|
||||
'SELECT is_installed, is_active FROM module_registry WHERE module_key = ?',
|
||||
[manifest['module_key']],
|
||||
one=True
|
||||
)
|
||||
|
||||
manifest['is_installed'] = db_module['is_installed'] if db_module else False
|
||||
manifest['is_active'] = db_module['is_active'] if db_module else False
|
||||
manifest['path'] = str(item)
|
||||
|
||||
available.append(manifest)
|
||||
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"⚠️ Invalid JSON in {manifest_path}: {e}")
|
||||
continue
|
||||
except Exception as e:
|
||||
print(f"⚠️ Error reading manifest from {item.name}: {e}")
|
||||
continue
|
||||
|
||||
return sorted(available, key=lambda x: x['name'])
|
||||
|
||||
def get_module_by_key(self, module_key: str) -> Optional[Dict]:
|
||||
"""Get module info by module_key"""
|
||||
modules = self.scan_available_modules()
|
||||
for module in modules:
|
||||
if module['module_key'] == module_key:
|
||||
return module
|
||||
return None
|
||||
|
||||
def install_module(self, module_key: str) -> Dict:
|
||||
"""
|
||||
Install a module:
|
||||
1. Load manifest
|
||||
2. Run migrations (create tables)
|
||||
3. Register in database
|
||||
4. Set is_installed=1, is_active=1
|
||||
|
||||
Returns: {'success': bool, 'message': str}
|
||||
"""
|
||||
try:
|
||||
# Get module info
|
||||
module = self.get_module_by_key(module_key)
|
||||
if not module:
|
||||
return {'success': False, 'message': f'Module {module_key} not found'}
|
||||
|
||||
# Check if already installed
|
||||
if module['is_installed']:
|
||||
return {'success': False, 'message': f'Module {module_key} is already installed'}
|
||||
|
||||
# Load module's migrations
|
||||
migrations_path = Path(module['path']) / 'migrations.py'
|
||||
if not migrations_path.exists():
|
||||
return {'success': False, 'message': 'Module is missing migrations.py'}
|
||||
|
||||
# Import migrations module
|
||||
spec = importlib.util.spec_from_file_location(f"{module_key}_migrations", migrations_path)
|
||||
migrations_module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(migrations_module)
|
||||
|
||||
# Run schema installation
|
||||
print(f"\n📦 Installing module: {module['name']}")
|
||||
|
||||
conn = get_db()
|
||||
|
||||
# Execute schema SQL
|
||||
if hasattr(migrations_module, 'get_schema'):
|
||||
schema_sql = migrations_module.get_schema()
|
||||
conn.executescript(schema_sql)
|
||||
print(f" ✅ Database schema created")
|
||||
|
||||
# Run module-specific migrations
|
||||
if hasattr(migrations_module, 'get_migrations'):
|
||||
migrations = migrations_module.get_migrations()
|
||||
for version, name, func in migrations:
|
||||
print(f" Running migration {version}: {name}")
|
||||
func(conn)
|
||||
|
||||
conn.commit()
|
||||
|
||||
# Register module in database
|
||||
existing = query_db('SELECT id FROM module_registry WHERE module_key = ?', [module_key], one=True)
|
||||
|
||||
if existing:
|
||||
execute_db('''
|
||||
UPDATE module_registry
|
||||
SET name = ?, version = ?, author = ?, description = ?,
|
||||
is_installed = 1, is_active = 1, installed_at = CURRENT_TIMESTAMP
|
||||
WHERE module_key = ?
|
||||
''', [module['name'], module['version'], module['author'],
|
||||
module['description'], module_key])
|
||||
else:
|
||||
execute_db('''
|
||||
INSERT INTO module_registry (module_key, name, version, author, description,
|
||||
is_installed, is_active, installed_at)
|
||||
VALUES (?, ?, ?, ?, ?, 1, 1, CURRENT_TIMESTAMP)
|
||||
''', [module_key, module['name'], module['version'],
|
||||
module['author'], module['description']])
|
||||
|
||||
# Also register in old Modules table for compatibility
|
||||
old_module = query_db('SELECT module_id FROM Modules WHERE module_key = ?', [module_key], one=True)
|
||||
if not old_module:
|
||||
execute_db('''
|
||||
INSERT INTO Modules (module_name, module_key, description, icon, is_active)
|
||||
VALUES (?, ?, ?, ?, 1)
|
||||
''', [module['name'], module_key, module['description'], module.get('icon', '')])
|
||||
|
||||
|
||||
# Also register in old Modules table for compatibility
|
||||
old_module = query_db('SELECT module_id FROM Modules WHERE module_key = ?', [module_key], one=True)
|
||||
if not old_module:
|
||||
execute_db('''
|
||||
INSERT INTO Modules (module_name, module_key, description, is_active)
|
||||
VALUES (?, ?, ?, 1)
|
||||
''', [module['name'], module_key, module['description']])
|
||||
|
||||
conn.close()
|
||||
|
||||
print(f"✅ Module {module['name']} installed successfully")
|
||||
return {'success': True, 'message': f'Module {module["name"]} installed successfully'}
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Installation failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return {'success': False, 'message': f'Installation failed: {str(e)}'}
|
||||
|
||||
|
||||
|
||||
def uninstall_module(self, module_key: str, drop_tables: bool = True) -> Dict:
|
||||
"""
|
||||
Uninstall a module:
|
||||
1. Set is_installed=0, is_active=0 in database
|
||||
2. Optionally drop all module tables
|
||||
3. Remove from old Modules table
|
||||
|
||||
Returns: {'success': bool, 'message': str}
|
||||
"""
|
||||
try:
|
||||
module = self.get_module_by_key(module_key)
|
||||
if not module:
|
||||
return {'success': False, 'message': f'Module {module_key} not found'}
|
||||
|
||||
if not module['is_installed']:
|
||||
return {'success': False, 'message': f'Module {module_key} is not installed'}
|
||||
|
||||
print(f"\n🗑️ Uninstalling module: {module['name']}")
|
||||
|
||||
conn = get_db()
|
||||
|
||||
# Drop tables if requested
|
||||
if drop_tables:
|
||||
print(f" Dropping database tables...")
|
||||
# Load migrations to get table names
|
||||
migrations_path = Path(module['path']) / 'migrations.py'
|
||||
if migrations_path.exists():
|
||||
spec = importlib.util.spec_from_file_location(f"{module_key}_migrations", migrations_path)
|
||||
migrations_module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(migrations_module)
|
||||
|
||||
# Get schema and extract table names
|
||||
if hasattr(migrations_module, 'get_schema'):
|
||||
schema = migrations_module.get_schema()
|
||||
# Simple regex to find CREATE TABLE statements
|
||||
import re
|
||||
tables = re.findall(r'CREATE TABLE IF NOT EXISTS (\w+)', schema)
|
||||
|
||||
for table in tables:
|
||||
try:
|
||||
conn.execute(f'DROP TABLE IF EXISTS {table}')
|
||||
print(f" Dropped table: {table}")
|
||||
except Exception as e:
|
||||
print(f" Warning: Could not drop {table}: {e}")
|
||||
|
||||
# Update module_registry table
|
||||
execute_db('''
|
||||
UPDATE module_registry
|
||||
SET is_installed = 0, is_active = 0
|
||||
WHERE module_key = ?
|
||||
''', [module_key])
|
||||
|
||||
# Remove from old Modules table
|
||||
execute_db('DELETE FROM Modules WHERE module_key = ?', [module_key])
|
||||
|
||||
# Remove user module assignments
|
||||
old_module_id = query_db('SELECT module_id FROM Modules WHERE module_key = ?', [module_key], one=True)
|
||||
if old_module_id:
|
||||
execute_db('DELETE FROM UserModules WHERE module_id = ?', [old_module_id['module_id']])
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
print(f"✅ Module {module['name']} uninstalled successfully")
|
||||
return {'success': True, 'message': f'Module {module["name"]} uninstalled successfully'}
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Uninstallation failed: {e}")
|
||||
return {'success': False, 'message': f'Uninstallation failed: {str(e)}'}
|
||||
|
||||
def activate_module(self, module_key: str) -> Dict:
|
||||
"""Activate an installed module"""
|
||||
module = self.get_module_by_key(module_key)
|
||||
if not module:
|
||||
return {'success': False, 'message': f'Module {module_key} not found'}
|
||||
|
||||
if not module['is_installed']:
|
||||
return {'success': False, 'message': 'Module must be installed first'}
|
||||
|
||||
execute_db('UPDATE module_registry SET is_active = 1 WHERE module_key = ?', [module_key])
|
||||
execute_db('UPDATE Modules SET is_active = 1 WHERE module_key = ?', [module_key])
|
||||
|
||||
return {'success': True, 'message': f'Module {module["name"]} activated'}
|
||||
|
||||
def deactivate_module(self, module_key: str) -> Dict:
|
||||
"""Deactivate a module (keeps it installed)"""
|
||||
module = self.get_module_by_key(module_key)
|
||||
if not module:
|
||||
return {'success': False, 'message': f'Module {module_key} not found'}
|
||||
|
||||
execute_db('UPDATE module_registry SET is_active = 0 WHERE module_key = ?', [module_key])
|
||||
execute_db('UPDATE Modules SET is_active = 0 WHERE module_key = ?', [module_key])
|
||||
|
||||
return {'success': True, 'message': f'Module {module["name"]} deactivated'}
|
||||
|
||||
def load_active_modules(self, app):
|
||||
"""
|
||||
Load all active modules and register their blueprints with Flask app.
|
||||
Called during app startup.
|
||||
"""
|
||||
modules = self.scan_available_modules()
|
||||
active_modules = [m for m in modules if m['is_installed'] and m['is_active']]
|
||||
|
||||
print(f"\n🔌 Loading {len(active_modules)} active module(s)...")
|
||||
|
||||
for module in active_modules:
|
||||
try:
|
||||
# Import module's __init__.py
|
||||
init_path = Path(module['path']) / '__init__.py'
|
||||
if not init_path.exists():
|
||||
print(f" ⚠️ {module['name']}: Missing __init__.py")
|
||||
continue
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
f"modules.{module['module_key']}",
|
||||
init_path
|
||||
)
|
||||
module_package = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module_package)
|
||||
|
||||
# Get blueprint from create_blueprint()
|
||||
if hasattr(module_package, 'create_blueprint'):
|
||||
blueprint = module_package.create_blueprint()
|
||||
app.register_blueprint(blueprint)
|
||||
print(f" ✅ {module['name']} loaded at {module.get('routes_prefix', '/unknown')}")
|
||||
else:
|
||||
print(f" ⚠️ {module['name']}: Missing create_blueprint() function")
|
||||
|
||||
except Exception as e:
|
||||
print(f" ❌ Failed to load {module['name']}: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
print("✅ Module loading complete\n")
|
||||
|
||||
|
||||
# Global instance
|
||||
manager = ModuleManager()
|
||||
|
||||
|
||||
def get_module_manager() -> ModuleManager:
|
||||
"""Get the global module manager instance"""
|
||||
return manager
|
||||
20
modules/conssheets/__init__.py
Normal file
20
modules/conssheets/__init__.py
Normal file
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
Consumption Sheets Module
|
||||
Handles production lot tracking and consumption reporting
|
||||
"""
|
||||
from flask import Blueprint
|
||||
|
||||
def create_blueprint():
|
||||
"""Create and return the conssheets blueprint"""
|
||||
bp = Blueprint(
|
||||
'conssheets',
|
||||
__name__,
|
||||
template_folder='templates',
|
||||
url_prefix='/conssheets'
|
||||
)
|
||||
|
||||
# Import and register routes
|
||||
from .routes import register_routes
|
||||
register_routes(bp)
|
||||
|
||||
return bp
|
||||
12
modules/conssheets/manifest.json
Normal file
12
modules/conssheets/manifest.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"module_key": "conssheets",
|
||||
"name": "Consumption Sheets",
|
||||
"version": "1.0.0",
|
||||
"author": "STUFF",
|
||||
"description": "Production lot tracking and consumption reporting with Excel export",
|
||||
"icon": "fa-clipboard-list",
|
||||
"requires_roles": ["owner", "admin", "staff"],
|
||||
"routes_prefix": "/conssheets",
|
||||
"has_migrations": true,
|
||||
"dependencies": []
|
||||
}
|
||||
138
modules/conssheets/migrations.py
Normal file
138
modules/conssheets/migrations.py
Normal file
@@ -0,0 +1,138 @@
|
||||
"""
|
||||
Consumption Sheets Module - Database Migrations
|
||||
Contains schema for all consumption tracking tables
|
||||
"""
|
||||
|
||||
def get_schema():
|
||||
"""
|
||||
Returns the complete schema SQL for this module.
|
||||
This is used when the module is installed.
|
||||
"""
|
||||
return """
|
||||
-- cons_processes - Master list of consumption sheet process types
|
||||
CREATE TABLE IF NOT EXISTS cons_processes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
process_key TEXT UNIQUE NOT NULL,
|
||||
process_name TEXT NOT NULL,
|
||||
template_file BLOB,
|
||||
template_filename TEXT,
|
||||
rows_per_page INTEGER DEFAULT 30,
|
||||
detail_start_row INTEGER DEFAULT 10,
|
||||
detail_end_row INTEGER,
|
||||
page_height INTEGER,
|
||||
print_start_col TEXT DEFAULT 'A',
|
||||
print_end_col TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
created_by INTEGER NOT NULL,
|
||||
is_active INTEGER DEFAULT 1,
|
||||
FOREIGN KEY (created_by) REFERENCES Users(user_id)
|
||||
);
|
||||
|
||||
-- cons_process_fields - Custom field definitions for each process
|
||||
CREATE TABLE IF NOT EXISTS cons_process_fields (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
process_id INTEGER NOT NULL,
|
||||
table_type TEXT NOT NULL CHECK(table_type IN ('header', 'detail')),
|
||||
field_name TEXT NOT NULL,
|
||||
field_label TEXT NOT NULL,
|
||||
field_type TEXT NOT NULL CHECK(field_type IN ('TEXT', 'INTEGER', 'REAL', 'DATE', 'DATETIME')),
|
||||
max_length INTEGER,
|
||||
is_required INTEGER DEFAULT 0,
|
||||
is_duplicate_key INTEGER DEFAULT 0,
|
||||
is_active INTEGER DEFAULT 1,
|
||||
sort_order INTEGER DEFAULT 0,
|
||||
excel_cell TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (process_id) REFERENCES cons_processes(id)
|
||||
);
|
||||
|
||||
-- cons_sessions - Staff scanning sessions
|
||||
CREATE TABLE IF NOT EXISTS cons_sessions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
process_id INTEGER NOT NULL,
|
||||
created_by INTEGER NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
status TEXT DEFAULT 'active' CHECK(status IN ('active', 'archived')),
|
||||
FOREIGN KEY (process_id) REFERENCES cons_processes(id),
|
||||
FOREIGN KEY (created_by) REFERENCES Users(user_id)
|
||||
);
|
||||
|
||||
-- cons_session_header_values - Flexible storage for header field values
|
||||
CREATE TABLE IF NOT EXISTS cons_session_header_values (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL,
|
||||
field_id INTEGER NOT NULL,
|
||||
field_value TEXT,
|
||||
FOREIGN KEY (session_id) REFERENCES cons_sessions(id),
|
||||
FOREIGN KEY (field_id) REFERENCES cons_process_fields(id)
|
||||
);
|
||||
|
||||
-- Indexes
|
||||
CREATE INDEX IF NOT EXISTS idx_cons_process_fields_process ON cons_process_fields(process_id, table_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_cons_process_fields_active ON cons_process_fields(process_id, is_active);
|
||||
CREATE INDEX IF NOT EXISTS idx_cons_sessions_process ON cons_sessions(process_id, status);
|
||||
CREATE INDEX IF NOT EXISTS idx_cons_sessions_user ON cons_sessions(created_by, status);
|
||||
"""
|
||||
|
||||
|
||||
def get_migrations():
|
||||
"""
|
||||
Returns list of migrations specific to this module.
|
||||
Format: [(version, name, up_function), ...]
|
||||
"""
|
||||
|
||||
def migration_001_add_is_duplicate_key(conn):
|
||||
"""Add is_duplicate_key column to cons_process_fields"""
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Check if column exists
|
||||
cursor.execute('PRAGMA table_info(cons_process_fields)')
|
||||
columns = [row[1] for row in cursor.fetchall()]
|
||||
|
||||
if 'is_duplicate_key' not in columns:
|
||||
cursor.execute('ALTER TABLE cons_process_fields ADD COLUMN is_duplicate_key INTEGER DEFAULT 0')
|
||||
print(" Added is_duplicate_key column to cons_process_fields")
|
||||
|
||||
def migration_002_add_detail_end_row(conn):
|
||||
"""Add detail_end_row column to cons_processes"""
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('PRAGMA table_info(cons_processes)')
|
||||
columns = [row[1] for row in cursor.fetchall()]
|
||||
|
||||
if 'detail_end_row' not in columns:
|
||||
cursor.execute('ALTER TABLE cons_processes ADD COLUMN detail_end_row INTEGER')
|
||||
print(" Added detail_end_row column to cons_processes")
|
||||
|
||||
def migration_003_add_page_height(conn):
|
||||
"""Add page_height column to cons_processes"""
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('PRAGMA table_info(cons_processes)')
|
||||
columns = [row[1] for row in cursor.fetchall()]
|
||||
|
||||
if 'page_height' not in columns:
|
||||
cursor.execute('ALTER TABLE cons_processes ADD COLUMN page_height INTEGER')
|
||||
print(" Added page_height column to cons_processes")
|
||||
|
||||
def migration_004_add_print_columns(conn):
|
||||
"""Add print_start_col and print_end_col to cons_processes"""
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('PRAGMA table_info(cons_processes)')
|
||||
columns = [row[1] for row in cursor.fetchall()]
|
||||
|
||||
if 'print_start_col' not in columns:
|
||||
cursor.execute('ALTER TABLE cons_processes ADD COLUMN print_start_col TEXT DEFAULT "A"')
|
||||
print(" Added print_start_col column to cons_processes")
|
||||
|
||||
if 'print_end_col' not in columns:
|
||||
cursor.execute('ALTER TABLE cons_processes ADD COLUMN print_end_col TEXT')
|
||||
print(" Added print_end_col column to cons_processes")
|
||||
|
||||
return [
|
||||
(1, 'add_is_duplicate_key', migration_001_add_is_duplicate_key),
|
||||
(2, 'add_detail_end_row', migration_002_add_detail_end_row),
|
||||
(3, 'add_page_height', migration_003_add_page_height),
|
||||
(4, 'add_print_columns', migration_004_add_print_columns),
|
||||
]
|
||||
1246
modules/conssheets/routes.py
Normal file
1246
modules/conssheets/routes.py
Normal file
File diff suppressed because it is too large
Load Diff
@@ -5,7 +5,7 @@
|
||||
{% block content %}
|
||||
<div class="dashboard-container">
|
||||
<div class="mode-selector">
|
||||
<a href="{{ url_for('cons_sheets.process_fields', process_id=process.id) }}" class="btn btn-secondary btn-sm">
|
||||
<a href="{{ url_for('conssheets.process_fields', process_id=process.id) }}" class="btn btn-secondary btn-sm">
|
||||
<i class="fa-solid fa-arrow-left"></i> Back to Fields
|
||||
</a>
|
||||
</div>
|
||||
@@ -72,7 +72,7 @@
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<a href="{{ url_for('cons_sheets.process_fields', process_id=process.id) }}" class="btn btn-secondary">Cancel</a>
|
||||
<a href="{{ url_for('conssheets.process_fields', process_id=process.id) }}" class="btn btn-secondary">Cancel</a>
|
||||
<button type="submit" class="btn btn-primary">Add Field</button>
|
||||
</div>
|
||||
</form>
|
||||
109
modules/conssheets/templates/conssheets/admin_processes.html
Normal file
109
modules/conssheets/templates/conssheets/admin_processes.html
Normal file
@@ -0,0 +1,109 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Consumption Sheets - Admin - ScanLook{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="dashboard-container">
|
||||
<div class="dashboard-header" style="margin-top: var(--space-lg);">
|
||||
<div class="header-left" style="display: flex; align-items: center; gap: var(--space-md);">
|
||||
<a href="{{ url_for('admin_dashboard') }}" class="btn btn-secondary btn-sm">
|
||||
<i class="fa-solid fa-arrow-left"></i> Back to Admin
|
||||
</a>
|
||||
|
||||
<div>
|
||||
<h1 class="page-title" style="margin-bottom: 0;{% if showing_archived %} color: var(--color-danger);{% endif %}">
|
||||
{{ 'Archived Processes' if showing_archived else 'Consumption Sheets' }}
|
||||
</h1>
|
||||
|
||||
<p class="page-subtitle" style="margin-bottom: var(--space-xs);">Manage process types and templates</p>
|
||||
|
||||
{% if showing_archived %}
|
||||
<a href="{{ url_for('conssheets.admin_processes') }}" style="font-size: 0.85rem; color: var(--color-primary); display: inline-flex; align-items: center; gap: 6px;">
|
||||
<i class="fa-solid fa-eye"></i> Return to Active List
|
||||
</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('conssheets.admin_processes', archived=1) }}" style="font-size: 0.85rem; color: var(--color-text-muted); display: inline-flex; align-items: center; gap: 6px;">
|
||||
<i class="fa-solid fa-box-archive"></i> View Archived Processes
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a href="{{ url_for('conssheets.create_process') }}" class="btn btn-primary">
|
||||
<span class="btn-icon">+</span> New Process
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{% if processes %}
|
||||
<div class="sessions-grid">
|
||||
{% for process in processes %}
|
||||
<div class="session-card">
|
||||
<div class="session-card-header" style="display: flex; justify-content: space-between; align-items: flex-start;">
|
||||
<div>
|
||||
<h3 class="session-name">{{ process.process_name }}</h3>
|
||||
<span class="session-type-badge">
|
||||
{{ process.field_count or 0 }} fields
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{% if showing_archived %}
|
||||
<form method="POST"
|
||||
action="{{ url_for('conssheets.restore_process', process_id=process.id) }}"
|
||||
style="margin: 0;">
|
||||
<button type="submit" class="btn-icon-only" title="Restore Process" style="color: var(--color-success);">
|
||||
<i class="fa-solid fa-trash-arrow-up"></i>
|
||||
</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<form method="POST"
|
||||
action="{{ url_for('conssheets.delete_process', process_id=process.id) }}"
|
||||
onsubmit="return confirm('Are you sure you want to delete {{ process.process_name }}?');"
|
||||
style="margin: 0;">
|
||||
<button type="submit" class="btn-icon-only" title="Delete Process">
|
||||
<i class="fa-solid fa-trash"></i>
|
||||
</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="session-meta">
|
||||
<div class="meta-item">
|
||||
<span class="meta-label">Key:</span>
|
||||
<span class="meta-value" style="font-family: var(--font-mono);">{{ process.process_key }}</span>
|
||||
</div>
|
||||
<div class="meta-item">
|
||||
<span class="meta-label">Created:</span>
|
||||
<span class="meta-value">{{ process.created_at[:16] if process.created_at else 'N/A' }}</span>
|
||||
</div>
|
||||
<div class="meta-item">
|
||||
<span class="meta-label">By:</span>
|
||||
<span class="meta-value">{{ process.created_by_name or 'Unknown' }}</span>
|
||||
</div>
|
||||
<div class="meta-item">
|
||||
<span class="meta-label">Template:</span>
|
||||
<span class="meta-value">{{ '✅ Uploaded' if process.template_file else '❌ None' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="session-actions">
|
||||
<a href="{{ url_for('conssheets.process_detail', process_id=process.id) }}" class="btn btn-secondary btn-block">
|
||||
Configure
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="empty-state">
|
||||
<div class="empty-icon">📝</div>
|
||||
<h2 class="empty-title">No Processes Defined</h2>
|
||||
<p class="empty-text">Create a process type to get started (e.g., "AD WIP")</p>
|
||||
<a href="{{ url_for('conssheets.create_process') }}" class="btn btn-primary">
|
||||
Create First Process
|
||||
</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -5,7 +5,7 @@
|
||||
{% block content %}
|
||||
<div class="dashboard-container">
|
||||
<div class="mode-selector">
|
||||
<a href="{{ url_for('cons_sheets.admin_processes') }}" class="btn btn-secondary btn-sm">
|
||||
<a href="{{ url_for('conssheets.admin_processes') }}" class="btn btn-secondary btn-sm">
|
||||
<i class="fa-solid fa-arrow-left"></i> Back to Processes
|
||||
</a>
|
||||
</div>
|
||||
@@ -27,7 +27,7 @@
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<a href="{{ url_for('cons_sheets.admin_processes') }}" class="btn btn-secondary">Cancel</a>
|
||||
<a href="{{ url_for('conssheets.admin_processes') }}" class="btn btn-secondary">Cancel</a>
|
||||
<button type="submit" class="btn btn-primary">Create Process</button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -5,7 +5,7 @@
|
||||
{% block content %}
|
||||
<div class="dashboard-container">
|
||||
<div class="mode-selector">
|
||||
<a href="{{ url_for('cons_sheets.process_fields', process_id=process.id) }}" class="btn btn-secondary btn-sm">
|
||||
<a href="{{ url_for('conssheets.process_fields', process_id=process.id) }}" class="btn btn-secondary btn-sm">
|
||||
<i class="fa-solid fa-arrow-left"></i> Back to Fields
|
||||
</a>
|
||||
</div>
|
||||
@@ -71,7 +71,7 @@
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<a href="{{ url_for('cons_sheets.process_fields', process_id=process.id) }}" class="btn btn-secondary">Cancel</a>
|
||||
<a href="{{ url_for('conssheets.process_fields', process_id=process.id) }}" class="btn btn-secondary">Cancel</a>
|
||||
<button type="submit" class="btn btn-primary">Save Changes</button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -5,7 +5,7 @@
|
||||
{% block content %}
|
||||
<div class="dashboard-container">
|
||||
<div class="mode-selector">
|
||||
<a href="{{ url_for('cons_sheets.index') }}" class="btn btn-secondary btn-sm">
|
||||
<a href="{{ url_for('conssheets.index') }}" class="btn btn-secondary btn-sm">
|
||||
<i class="fa-solid fa-arrow-left"></i> Back
|
||||
</a>
|
||||
</div>
|
||||
@@ -76,7 +76,7 @@
|
||||
{% endif %}
|
||||
|
||||
<div class="form-actions">
|
||||
<a href="{{ url_for('cons_sheets.index') }}" class="btn btn-secondary">Cancel</a>
|
||||
<a href="{{ url_for('conssheets.index') }}" class="btn btn-secondary">Cancel</a>
|
||||
<button type="submit" class="btn btn-primary" {% if not header_fields %}disabled{% endif %}>
|
||||
Start Scanning
|
||||
</button>
|
||||
@@ -5,7 +5,7 @@
|
||||
{% block content %}
|
||||
<div class="dashboard-container">
|
||||
<div class="mode-selector">
|
||||
<a href="{{ url_for('cons_sheets.admin_processes') }}" class="btn btn-secondary btn-sm">
|
||||
<a href="{{ url_for('conssheets.admin_processes') }}" class="btn btn-secondary btn-sm">
|
||||
<i class="fa-solid fa-arrow-left"></i> Back to Processes
|
||||
</a>
|
||||
</div>
|
||||
@@ -38,7 +38,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a href="{{ url_for('cons_sheets.process_fields', process_id=process.id) }}" class="btn btn-primary btn-block">
|
||||
<a href="{{ url_for('conssheets.process_fields', process_id=process.id) }}" class="btn btn-primary btn-block">
|
||||
Configure Fields
|
||||
</a>
|
||||
</div>
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a href="{{ url_for('cons_sheets.process_template', process_id=process.id) }}" class="btn btn-primary btn-block">
|
||||
<a href="{{ url_for('conssheets.process_template', process_id=process.id) }}" class="btn btn-primary btn-block">
|
||||
Configure Template
|
||||
</a>
|
||||
</div>
|
||||
@@ -5,7 +5,7 @@
|
||||
{% block content %}
|
||||
<div class="dashboard-container">
|
||||
<div class="mode-selector">
|
||||
<a href="{{ url_for('cons_sheets.process_detail', process_id=process.id) }}" class="btn btn-secondary btn-sm">
|
||||
<a href="{{ url_for('conssheets.process_detail', process_id=process.id) }}" class="btn btn-secondary btn-sm">
|
||||
<i class="fa-solid fa-arrow-left"></i> Back to {{ process.process_name }}
|
||||
</a>
|
||||
</div>
|
||||
@@ -21,7 +21,7 @@
|
||||
<div class="fields-section">
|
||||
<div class="section-header">
|
||||
<h2 class="section-title">Header Fields</h2>
|
||||
<a href="{{ url_for('cons_sheets.add_field', process_id=process.id, table_type='header') }}" class="btn btn-primary btn-sm">
|
||||
<a href="{{ url_for('conssheets.add_field', process_id=process.id, table_type='header') }}" class="btn btn-primary btn-sm">
|
||||
<span class="btn-icon">+</span> Add Field
|
||||
</a>
|
||||
</div>
|
||||
@@ -48,7 +48,7 @@
|
||||
<td>{{ '✓' if field.is_required else '—' }}</td>
|
||||
<td>{{ field.excel_cell or '—' }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('cons_sheets.edit_field', process_id=process.id, field_id=field.id) }}" class="btn btn-secondary btn-sm">Edit</a>
|
||||
<a href="{{ url_for('conssheets.edit_field', process_id=process.id, field_id=field.id) }}" class="btn btn-secondary btn-sm">Edit</a>
|
||||
<button onclick="confirmDelete(this)"
|
||||
data-id="{{ field.id }}"
|
||||
data-label="{{ field.field_label }}"
|
||||
@@ -73,7 +73,7 @@
|
||||
<div class="fields-section">
|
||||
<div class="section-header">
|
||||
<h2 class="section-title">Detail Fields</h2>
|
||||
<a href="{{ url_for('cons_sheets.add_field', process_id=process.id, table_type='detail') }}" class="btn btn-primary btn-sm">
|
||||
<a href="{{ url_for('conssheets.add_field', process_id=process.id, table_type='detail') }}" class="btn btn-primary btn-sm">
|
||||
<span class="btn-icon">+</span> Add Field
|
||||
</a>
|
||||
</div>
|
||||
@@ -100,7 +100,7 @@
|
||||
<td>{{ '✓' if field.is_required else '—' }}</td>
|
||||
<td>{{ field.excel_cell or '—' }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('cons_sheets.edit_field', process_id=process.id, field_id=field.id) }}" class="btn btn-secondary btn-sm">Edit</a>
|
||||
<a href="{{ url_for('conssheets.edit_field', process_id=process.id, field_id=field.id) }}" class="btn btn-secondary btn-sm">Edit</a>
|
||||
<button onclick="confirmDelete(this)"
|
||||
data-id="{{ field.id }}"
|
||||
data-label="{{ field.field_label }}"
|
||||
@@ -156,7 +156,7 @@ function confirmDelete(btn) {
|
||||
const fieldLabel = btn.dataset.label;
|
||||
|
||||
if (confirm('Delete field "' + fieldLabel + '"?\n\nThis will soft-delete the field (data preserved but hidden).')) {
|
||||
fetch('{{ url_for("cons_sheets.delete_field", process_id=process.id, field_id=0) }}'.replace('0', fieldId), {
|
||||
fetch('{{ url_for("conssheets.delete_field", process_id=process.id, field_id=0) }}'.replace('0', fieldId), {
|
||||
method: 'POST'
|
||||
})
|
||||
.then(response => response.json())
|
||||
@@ -5,7 +5,7 @@
|
||||
{% block content %}
|
||||
<div class="dashboard-container">
|
||||
<div class="mode-selector">
|
||||
<a href="{{ url_for('cons_sheets.process_detail', process_id=process.id) }}" class="btn btn-secondary btn-sm">
|
||||
<a href="{{ url_for('conssheets.process_detail', process_id=process.id) }}" class="btn btn-secondary btn-sm">
|
||||
<i class="fa-solid fa-arrow-left"></i> Back to {{ process.process_name }}
|
||||
</a>
|
||||
</div>
|
||||
@@ -27,14 +27,14 @@
|
||||
<div class="template-info">
|
||||
<span class="template-icon">📄</span>
|
||||
<span class="template-name">{{ process.template_filename }}</span>
|
||||
<a href="{{ url_for('cons_sheets.download_template', process_id=process.id) }}" class="btn btn-secondary btn-sm">Download</a>
|
||||
<a href="{{ url_for('conssheets.download_template', process_id=process.id) }}" class="btn btn-secondary btn-sm">Download</a>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="no-template">No template uploaded yet</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<form method="POST" action="{{ url_for('cons_sheets.upload_template', process_id=process.id) }}" enctype="multipart/form-data" class="upload-form">
|
||||
<form method="POST" action="{{ url_for('conssheets.upload_template', process_id=process.id) }}" enctype="multipart/form-data" class="upload-form">
|
||||
<div class="form-group">
|
||||
<label for="template_file" class="form-label">Upload New Template</label>
|
||||
<input type="file" id="template_file" name="template_file" accept=".xlsx" class="form-input" required>
|
||||
@@ -48,7 +48,7 @@
|
||||
<div class="config-section">
|
||||
<h2 class="section-title">Page Settings</h2>
|
||||
|
||||
<form method="POST" action="{{ url_for('cons_sheets.update_template_settings', process_id=process.id) }}">
|
||||
<form method="POST" action="{{ url_for('conssheets.update_template_settings', process_id=process.id) }}">
|
||||
<div class="form-group">
|
||||
<label for="rows_per_page" class="form-label">Rows Per Page (Capacity)</label>
|
||||
<input type="number" id="rows_per_page" name="rows_per_page"
|
||||
@@ -157,12 +157,12 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<a href="{{ url_for('cons_sheets.process_fields', process_id=process.id) }}" class="btn btn-secondary" style="margin-top: var(--space-lg);">
|
||||
<a href="{{ url_for('conssheets.process_fields', process_id=process.id) }}" class="btn btn-secondary" style="margin-top: var(--space-lg);">
|
||||
Edit Field Mappings
|
||||
</a>
|
||||
{% else %}
|
||||
<div class="empty-state-small">
|
||||
<p>No fields defined yet. <a href="{{ url_for('cons_sheets.process_fields', process_id=process.id) }}">Add fields first</a>.</p>
|
||||
<p>No fields defined yet. <a href="{{ url_for('conssheets.process_fields', process_id=process.id) }}">Add fields first</a>.</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
@@ -6,7 +6,7 @@
|
||||
<div class="count-location-container">
|
||||
<div class="location-header">
|
||||
<div class="location-info">
|
||||
<a href="{{ url_for('cons_sheets.index') }}" class="breadcrumb">← Back to Sessions</a>
|
||||
<a href="{{ url_for('conssheets.index') }}" class="breadcrumb">← Back to Sessions</a>
|
||||
<div class="location-label">{{ session.process_name }}</div>
|
||||
<div class="header-values">
|
||||
{% for hv in header_values %}
|
||||
@@ -136,7 +136,7 @@
|
||||
|
||||
<div class="finish-section">
|
||||
<div class="action-buttons-row">
|
||||
<a href="{{ url_for('cons_sheets.index') }}" class="btn btn-secondary btn-block btn-lg">← Back to Sessions</a>
|
||||
<a href="{{ url_for('conssheets.index') }}" class="btn btn-secondary btn-block btn-lg">← Back to Sessions</a>
|
||||
<button class="btn btn-success btn-block btn-lg" onclick="exportToExcel()">📊 Export to Excel</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -157,12 +157,12 @@
|
||||
|
||||
<div style="margin-bottom: 30px; padding: 15px; background: var(--color-bg); border-radius: 8px;">
|
||||
<p style="font-size: 0.9rem; margin-bottom: 10px;">Step 1: Get the correct format</p>
|
||||
<a href="{{ url_for('cons_sheets.download_import_template', session_id=session['id']) }}" class="btn btn-secondary btn-sm">
|
||||
<a href="{{ url_for('conssheets.download_import_template', session_id=session['id']) }}" class="btn btn-secondary btn-sm">
|
||||
<i class="fa-solid fa-download"></i> Download Template
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<form action="{{ url_for('cons_sheets.import_session_data', session_id=session['id']) }}" method="POST" enctype="multipart/form-data">
|
||||
<form action="{{ url_for('conssheets.import_session_data', session_id=session['id']) }}" method="POST" enctype="multipart/form-data">
|
||||
<div style="margin-bottom: 20px;">
|
||||
<input type="file" name="file" accept=".xlsx" class="file-input" required style="width: 100%;">
|
||||
</div>
|
||||
@@ -226,7 +226,7 @@ document.getElementById('lotScanForm').addEventListener('submit', function(e) {
|
||||
function checkDuplicate() {
|
||||
const fieldValues = {};
|
||||
fieldValues[dupKeyFieldName] = currentDupKeyValue;
|
||||
fetch(`/cons-sheets/session/${sessionId}/scan`, {
|
||||
fetch(`/conssheets/session/${sessionId}/scan`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({ field_values: fieldValues, check_only: true })
|
||||
@@ -300,7 +300,7 @@ function submitScan() {
|
||||
if (input) fieldValues[field.field_name] = input.value;
|
||||
}
|
||||
});
|
||||
fetch(`/cons-sheets/session/${sessionId}/scan`, {
|
||||
fetch(`/conssheets/session/${sessionId}/scan`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({ field_values: fieldValues, confirm_duplicate: isDuplicateConfirmed })
|
||||
@@ -359,7 +359,7 @@ function addScanToList(detailId, fieldValues, duplicateStatus) {
|
||||
}
|
||||
|
||||
function openScanDetail(detailId) {
|
||||
fetch(`/cons-sheets/session/${sessionId}/detail/${detailId}`)
|
||||
fetch(`/conssheets/session/${sessionId}/detail/${detailId}`)
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.success) displayScanDetail(data.detail);
|
||||
@@ -413,7 +413,7 @@ function saveDetail(detailId) {
|
||||
if (input) fieldValues[field.field_name] = input.value;
|
||||
});
|
||||
const comment = document.getElementById('editComment').value;
|
||||
fetch(`/cons-sheets/session/${sessionId}/detail/${detailId}/update`, {
|
||||
fetch(`/conssheets/session/${sessionId}/detail/${detailId}/update`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({ field_values: fieldValues, comment: comment })
|
||||
@@ -427,7 +427,7 @@ function saveDetail(detailId) {
|
||||
|
||||
function deleteDetail(detailId) {
|
||||
if (!confirm('Delete this scan?')) return;
|
||||
fetch(`/cons-sheets/session/${sessionId}/detail/${detailId}/delete`, {
|
||||
fetch(`/conssheets/session/${sessionId}/detail/${detailId}/delete`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'}
|
||||
})
|
||||
@@ -439,7 +439,7 @@ function deleteDetail(detailId) {
|
||||
}
|
||||
|
||||
function exportToExcel() {
|
||||
window.location.href = `/cons-sheets/session/${sessionId}/export?format=xlsx`;
|
||||
window.location.href = `/conssheets/session/${sessionId}/export?format=xlsx`;
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', function(e) {
|
||||
@@ -17,7 +17,7 @@
|
||||
<h2 class="section-title">Start New Session</h2>
|
||||
<div class="process-buttons">
|
||||
{% for p in processes %}
|
||||
<a href="{{ url_for('cons_sheets.new_session', process_id=p.id) }}" class="btn btn-primary">
|
||||
<a href="{{ url_for('conssheets.new_session', process_id=p.id) }}" class="btn btn-primary">
|
||||
<span class="btn-icon">+</span> {{ p.process_name }}
|
||||
</a>
|
||||
{% endfor %}
|
||||
@@ -34,7 +34,7 @@
|
||||
<div class="sessions-list">
|
||||
{% for s in sessions %}
|
||||
<div class="session-list-item-container">
|
||||
<a href="{{ url_for('cons_sheets.scan_session', session_id=s.id) }}" class="session-list-item">
|
||||
<a href="{{ url_for('conssheets.scan_session', session_id=s.id) }}" class="session-list-item">
|
||||
<div class="session-list-info">
|
||||
<h3 class="session-list-name">{{ s.process_name }}</h3>
|
||||
<div class="session-list-meta">
|
||||
20
modules/invcount/__init__.py
Normal file
20
modules/invcount/__init__.py
Normal file
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
Inventory Counts Module
|
||||
Handles cycle counting and physical inventory workflows
|
||||
"""
|
||||
from flask import Blueprint
|
||||
|
||||
def create_blueprint():
|
||||
"""Create and return the invcount blueprint"""
|
||||
bp = Blueprint(
|
||||
'invcount',
|
||||
__name__,
|
||||
template_folder='templates',
|
||||
url_prefix='/invcount'
|
||||
)
|
||||
|
||||
# Import and register routes
|
||||
from .routes import register_routes
|
||||
register_routes(bp)
|
||||
|
||||
return bp
|
||||
12
modules/invcount/manifest.json
Normal file
12
modules/invcount/manifest.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"module_key": "invcount",
|
||||
"name": "Inventory Counts",
|
||||
"version": "1.0.0",
|
||||
"author": "STUFF",
|
||||
"description": "Cycle Counts and Physical Inventory",
|
||||
"icon": "fa-clipboard-check",
|
||||
"requires_roles": ["owner", "admin", "staff"],
|
||||
"routes_prefix": "/invcount",
|
||||
"has_migrations": true,
|
||||
"dependencies": []
|
||||
}
|
||||
158
modules/invcount/migrations.py
Normal file
158
modules/invcount/migrations.py
Normal file
@@ -0,0 +1,158 @@
|
||||
"""
|
||||
Inventory Counts Module - Database Migrations
|
||||
Contains schema for all inventory counting tables
|
||||
"""
|
||||
|
||||
def get_schema():
|
||||
"""
|
||||
Returns the complete schema SQL for this module.
|
||||
This is used when the module is installed.
|
||||
"""
|
||||
return """
|
||||
-- CountSessions Table
|
||||
CREATE TABLE IF NOT EXISTS CountSessions (
|
||||
session_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_name TEXT NOT NULL,
|
||||
session_type TEXT NOT NULL CHECK(session_type IN ('cycle_count', 'full_physical')),
|
||||
created_by INTEGER NOT NULL,
|
||||
created_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
master_baseline_timestamp DATETIME,
|
||||
current_baseline_timestamp DATETIME,
|
||||
status TEXT DEFAULT 'active' CHECK(status IN ('active', 'completed', 'archived')),
|
||||
branch TEXT DEFAULT 'Main',
|
||||
FOREIGN KEY (created_by) REFERENCES Users(user_id)
|
||||
);
|
||||
|
||||
-- BaselineInventory_Master Table (Session-specific, immutable)
|
||||
CREATE TABLE IF NOT EXISTS BaselineInventory_Master (
|
||||
baseline_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL,
|
||||
lot_number TEXT NOT NULL,
|
||||
item TEXT NOT NULL,
|
||||
description TEXT,
|
||||
system_location TEXT NOT NULL,
|
||||
system_bin TEXT NOT NULL,
|
||||
system_quantity REAL NOT NULL,
|
||||
uploaded_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (session_id) REFERENCES CountSessions(session_id)
|
||||
);
|
||||
|
||||
-- BaselineInventory_Current Table (GLOBAL - shared across all sessions)
|
||||
CREATE TABLE IF NOT EXISTS BaselineInventory_Current (
|
||||
current_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
lot_number TEXT NOT NULL,
|
||||
item TEXT NOT NULL,
|
||||
description TEXT,
|
||||
system_location TEXT,
|
||||
system_bin TEXT NOT NULL,
|
||||
system_quantity REAL NOT NULL,
|
||||
upload_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(lot_number, system_bin)
|
||||
);
|
||||
|
||||
-- LocationCounts Table
|
||||
CREATE TABLE IF NOT EXISTS LocationCounts (
|
||||
location_count_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL,
|
||||
location_name TEXT NOT NULL,
|
||||
counted_by INTEGER NOT NULL,
|
||||
start_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
end_timestamp DATETIME,
|
||||
status TEXT DEFAULT 'not_started' CHECK(status IN ('not_started', 'in_progress', 'completed')),
|
||||
expected_lots_master INTEGER DEFAULT 0,
|
||||
lots_found INTEGER DEFAULT 0,
|
||||
lots_missing INTEGER DEFAULT 0,
|
||||
is_deleted INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (session_id) REFERENCES CountSessions(session_id),
|
||||
FOREIGN KEY (counted_by) REFERENCES Users(user_id)
|
||||
);
|
||||
|
||||
-- ScanEntries Table
|
||||
CREATE TABLE IF NOT EXISTS ScanEntries (
|
||||
entry_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL,
|
||||
location_count_id INTEGER NOT NULL,
|
||||
lot_number TEXT NOT NULL,
|
||||
item TEXT,
|
||||
description TEXT,
|
||||
scanned_location TEXT NOT NULL,
|
||||
actual_weight REAL NOT NULL,
|
||||
scanned_by INTEGER NOT NULL,
|
||||
scan_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
-- MASTER baseline comparison
|
||||
master_status TEXT CHECK(master_status IN ('match', 'wrong_location', 'ghost_lot', 'missing')),
|
||||
master_expected_location TEXT,
|
||||
master_expected_weight REAL,
|
||||
master_variance_lbs REAL,
|
||||
master_variance_pct REAL,
|
||||
|
||||
-- Duplicate detection
|
||||
duplicate_status TEXT DEFAULT '00' CHECK(duplicate_status IN ('00', '01', '03', '04')),
|
||||
duplicate_info TEXT,
|
||||
|
||||
-- Metadata
|
||||
comment TEXT,
|
||||
is_deleted INTEGER DEFAULT 0,
|
||||
deleted_by INTEGER,
|
||||
deleted_timestamp DATETIME,
|
||||
modified_timestamp DATETIME,
|
||||
|
||||
FOREIGN KEY (session_id) REFERENCES CountSessions(session_id),
|
||||
FOREIGN KEY (location_count_id) REFERENCES LocationCounts(location_count_id),
|
||||
FOREIGN KEY (scanned_by) REFERENCES Users(user_id),
|
||||
FOREIGN KEY (deleted_by) REFERENCES Users(user_id)
|
||||
);
|
||||
|
||||
-- MissingLots Table
|
||||
CREATE TABLE IF NOT EXISTS MissingLots (
|
||||
missing_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL,
|
||||
location_count_id INTEGER,
|
||||
lot_number TEXT NOT NULL,
|
||||
item TEXT,
|
||||
master_expected_location TEXT NOT NULL,
|
||||
master_expected_quantity REAL NOT NULL,
|
||||
current_system_location TEXT,
|
||||
current_system_quantity REAL,
|
||||
marked_by INTEGER NOT NULL,
|
||||
marked_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
found_later TEXT DEFAULT 'N' CHECK(found_later IN ('Y', 'N')),
|
||||
found_location TEXT,
|
||||
FOREIGN KEY (session_id) REFERENCES CountSessions(session_id),
|
||||
FOREIGN KEY (location_count_id) REFERENCES LocationCounts(location_count_id),
|
||||
FOREIGN KEY (marked_by) REFERENCES Users(user_id)
|
||||
);
|
||||
|
||||
-- Indexes
|
||||
CREATE INDEX IF NOT EXISTS idx_baseline_master_lot ON BaselineInventory_Master(session_id, lot_number);
|
||||
CREATE INDEX IF NOT EXISTS idx_baseline_master_loc ON BaselineInventory_Master(session_id, system_location);
|
||||
CREATE INDEX IF NOT EXISTS idx_scanentries_session ON ScanEntries(session_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_scanentries_location ON ScanEntries(location_count_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_scanentries_lot ON ScanEntries(lot_number);
|
||||
CREATE INDEX IF NOT EXISTS idx_scanentries_deleted ON ScanEntries(is_deleted);
|
||||
CREATE INDEX IF NOT EXISTS idx_location_counts ON LocationCounts(session_id, status);
|
||||
"""
|
||||
|
||||
|
||||
def get_migrations():
|
||||
"""
|
||||
Returns list of migrations specific to this module.
|
||||
Format: [(version, name, up_function), ...]
|
||||
"""
|
||||
|
||||
def migration_001_add_is_deleted_to_locationcounts(conn):
|
||||
"""Add is_deleted column to LocationCounts table"""
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Check if column exists
|
||||
cursor.execute('PRAGMA table_info(LocationCounts)')
|
||||
columns = [row[1] for row in cursor.fetchall()]
|
||||
|
||||
if 'is_deleted' not in columns:
|
||||
cursor.execute('ALTER TABLE LocationCounts ADD COLUMN is_deleted INTEGER DEFAULT 0')
|
||||
print(" Added is_deleted column to LocationCounts")
|
||||
|
||||
return [
|
||||
(1, 'add_is_deleted_to_locationcounts', migration_001_add_is_deleted_to_locationcounts),
|
||||
]
|
||||
1391
modules/invcount/routes.py
Normal file
1391
modules/invcount/routes.py
Normal file
File diff suppressed because it is too large
Load Diff
@@ -19,7 +19,7 @@
|
||||
<input type="checkbox" id="showArchived" {% if show_archived %}checked{% endif %} onchange="toggleArchived()">
|
||||
<span class="filter-label">Show Archived</span>
|
||||
</label>
|
||||
<a href="{{ url_for('sessions.create_session') }}" class="btn btn-primary">
|
||||
<a href="{{ url_for('invcount.create_session') }}" class="btn btn-primary">
|
||||
<span class="btn-icon">+</span> New Session
|
||||
</a>
|
||||
</div>
|
||||
@@ -66,7 +66,7 @@
|
||||
</div>
|
||||
|
||||
<div class="session-actions">
|
||||
<a href="{{ url_for('sessions.session_detail', session_id=session.session_id) }}" class="btn btn-secondary btn-block">
|
||||
<a href="{{ url_for('invcount.session_detail', session_id=session.session_id) }}" class="btn btn-secondary btn-block">
|
||||
View Details
|
||||
</a>
|
||||
</div>
|
||||
@@ -85,7 +85,7 @@
|
||||
<script>
|
||||
function toggleArchived() {
|
||||
const checked = document.getElementById('showArchived').checked;
|
||||
window.location.href = '{{ url_for("counting.admin_dashboard") }}' + (checked ? '?show_archived=1' : '');
|
||||
window.location.href = '{{ url_for("invcount.admin_dashboard") }}' + (checked ? '?show_archived=1' : '');
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -160,7 +160,7 @@
|
||||
|
||||
<div class="finish-section">
|
||||
<div class="action-buttons-row">
|
||||
<a href="{{ url_for('counting.my_counts', session_id=session_id) }}" class="btn btn-secondary btn-block btn-lg">
|
||||
<a href="{{ url_for('invcount.my_counts', session_id=session_id) }}" class="btn btn-secondary btn-block btn-lg">
|
||||
← Back to My Counts
|
||||
</a>
|
||||
{# Finish button moved to Admin Dashboard #}
|
||||
@@ -216,7 +216,7 @@ document.getElementById('lotScanForm').addEventListener('submit', function(e) {
|
||||
});
|
||||
|
||||
function checkDuplicate() {
|
||||
fetch('{{ url_for("counting.scan_lot", session_id=session_id, location_count_id=location.location_count_id) }}', {
|
||||
fetch('{{ url_for("invcount.scan_lot", session_id=session_id, location_count_id=location.location_count_id) }}', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
@@ -285,7 +285,7 @@ function submitScan(weight) {
|
||||
return;
|
||||
}
|
||||
|
||||
fetch('{{ url_for("counting.scan_lot", session_id=session_id, location_count_id=location.location_count_id) }}', {
|
||||
fetch('{{ url_for("invcount.scan_lot", session_id=session_id, location_count_id=location.location_count_id) }}', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
@@ -585,7 +585,7 @@ function deleteFromDetail(entryId) {
|
||||
function finishLocation() {
|
||||
if (!confirm('Are you finished counting this location?')) return;
|
||||
|
||||
fetch('{{ url_for("counting.finish_location", session_id=session_id, location_count_id=location.location_count_id) }}', {
|
||||
fetch('{{ url_for("invcount.finish_location", session_id=session_id, location_count_id=location.location_count_id) }}', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'}
|
||||
})
|
||||
@@ -6,7 +6,7 @@
|
||||
<div class="dashboard-container">
|
||||
<div class="page-header">
|
||||
<div>
|
||||
<a href="{{ url_for('counting.index') }}" class="breadcrumb">← Back to Sessions</a>
|
||||
<a href="{{ url_for('invcount.index') }}" class="breadcrumb">← Back to Sessions</a>
|
||||
<h1 class="page-title">My Active Counts</h1>
|
||||
<p class="page-subtitle">{{ count_session.session_name }}</p>
|
||||
{% if not count_session.master_baseline_timestamp %}
|
||||
@@ -46,7 +46,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="bin-actions">
|
||||
<a href="{{ url_for('counting.count_location', session_id=count_session.session_id, location_count_id=bin.location_count_id) }}" class="btn btn-primary btn-block">
|
||||
<a href="{{ url_for('invcount.count_location', session_id=count_session.session_id, location_count_id=bin.location_count_id) }}" class="btn btn-primary btn-block">
|
||||
Resume Counting
|
||||
</a>
|
||||
</div>
|
||||
@@ -106,7 +106,7 @@
|
||||
<button type="button" class="btn-close-modal" onclick="closeStartBinModal()">✕</button>
|
||||
</div>
|
||||
|
||||
<form id="startBinForm" action="{{ url_for('counting.start_bin_count', session_id=count_session.session_id) }}" method="POST">
|
||||
<form id="startBinForm" action="{{ url_for('invcount.start_bin_count', session_id=count_session.session_id) }}" method="POST">
|
||||
<div class="form-group">
|
||||
<label class="form-label">Bin Number *</label>
|
||||
<input type="text" name="location_name" class="form-input scan-input" required autofocus placeholder="Scan or type bin number">
|
||||
@@ -41,7 +41,7 @@
|
||||
</div>
|
||||
{% if not count_session.master_baseline_timestamp %}
|
||||
<!-- Note: Using data_imports blueprint URL -->
|
||||
<form method="POST" action="{{ url_for('data_imports.upload_master', session_id=count_session.session_id) }}" enctype="multipart/form-data" class="upload-form">
|
||||
<form method="POST" action="{{ url_for('invcount.upload_master', session_id=count_session.session_id) }}" enctype="multipart/form-data" class="upload-form">
|
||||
<input type="file" name="csv_file" accept=".csv" required class="file-input">
|
||||
<button type="submit" class="btn btn-primary btn-sm">Upload MASTER</button>
|
||||
</form>
|
||||
@@ -59,7 +59,7 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if count_session.master_baseline_timestamp %}
|
||||
<form method="POST" action="{{ url_for('data_imports.upload_current', session_id=count_session.session_id) }}" enctype="multipart/form-data" class="upload-form">
|
||||
<form method="POST" action="{{ url_for('invcount.upload_current', session_id=count_session.session_id) }}" enctype="multipart/form-data" class="upload-form">
|
||||
<input type="hidden" name="baseline_type" value="current">
|
||||
<input type="file" name="csv_file" accept=".csv" required class="file-input">
|
||||
<button type="submit" class="btn btn-secondary btn-sm">
|
||||
@@ -289,7 +289,7 @@ function showStatusDetails(status) {
|
||||
document.getElementById('statusModalTitle').textContent = titles[status] || 'Details';
|
||||
|
||||
// Fetch details using the blueprint URL structure
|
||||
fetch(`/session/${CURRENT_SESSION_ID}/status-details/${status}`)
|
||||
fetch(`/invcount/session/${CURRENT_SESSION_ID}/status-details/${status}`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
@@ -484,7 +484,7 @@ function showLocationDetails(locationCountId, locationName, status) {
|
||||
}
|
||||
|
||||
// Fetch all scans for this location
|
||||
fetch(`/location/${locationCountId}/scans`)
|
||||
fetch(`/invcount/location/${locationCountId}/scans`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
@@ -633,7 +633,7 @@ function closeFinalizeConfirm() {
|
||||
|
||||
function confirmFinalize() {
|
||||
// Correctly points to the /finish route to trigger Missing Lot calculations
|
||||
fetch(`/count/${CURRENT_SESSION_ID}/location/${currentLocationId}/finish`, {
|
||||
fetch(`/invcount/count/${CURRENT_SESSION_ID}/location/${currentLocationId}/finish`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -667,7 +667,7 @@ function closeReopenConfirm() {
|
||||
|
||||
function confirmReopen() {
|
||||
// Note: The /reopen endpoint is handled by blueprints/admin_locations.py
|
||||
fetch(`/location/${currentLocationId}/reopen`, {
|
||||
fetch(`/invcount/location/${currentLocationId}/reopen`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -700,7 +700,7 @@ document.addEventListener('keydown', function(e) {
|
||||
function archiveSession() {
|
||||
if (!confirm('Archive this session? It will be hidden from the main dashboard but can be reactivated later.')) return;
|
||||
|
||||
fetch('{{ url_for("sessions.archive_session", session_id=count_session.session_id) }}', {
|
||||
fetch('{{ url_for("invcount.archive_session", session_id=count_session.session_id) }}', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'}
|
||||
})
|
||||
@@ -717,7 +717,7 @@ function archiveSession() {
|
||||
function activateSession() {
|
||||
if (!confirm('Reactivate this session? It will appear on the main dashboard again.')) return;
|
||||
|
||||
fetch('{{ url_for("sessions.activate_session", session_id=count_session.session_id) }}', {
|
||||
fetch('{{ url_for("invcount.activate_session", session_id=count_session.session_id) }}', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'}
|
||||
})
|
||||
@@ -733,7 +733,7 @@ function activateSession() {
|
||||
|
||||
function showFinalizeAllConfirm() {
|
||||
if (confirm("⚠️ WARNING: This will finalize ALL open bins in this session and calculate missing items. This cannot be undone. Are you sure?")) {
|
||||
fetch(`/session/${CURRENT_SESSION_ID}/finalize-all`, {
|
||||
fetch(`/invcount/session/${CURRENT_SESSION_ID}/finalize-all`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'}
|
||||
})
|
||||
@@ -751,7 +751,7 @@ function showFinalizeAllConfirm() {
|
||||
|
||||
function showDeleteBinConfirm() {
|
||||
if (confirm(`⚠️ DANGER: Are you sure you want to delete ALL data for ${currentLocationName}? This will hide the bin from staff and wipe any missing lot flags.`)) {
|
||||
fetch(`/location/${currentLocationId}/delete`, {
|
||||
fetch(`/invcount/location/${currentLocationId}/delete`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
@@ -773,7 +773,7 @@ function showDeleteBinConfirm() {
|
||||
function refreshDashboardStats() {
|
||||
const sessionId = CURRENT_SESSION_ID;
|
||||
|
||||
fetch(`/session/${sessionId}/get_stats`)
|
||||
fetch(`/invcount/session/${sessionId}/get_stats`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
@@ -789,7 +789,7 @@ function refreshDashboardStats() {
|
||||
})
|
||||
.catch(err => console.error('Error refreshing stats:', err));
|
||||
|
||||
fetch(`/session/${sessionId}/active-counters-fragment`)
|
||||
fetch(`/invcount/session/${sessionId}/active-counters-fragment`)
|
||||
.then(response => response.text())
|
||||
.then(html => {
|
||||
const container = document.getElementById('active-counters-container');
|
||||
@@ -26,7 +26,7 @@
|
||||
{% if sessions %}
|
||||
<div class="sessions-list">
|
||||
{% for s in sessions %}
|
||||
<a href="{{ url_for('counting.count_session', session_id=s.session_id) }}" class="session-list-item">
|
||||
<a href="{{ url_for('invcount.count_session', session_id=s.session_id) }}" class="session-list-item">
|
||||
<div class="session-list-info">
|
||||
<h3 class="session-list-name">{{ s.session_name }}</h3>
|
||||
<span class="session-list-type">{{ 'Full Physical' if s.session_type == 'full_physical' else 'Cycle Count' }}</span>
|
||||
@@ -6,26 +6,39 @@
|
||||
<div class="dashboard-container">
|
||||
<div class="dashboard-header" style="margin-top: var(--space-lg);">
|
||||
<div class="header-left" style="display: flex; align-items: center; gap: var(--space-md);">
|
||||
<a href="{{ url_for('home') }}" class="btn btn-secondary btn-sm">
|
||||
<i class="fa-solid fa-arrow-left"></i> Back to Home
|
||||
<a href="{{ url_for('home') }}" class="btn btn-secondary btn-sm" title="Back to Home">
|
||||
<i class="fa-solid fa-house"></i>
|
||||
</a>
|
||||
<h1 class="page-title" style="margin-bottom: 0;">Admin Dashboard</h1>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="modules-section">
|
||||
<h2 class="section-title">Modules</h2>
|
||||
<div class="modules-grid">
|
||||
<a href="{{ url_for('counting.admin_dashboard') }}" class="module-card">
|
||||
<div class="module-icon">📊</div> <h3 class="module-name">Counts</h3>
|
||||
<p class="module-desc">Cycle counts & physical inventory</p>
|
||||
</a>
|
||||
|
||||
<a href="{{ url_for('cons_sheets.admin_processes') }}" class="module-card module-card-link">
|
||||
<div class="module-icon">📝</div> <h3 class="module-name">Consumption Sheets</h3>
|
||||
<p class="module-desc">Production consumption tracking</p>
|
||||
</a>
|
||||
{% if modules %}
|
||||
<div class="modules-grid">
|
||||
{% for module in modules %}
|
||||
<a href="/{{ module.module_key }}/admin" class="module-card module-card-link">
|
||||
<div class="module-icon">
|
||||
{% if module.icon %}
|
||||
<i class="fa-solid {{ module.icon }}"></i>
|
||||
{% else %}
|
||||
📦
|
||||
{% endif %}
|
||||
</div>
|
||||
<h3 class="module-name">{{ module.module_name }}</h3>
|
||||
<p class="module-desc">{{ module.description }}</p>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-info">
|
||||
<i class="fa-solid fa-info-circle"></i> No modules installed yet.
|
||||
<a href="{{ url_for('module_manager_ui') }}">Install modules</a> to get started.
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -29,8 +29,14 @@
|
||||
<div class="settings-dropdown">
|
||||
<button class="btn-settings" onclick="toggleSettings()">⚙️</button>
|
||||
<div id="settingsMenu" class="settings-menu">
|
||||
<a href="{{ url_for('admin_dashboard') }}" class="settings-item">
|
||||
<span class="settings-icon"><i class="fas fa-gauge"></i></span> Admin Dashboard
|
||||
</a>
|
||||
<a href="{{ url_for('users.manage_users') }}" class="settings-item">
|
||||
<span class="settings-icon">👥</span> Manage Users
|
||||
<span class="settings-icon"><i class="fas fa-users"></i></span> Manage Users
|
||||
</a>
|
||||
<a href="{{ url_for('module_manager_ui') }}" class="settings-item">
|
||||
<span class="settings-icon"><i class="fas fa-puzzle-piece"></i></span> Module Manager
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -18,18 +18,18 @@
|
||||
<p class="page-subtitle" style="margin-bottom: var(--space-xs);">Manage process types and templates</p>
|
||||
|
||||
{% if showing_archived %}
|
||||
<a href="{{ url_for('cons_sheets.admin_processes') }}" style="font-size: 0.85rem; color: var(--color-primary); display: inline-flex; align-items: center; gap: 6px;">
|
||||
<a href="{{ url_for('conssheets.admin_processes') }}" style="font-size: 0.85rem; color: var(--color-primary); display: inline-flex; align-items: center; gap: 6px;">
|
||||
<i class="fa-solid fa-eye"></i> Return to Active List
|
||||
</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('cons_sheets.admin_processes', archived=1) }}" style="font-size: 0.85rem; color: var(--color-text-muted); display: inline-flex; align-items: center; gap: 6px;">
|
||||
<a href="{{ url_for('conssheets.admin_processes', archived=1) }}" style="font-size: 0.85rem; color: var(--color-text-muted); display: inline-flex; align-items: center; gap: 6px;">
|
||||
<i class="fa-solid fa-box-archive"></i> View Archived Processes
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a href="{{ url_for('cons_sheets.create_process') }}" class="btn btn-primary">
|
||||
<a href="{{ url_for('conssheets.create_process') }}" class="btn btn-primary">
|
||||
<span class="btn-icon">+</span> New Process
|
||||
</a>
|
||||
</div>
|
||||
@@ -48,7 +48,7 @@
|
||||
|
||||
{% if showing_archived %}
|
||||
<form method="POST"
|
||||
action="{{ url_for('cons_sheets.restore_process', process_id=process.id) }}"
|
||||
action="{{ url_for('conssheets.restore_process', process_id=process.id) }}"
|
||||
style="margin: 0;">
|
||||
<button type="submit" class="btn-icon-only" title="Restore Process" style="color: var(--color-success);">
|
||||
<i class="fa-solid fa-trash-arrow-up"></i>
|
||||
@@ -56,7 +56,7 @@
|
||||
</form>
|
||||
{% else %}
|
||||
<form method="POST"
|
||||
action="{{ url_for('cons_sheets.delete_process', process_id=process.id) }}"
|
||||
action="{{ url_for('conssheets.delete_process', process_id=process.id) }}"
|
||||
onsubmit="return confirm('Are you sure you want to delete {{ process.process_name }}?');"
|
||||
style="margin: 0;">
|
||||
<button type="submit" class="btn-icon-only" title="Delete Process">
|
||||
@@ -86,7 +86,7 @@
|
||||
</div>
|
||||
|
||||
<div class="session-actions">
|
||||
<a href="{{ url_for('cons_sheets.process_detail', process_id=process.id) }}" class="btn btn-secondary btn-block">
|
||||
<a href="{{ url_for('conssheets.process_detail', process_id=process.id) }}" class="btn btn-secondary btn-block">
|
||||
Configure
|
||||
</a>
|
||||
</div>
|
||||
@@ -100,7 +100,7 @@
|
||||
<div class="empty-icon">📝</div>
|
||||
<h2 class="empty-title">No Processes Defined</h2>
|
||||
<p class="empty-text">Create a process type to get started (e.g., "AD WIP")</p>
|
||||
<a href="{{ url_for('cons_sheets.create_process') }}" class="btn btn-primary">
|
||||
<a href="{{ url_for('conssheets.create_process') }}" class="btn btn-primary">
|
||||
Create First Process
|
||||
</a>
|
||||
</div>
|
||||
|
||||
@@ -5,24 +5,17 @@
|
||||
{% block content %}
|
||||
<div class="dashboard-container">
|
||||
|
||||
<!-- Admin Button (only for admins/owners) -->
|
||||
{% if session.role in ['owner', 'admin'] %}
|
||||
<div class="mode-selector">
|
||||
<a href="{{ url_for('admin_dashboard') }}" class="mode-btn">
|
||||
👔 Admin Console
|
||||
</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
|
||||
<div class="dashboard-header">
|
||||
<h1 class="page-title">Welcome, {{ session.full_name }}</h1>
|
||||
<p class="page-subtitle">Select a module to get started</p>
|
||||
</div>
|
||||
<div><p class="page-subtitle">Select a module to get started</p></div>
|
||||
|
||||
{% if modules %}
|
||||
<div class="module-grid">
|
||||
{% for m in modules %}
|
||||
<a href="{{ url_for(m.module_key + '.index') }}" class="module-card">
|
||||
<a href="/{{ m.module_key }}" class="module-card">
|
||||
<div class="module-icon">
|
||||
<i class="fa-solid {{ m.icon }}"></i>
|
||||
</div>
|
||||
|
||||
866
templates/module_manager.html
Normal file
866
templates/module_manager.html
Normal file
@@ -0,0 +1,866 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Module Manager - ScanLook{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="dashboard-container">
|
||||
<div class="dashboard-header" style="display: flex; justify-content: space-between; align-items: flex-start;">
|
||||
<div>
|
||||
<h1 class="page-title"><i class="fas fa-puzzle-piece"></i> Module Manager</h1>
|
||||
<p class="page-subtitle">Install, manage, and configure ScanLook modules</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" onclick="openUploadModal()" style="margin-top: 10px;">
|
||||
<i class="fas fa-upload"></i> Upload
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{% if modules %}
|
||||
<div class="module-grid">
|
||||
{% for module in modules %}
|
||||
<div class="module-card {% if module.is_active %}module-card-active{% endif %}">
|
||||
<!-- Module Icon -->
|
||||
<div class="module-icon">
|
||||
{% if module.icon %}
|
||||
<i class="fa-solid {{ module.icon }}"></i>
|
||||
{% else %}
|
||||
<i class="fa-solid fa-cube"></i>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- Module Info -->
|
||||
<h3 class="module-name">{{ module.name }}</h3>
|
||||
<p class="module-desc">{{ module.description }}</p>
|
||||
|
||||
<!-- Module Metadata -->
|
||||
<div class="module-metadata">
|
||||
<div class="metadata-row">
|
||||
<span class="metadata-label">Version:</span>
|
||||
<span class="metadata-value">{{ module.version }}</span>
|
||||
</div>
|
||||
<div class="metadata-row">
|
||||
<span class="metadata-label">Author:</span>
|
||||
<span class="metadata-value">{{ module.author }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Status Badge -->
|
||||
<div class="module-status">
|
||||
{% if module.is_installed and module.is_active %}
|
||||
<span class="status-badge status-active">
|
||||
<i class="fas fa-check-circle"></i> Active
|
||||
</span>
|
||||
{% elif module.is_installed %}
|
||||
<span class="status-badge status-inactive">
|
||||
<i class="fas fa-pause-circle"></i> Inactive
|
||||
</span>
|
||||
{% else %}
|
||||
<span class="status-badge status-not-installed">
|
||||
<i class="fas fa-times-circle"></i> Not Installed
|
||||
</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- Action Buttons -->
|
||||
<div class="module-actions">
|
||||
{% if not module.is_installed %}
|
||||
<!-- Not Installed: Show Install Button -->
|
||||
<button class="btn btn-primary btn-block" onclick="installModule('{{ module.module_key }}')">
|
||||
<i class="fas fa-download"></i> Install Module
|
||||
</button>
|
||||
|
||||
{% elif module.is_active %}
|
||||
<!-- Active: Show Deactivate and Uninstall -->
|
||||
<button class="btn btn-warning btn-block" onclick="deactivateModule('{{ module.module_key }}')">
|
||||
<i class="fas fa-pause"></i> Deactivate
|
||||
</button>
|
||||
<button class="btn btn-danger btn-block" onclick="uninstallModule('{{ module.module_key }}', '{{ module.name }}')">
|
||||
<i class="fas fa-trash"></i> Uninstall
|
||||
</button>
|
||||
|
||||
{% else %}
|
||||
<!-- Installed but Inactive: Show Activate and Uninstall -->
|
||||
<button class="btn btn-success btn-block" onclick="activateModule('{{ module.module_key }}')">
|
||||
<i class="fas fa-play"></i> Activate
|
||||
</button>
|
||||
<button class="btn btn-danger btn-block" onclick="uninstallModule('{{ module.module_key }}', '{{ module.name }}')">
|
||||
<i class="fas fa-trash"></i> Uninstall
|
||||
</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="empty-state">
|
||||
<div class="empty-icon"><i class="fas fa-puzzle-piece"></i></div>
|
||||
<h2 class="empty-title">No Modules Found</h2>
|
||||
<p class="empty-text">No modules found in the <code>/modules</code> directory.</p>
|
||||
<p class="empty-text">Upload a module package to get started.</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Module Manager Specific Styles */
|
||||
.module-metadata {
|
||||
margin: var(--space-md) 0;
|
||||
padding: var(--space-sm) 0;
|
||||
border-top: 1px solid var(--border-color);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.metadata-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 4px 0;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.metadata-label {
|
||||
color: var(--text-muted);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.metadata-value {
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.module-status {
|
||||
margin: var(--space-sm) 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 16px;
|
||||
border-radius: 20px;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.status-active {
|
||||
background: rgba(40, 167, 69, 0.2);
|
||||
color: #28a745;
|
||||
border: 1px solid #28a745;
|
||||
}
|
||||
|
||||
.status-inactive {
|
||||
background: rgba(255, 193, 7, 0.2);
|
||||
color: #ffc107;
|
||||
border: 1px solid #ffc107;
|
||||
}
|
||||
|
||||
.status-not-installed {
|
||||
background: rgba(108, 117, 125, 0.2);
|
||||
color: #6c757d;
|
||||
border: 1px solid #6c757d;
|
||||
}
|
||||
|
||||
.module-actions {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: var(--space-sm);
|
||||
margin-top: auto;
|
||||
}
|
||||
|
||||
.module-actions .btn {
|
||||
flex: 1;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* Override for active module cards */
|
||||
.module-card-active {
|
||||
border-color: var(--success-color);
|
||||
box-shadow: 0 4px 12px rgba(40, 167, 69, 0.15);
|
||||
}
|
||||
|
||||
.module-card-active .module-icon {
|
||||
background: linear-gradient(135deg, rgba(40, 167, 69, 0.2), rgba(40, 167, 69, 0.1));
|
||||
color: var(--success-color);
|
||||
}
|
||||
|
||||
/* Make module cards compact */
|
||||
.module-grid .module-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: var(--space-md);
|
||||
gap: var(--space-xs);
|
||||
}
|
||||
|
||||
.module-grid .module-icon {
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
font-size: 1.5rem;
|
||||
margin: 0 auto var(--space-xs);
|
||||
}
|
||||
|
||||
.module-grid .module-name {
|
||||
margin: var(--space-xs) 0;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.module-grid .module-desc {
|
||||
flex-grow: 0;
|
||||
margin: 0 0 var(--space-xs) 0;
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.module-metadata {
|
||||
margin: var(--space-xs) 0;
|
||||
padding: var(--space-xs) 0;
|
||||
}
|
||||
|
||||
.metadata-row {
|
||||
padding: 2px 0;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
.module-status {
|
||||
margin: var(--space-xs) 0;
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
padding: 4px 12px;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.module-actions {
|
||||
margin-top: var(--space-xs);
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// Keep all your existing JavaScript functions exactly as they are
|
||||
function installModule(moduleKey) {
|
||||
if (!confirm(`Install module "${moduleKey}"?\n\nThis will create database tables and activate the module.`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
fetch(`/admin/modules/${moduleKey}/install`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
if (data.restart_required) {
|
||||
alert(`✅ ${data.message}\n\nServer will restart automatically...`);
|
||||
restartServerSilent();
|
||||
} else {
|
||||
alert(`✅ ${data.message}`);
|
||||
location.reload();
|
||||
}
|
||||
} else {
|
||||
alert(`❌ ${data.message}`);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
alert(`❌ Error: ${error}`);
|
||||
});
|
||||
}
|
||||
|
||||
function restartServerSilent() {
|
||||
fetch('/admin/restart', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
document.body.innerHTML = `
|
||||
<div style="display: flex; align-items: center; justify-content: center; height: 100vh; flex-direction: column; background: #1a1a1a; color: white;">
|
||||
<div style="font-size: 48px; margin-bottom: 20px;">🔄</div>
|
||||
<h1>Server Restarting...</h1>
|
||||
<p>Module installed successfully. Please wait...</p>
|
||||
</div>
|
||||
`;
|
||||
setTimeout(() => {
|
||||
location.reload();
|
||||
}, 3000);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
alert(`❌ Restart failed: ${error}\n\nPlease restart manually.`);
|
||||
});
|
||||
}
|
||||
|
||||
function uninstallModule(moduleKey, moduleName) {
|
||||
const stage1Modal = `
|
||||
<div id="uninstall-modal-stage1" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.8); display: flex; align-items: center; justify-content: center; z-index: 9999;">
|
||||
<div style="background: #1a1a1a; border: 2px solid #ffc107; border-radius: 8px; padding: 30px; max-width: 500px; color: white;">
|
||||
<h2 style="color: #ffc107; margin-top: 0;">⚠️ Uninstall Module?</h2>
|
||||
<p style="margin: 20px 0; font-size: 18px;">Module: <strong>${moduleName}</strong></p>
|
||||
<p style="margin: 20px 0;">This will:</p>
|
||||
<ul style="margin: 20px 0; padding-left: 20px;">
|
||||
<li>Deactivate the module</li>
|
||||
<li>Remove it from the system</li>
|
||||
<li>Users will lose access</li>
|
||||
<li style="color: #dc3545; font-weight: bold;">DELETE ALL DATA PERMANENTLY</li>
|
||||
</ul>
|
||||
<p style="margin: 20px 0; background: #2d2d2d; padding: 15px; border-radius: 4px; color: #28a745;">
|
||||
💡 <strong>Want to keep the data?</strong><br>
|
||||
Use "Deactivate" instead of "Uninstall"
|
||||
</p>
|
||||
<div style="display: flex; gap: 10px; margin-top: 20px;">
|
||||
<button onclick="cancelUninstall()" style="flex: 1; padding: 12px; background: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; font-weight: bold;">
|
||||
Cancel
|
||||
</button>
|
||||
<button onclick="proceedToStage2('${moduleKey}', '${moduleName}')" style="flex: 1; padding: 12px; background: #ffc107; color: #1a1a1a; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; font-weight: bold;">
|
||||
Continue
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
document.body.insertAdjacentHTML('beforeend', stage1Modal);
|
||||
}
|
||||
|
||||
function proceedToStage2(moduleKey, moduleName) {
|
||||
document.getElementById('uninstall-modal-stage1').remove();
|
||||
|
||||
const stage2Modal = `
|
||||
<div id="uninstall-modal-stage2" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.85); display: flex; align-items: center; justify-content: center; z-index: 9999;">
|
||||
<div style="background: #1a1a1a; border: 3px solid #dc3545; border-radius: 8px; padding: 30px; max-width: 550px; color: white;">
|
||||
<h2 style="color: #dc3545; margin-top: 0;">🚨 Data Will Be Deleted</h2>
|
||||
<p style="margin: 20px 0; font-size: 18px;">Module: <strong>${moduleName}</strong></p>
|
||||
<div style="background: #2d2d2d; padding: 20px; border-radius: 4px; margin: 20px 0; border-left: 4px solid #dc3545;">
|
||||
<p style="margin: 0 0 15px 0; color: #dc3545; font-weight: bold; font-size: 16px;">⚠️ This will permanently delete:</p>
|
||||
<ul style="margin: 10px 0; color: #fff; line-height: 1.8;">
|
||||
<li>All sessions</li>
|
||||
<li>All scans and entries</li>
|
||||
<li>All locations</li>
|
||||
<li>All historical data</li>
|
||||
<li>All database tables</li>
|
||||
</ul>
|
||||
<p style="margin: 15px 0 0 0; color: #dc3545; font-weight: bold; font-size: 18px;">THIS CANNOT BE UNDONE!</p>
|
||||
</div>
|
||||
<p style="margin: 20px 0; color: #ffc107; text-align: center; font-weight: bold;">
|
||||
Are you absolutely sure you want to proceed?
|
||||
</p>
|
||||
<div style="display: flex; gap: 10px; margin-top: 20px;">
|
||||
<button onclick="cancelUninstall()" style="flex: 1; padding: 14px; background: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; font-weight: bold;">
|
||||
✓ Cancel (Safe)
|
||||
</button>
|
||||
<button onclick="proceedToStage3('${moduleKey}', '${moduleName}')" style="flex: 1; padding: 14px; background: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; font-weight: bold;">
|
||||
Yes, Continue
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
document.body.insertAdjacentHTML('beforeend', stage2Modal);
|
||||
}
|
||||
|
||||
function proceedToStage3(moduleKey, moduleName) {
|
||||
document.getElementById('uninstall-modal-stage2').remove();
|
||||
|
||||
const stage3Modal = `
|
||||
<div id="uninstall-modal-stage3" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.95); display: flex; align-items: center; justify-content: center; z-index: 9999;">
|
||||
<div style="background: #1a1a1a; border: 4px solid #dc3545; border-radius: 8px; padding: 35px; max-width: 500px; color: white; box-shadow: 0 0 30px rgba(220, 53, 69, 0.5);">
|
||||
<h2 style="color: #dc3545; margin-top: 0; text-align: center;">🚨 FINAL WARNING 🚨</h2>
|
||||
<p style="margin: 25px 0; font-size: 18px; text-align: center;">Module: <strong>${moduleName}</strong></p>
|
||||
<div style="background: #dc3545; color: white; padding: 20px; border-radius: 4px; margin: 25px 0; text-align: center;">
|
||||
<p style="margin: 0; font-weight: bold; font-size: 20px;">
|
||||
ALL DATA WILL BE<br>PERMANENTLY DELETED
|
||||
</p>
|
||||
</div>
|
||||
<p style="margin: 25px 0; text-align: center; font-size: 15px;">
|
||||
This is your <strong style="color: #dc3545;">LAST CHANCE</strong> to cancel.
|
||||
</p>
|
||||
<p style="margin: 20px 0; font-weight: bold;">Type <span style="color: #dc3545; font-size: 18px;">DELETE</span> to confirm:</p>
|
||||
<input type="text" id="delete-confirmation-text" placeholder="Type DELETE here" style="width: 100%; padding: 14px; font-size: 18px; border: 3px solid #dc3545; border-radius: 4px; background: #2d2d2d; color: white; box-sizing: border-box; text-align: center; font-weight: bold;" autocomplete="off">
|
||||
<p id="delete-text-error" style="color: #dc3545; margin: 10px 0; text-align: center; font-weight: bold; display: none;">❌ You must type DELETE exactly</p>
|
||||
<div style="display: flex; gap: 10px; margin-top: 25px;">
|
||||
<button onclick="cancelUninstall()" style="flex: 1; padding: 14px; background: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 17px; font-weight: bold;">
|
||||
✓ Cancel (Safe)
|
||||
</button>
|
||||
<button onclick="finalUninstall('${moduleKey}', '${moduleName}')" style="flex: 1; padding: 14px; background: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 17px; font-weight: bold;">
|
||||
Delete Everything
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
document.body.insertAdjacentHTML('beforeend', stage3Modal);
|
||||
setTimeout(() => document.getElementById('delete-confirmation-text').focus(), 100);
|
||||
}
|
||||
|
||||
function cancelUninstall() {
|
||||
['uninstall-modal-stage1', 'uninstall-modal-stage2', 'uninstall-modal-stage3'].forEach(id => {
|
||||
const modal = document.getElementById(id);
|
||||
if (modal) modal.remove();
|
||||
});
|
||||
}
|
||||
|
||||
function finalUninstall(moduleKey, moduleName) {
|
||||
const confirmText = document.getElementById('delete-confirmation-text').value;
|
||||
|
||||
if (confirmText !== 'DELETE') {
|
||||
document.getElementById('delete-text-error').style.display = 'block';
|
||||
document.getElementById('delete-confirmation-text').style.borderColor = '#ff0000';
|
||||
document.getElementById('delete-confirmation-text').style.boxShadow = '0 0 10px rgba(255, 0, 0, 0.5)';
|
||||
document.getElementById('delete-confirmation-text').focus();
|
||||
return;
|
||||
}
|
||||
|
||||
document.getElementById('uninstall-modal-stage3').remove();
|
||||
|
||||
fetch(`/admin/modules/${moduleKey}/uninstall`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
alert(`✅ ${data.message}\n\nAll data has been permanently deleted.\n\nPlease reload the page.`);
|
||||
location.reload();
|
||||
} else {
|
||||
alert(`❌ ${data.message}`);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
alert(`❌ Error: ${error}`);
|
||||
});
|
||||
}
|
||||
|
||||
function activateModule(moduleKey) {
|
||||
fetch(`/admin/modules/${moduleKey}/activate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
alert(`✅ ${data.message}\n\nPlease reload the page.`);
|
||||
location.reload();
|
||||
} else {
|
||||
alert(`❌ ${data.message}`);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
alert(`❌ Error: ${error}`);
|
||||
});
|
||||
}
|
||||
|
||||
function deactivateModule(moduleKey) {
|
||||
if (!confirm(`Deactivate module "${moduleKey}"?\n\nUsers will lose access until reactivated.`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
fetch(`/admin/modules/${moduleKey}/deactivate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
alert(`✅ ${data.message}\n\nPlease reload the page.`);
|
||||
location.reload();
|
||||
} else {
|
||||
alert(`❌ ${data.message}`);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
alert(`❌ Error: ${error}`);
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== MODULE UPLOAD FUNCTIONS ====================
|
||||
|
||||
function openUploadModal() {
|
||||
document.getElementById('upload-modal').style.display = 'flex';
|
||||
resetUploadModal();
|
||||
}
|
||||
|
||||
function closeUploadModal() {
|
||||
document.getElementById('upload-modal').style.display = 'none';
|
||||
resetUploadModal();
|
||||
}
|
||||
|
||||
function closeUploadModalAndReload() {
|
||||
closeUploadModal();
|
||||
location.reload();
|
||||
}
|
||||
|
||||
function resetUploadModal() {
|
||||
document.getElementById('drop-zone').style.display = 'flex';
|
||||
document.getElementById('upload-progress').style.display = 'none';
|
||||
document.getElementById('upload-result').style.display = 'none';
|
||||
document.getElementById('file-input').value = '';
|
||||
}
|
||||
|
||||
// Drag and Drop Handlers
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const dropZone = document.getElementById('drop-zone');
|
||||
const fileInput = document.getElementById('file-input');
|
||||
|
||||
dropZone.addEventListener('dragover', (e) => {
|
||||
e.preventDefault();
|
||||
dropZone.classList.add('drag-over');
|
||||
});
|
||||
|
||||
dropZone.addEventListener('dragleave', () => {
|
||||
dropZone.classList.remove('drag-over');
|
||||
});
|
||||
|
||||
dropZone.addEventListener('drop', (e) => {
|
||||
e.preventDefault();
|
||||
dropZone.classList.remove('drag-over');
|
||||
|
||||
const files = e.dataTransfer.files;
|
||||
if (files.length > 0) {
|
||||
handleFileUpload(files[0]);
|
||||
}
|
||||
});
|
||||
|
||||
fileInput.addEventListener('change', (e) => {
|
||||
if (e.target.files.length > 0) {
|
||||
handleFileUpload(e.target.files[0]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Handle File Upload
|
||||
function handleFileUpload(file) {
|
||||
// Validate file type
|
||||
if (!file.name.endsWith('.zip')) {
|
||||
showUploadResult(false, 'Invalid File Type', 'Please upload a ZIP file containing your module.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Show progress
|
||||
document.getElementById('drop-zone').style.display = 'none';
|
||||
document.getElementById('upload-progress').style.display = 'block';
|
||||
document.getElementById('upload-filename').textContent = file.name;
|
||||
|
||||
// Create FormData
|
||||
const formData = new FormData();
|
||||
formData.append('module_file', file);
|
||||
|
||||
// Upload with progress
|
||||
const xhr = new XMLHttpRequest();
|
||||
|
||||
xhr.upload.addEventListener('progress', (e) => {
|
||||
if (e.lengthComputable) {
|
||||
const percentComplete = Math.round((e.loaded / e.total) * 100);
|
||||
updateProgress(percentComplete);
|
||||
}
|
||||
});
|
||||
|
||||
xhr.addEventListener('load', () => {
|
||||
if (xhr.status === 200) {
|
||||
const response = JSON.parse(xhr.responseText);
|
||||
if (response.success) {
|
||||
showUploadResult(true, 'Upload Successful!', response.message);
|
||||
} else {
|
||||
showUploadResult(false, 'Upload Failed', response.message);
|
||||
}
|
||||
} else {
|
||||
showUploadResult(false, 'Upload Failed', 'Server error: ' + xhr.status);
|
||||
}
|
||||
});
|
||||
|
||||
xhr.addEventListener('error', () => {
|
||||
showUploadResult(false, 'Upload Failed', 'Network error occurred');
|
||||
});
|
||||
|
||||
xhr.open('POST', '/admin/modules/upload', true);
|
||||
xhr.send(formData);
|
||||
}
|
||||
|
||||
function updateProgress(percent) {
|
||||
document.getElementById('progress-bar').style.width = percent + '%';
|
||||
document.getElementById('progress-text').textContent = percent + '%';
|
||||
|
||||
if (percent === 100) {
|
||||
document.getElementById('upload-status').textContent = 'Processing...';
|
||||
}
|
||||
}
|
||||
|
||||
function showUploadResult(success, title, message) {
|
||||
document.getElementById('upload-progress').style.display = 'none';
|
||||
|
||||
const resultDiv = document.getElementById('upload-result');
|
||||
resultDiv.style.display = 'block';
|
||||
resultDiv.className = 'upload-result ' + (success ? 'success' : 'error');
|
||||
|
||||
const icon = success
|
||||
? '<i class="fas fa-check-circle"></i>'
|
||||
: '<i class="fas fa-exclamation-circle"></i>';
|
||||
|
||||
document.getElementById('result-icon').innerHTML = icon;
|
||||
document.getElementById('result-title').textContent = title;
|
||||
document.getElementById('result-message').textContent = message;
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Upload Modal -->
|
||||
<div id="upload-modal" class="upload-modal" style="display: none;">
|
||||
<div class="upload-modal-overlay" onclick="closeUploadModal()"></div>
|
||||
<div class="upload-modal-content">
|
||||
<div class="upload-modal-header">
|
||||
<h2><i class="fas fa-upload"></i> Upload Module Package</h2>
|
||||
<button class="close-btn" onclick="closeUploadModal()">
|
||||
<i class="fas fa-times"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="upload-modal-body">
|
||||
<!-- Drag & Drop Zone -->
|
||||
<div id="drop-zone" class="drop-zone">
|
||||
<div class="drop-zone-content">
|
||||
<i class="fas fa-cloud-upload-alt"></i>
|
||||
<h3>Drag & Drop Module ZIP</h3>
|
||||
<p>or</p>
|
||||
<label for="file-input" class="btn btn-secondary">
|
||||
<i class="fas fa-folder-open"></i> Browse Files
|
||||
</label>
|
||||
<input type="file" id="file-input" accept=".zip" style="display: none;">
|
||||
<p class="file-requirements">
|
||||
<small>
|
||||
<strong>Requirements:</strong><br>
|
||||
• ZIP file containing module folder<br>
|
||||
• Must include manifest.json<br>
|
||||
• Module key must be unique
|
||||
</small>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Upload Progress (hidden by default) -->
|
||||
<div id="upload-progress" class="upload-progress" style="display: none;">
|
||||
<div class="progress-info">
|
||||
<span id="upload-filename"></span>
|
||||
<span id="upload-status">Uploading...</span>
|
||||
</div>
|
||||
<div class="progress-bar-container">
|
||||
<div id="progress-bar" class="progress-bar"></div>
|
||||
</div>
|
||||
<div class="progress-percentage">
|
||||
<span id="progress-text">0%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Upload Result (hidden by default) -->
|
||||
<div id="upload-result" class="upload-result" style="display: none;">
|
||||
<div id="result-icon"></div>
|
||||
<h3 id="result-title"></h3>
|
||||
<p id="result-message"></p>
|
||||
<button class="btn btn-primary" onclick="closeUploadModalAndReload()">
|
||||
Close & Refresh
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Upload Modal */
|
||||
.upload-modal {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.upload-modal-overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
}
|
||||
|
||||
.upload-modal-content {
|
||||
position: relative;
|
||||
background: var(--bg-primary);
|
||||
border: 2px solid var(--border-color);
|
||||
border-radius: 12px;
|
||||
width: 90%;
|
||||
max-width: 600px;
|
||||
max-height: 90vh;
|
||||
overflow: auto;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.upload-modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: var(--space-lg);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.upload-modal-header h2 {
|
||||
margin: 0;
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-sm);
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
font-size: 1.5rem;
|
||||
cursor: pointer;
|
||||
padding: var(--space-sm);
|
||||
line-height: 1;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.close-btn:hover {
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.upload-modal-body {
|
||||
padding: var(--space-xl);
|
||||
}
|
||||
|
||||
/* Drop Zone */
|
||||
.drop-zone {
|
||||
border: 3px dashed var(--border-color);
|
||||
border-radius: 12px;
|
||||
padding: var(--space-xl);
|
||||
text-align: center;
|
||||
transition: all 0.3s;
|
||||
background: var(--bg-secondary);
|
||||
min-height: 300px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.drop-zone:hover {
|
||||
border-color: var(--primary-color);
|
||||
background: rgba(0, 188, 212, 0.05);
|
||||
}
|
||||
|
||||
.drop-zone.drag-over {
|
||||
border-color: var(--primary-color);
|
||||
background: rgba(0, 188, 212, 0.1);
|
||||
transform: scale(1.02);
|
||||
}
|
||||
|
||||
.drop-zone-content {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.drop-zone-content i {
|
||||
font-size: 4rem;
|
||||
color: var(--primary-color);
|
||||
margin-bottom: var(--space-md);
|
||||
}
|
||||
|
||||
.drop-zone-content h3 {
|
||||
margin: var(--space-md) 0;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.drop-zone-content p {
|
||||
color: var(--text-muted);
|
||||
margin: var(--space-sm) 0;
|
||||
}
|
||||
|
||||
.file-requirements {
|
||||
margin-top: var(--space-lg);
|
||||
padding: var(--space-md);
|
||||
background: var(--bg-primary);
|
||||
border-radius: 8px;
|
||||
border-left: 4px solid var(--primary-color);
|
||||
}
|
||||
|
||||
/* Upload Progress */
|
||||
.upload-progress {
|
||||
text-align: center;
|
||||
padding: var(--space-xl);
|
||||
}
|
||||
|
||||
.progress-info {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: var(--space-md);
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.progress-bar-container {
|
||||
width: 100%;
|
||||
height: 30px;
|
||||
background: var(--bg-secondary);
|
||||
border-radius: 15px;
|
||||
overflow: hidden;
|
||||
margin-bottom: var(--space-sm);
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, var(--primary-color), var(--accent-color));
|
||||
transition: width 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: white;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.progress-percentage {
|
||||
text-align: center;
|
||||
font-size: 1.5rem;
|
||||
font-weight: bold;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
/* Upload Result */
|
||||
.upload-result {
|
||||
text-align: center;
|
||||
padding: var(--space-xl);
|
||||
}
|
||||
|
||||
.upload-result i {
|
||||
font-size: 5rem;
|
||||
margin-bottom: var(--space-lg);
|
||||
}
|
||||
|
||||
.upload-result.success i {
|
||||
color: var(--success-color);
|
||||
}
|
||||
|
||||
.upload-result.error i {
|
||||
color: var(--danger-color);
|
||||
}
|
||||
|
||||
.upload-result h3 {
|
||||
margin: var(--space-md) 0;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.upload-result p {
|
||||
color: var(--text-muted);
|
||||
margin-bottom: var(--space-lg);
|
||||
}
|
||||
</style>
|
||||
|
||||
{% endblock %}
|
||||
393
templates/module_upload_ui.html
Normal file
393
templates/module_upload_ui.html
Normal file
@@ -0,0 +1,393 @@
|
||||
<!-- Add this button to the top of module_manager.html, right after the dashboard-header -->
|
||||
|
||||
<div class="upload-section">
|
||||
<button class="btn btn-primary btn-lg" onclick="openUploadModal()">
|
||||
<i class="fas fa-upload"></i> Upload New Module
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Upload Modal -->
|
||||
<div id="upload-modal" class="upload-modal" style="display: none;">
|
||||
<div class="upload-modal-overlay" onclick="closeUploadModal()"></div>
|
||||
<div class="upload-modal-content">
|
||||
<div class="upload-modal-header">
|
||||
<h2><i class="fas fa-upload"></i> Upload Module Package</h2>
|
||||
<button class="close-btn" onclick="closeUploadModal()">
|
||||
<i class="fas fa-times"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="upload-modal-body">
|
||||
<!-- Drag & Drop Zone -->
|
||||
<div id="drop-zone" class="drop-zone">
|
||||
<div class="drop-zone-content">
|
||||
<i class="fas fa-cloud-upload-alt"></i>
|
||||
<h3>Drag & Drop Module ZIP</h3>
|
||||
<p>or</p>
|
||||
<label for="file-input" class="btn btn-secondary">
|
||||
<i class="fas fa-folder-open"></i> Browse Files
|
||||
</label>
|
||||
<input type="file" id="file-input" accept=".zip" style="display: none;">
|
||||
<p class="file-requirements">
|
||||
<small>
|
||||
<strong>Requirements:</strong><br>
|
||||
• ZIP file containing module folder<br>
|
||||
• Must include manifest.json<br>
|
||||
• Module key must be unique
|
||||
</small>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Upload Progress (hidden by default) -->
|
||||
<div id="upload-progress" class="upload-progress" style="display: none;">
|
||||
<div class="progress-info">
|
||||
<span id="upload-filename"></span>
|
||||
<span id="upload-status">Uploading...</span>
|
||||
</div>
|
||||
<div class="progress-bar-container">
|
||||
<div id="progress-bar" class="progress-bar"></div>
|
||||
</div>
|
||||
<div class="progress-percentage">
|
||||
<span id="progress-text">0%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Upload Result (hidden by default) -->
|
||||
<div id="upload-result" class="upload-result" style="display: none;">
|
||||
<div id="result-icon"></div>
|
||||
<h3 id="result-title"></h3>
|
||||
<p id="result-message"></p>
|
||||
<button class="btn btn-primary" onclick="closeUploadModalAndReload()">
|
||||
Close & Refresh
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Upload Section */
|
||||
.upload-section {
|
||||
margin: var(--space-lg) 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Upload Modal */
|
||||
.upload-modal {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.upload-modal-overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
}
|
||||
|
||||
.upload-modal-content {
|
||||
position: relative;
|
||||
background: var(--bg-primary);
|
||||
border: 2px solid var(--border-color);
|
||||
border-radius: 12px;
|
||||
width: 90%;
|
||||
max-width: 600px;
|
||||
max-height: 90vh;
|
||||
overflow: auto;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.upload-modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: var(--space-lg);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.upload-modal-header h2 {
|
||||
margin: 0;
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-sm);
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
font-size: 1.5rem;
|
||||
cursor: pointer;
|
||||
padding: var(--space-sm);
|
||||
line-height: 1;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.close-btn:hover {
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.upload-modal-body {
|
||||
padding: var(--space-xl);
|
||||
}
|
||||
|
||||
/* Drop Zone */
|
||||
.drop-zone {
|
||||
border: 3px dashed var(--border-color);
|
||||
border-radius: 12px;
|
||||
padding: var(--space-xl);
|
||||
text-align: center;
|
||||
transition: all 0.3s;
|
||||
background: var(--bg-secondary);
|
||||
min-height: 300px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.drop-zone:hover {
|
||||
border-color: var(--primary-color);
|
||||
background: rgba(0, 188, 212, 0.05);
|
||||
}
|
||||
|
||||
.drop-zone.drag-over {
|
||||
border-color: var(--primary-color);
|
||||
background: rgba(0, 188, 212, 0.1);
|
||||
transform: scale(1.02);
|
||||
}
|
||||
|
||||
.drop-zone-content {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.drop-zone-content i {
|
||||
font-size: 4rem;
|
||||
color: var(--primary-color);
|
||||
margin-bottom: var(--space-md);
|
||||
}
|
||||
|
||||
.drop-zone-content h3 {
|
||||
margin: var(--space-md) 0;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.drop-zone-content p {
|
||||
color: var(--text-muted);
|
||||
margin: var(--space-sm) 0;
|
||||
}
|
||||
|
||||
.file-requirements {
|
||||
margin-top: var(--space-lg);
|
||||
padding: var(--space-md);
|
||||
background: var(--bg-primary);
|
||||
border-radius: 8px;
|
||||
border-left: 4px solid var(--primary-color);
|
||||
}
|
||||
|
||||
/* Upload Progress */
|
||||
.upload-progress {
|
||||
text-align: center;
|
||||
padding: var(--space-xl);
|
||||
}
|
||||
|
||||
.progress-info {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: var(--space-md);
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.progress-bar-container {
|
||||
width: 100%;
|
||||
height: 30px;
|
||||
background: var(--bg-secondary);
|
||||
border-radius: 15px;
|
||||
overflow: hidden;
|
||||
margin-bottom: var(--space-sm);
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, var(--primary-color), var(--accent-color));
|
||||
transition: width 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: white;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.progress-percentage {
|
||||
text-align: center;
|
||||
font-size: 1.5rem;
|
||||
font-weight: bold;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
/* Upload Result */
|
||||
.upload-result {
|
||||
text-align: center;
|
||||
padding: var(--space-xl);
|
||||
}
|
||||
|
||||
.upload-result i {
|
||||
font-size: 5rem;
|
||||
margin-bottom: var(--space-lg);
|
||||
}
|
||||
|
||||
.upload-result.success i {
|
||||
color: var(--success-color);
|
||||
}
|
||||
|
||||
.upload-result.error i {
|
||||
color: var(--danger-color);
|
||||
}
|
||||
|
||||
.upload-result h3 {
|
||||
margin: var(--space-md) 0;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.upload-result p {
|
||||
color: var(--text-muted);
|
||||
margin-bottom: var(--space-lg);
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// Upload Modal Functions
|
||||
function openUploadModal() {
|
||||
document.getElementById('upload-modal').style.display = 'flex';
|
||||
resetUploadModal();
|
||||
}
|
||||
|
||||
function closeUploadModal() {
|
||||
document.getElementById('upload-modal').style.display = 'none';
|
||||
resetUploadModal();
|
||||
}
|
||||
|
||||
function closeUploadModalAndReload() {
|
||||
closeUploadModal();
|
||||
location.reload();
|
||||
}
|
||||
|
||||
function resetUploadModal() {
|
||||
document.getElementById('drop-zone').style.display = 'flex';
|
||||
document.getElementById('upload-progress').style.display = 'none';
|
||||
document.getElementById('upload-result').style.display = 'none';
|
||||
document.getElementById('file-input').value = '';
|
||||
}
|
||||
|
||||
// Drag and Drop Handlers
|
||||
const dropZone = document.getElementById('drop-zone');
|
||||
const fileInput = document.getElementById('file-input');
|
||||
|
||||
dropZone.addEventListener('dragover', (e) => {
|
||||
e.preventDefault();
|
||||
dropZone.classList.add('drag-over');
|
||||
});
|
||||
|
||||
dropZone.addEventListener('dragleave', () => {
|
||||
dropZone.classList.remove('drag-over');
|
||||
});
|
||||
|
||||
dropZone.addEventListener('drop', (e) => {
|
||||
e.preventDefault();
|
||||
dropZone.classList.remove('drag-over');
|
||||
|
||||
const files = e.dataTransfer.files;
|
||||
if (files.length > 0) {
|
||||
handleFileUpload(files[0]);
|
||||
}
|
||||
});
|
||||
|
||||
fileInput.addEventListener('change', (e) => {
|
||||
if (e.target.files.length > 0) {
|
||||
handleFileUpload(e.target.files[0]);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle File Upload
|
||||
function handleFileUpload(file) {
|
||||
// Validate file type
|
||||
if (!file.name.endsWith('.zip')) {
|
||||
showUploadResult(false, 'Invalid File Type', 'Please upload a ZIP file containing your module.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Show progress
|
||||
document.getElementById('drop-zone').style.display = 'none';
|
||||
document.getElementById('upload-progress').style.display = 'block';
|
||||
document.getElementById('upload-filename').textContent = file.name;
|
||||
|
||||
// Create FormData
|
||||
const formData = new FormData();
|
||||
formData.append('module_file', file);
|
||||
|
||||
// Upload with progress
|
||||
const xhr = new XMLHttpRequest();
|
||||
|
||||
xhr.upload.addEventListener('progress', (e) => {
|
||||
if (e.lengthComputable) {
|
||||
const percentComplete = Math.round((e.loaded / e.total) * 100);
|
||||
updateProgress(percentComplete);
|
||||
}
|
||||
});
|
||||
|
||||
xhr.addEventListener('load', () => {
|
||||
if (xhr.status === 200) {
|
||||
const response = JSON.parse(xhr.responseText);
|
||||
if (response.success) {
|
||||
showUploadResult(true, 'Upload Successful!', response.message);
|
||||
} else {
|
||||
showUploadResult(false, 'Upload Failed', response.message);
|
||||
}
|
||||
} else {
|
||||
showUploadResult(false, 'Upload Failed', 'Server error: ' + xhr.status);
|
||||
}
|
||||
});
|
||||
|
||||
xhr.addEventListener('error', () => {
|
||||
showUploadResult(false, 'Upload Failed', 'Network error occurred');
|
||||
});
|
||||
|
||||
xhr.open('POST', '/admin/modules/upload', true);
|
||||
xhr.send(formData);
|
||||
}
|
||||
|
||||
function updateProgress(percent) {
|
||||
document.getElementById('progress-bar').style.width = percent + '%';
|
||||
document.getElementById('progress-text').textContent = percent + '%';
|
||||
|
||||
if (percent === 100) {
|
||||
document.getElementById('upload-status').textContent = 'Processing...';
|
||||
}
|
||||
}
|
||||
|
||||
function showUploadResult(success, title, message) {
|
||||
document.getElementById('upload-progress').style.display = 'none';
|
||||
|
||||
const resultDiv = document.getElementById('upload-result');
|
||||
resultDiv.style.display = 'block';
|
||||
resultDiv.className = 'upload-result ' + (success ? 'success' : 'error');
|
||||
|
||||
const icon = success
|
||||
? '<i class="fas fa-check-circle"></i>'
|
||||
: '<i class="fas fa-exclamation-circle"></i>';
|
||||
|
||||
document.getElementById('result-icon').innerHTML = icon;
|
||||
document.getElementById('result-title').textContent = title;
|
||||
document.getElementById('result-message').textContent = message;
|
||||
}
|
||||
</script>
|
||||
Reference in New Issue
Block a user