9 Commits

Author SHA1 Message Date
Javier
406219547d feat: Implement modular plugin architecture
- Convert invcount to self-contained module
- Add Module Manager for install/uninstall
- Create module_registry database table
- Support hot-reloading of modules
- Move data imports into invcount module
- Update all templates and routes to new structure

Version bumped to 0.16.0
2026-02-07 01:47:49 -06:00
Javier
2a649fdbcc V0.15.0 - Not done yet 2026-02-01 16:22:59 -06:00
Javier
89be88566f Excel Template working better, still not finished. 2026-02-01 01:35:02 -06:00
Javier
1359e036d5 Update 2026-01-31 22:20:10 -06:00
Javier
ad071438cc Merge branch 'Refractor--Changing-how-counting-works' 2026-01-31 20:32:18 -06:00
Javier
5604686630 update: added files to gitignore 2026-01-31 20:30:12 -06:00
Javier
2d333c16a3 v0.14.0 - Major Logic Overhaul & Real-Time Dashboard
Logic: Implemented "One User, One Bin" locking to prevent duplicate counting.

    Integrity: Standardized is_deleted = 0 and tightened "Matched" criteria to require zero weight variance.

    Refresh: Added silent 30-second dashboard polling for all 6 status categories and active counter list.

    Tracking: Built user-specific activity tracking to identify who is counting where in real-time.

    Stability: Resolved persistent 500 errors by finalizing the active-counters-fragment structure.
2026-01-31 19:17:36 -06:00
Javier
288b390618 Merge branch 'refactor/counts-dashboard' 2026-01-30 10:43:51 -06:00
Javier
fcdef6875e Stop tracking compiled python files 2026-01-30 10:41:34 -06:00
45 changed files with 4651 additions and 754 deletions

View File

@@ -4,20 +4,7 @@ You are helping build a project called **Scanlook**.
## Scanlook (current product summary)
Scanlook is a web app for warehouse counting workflows.
- Admin creates a **Count Session** (e.g., “Jan 24 2026 - First Shift”) and uploads a **Master Inventory list**.
- Staff select the active Count Session, enter a **Location/BIN**, and the app shows the **Expected** lots/items/weights that should be there (Cycle Count mode).
- Staff **scan lot numbers**, enter **weights**, and each scan moves from **Expected → Scanned**.
- System flags:
- duplicates
- wrong location
- “ghost” lots (physically found but not in system/master list)
- Staff can **Finalize** a BIN; once finalized, it should clearly report **missing items/lots**.
- Admin sees live progress in an **Admin Dashboard**.
- Multiple Count Sessions can exist even on the same day (e.g., First Shift vs Second Shift) and must be completely isolated.
There are two types of counts:
1) **Cycle Count**: shows Expected list for the BIN.
2) **Physical Inventory**: same workflow but **blind** (does NOT show Expected list; only scanned results, then missing is determined after).
Scanlook is modular.
Long-term goal: evolve into a WMS, but right now focus on making this workflow reliable.
@@ -44,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.13.0
**Current Version:** 0.15.0
**Tech Stack:**
- Backend: Python/Flask, raw SQL (no ORM), openpyxl (Excel file generation)
@@ -79,13 +66,9 @@ Scanlook is a web app for warehouse counting workflows built with Flask + SQLite
- Consumption Sheets module (production lot tracking with Excel export)
- Database migration system (auto-applies schema changes on startup)
**Two count types:**
1. Cycle Count: shows Expected list for the BIN
2. Physical Inventory: blind count (no Expected list shown)
**Long-term goal:** Modular WMS with future modules for Shipping, Receiving, Transfers, Production.
**Module System (v0.13.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
@@ -104,5 +87,5 @@ Scanlook is a web app for warehouse counting workflows built with Flask + SQLite
- Scanner viewport: 320px wide (MC9300)
- Mobile breakpoint: 360-767px
- Desktop: 768px+
- Git remote: http://10.44.44.33:3000/stuff/ScanLook.git
- Git remote: https://tsngit.tsnx.net/stuff/ScanLook.git
- Docker registry: 10.44.44.33:3000/stuff/scanlook

184
app.py
View File

@@ -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.13.2'
APP_VERSION = '0.16.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,49 +115,124 @@ 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 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
''')
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
''')
return render_template('admin_dashboard.html', sessions=sessions_list, show_archived=show_archived)
if role not in ['owner', 'admin']:
flash('Access denied. Admin role required.', 'danger')
return redirect(url_for('home'))
# 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)
# Hot-reload: Register the blueprint immediately if installation succeeded
if result['success']:
try:
from pathlib import Path
import importlib.util
import sys
module = module_manager.get_module_by_key(module_key)
if module:
init_path = Path(module['path']) / '__init__.py'
# Import the module
spec = importlib.util.spec_from_file_location(
f"modules.{module_key}",
init_path
)
module_package = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module_package
spec.loader.exec_module(module_package)
# Create and register blueprint
if hasattr(module_package, 'create_blueprint'):
blueprint = module_package.create_blueprint()
app.register_blueprint(blueprint)
print(f"🔥 Hot-loaded: {module['name']} at {module.get('routes_prefix')}")
result['message'] += ' (Module loaded - no restart needed!)'
else:
print(f"⚠️ Module {module_key} missing create_blueprint()")
result['message'] += ' (Restart required - missing create_blueprint)'
else:
print(f"⚠️ Could not find module {module_key} after installation")
result['message'] += ' (Restart required - module not found)'
except Exception as e:
print(f"❌ Hot-reload failed for {module_key}: {e}")
import traceback
traceback.print_exc()
result['message'] += f' (Restart required - hot-reload failed)'
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
result = module_manager.uninstall_module(module_key, drop_tables=True)
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)
# ==================== PWA SUPPORT ROUTES ====================
@@ -204,6 +275,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__':

View File

@@ -29,35 +29,6 @@ def reopen_location(location_count_id):
return jsonify({'success': True, 'message': 'Bin reopened for counting'})
@admin_locations_bp.route('/location/<int:location_count_id>/delete', methods=['POST'])
@login_required
def delete_location_count(location_count_id):
"""Delete all counts for a location (soft delete)"""
# Verify ownership
loc = query_db('SELECT * FROM LocationCounts WHERE location_count_id = ?', [location_count_id], one=True)
if not loc:
return jsonify({'success': False, 'message': 'Location not found'})
if loc['counted_by'] != session['user_id'] and session['role'] not in ['owner', 'admin']:
return jsonify({'success': False, 'message': 'Permission denied'})
# Soft delete all scan entries for this location
execute_db('''
UPDATE ScanEntries
SET is_deleted = 1
WHERE location_count_id = ?
''', [location_count_id])
# Delete the location count record
execute_db('''
DELETE FROM LocationCounts
WHERE location_count_id = ?
''', [location_count_id])
return jsonify({'success': True, 'message': 'Bin count deleted'})
@admin_locations_bp.route('/location/<int:location_count_id>/scans')
@login_required
def get_location_scans(location_count_id):
@@ -86,4 +57,40 @@ def get_location_scans(location_count_id):
return jsonify({'success': True, 'scans': scans_list})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
return jsonify({'success': False, 'message': str(e)})
@admin_locations_bp.route('/location/<int:location_count_id>/delete', methods=['POST'])
@login_required
def soft_delete_location(location_count_id):
"""Admin-only: Soft delete a bin count and its associated data"""
if session.get('role') not in ['owner', 'admin']:
return jsonify({'success': False, 'message': 'Admin role required'}), 403
# 1. Verify location exists
loc = query_db('SELECT session_id, location_name FROM LocationCounts WHERE location_count_id = ?',
[location_count_id], one=True)
if not loc:
return jsonify({'success': False, 'message': 'Location not found'})
# 2. Soft delete the bin count itself
execute_db('''
UPDATE LocationCounts
SET is_deleted = 1
WHERE location_count_id = ?
''', [location_count_id])
# 3. Soft delete all scans in that bin
execute_db('''
UPDATE ScanEntries
SET is_deleted = 1
WHERE location_count_id = ?
''', [location_count_id])
# 4. Remove any MissingLots records generated for this bin
execute_db('''
DELETE FROM MissingLots
WHERE session_id = ? AND master_expected_location = ?
''', [loc['session_id'], loc['location_name']])
return jsonify({'success': True, 'message': 'Bin count and associated data soft-deleted'})

View File

@@ -8,18 +8,23 @@ cons_sheets_bp = Blueprint('cons_sheets', __name__)
@cons_sheets_bp.route('/admin/consumption-sheets')
@role_required('owner', 'admin')
def admin_processes():
"""List all consumption sheet process types"""
processes = query_db('''
SELECT cp.*, u.full_name as created_by_name,
(SELECT COUNT(*) FROM cons_process_fields
WHERE process_id = cp.id AND is_active = 1) as field_count
FROM cons_processes cp
LEFT JOIN Users u ON cp.created_by = u.user_id
WHERE cp.is_active = 1
ORDER BY cp.process_name
''')
"""List all consumption sheet process types (Active or Archived)"""
show_archived = request.args.get('archived') == '1'
is_active_val = 0 if show_archived else 1
return render_template('cons_sheets/admin_processes.html', processes=processes)
processes = query_db('''
SELECT cp.*,
u.full_name as created_by_name,
(SELECT COUNT(*) FROM cons_process_fields WHERE process_id = cp.id) as field_count
FROM cons_processes cp
LEFT JOIN users u ON cp.created_by = u.user_id
WHERE cp.is_active = ?
ORDER BY cp.process_name ASC
''', [is_active_val])
return render_template('cons_sheets/admin_processes.html',
processes=processes,
showing_archived=show_archived)
@cons_sheets_bp.route('/admin/consumption-sheets/create', methods=['GET', 'POST'])
@@ -144,6 +149,36 @@ def rename_column_in_detail_table(process_key, old_name, new_name):
conn.close()
@cons_sheets_bp.route('/admin/consumption-sheets/<int:process_id>/delete', methods=['POST'])
@role_required('owner', 'admin')
def delete_process(process_id):
"""Soft-delete a process type (Archive it)"""
# Check if process exists
process = query_db('SELECT * FROM cons_processes WHERE id = ?', [process_id], one=True)
if not process:
flash('Process not found', 'danger')
return redirect(url_for('cons_sheets.admin_processes'))
# Soft delete: Set is_active = 0
# The existing admin_processes route already filters for is_active=1,
# so this will effectively hide it from the list.
execute_db('UPDATE cons_processes SET is_active = 0 WHERE id = ?', [process_id])
flash(f'Process "{process["process_name"]}" has been deleted.', 'success')
return redirect(url_for('cons_sheets.admin_processes'))
@cons_sheets_bp.route('/admin/consumption-sheets/<int:process_id>/restore', methods=['POST'])
@role_required('owner', 'admin')
def restore_process(process_id):
"""Restore a soft-deleted process type"""
execute_db('UPDATE cons_processes SET is_active = 1 WHERE id = ?', [process_id])
flash('Process has been restored.', 'success')
return redirect(url_for('cons_sheets.admin_processes', archived=1))
@cons_sheets_bp.route('/admin/consumption-sheets/<int:process_id>')
@role_required('owner', 'admin')
def process_detail(process_id):
@@ -284,24 +319,35 @@ def update_template_settings(process_id):
rows_per_page = request.form.get('rows_per_page', 30)
detail_start_row = request.form.get('detail_start_row', 10)
page_height = request.form.get('page_height')
print_start_col = request.form.get('print_start_col', 'A').strip().upper()
print_end_col = request.form.get('print_end_col', '').strip().upper()
try:
rows_per_page = int(rows_per_page)
detail_start_row = int(detail_start_row)
# We enforce page_height is required now
page_height = int(page_height) if page_height and page_height.strip() else None
if not page_height:
flash('Page Height is required for the new strategy', 'danger')
return redirect(url_for('cons_sheets.process_template', process_id=process_id))
except ValueError:
flash('Invalid number values', 'danger')
return redirect(url_for('cons_sheets.process_template', process_id=process_id))
# Update query - We ignore detail_end_row (leave it as is or null)
execute_db('''
UPDATE cons_processes
SET rows_per_page = ?, detail_start_row = ?
WHERE id = ?
''', [rows_per_page, detail_start_row, process_id])
UPDATE cons_processes
SET rows_per_page = ?, detail_start_row = ?, page_height = ?,
print_start_col = ?, print_end_col = ?
WHERE id = ?
''', [rows_per_page, detail_start_row, page_height, print_start_col, print_end_col, process_id])
flash('Settings updated successfully!', 'success')
return redirect(url_for('cons_sheets.process_template', process_id=process_id))
@cons_sheets_bp.route('/admin/consumption-sheets/<int:process_id>/template/download')
@role_required('owner', 'admin')
def download_template(process_id):
@@ -905,22 +951,59 @@ def archive_session(session_id):
return jsonify({'success': True})
# --- BULK IMPORT ROUTES ---
@cons_sheets_bp.route('/cons-sheets/session/<int:session_id>/export')
@cons_sheets_bp.route('/cons-sheets/session/<int:session_id>/template')
@login_required
def export_session(session_id):
"""Export session to Excel using the process template"""
from flask import Response
def download_import_template(session_id):
"""Generate a blank Excel template for bulk import"""
from flask import Response # <--- ADDED THIS
from io import BytesIO
import openpyxl
from openpyxl.utils import get_column_letter, column_index_from_string
from copy import copy
from datetime import datetime
# Get session with process info
# Get Process ID
sess = query_db('SELECT process_id FROM cons_sessions WHERE id = ?', [session_id], one=True)
if not sess: return redirect(url_for('cons_sheets.index'))
# Get Detail Fields
fields = query_db('''
SELECT field_name, field_label
FROM cons_process_fields
WHERE process_id = ? AND table_type = 'detail' AND is_active = 1
ORDER BY sort_order
''', [sess['process_id']])
# Create Workbook
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Import Data"
# Write Header Row (Field Names)
headers = [f['field_name'] for f in fields]
ws.append(headers)
output = BytesIO()
wb.save(output)
output.seek(0)
return Response(
output.getvalue(),
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers={'Content-Disposition': 'attachment; filename=import_template.xlsx'}
)
@cons_sheets_bp.route('/cons-sheets/session/<int:session_id>/import', methods=['POST'])
@login_required
def import_session_data(session_id):
"""Bulk import detail rows from Excel"""
# Import EVERYTHING locally to avoid NameErrors
import openpyxl
from datetime import datetime
from flask import request, flash, redirect, url_for, session
# 1. Get Session Info
sess = query_db('''
SELECT cs.*, cp.process_name, cp.process_key, cp.id as process_id,
cp.template_file, cp.template_filename, cp.rows_per_page, cp.detail_start_row
SELECT cs.*, cp.process_key
FROM cons_sessions cs
JOIN cons_processes cp ON cs.process_id = cp.id
WHERE cs.id = ?
@@ -929,12 +1012,125 @@ def export_session(session_id):
if not sess:
flash('Session not found', 'danger')
return redirect(url_for('cons_sheets.index'))
if not sess['template_file']:
flash('No template configured for this process', 'danger')
# 2. Check File
if 'file' not in request.files:
flash('No file uploaded', 'danger')
return redirect(url_for('cons_sheets.scan_session', session_id=session_id))
file = request.files['file']
if file.filename == '':
flash('No file selected', 'danger')
return redirect(url_for('cons_sheets.scan_session', session_id=session_id))
try:
# 3. Read Excel
wb = openpyxl.load_workbook(file)
ws = wb.active
# Get headers from first row
headers = [cell.value for cell in ws[1]]
# Get valid field names for this process
valid_fields = query_db('''
SELECT field_name
FROM cons_process_fields
WHERE process_id = ? AND table_type = 'detail' AND is_active = 1
''', [sess['process_id']])
valid_field_names = [f['field_name'] for f in valid_fields]
# Map Excel Columns to DB Fields
col_mapping = {}
for idx, header in enumerate(headers):
if header and header in valid_field_names:
col_mapping[idx] = header
if not col_mapping:
flash('Error: No matching columns found in Excel. Please use the template.', 'danger')
return redirect(url_for('cons_sheets.scan_session', session_id=session_id))
# 4. Process Rows
table_name = f"cons_proc_{sess['process_key']}_details"
rows_inserted = 0
# Get User ID safely from session
user_id = session.get('user_id')
for row in ws.iter_rows(min_row=2, values_only=True):
if not any(row): continue
data = {}
for col_idx, value in enumerate(row):
if col_idx in col_mapping:
data[col_mapping[col_idx]] = value
if not data: continue
# Add Metadata
data['session_id'] = session_id
data['scanned_at'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
data['scanned_by'] = user_id
# REMOVED: data['is_valid'] = 1 (This column does not exist)
data['is_deleted'] = 0
# Dynamic Insert SQL
columns = ', '.join(data.keys())
placeholders = ', '.join(['?'] * len(data))
values = list(data.values())
sql = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})"
execute_db(sql, values)
rows_inserted += 1
flash(f'Successfully imported {rows_inserted} records!', 'success')
except Exception as e:
# This will catch any other errors and show them to you
flash(f'Import Error: {str(e)}', 'danger')
print(f"DEBUG IMPORT ERROR: {str(e)}") # Print to console for good measure
return redirect(url_for('cons_sheets.scan_session', session_id=session_id))
@cons_sheets_bp.route('/cons-sheets/session/<int:session_id>/export')
@login_required
def export_session(session_id):
"""Export session: Hide Rows Strategy + Manual Column Widths"""
from flask import Response
from io import BytesIO
import openpyxl
# Correct imports for newer openpyxl
from openpyxl.utils.cell import coordinate_from_string, get_column_letter
from openpyxl.worksheet.pagebreak import Break
from datetime import datetime
import math
# Get header fields and values
# --- FIX 1: Update SQL to fetch the new columns ---
sess = query_db('''
SELECT cs.*, cp.process_name, cp.process_key, cp.id as process_id,
cp.template_file, cp.template_filename,
cp.rows_per_page, cp.detail_start_row, cp.page_height,
cp.print_start_col, cp.print_end_col
FROM cons_sessions cs
JOIN cons_processes cp ON cs.process_id = cp.id
WHERE cs.id = ?
''', [session_id], one=True)
if not sess or not sess['template_file']:
flash('Session or Template not found', 'danger')
return redirect(url_for('cons_sheets.index'))
# Validation
page_height = sess['page_height']
rows_per_page = sess['rows_per_page'] or 30
detail_start_row = sess['detail_start_row'] or 10
if not page_height:
flash('Configuration Error: Page Height is not set.', 'danger')
return redirect(url_for('cons_sheets.scan_session', session_id=session_id))
# Get Data
header_fields = query_db('''
SELECT cpf.field_name, cpf.excel_cell, cshv.field_value
FROM cons_process_fields cpf
@@ -942,7 +1138,6 @@ def export_session(session_id):
WHERE cpf.process_id = ? AND cpf.table_type = 'header' AND cpf.is_active = 1 AND cpf.excel_cell IS NOT NULL
''', [session_id, sess['process_id']])
# Get detail fields with their column mappings
detail_fields = query_db('''
SELECT field_name, excel_cell, field_type
FROM cons_process_fields
@@ -950,169 +1145,94 @@ def export_session(session_id):
ORDER BY sort_order, id
''', [sess['process_id']])
# Get all scanned details
table_name = get_detail_table_name(sess['process_key'])
table_name = f'cons_proc_{sess["process_key"]}_details'
scans = query_db(f'''
SELECT * FROM {table_name}
WHERE session_id = ? AND is_deleted = 0
ORDER BY scanned_at ASC
''', [session_id])
# Load the template
template_bytes = BytesIO(sess['template_file'])
wb = openpyxl.load_workbook(template_bytes)
# Setup Excel
wb = openpyxl.load_workbook(BytesIO(sess['template_file']))
ws = wb.active
rows_per_page = sess['rows_per_page'] or 30
detail_start_row = sess['detail_start_row'] or 11
# Clear existing breaks
ws.row_breaks.brk = []
ws.col_breaks.brk = []
# Calculate how many pages we need
total_scans = len(scans) if scans else 0
num_pages = max(1, (total_scans + rows_per_page - 1) // rows_per_page) if total_scans > 0 else 1
# Calculate Pages Needed
total_items = len(scans)
total_pages = math.ceil(total_items / rows_per_page) if total_items > 0 else 1
# Helper function to fill header values on a sheet
def fill_header(worksheet, header_fields):
# --- MAIN LOOP ---
for page_idx in range(total_pages):
# 1. Fill Header
for field in header_fields:
if field['excel_cell'] and field['field_value']:
try:
worksheet[field['excel_cell']] = field['field_value']
except:
pass # Skip invalid cell references
# Helper function to clear detail rows on a sheet
def clear_details(worksheet, detail_fields, start_row, num_rows):
for i in range(num_rows):
row_num = start_row + i
for field in detail_fields:
if field['excel_cell']:
try:
col_letter = field['excel_cell'].upper().strip()
cell_ref = f"{col_letter}{row_num}"
worksheet[cell_ref] = None
except:
pass
# Helper function to fill detail rows on a sheet
def fill_details(worksheet, scans_subset, detail_fields, start_row):
for i, scan in enumerate(scans_subset):
row_num = start_row + i
for field in detail_fields:
if field['excel_cell']:
try:
col_letter = field['excel_cell'].upper().strip()
cell_ref = f"{col_letter}{row_num}"
value = scan[field['field_name']]
# Convert to appropriate type
if field['field_type'] == 'REAL' and value:
value = float(value)
elif field['field_type'] == 'INTEGER' and value:
value = int(value)
worksheet[cell_ref] = value
except Exception as e:
print(f"Error filling cell: {e}")
# Fill the first page
fill_header(ws, header_fields)
first_page_scans = scans[:rows_per_page] if scans else []
fill_details(ws, first_page_scans, detail_fields, detail_start_row)
# Create additional pages if needed
for page_num in range(2, num_pages + 1):
# Copy the worksheet within the same workbook
new_ws = wb.copy_worksheet(ws)
new_ws.title = f"Page {page_num}"
# Clear detail rows (they have Page 1 data)
clear_details(new_ws, detail_fields, detail_start_row, rows_per_page)
# Fill details for this page
start_idx = (page_num - 1) * rows_per_page
col_letter, row_str = coordinate_from_string(field['excel_cell'])
base_row = int(row_str)
target_row = base_row + (page_idx * page_height)
ws[f"{col_letter}{target_row}"] = field['field_value']
except: pass
# 2. Fill Details
start_idx = page_idx * rows_per_page
end_idx = start_idx + rows_per_page
page_scans = scans[start_idx:end_idx]
fill_details(new_ws, page_scans, detail_fields, detail_start_row)
for i, scan in enumerate(page_scans):
target_row = detail_start_row + (page_idx * page_height) + i
for field in detail_fields:
if field['excel_cell']:
try:
col_letter = field['excel_cell'].upper().strip()
cell_ref = f"{col_letter}{target_row}"
value = scan[field['field_name']]
if field['field_type'] == 'REAL' and value: value = float(value)
elif field['field_type'] == 'INTEGER' and value: value = int(value)
ws[cell_ref] = value
except: pass
# 3. Force Page Break (BEFORE the new header)
if page_idx < total_pages - 1:
next_page_start_row = ((page_idx + 1) * page_height) # No +1 here!
ws.row_breaks.append(Break(id=next_page_start_row))
# --- STEP 3: CLEANUP (Hide Unused Rows) ---
last_used_row = (total_pages * page_height)
SAFE_MAX_ROW = 5000
# Rename first sheet if we have multiple pages
if num_pages > 1:
ws.title = "Page 1"
for row_num in range(last_used_row + 1, SAFE_MAX_ROW):
ws.row_dimensions[row_num].hidden = True
# --- FINAL POLISH (Manual Widths) ---
# Save to BytesIO
# --- FIX 2: Use bracket notation (sess['col']) instead of .get() ---
# We use 'or' to provide defaults if the DB value is None
start_col = sess['print_start_col'] or 'A'
if sess['print_end_col']:
end_col = sess['print_end_col']
else:
# Fallback to auto-detection if user left it blank
end_col = get_column_letter(ws.max_column)
# Set Print Area
ws.print_area = f"{start_col}1:{end_col}{last_used_row}"
if ws.sheet_properties.pageSetUpPr:
ws.sheet_properties.pageSetUpPr.fitToPage = False
# Save
output = BytesIO()
wb.save(output)
output.seek(0)
# Generate filename
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
base_filename = f"{sess['process_key']}_{session_id}_{timestamp}"
# Check if PDF export is requested
export_format = request.args.get('format', 'xlsx')
print(f"DEBUG: Export format requested: {export_format}")
if export_format == 'pdf':
# Use win32com to convert to PDF (requires Excel installed)
try:
import tempfile
import pythoncom
import win32com.client as win32
print("DEBUG: pywin32 imported successfully")
# Save Excel to temp file
temp_xlsx = tempfile.NamedTemporaryFile(suffix='.xlsx', delete=False)
temp_xlsx.write(output.getvalue())
temp_xlsx.close()
print(f"DEBUG: Temp Excel saved to: {temp_xlsx.name}")
temp_pdf = temp_xlsx.name.replace('.xlsx', '.pdf')
# Initialize COM for this thread
pythoncom.CoInitialize()
print("DEBUG: COM initialized")
try:
excel = win32.Dispatch('Excel.Application')
excel.Visible = False
excel.DisplayAlerts = False
print("DEBUG: Excel application started")
workbook = excel.Workbooks.Open(temp_xlsx.name)
print("DEBUG: Workbook opened")
workbook.ExportAsFixedFormat(0, temp_pdf) # 0 = PDF format
print(f"DEBUG: Exported to PDF: {temp_pdf}")
workbook.Close(False)
excel.Quit()
print("DEBUG: Excel closed")
finally:
pythoncom.CoUninitialize()
# Read the PDF
with open(temp_pdf, 'rb') as f:
pdf_data = f.read()
print(f"DEBUG: PDF read, size: {len(pdf_data)} bytes")
# Clean up temp files
import os
os.unlink(temp_xlsx.name)
os.unlink(temp_pdf)
print("DEBUG: Temp files cleaned up")
return Response(
pdf_data,
mimetype='application/pdf',
headers={'Content-Disposition': f'attachment; filename={base_filename}.pdf'}
)
except ImportError as e:
print(f"ERROR: Import failed - {e}")
# Fall back to Excel export
except Exception as e:
print(f"ERROR: PDF export failed - {e}")
import traceback
traceback.print_exc()
# Fall back to Excel export
# Default: return Excel file
print("DEBUG: Returning Excel file")
return Response(
output.getvalue(),
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',

View File

@@ -111,16 +111,23 @@ def my_counts(session_id):
# Get this user's active bins
active_bins = query_db('''
SELECT lc.*,
COUNT(se.entry_id) as scan_count
FROM LocationCounts lc
LEFT JOIN ScanEntries se ON lc.location_count_id = se.location_count_id AND se.is_deleted = 0
WHERE lc.session_id = ?
AND lc.counted_by = ?
AND lc.status = 'in_progress'
GROUP BY lc.location_count_id
ORDER BY lc.start_timestamp DESC
''', [session_id, session['user_id']])
SELECT lc.*,
COUNT(se.entry_id) as scan_count
FROM LocationCounts lc
LEFT JOIN ScanEntries se ON lc.location_count_id = se.location_count_id AND se.is_deleted = 0
WHERE lc.session_id = ?
AND lc.status = 'in_progress'
AND lc.is_deleted = 0
AND (
lc.counted_by = ?
OR lc.location_count_id IN (
SELECT location_count_id FROM ScanEntries
WHERE scanned_by = ? AND is_deleted = 0
)
)
GROUP BY lc.location_count_id
ORDER BY lc.start_timestamp DESC
''', [session_id, session['user_id'], session['user_id']])
# Get this user's completed bins
completed_bins = query_db('''
@@ -129,11 +136,17 @@ def my_counts(session_id):
FROM LocationCounts lc
LEFT JOIN ScanEntries se ON lc.location_count_id = se.location_count_id AND se.is_deleted = 0
WHERE lc.session_id = ?
AND lc.counted_by = ?
AND lc.status = 'completed'
AND (
lc.counted_by = ?
OR lc.location_count_id IN (
SELECT location_count_id FROM ScanEntries
WHERE scanned_by = ? AND is_deleted = 0
)
)
GROUP BY lc.location_count_id
ORDER BY lc.end_timestamp DESC
''', [session_id, session['user_id']])
ORDER BY lc.start_timestamp DESC
''', [session_id, session['user_id'], session['user_id']])
return render_template('counts/my_counts.html',
count_session=sess,
@@ -144,7 +157,7 @@ def my_counts(session_id):
@counting_bp.route('/session/<int:session_id>/start-bin', methods=['POST'])
@login_required
def start_bin_count(session_id):
"""Start counting a new bin"""
"""Start counting a new bin or resume an existing in-progress one"""
sess = get_active_session(session_id)
if not sess:
flash('Session not found or archived', 'warning')
@@ -158,7 +171,21 @@ def start_bin_count(session_id):
if not location_name:
flash('Bin number is required', 'danger')
return redirect(url_for('counting.my_counts', session_id=session_id))
# --- NEW LOGIC: Check for existing in-progress bin ---
existing_bin = query_db('''
SELECT location_count_id
FROM LocationCounts
WHERE session_id = ? AND location_name = ? AND status = 'in_progress'
''', [session_id, location_name], one=True)
if existing_bin:
flash(f'Resuming bin: {location_name}', 'info')
return redirect(url_for('counting.count_location',
session_id=session_id,
location_count_id=existing_bin['location_count_id']))
# --- END NEW LOGIC ---
# Count expected lots from MASTER baseline for this location
expected_lots = query_db('''
SELECT COUNT(DISTINCT lot_number) as count
@@ -168,7 +195,7 @@ def start_bin_count(session_id):
expected_count = expected_lots['count'] if expected_lots else 0
# Create new location count
# Create new location count if none existed
conn = get_db()
cursor = conn.cursor()
@@ -184,7 +211,6 @@ def start_bin_count(session_id):
flash(f'Started counting bin: {location_name}', 'success')
return redirect(url_for('counting.count_location', session_id=session_id, location_count_id=location_count_id))
@counting_bp.route('/location/<int:location_count_id>/complete', methods=['POST'])
@login_required
def complete_location(location_count_id):
@@ -512,7 +538,7 @@ def scan_lot(session_id, location_count_id):
def delete_scan(entry_id):
"""Soft delete a scan and recalculate duplicate statuses"""
# Get the scan being deleted
scan = query_db('SELECT * FROM ScanEntries WHERE entry_id = ?', [entry_id], one=True)
scan = query_db('SELECT * FROM ScanEntries WHERE entry_id = ? AND is_deleted = 0', [entry_id], one=True)
if not scan:
return jsonify({'success': False, 'message': 'Scan not found'})
@@ -572,7 +598,7 @@ def update_scan(entry_id):
comment = data.get('comment', '')
# Get the scan
scan = query_db('SELECT * FROM ScanEntries WHERE entry_id = ?', [entry_id], one=True)
scan = query_db('SELECT * FROM ScanEntries WHERE entry_id = ? AND is_deleted = 0', [entry_id], one=True)
if not scan:
return jsonify({'success': False, 'message': 'Scan not found'})
@@ -593,7 +619,7 @@ def update_scan(entry_id):
actual_weight = ?,
comment = ?,
modified_timestamp = CURRENT_TIMESTAMP
WHERE entry_id = ?
WHERE entry_id = ? and is_deleted = 0
''', [item, weight, comment, entry_id])
return jsonify({'success': True, 'message': 'Scan updated'})
@@ -625,7 +651,7 @@ def recalculate_duplicate_status(session_id, lot_number, current_location):
duplicate_info = NULL,
comment = NULL,
modified_timestamp = CURRENT_TIMESTAMP
WHERE entry_id = ?
WHERE entry_id = ? and is_deleted = 0
''', [scan['entry_id']])
updated_entries.append({
'entry_id': scan['entry_id'],
@@ -670,7 +696,7 @@ def recalculate_duplicate_status(session_id, lot_number, current_location):
duplicate_info = ?,
comment = ?,
modified_timestamp = CURRENT_TIMESTAMP
WHERE entry_id = ?
WHERE entry_id = ? and is_deleted = 0
''', [duplicate_status, duplicate_info, duplicate_info, scan['entry_id']])
# Update our tracking list
@@ -689,7 +715,7 @@ def recalculate_duplicate_status(session_id, lot_number, current_location):
duplicate_info = ?,
comment = ?,
modified_timestamp = CURRENT_TIMESTAMP
WHERE entry_id = ?
WHERE entry_id = ? and is_deleted = 0
''', [duplicate_status, duplicate_info, duplicate_info, prev_scan['entry_id']])
# Update tracking for previous scans
@@ -754,4 +780,57 @@ def finish_location(session_id, location_count_id):
return jsonify({
'success': True,
'redirect': url_for('counting.count_session', session_id=session_id)
})
})
@counting_bp.route('/session/<int:session_id>/finalize-all', methods=['POST'])
@login_required
def finalize_all_locations(session_id):
"""Finalize all 'in_progress' locations in a session"""
if session.get('role') not in ['owner', 'admin']:
return jsonify({'success': False, 'message': 'Permission denied'}), 403
# 1. Get all in_progress locations for this session
locations = query_db('''
SELECT location_count_id, location_name
FROM LocationCounts
WHERE session_id = ?
AND status = 'in_progress'
AND is_deleted = 0
''', [session_id])
if not locations:
return jsonify({'success': True, 'message': 'No open bins to finalize.'})
# 2. Loop through and run the finalize logic for each
for loc in locations:
# We reuse the logic from your existing finish_location route
execute_db('''
UPDATE LocationCounts
SET status = 'completed', end_timestamp = CURRENT_TIMESTAMP
WHERE location_count_id = ?
''', [loc['location_count_id']])
# Identify missing lots from MASTER baseline
expected_lots = query_db('''
SELECT lot_number, item, description, system_quantity
FROM BaselineInventory_Master
WHERE session_id = ? AND system_bin = ?
''', [session_id, loc['location_name']])
scanned_lots = query_db('''
SELECT DISTINCT lot_number
FROM ScanEntries
WHERE location_count_id = ? AND is_deleted = 0
''', [loc['location_count_id']])
scanned_lot_numbers = {s['lot_number'] for s in scanned_lots}
for expected in expected_lots:
if expected['lot_number'] not in scanned_lot_numbers:
execute_db('''
INSERT INTO MissingLots (session_id, lot_number, master_expected_location, item, master_expected_quantity, marked_by)
VALUES (?, ?, ?, ?, ?, ?)
''', [session_id, expected['lot_number'], loc['location_name'],
expected['item'], expected['system_quantity'], session['user_id']])
return jsonify({'success': True, 'message': f'Successfully finalized {len(locations)} bins.'})

View File

@@ -24,7 +24,7 @@ def create_session():
flash(f'Session "{session_name}" created successfully!', 'success')
return redirect(url_for('sessions.session_detail', session_id=session_id))
return render_template('create_session.html')
return render_template('/counts/create_session.html')
@sessions_bp.route('/session/<int:session_id>')
@@ -54,24 +54,38 @@ def session_detail(session_id):
''', [session_id], one=True)
# Get location progress
# We add a subquery to count the actual missing lots for each bin
locations = query_db('''
SELECT lc.*, u.full_name as counter_name
SELECT
lc.*,
u.full_name as counter_name,
(SELECT COUNT(*) FROM MissingLots ml
WHERE ml.session_id = lc.session_id
AND ml.master_expected_location = lc.location_name) as lots_missing_calc
FROM LocationCounts lc
LEFT JOIN Users u ON lc.counted_by = u.user_id
WHERE lc.session_id = ?
AND lc.is_deleted = 0
ORDER BY lc.status DESC, lc.location_name
''', [session_id])
# Get active counters
active_counters = query_db('''
SELECT DISTINCT u.full_name, lc.location_name, lc.start_timestamp
SELECT
u.full_name,
u.user_id,
MAX(lc.start_timestamp) AS start_timestamp, -- Add the alias here!
lc.location_name
FROM LocationCounts lc
JOIN Users u ON lc.counted_by = u.user_id
WHERE lc.session_id = ? AND lc.status = 'in_progress'
ORDER BY lc.start_timestamp DESC
WHERE lc.session_id = ?
AND lc.status = 'in_progress'
AND lc.is_deleted = 0
GROUP BY u.user_id
ORDER BY start_timestamp DESC
''', [session_id])
return render_template('session_detail.html',
return render_template('/counts/session_detail.html',
count_session=sess,
stats=stats,
locations=locations,
@@ -98,6 +112,7 @@ def get_status_details(session_id, status):
WHERE se.session_id = ?
AND se.master_status = 'match'
AND se.duplicate_status = '00'
AND se.master_variance_lbs = 0
AND se.is_deleted = 0
ORDER BY se.scan_timestamp DESC
''', [session_id])
@@ -184,20 +199,21 @@ def get_status_details(session_id, status):
# Missing lots (in master but not scanned)
items = query_db('''
SELECT
bim.lot_number,
bim.item,
ml.lot_number,
ml.item,
bim.description,
bim.system_bin,
bim.system_quantity
FROM BaselineInventory_Master bim
WHERE bim.session_id = ?
AND bim.lot_number NOT IN (
SELECT lot_number
FROM ScanEntries
WHERE session_id = ? AND is_deleted = 0
)
ORDER BY bim.system_bin, bim.lot_number
''', [session_id, session_id])
ml.master_expected_location as system_bin,
ml.master_expected_quantity as system_quantity
FROM MissingLots ml
LEFT JOIN BaselineInventory_Master bim ON
ml.lot_number = bim.lot_number AND
ml.item = bim.item AND
ml.master_expected_location = bim.system_bin AND
ml.session_id = bim.session_id
WHERE ml.session_id = ?
GROUP BY ml.lot_number, ml.item, ml.master_expected_location
ORDER BY ml.master_expected_location, ml.lot_number
''', [session_id])
else:
return jsonify({'success': False, 'message': 'Invalid status'})
@@ -241,4 +257,40 @@ def activate_session(session_id):
execute_db('UPDATE CountSessions SET status = ? WHERE session_id = ?', ['active', session_id])
return jsonify({'success': True, 'message': 'Session activated successfully'})
return jsonify({'success': True, 'message': 'Session activated successfully'})
@sessions_bp.route('/session/<int:session_id>/get_stats')
@role_required('owner', 'admin')
def get_session_stats(session_id):
stats = query_db('''
SELECT
COUNT(DISTINCT se.entry_id) FILTER (WHERE se.master_status = 'match' AND se.duplicate_status = '00' AND se.master_variance_lbs = 0 AND se.is_deleted = 0 AND ABS(se.actual_weight - se.master_expected_weight) < 0.01) as matched,
COUNT(DISTINCT se.lot_number) FILTER (WHERE se.duplicate_status IN ('01', '03', '04') AND se.is_deleted = 0) as duplicates,
COUNT(DISTINCT se.entry_id) FILTER (WHERE se.master_status = 'match' AND se.duplicate_status = '00' AND se.is_deleted = 0 AND ABS(se.actual_weight - se.master_expected_weight) >= 0.01) as discrepancy,
COUNT(DISTINCT se.entry_id) FILTER (WHERE se.master_status = 'wrong_location' AND se.is_deleted = 0) as wrong_location,
COUNT(DISTINCT se.entry_id) FILTER (WHERE se.master_status = 'ghost_lot' AND se.is_deleted = 0) as ghost_lots,
COUNT(DISTINCT ml.missing_id) as missing
FROM CountSessions cs
LEFT JOIN ScanEntries se ON cs.session_id = se.session_id
LEFT JOIN MissingLots ml ON cs.session_id = ml.session_id
WHERE cs.session_id = ?
''', [session_id], one=True)
return jsonify(success=True, stats=dict(stats))
@sessions_bp.route('/session/<int:session_id>/active-counters-fragment')
@role_required('owner', 'admin')
def active_counters_fragment(session_id):
# Use that unique-user query we just built together
active_counters = query_db('''
SELECT
u.full_name,
MAX(lc.start_timestamp) AS start_timestamp,
lc.location_name
FROM LocationCounts lc
JOIN Users u ON lc.counted_by = u.user_id
WHERE lc.session_id = ? AND lc.status = 'in_progress' AND lc.is_deleted = 0
GROUP BY u.user_id
''', [session_id])
# This renders JUST the list part, not the whole page
return render_template('counts/partials/_active_counters.html', active_counters=active_counters)

View File

@@ -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()

Binary file not shown.

View File

@@ -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,77 +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()
# 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),
(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()
@@ -223,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}")
@@ -238,8 +193,8 @@ def run_migrations():
print(f" ❌ Migration {version} failed: {e}")
raise
print("\n✅ All migrations complete")
print("\n✅ All core migrations complete")
if __name__ == '__main__':
run_migrations()
run_migrations()

359
module_manager.py Normal file
View File

@@ -0,0 +1,359 @@
"""
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, 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

View 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

View File

@@ -0,0 +1,11 @@
{
"module_key": "conssheets",
"name": "Consumption Sheets",
"version": "1.0.0",
"author": "STUFF",
"description": "Production lot tracking and consumption reporting with Excel export",
"requires_roles": ["owner", "admin", "staff"],
"routes_prefix": "/conssheets",
"has_migrations": true,
"dependencies": []
}

View 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),
]

1244
modules/conssheets/routes.py Normal file

File diff suppressed because it is too large Load Diff

View 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('cons_sheets.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;">
<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">
<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('cons_sheets.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('cons_sheets.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('cons_sheets.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('cons_sheets.create_process') }}" class="btn btn-primary">
Create First Process
</a>
</div>
{% endif %}
</div>
{% endblock %}

View File

@@ -50,16 +50,40 @@
<form method="POST" action="{{ url_for('cons_sheets.update_template_settings', process_id=process.id) }}">
<div class="form-group">
<label for="rows_per_page" class="form-label">Rows Per Page</label>
<label for="rows_per_page" class="form-label">Rows Per Page (Capacity)</label>
<input type="number" id="rows_per_page" name="rows_per_page"
value="{{ process.rows_per_page or 30 }}" min="1" max="500" class="form-input">
<p class="form-hint">Max detail rows before starting a new page</p>
value="{{ process.rows_per_page or 30 }}" min="1" max="5000" class="form-input">
<p class="form-hint">How many items fit in the grid before we need a new page?</p>
</div>
<div class="form-group" style="flex: 1;">
<label for="print_start_col" class="form-label">Print Start Column</label>
<input type="text" id="print_start_col" name="print_start_col"
value="{{ process.print_start_col or 'A' }}" class="form-input"
placeholder="e.g. A" pattern="[A-Za-z]+" title="Letters only">
<p class="form-hint">First column to print.</p>
</div>
<div class="form-group" style="flex: 1;">
<label for="print_end_col" class="form-label">Print End Column</label>
<input type="text" id="print_end_col" name="print_end_col"
value="{{ process.print_end_col or '' }}" class="form-input"
placeholder="e.g. K" pattern="[A-Za-z]+" title="Letters only">
<p class="form-hint">Last column to print (defines width).</p>
</div>
<div class="form-group">
<label for="page_height" class="form-label">Page Height (Total Rows)</label>
<input type="number" id="page_height" name="page_height"
value="{{ process.page_height or '' }}" min="1" class="form-input">
<p class="form-hint">The exact distance (in Excel rows) from the top of Page 1 to the top of Page 2.</p>
</div>
<div class="form-group">
<label for="detail_start_row" class="form-label">Detail Start Row</label>
<input type="number" id="detail_start_row" name="detail_start_row"
value="{{ process.detail_start_row or 10 }}" min="1" max="500" class="form-input">
value="{{ process.detail_start_row or 10 }}" min="1" max="5000" class="form-input">
<p class="form-hint">Excel row number where detail data begins</p>
</div>

View File

@@ -101,6 +101,11 @@
<div class="scans-header">
<h3 class="scans-title">Scanned Items (<span id="scanListCount">{{ scans|length }}</span>)</h3>
</div>
<div style="margin-top: 10px;">
<button type="button" class="btn btn-secondary btn-sm" onclick="document.getElementById('importModal').style.display='flex'">
<i class="fa-solid fa-file-import"></i> Bulk Import Excel
</button>
</div>
<div id="scansList" class="scans-grid" style="--field-count: {{ detail_fields|length }};">
{% for scan in scans %}
<div class="scan-row scan-row-{{ scan.duplicate_status }}"
@@ -137,6 +142,39 @@
</div>
</div>
<div id="importModal" class="modal">
<div class="modal-content">
<div class="modal-header-bar">
<h3 class="modal-title">Bulk Import Data</h3>
<button type="button" class="btn-close-modal" onclick="document.getElementById('importModal').style.display='none'">&times;</button>
</div>
<div class="modal-body" style="text-align: center;">
<p style="color: var(--color-text-muted); margin-bottom: 20px;">
Upload an Excel file (.xlsx) to automatically populate this session.
<br><strong>Warning:</strong> This bypasses all validation checks.
</p>
<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">
<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">
<div style="margin-bottom: 20px;">
<input type="file" name="file" accept=".xlsx" class="file-input" required style="width: 100%;">
</div>
<button type="submit" class="btn btn-primary btn-block">
<i class="fa-solid fa-upload"></i> Upload & Process
</button>
</form>
</div>
</div>
</div>
<style>
.header-values { display: flex; flex-wrap: wrap; gap: var(--space-sm); margin: var(--space-sm) 0; }
.header-pill { background: var(--color-surface-elevated); padding: var(--space-xs) var(--space-sm); border-radius: var(--radius-sm); font-size: 0.8rem; color: var(--color-text-muted); }

View 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

View File

@@ -0,0 +1,11 @@
{
"module_key": "invcount",
"name": "Inventory Counts",
"version": "1.0.0",
"author": "STUFF",
"description": "Cycle counting and physical inventory workflows with session-based tracking",
"requires_roles": ["owner", "admin", "staff"],
"routes_prefix": "/invcount",
"has_migrations": true,
"dependencies": []
}

View 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

File diff suppressed because it is too large Load Diff

View File

@@ -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>

View File

@@ -160,12 +160,10 @@
<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>
<button id="finishBtn" class="btn btn-success btn-block btn-lg" onclick="finishLocation()">
✓ Finish Location
</button>
{# Finish button moved to Admin Dashboard #}
</div>
</div>
<button class="scroll-to-top" onclick="window.scrollTo({top: 0, behavior: 'smooth'})">
@@ -218,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({
@@ -287,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({
@@ -587,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'}
})

View File

@@ -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,17 +46,9 @@
</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 class="bin-actions-row">
<button class="btn btn-secondary" onclick="markComplete('{{ bin.location_count_id }}')">
✓ Mark Complete
</button>
<button class="btn btn-danger" onclick="deleteBinCount('{{ bin.location_count_id }}', '{{ bin.location_name }}')">
🗑️ Delete
</button>
</div>
</div>
</div>
{% endfor %}
@@ -114,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">

View File

@@ -0,0 +1,12 @@
<div class="counter-list">
{% for counter in active_counters %}
<div class="counter-item">
<div class="counter-avatar">{{ counter.full_name[0] }}</div>
<div class="counter-info">
<div class="counter-name">{{ counter.full_name }}</div>
<div class="counter-location">📍 {{ counter.location_name }}</div>
</div>
<div class="counter-time">{{ counter.start_timestamp[11:16] }}</div>
</div>
{% endfor %}
</div>

View File

@@ -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">
@@ -72,43 +72,43 @@
</div>
<!-- Statistics Section -->
<div class="section-card">
<h2 class="section-title">Real-Time Statistics</h2>
<div class="stats-grid">
<div class="stat-card stat-match" onclick="showStatusDetails('match')">
<div class="stat-number">{{ stats.matched or 0 }}</div>
<div class="stat-label">✓ Matched</div>
</div>
<div class="stat-card stat-duplicate" onclick="showStatusDetails('duplicates')">
<div class="stat-number">{{ stats.duplicates or 0 }}</div>
<div class="stat-label">🔵 Duplicates</div>
</div>
<div class="stat-card stat-weight-disc" onclick="showStatusDetails('weight_discrepancy')">
<div class="stat-number">{{ stats.weight_discrepancy or 0 }}</div>
<div class="stat-label">⚖️ Weight Discrepancy</div>
</div>
<div class="stat-card stat-wrong" onclick="showStatusDetails('wrong_location')">
<div class="stat-number">{{ stats.wrong_location or 0 }}</div>
<div class="stat-label">⚠ Wrong Location</div>
</div>
<div class="stat-card stat-ghost" onclick="showStatusDetails('ghost_lot')">
<div class="stat-number">{{ stats.ghost_lots or 0 }}</div>
<div class="stat-label">🟣 Ghost Lots</div>
</div>
<div class="stat-card stat-missing" onclick="showStatusDetails('missing')">
<div class="stat-number">{{ stats.missing_lots or 0 }}</div>
<div class="stat-label">🔴 Missing</div>
</div>
<div class="section-card">
<h2 class="section-title">Real-Time Statistics</h2>
<div class="stats-grid">
<div class="stat-card stat-match" onclick="showStatusDetails('match')">
<div class="stat-number" id="count-matched">{{ stats.matched or 0 }}</div>
<div class="stat-label">✓ Matched</div>
</div>
<div class="stat-card stat-duplicate" onclick="showStatusDetails('duplicates')">
<div class="stat-number" id="count-duplicates">{{ stats.duplicates or 0 }}</div>
<div class="stat-label">🔵 Duplicates</div>
</div>
<div class="stat-card stat-weight-disc" onclick="showStatusDetails('weight_discrepancy')">
<div class="stat-number" id="count-discrepancy">{{ stats.weight_discrepancy or 0 }}</div>
<div class="stat-label">⚖️ Weight Discrepancy</div>
</div>
<div class="stat-card stat-wrong" onclick="showStatusDetails('wrong_location')">
<div class="stat-number" id="count-wrong">{{ stats.wrong_location or 0 }}</div>
<div class="stat-label">⚠ Wrong Location</div>
</div>
<div class="stat-card stat-ghost" onclick="showStatusDetails('ghost_lot')">
<div class="stat-number" id="count-ghost">{{ stats.ghost_lots or 0 }}</div>
<div class="stat-label">🟣 Ghost Lots</div>
</div>
<div class="stat-card stat-missing" onclick="showStatusDetails('missing')">
<div class="stat-number" id="count-missing">{{ stats.missing_lots or 0 }}</div>
<div class="stat-label">🔴 Missing</div>
</div>
</div>
</div>
<!-- Active Counters Section -->
{% if active_counters %}
<div class="section-card">
<h2 class="section-title">Active Counters</h2>
<div class="counter-list">
{% for counter in active_counters %}
<div id="active-counters-container"> <div class="counter-list">
{% for counter in active_counters %}
<div class="counter-item">
<div class="counter-avatar">{{ counter.full_name[0] }}</div>
<div class="counter-info">
@@ -125,7 +125,12 @@
<!-- Location Progress Section -->
{% if locations %}
<div class="section-card">
<h2 class="section-title">Location Progress</h2>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: var(--space-md);">
<h2 class="section-title" style="margin-bottom: 0;">Location Progress</h2>
<button class="btn btn-danger btn-sm" onclick="showFinalizeAllConfirm()">
⚠️ Finalize All Bins
</button>
</div>
<div class="location-table">
<table>
<thead>
@@ -157,7 +162,7 @@
<td>{{ loc.counter_name or '-' }}</td>
<td>{{ loc.expected_lots_master }}</td>
<td>{{ loc.lots_found }}</td>
<td>{{ loc.lots_missing }}</td>
<td>{{ loc.lots_missing_calc }}</td>
</tr>
{% endfor %}
</tbody>
@@ -198,6 +203,9 @@
<button id="reopenLocationBtn" class="btn btn-warning btn-sm" style="display: none;" onclick="showReopenConfirm()">
🔓 Reopen Location
</button>
<button id="deleteLocationBtn" class="btn btn-danger btn-sm" style="display: none;" onclick="showDeleteBinConfirm()">
🗑️ Delete Bin
</button>
<button class="btn btn-secondary btn-sm" onclick="exportLocationToCSV()">
📥 Export CSV
</button>
@@ -281,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) {
@@ -460,7 +468,10 @@ function showLocationDetails(locationCountId, locationName, status) {
// Show finalize or reopen button based on status
const finalizeBtn = document.getElementById('finalizeLocationBtn');
const reopenBtn = document.getElementById('reopenLocationBtn');
const deleteBtn = document.getElementById('deleteLocationBtn'); // ADD THIS LINE
deleteBtn.style.display = 'block';
if (status === 'in_progress') {
finalizeBtn.style.display = 'block';
reopenBtn.style.display = 'none';
@@ -473,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) {
@@ -621,8 +632,8 @@ function closeFinalizeConfirm() {
}
function confirmFinalize() {
// Note: The /complete endpoint is handled by blueprints/counting.py
fetch(`/location/${currentLocationId}/complete`, {
// Correctly points to the /finish route to trigger Missing Lot calculations
fetch(`/invcount/count/${CURRENT_SESSION_ID}/location/${currentLocationId}/finish`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -633,16 +644,18 @@ function confirmFinalize() {
if (data.success) {
closeFinalizeConfirm();
closeLocationModal();
location.reload(); // Reload to show updated status
location.reload(); // Reload to show updated status and Missing counts
} else {
alert(data.message || 'Error finalizing location');
}
})
.catch(error => {
console.error('Finalize Error:', error);
alert('Error: ' + error.message);
});
}
function showReopenConfirm() {
document.getElementById('reopenBinName').textContent = currentLocationName;
document.getElementById('reopenConfirmModal').style.display = 'flex';
@@ -654,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',
@@ -687,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'}
})
@@ -704,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'}
})
@@ -717,5 +730,78 @@ 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(`/invcount/session/${CURRENT_SESSION_ID}/finalize-all`, {
method: 'POST',
headers: {'Content-Type': 'application/json'}
})
.then(r => r.json())
.then(data => {
if (data.success) {
alert(data.message);
location.reload();
} else {
alert("Error: " + data.message);
}
});
}
}
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(`/invcount/location/${currentLocationId}/delete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => {
if (data.success) {
closeLocationModal();
location.reload();
} else {
alert(data.message || 'Error deleting bin');
}
})
.catch(error => {
alert('Error: ' + error.message);
});
}
}
function refreshDashboardStats() {
const sessionId = CURRENT_SESSION_ID;
fetch(`/invcount/session/${sessionId}/get_stats`)
.then(response => response.json())
.then(data => {
if (data.success) {
const s = data.stats;
// These IDs must match your HTML and the keys must match sessions.py
if (document.getElementById('count-matched')) document.getElementById('count-matched').innerText = s.matched;
if (document.getElementById('count-duplicates')) document.getElementById('count-duplicates').innerText = s.duplicates;
if (document.getElementById('count-discrepancy')) document.getElementById('count-discrepancy').innerText = s.discrepancy;
if (document.getElementById('count-wrong')) document.getElementById('count-wrong').innerText = s.wrong_location; // Fixed
if (document.getElementById('count-ghost')) document.getElementById('count-ghost').innerText = s.ghost_lots; // Fixed
if (document.getElementById('count-missing')) document.getElementById('count-missing').innerText = s.missing;
}
})
.catch(err => console.error('Error refreshing stats:', err));
fetch(`/invcount/session/${sessionId}/active-counters-fragment`)
.then(response => response.text())
.then(html => {
const container = document.getElementById('active-counters-container');
if (container) container.innerHTML = html;
})
.catch(err => console.error('Error refreshing counters:', err));
}
// This tells the browser: "Run the refresh function every 30 seconds"
setInterval(refreshDashboardStats, 30000);
// This runs it IMMEDIATELY once so you don't wait 30 seconds for the first update
refreshDashboardStats();
</script>
{% endblock %}

View File

@@ -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>

View File

@@ -1,3 +1,4 @@
Flask==3.1.2
Werkzeug==3.1.5
openpyxl
openpyxl
Pillow

View File

@@ -2282,4 +2282,23 @@ body {
.module-card-active .module-icon {
background: var(--color-primary);
color: var(--color-bg);
}
/* ==================== ICON BUTTONS ==================== */
.btn-icon-only {
background: transparent;
border: none;
color: var(--color-text-muted);
cursor: pointer;
padding: 4px 8px;
transition: var(--transition);
font-size: 0.9rem;
display: inline-flex;
align-items: center;
justify-content: center;
}
.btn-icon-only:hover {
color: var(--color-danger);
transform: scale(1.1);
}

View File

@@ -4,28 +4,45 @@
{% block content %}
<div class="dashboard-container">
<div class="dashboard-header" style="margin-top: var(--space-lg);">
<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>
<h1 class="page-title" style="margin-bottom: 0;">Admin Dashboard</h1>
</div>
<div class="header-right">
<a href="{{ url_for('module_manager_ui') }}" class="btn btn-primary btn-sm">
<i class="fa-solid fa-puzzle-piece"></i> Module Manager
</a>
</div>
</div>
<div class="modules-section">
<h2 class="section-title">Modules</h2>
{% if modules %}
<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>
{% 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="{{ 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 %}

View File

@@ -11,8 +11,21 @@
</a>
<div>
<h1 class="page-title" style="margin-bottom: 0;">Consumption Sheets</h1>
<p class="page-subtitle" style="margin-bottom: 0;">Manage process types and templates</p>
<h1 class="page-title" style="margin-bottom: 0; {{ 'color: var(--color-danger);' if showing_archived else '' }}">
{{ '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('cons_sheets.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;">
<i class="fa-solid fa-box-archive"></i> View Archived Processes
</a>
{% endif %}
</div>
</div>
@@ -25,11 +38,32 @@
<div class="sessions-grid">
{% for process in processes %}
<div class="session-card">
<div class="session-card-header">
<h3 class="session-name">{{ process.process_name }}</h3>
<span class="session-type-badge">
{{ process.field_count or 0 }} fields
</span>
<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('cons_sheets.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('cons_sheets.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">
@@ -57,6 +91,8 @@
</a>
</div>
</div>
{% endfor %}
</div>
{% else %}

View File

@@ -22,7 +22,7 @@
{% 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>

View File

@@ -0,0 +1,182 @@
{% extends "base.html" %}
{% block title %}Module Manager - ScanLook{% endblock %}
{% block content %}
<div class="container mt-4">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1><i class="fas fa-puzzle-piece"></i> Module Manager</h1>
<a href="{{ url_for('home') }}" class="btn btn-secondary">
<i class="fas fa-arrow-left"></i> Back to Home
</a>
</div>
<p class="lead">Install, uninstall, and manage ScanLook modules</p>
<div class="row">
{% for module in modules %}
<div class="col-md-6 col-lg-4 mb-4">
<div class="card h-100 {% if module.is_active %}border-success{% elif module.is_installed %}border-warning{% endif %}">
<div class="card-header {% if module.is_active %}bg-success text-white{% elif module.is_installed %}bg-warning text-dark{% else %}bg-light{% endif %}">
<h5 class="mb-0">
<i class="fas fa-cube"></i> {{ module.name }}
<span class="badge badge-secondary float-right">v{{ module.version }}</span>
</h5>
</div>
<div class="card-body">
<p class="card-text">{{ module.description }}</p>
<p class="mb-2">
<small class="text-muted">
<strong>Author:</strong> {{ module.author }}<br>
<strong>Module Key:</strong> <code>{{ module.module_key }}</code>
</small>
</p>
<div class="mt-3">
{% if module.is_installed and module.is_active %}
<span class="badge badge-success mb-2">
<i class="fas fa-check-circle"></i> Active
</span>
{% elif module.is_installed %}
<span class="badge badge-warning mb-2">
<i class="fas fa-pause-circle"></i> Installed (Inactive)
</span>
{% else %}
<span class="badge badge-secondary mb-2">
<i class="fas fa-times-circle"></i> Not Installed
</span>
{% endif %}
</div>
</div>
<div class="card-footer bg-light">
{% if not module.is_installed %}
<button class="btn btn-primary btn-sm btn-block" onclick="installModule('{{ module.module_key }}')">
<i class="fas fa-download"></i> Install
</button>
{% elif module.is_active %}
<button class="btn btn-warning btn-sm btn-block mb-2" onclick="deactivateModule('{{ module.module_key }}')">
<i class="fas fa-pause"></i> Deactivate
</button>
<button class="btn btn-danger btn-sm btn-block" onclick="uninstallModule('{{ module.module_key }}')">
<i class="fas fa-trash"></i> Uninstall
</button>
{% else %}
<button class="btn btn-success btn-sm btn-block mb-2" onclick="activateModule('{{ module.module_key }}')">
<i class="fas fa-play"></i> Activate
</button>
<button class="btn btn-danger btn-sm btn-block" onclick="uninstallModule('{{ module.module_key }}')">
<i class="fas fa-trash"></i> Uninstall
</button>
{% endif %}
</div>
</div>
</div>
{% endfor %}
</div>
{% if not modules %}
<div class="alert alert-info">
<i class="fas fa-info-circle"></i> No modules found in the <code>/modules</code> directory.
</div>
{% endif %}
</div>
<script>
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) {
alert(`${data.message}\n\nPlease reload the page.`);
location.reload();
} else {
alert(`${data.message}`);
}
})
.catch(error => {
alert(`❌ Error: ${error}`);
});
}
function uninstallModule(moduleKey) {
if (!confirm(`⚠️ UNINSTALL module "${moduleKey}"?\n\nThis will DELETE all module data and cannot be undone!`)) {
return;
}
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\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}`);
});
}
</script>
{% endblock %}