Compare commits
12 Commits
3ec00613ca
...
Update-Exc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a649fdbcc | ||
|
|
89be88566f | ||
|
|
1359e036d5 | ||
|
|
ad071438cc | ||
|
|
5604686630 | ||
|
|
2d333c16a3 | ||
|
|
288b390618 | ||
|
|
fcdef6875e | ||
|
|
a6d8767c28 | ||
|
|
d6e9f20757 | ||
|
|
674a8f8a0c | ||
|
|
5097ceb82f |
@@ -4,20 +4,7 @@ You are helping build a project called **Scanlook**.
|
|||||||
|
|
||||||
## Scanlook (current product summary)
|
## Scanlook (current product summary)
|
||||||
Scanlook is a web app for warehouse counting workflows.
|
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**.
|
Scanlook is modular.
|
||||||
- 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).
|
|
||||||
|
|
||||||
Long-term goal: evolve into a WMS, but right now focus on making this workflow reliable.
|
Long-term goal: evolve into a WMS, but right now focus on making this workflow reliable.
|
||||||
|
|
||||||
@@ -30,8 +17,9 @@ Long-term goal: evolve into a WMS, but right now focus on making this workflow r
|
|||||||
6) **Verify safety.** Warn me before destructive actions (delete/overwrite/migrations). Offer a safer alternative.
|
6) **Verify safety.** Warn me before destructive actions (delete/overwrite/migrations). Offer a safer alternative.
|
||||||
7) **Evidence-based debugging.** Ask for exact error text/logs and versions before guessing.
|
7) **Evidence-based debugging.** Ask for exact error text/logs and versions before guessing.
|
||||||
8) **CSS changes:** Ask which device(s) the change is for (desktop/mobile/scanner) before editing. Each has its own file.
|
8) **CSS changes:** Ask which device(s) the change is for (desktop/mobile/scanner) before editing. Each has its own file.
|
||||||
9) **Database changes:** The app auto-initializes the database if it doesn't exist. Schema is in /database/init_db.py.
|
9) **Docker deployment:** Production runs in Docker on Linux (PortainerVM). Volume mounts only /app/database to preserve data between updates.
|
||||||
10) **Docker deployment:** Production runs in Docker on Linux (jisoo). Volume mounts only /app/database to preserve data between updates.
|
10) Database changes: Never tell user to "manually run SQL". Always add changes to migrations.py so they auto-apply on deployment.
|
||||||
|
|
||||||
|
|
||||||
## How you should respond
|
## How you should respond
|
||||||
- Start by confirming which mode we’re working on: Cycle Count or Physical Inventory.
|
- Start by confirming which mode we’re working on: Cycle Count or Physical Inventory.
|
||||||
@@ -43,10 +31,10 @@ Long-term goal: evolve into a WMS, but right now focus on making this workflow r
|
|||||||
## Scanlook (current product summary)
|
## Scanlook (current product summary)
|
||||||
Scanlook is a web app for warehouse counting workflows built with Flask + SQLite.
|
Scanlook is a web app for warehouse counting workflows built with Flask + SQLite.
|
||||||
|
|
||||||
**Current Version:** 0.12.0
|
**Current Version:** 0.14.0
|
||||||
|
|
||||||
**Tech Stack:**
|
**Tech Stack:**
|
||||||
- Backend: Python/Flask, raw SQL (no ORM)
|
- Backend: Python/Flask, raw SQL (no ORM), openpyxl (Excel file generation)
|
||||||
- Database: SQLite (located in /database/scanlook.db)
|
- Database: SQLite (located in /database/scanlook.db)
|
||||||
- Frontend: Jinja2 templates, vanilla JS, custom CSS
|
- Frontend: Jinja2 templates, vanilla JS, custom CSS
|
||||||
- CSS Architecture: Desktop-first with device-specific overrides
|
- CSS Architecture: Desktop-first with device-specific overrides
|
||||||
@@ -63,6 +51,7 @@ Scanlook is a web app for warehouse counting workflows built with Flask + SQLite
|
|||||||
- /database/ (scanlook.db, init_db.py)
|
- /database/ (scanlook.db, init_db.py)
|
||||||
- db.py (database helper functions: query_db, execute_db)
|
- db.py (database helper functions: query_db, execute_db)
|
||||||
- utils.py (decorators: login_required, role_required)
|
- utils.py (decorators: login_required, role_required)
|
||||||
|
- migrations.py (database migration system)
|
||||||
|
|
||||||
**Key Features (implemented):**
|
**Key Features (implemented):**
|
||||||
- Count Sessions with archive/activate functionality
|
- Count Sessions with archive/activate functionality
|
||||||
@@ -74,14 +63,12 @@ Scanlook is a web app for warehouse counting workflows built with Flask + SQLite
|
|||||||
- Session isolation (archived sessions blocked from access)
|
- Session isolation (archived sessions blocked from access)
|
||||||
- Role-based access: owner, admin, staff
|
- Role-based access: owner, admin, staff
|
||||||
- Auto-initialize database on first run
|
- Auto-initialize database on first run
|
||||||
|
- Consumption Sheets module (production lot tracking with Excel export)
|
||||||
**Two count types:**
|
- Database migration system (auto-applies schema changes on startup)
|
||||||
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.
|
**Long-term goal:** Modular WMS with future modules for Shipping, Receiving, Transfers, Production.
|
||||||
|
|
||||||
**Module System (v0.12.0):**
|
**Module System (v0.14.0):**
|
||||||
- Modules table defines available modules (module_key used for routing)
|
- Modules table defines available modules (module_key used for routing)
|
||||||
- UserModules table tracks per-user access
|
- UserModules table tracks per-user access
|
||||||
- Home page (/home) shows module cards based on user's access
|
- Home page (/home) shows module cards based on user's access
|
||||||
@@ -90,6 +77,9 @@ Scanlook is a web app for warehouse counting workflows built with Flask + SQLite
|
|||||||
- __init__.py (blueprint registration)
|
- __init__.py (blueprint registration)
|
||||||
- routes.py (all routes)
|
- routes.py (all routes)
|
||||||
- templates/ (module-specific templates)
|
- templates/ (module-specific templates)
|
||||||
|
- Current modules:
|
||||||
|
- Inventory Counts (counting)
|
||||||
|
- Consumption Sheets (cons_sheets)
|
||||||
|
|
||||||
|
|
||||||
## Quick Reference
|
## Quick Reference
|
||||||
@@ -97,5 +87,5 @@ Scanlook is a web app for warehouse counting workflows built with Flask + SQLite
|
|||||||
- Scanner viewport: 320px wide (MC9300)
|
- Scanner viewport: 320px wide (MC9300)
|
||||||
- Mobile breakpoint: 360-767px
|
- Mobile breakpoint: 360-767px
|
||||||
- Desktop: 768px+
|
- 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
|
- Docker registry: 10.44.44.33:3000/stuff/scanlook
|
||||||
22
app.py
22
app.py
@@ -38,7 +38,7 @@ app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=1)
|
|||||||
|
|
||||||
|
|
||||||
# 1. Define the version
|
# 1. Define the version
|
||||||
APP_VERSION = '0.13.0'
|
APP_VERSION = '0.15.0'
|
||||||
|
|
||||||
# 2. Inject it into all templates automatically
|
# 2. Inject it into all templates automatically
|
||||||
@app.context_processor
|
@app.context_processor
|
||||||
@@ -54,6 +54,10 @@ if not os.path.exists(db_path):
|
|||||||
create_default_users()
|
create_default_users()
|
||||||
print("Database initialized!")
|
print("Database initialized!")
|
||||||
|
|
||||||
|
# Run migrations to apply any pending database changes
|
||||||
|
from migrations import run_migrations
|
||||||
|
run_migrations()
|
||||||
|
|
||||||
|
|
||||||
# ==================== ROUTES: AUTHENTICATION ====================
|
# ==================== ROUTES: AUTHENTICATION ====================
|
||||||
|
|
||||||
@@ -160,22 +164,6 @@ def admin_dashboard():
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/staff-mode')
|
|
||||||
@login_required
|
|
||||||
def staff_mode():
|
|
||||||
"""Allow admin/owner to switch to staff view for scanning"""
|
|
||||||
# Show staff dashboard view regardless of role
|
|
||||||
active_sessions = query_db('''
|
|
||||||
SELECT session_id, session_name, session_type, created_timestamp
|
|
||||||
FROM CountSessions
|
|
||||||
WHERE status = 'active'
|
|
||||||
ORDER BY created_timestamp DESC
|
|
||||||
''')
|
|
||||||
|
|
||||||
return render_template('staff_dashboard.html', sessions=active_sessions, is_admin_mode=True)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== PWA SUPPORT ROUTES ====================
|
# ==================== PWA SUPPORT ROUTES ====================
|
||||||
|
|
||||||
@app.route('/manifest.json')
|
@app.route('/manifest.json')
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -29,35 +29,6 @@ def reopen_location(location_count_id):
|
|||||||
return jsonify({'success': True, 'message': 'Bin reopened for counting'})
|
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')
|
@admin_locations_bp.route('/location/<int:location_count_id>/scans')
|
||||||
@login_required
|
@login_required
|
||||||
def get_location_scans(location_count_id):
|
def get_location_scans(location_count_id):
|
||||||
@@ -87,3 +58,39 @@ def get_location_scans(location_count_id):
|
|||||||
|
|
||||||
except Exception as e:
|
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'})
|
||||||
@@ -8,18 +8,23 @@ cons_sheets_bp = Blueprint('cons_sheets', __name__)
|
|||||||
@cons_sheets_bp.route('/admin/consumption-sheets')
|
@cons_sheets_bp.route('/admin/consumption-sheets')
|
||||||
@role_required('owner', 'admin')
|
@role_required('owner', 'admin')
|
||||||
def admin_processes():
|
def admin_processes():
|
||||||
"""List all consumption sheet process types"""
|
"""List all consumption sheet process types (Active or Archived)"""
|
||||||
processes = query_db('''
|
show_archived = request.args.get('archived') == '1'
|
||||||
SELECT cp.*, u.full_name as created_by_name,
|
is_active_val = 0 if show_archived else 1
|
||||||
(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
|
|
||||||
''')
|
|
||||||
|
|
||||||
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'])
|
@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()
|
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>')
|
@cons_sheets_bp.route('/admin/consumption-sheets/<int:process_id>')
|
||||||
@role_required('owner', 'admin')
|
@role_required('owner', 'admin')
|
||||||
def process_detail(process_id):
|
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)
|
rows_per_page = request.form.get('rows_per_page', 30)
|
||||||
detail_start_row = request.form.get('detail_start_row', 10)
|
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:
|
try:
|
||||||
rows_per_page = int(rows_per_page)
|
rows_per_page = int(rows_per_page)
|
||||||
detail_start_row = int(detail_start_row)
|
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:
|
except ValueError:
|
||||||
flash('Invalid number values', 'danger')
|
flash('Invalid number values', 'danger')
|
||||||
return redirect(url_for('cons_sheets.process_template', process_id=process_id))
|
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('''
|
execute_db('''
|
||||||
UPDATE cons_processes
|
UPDATE cons_processes
|
||||||
SET rows_per_page = ?, detail_start_row = ?
|
SET rows_per_page = ?, detail_start_row = ?, page_height = ?,
|
||||||
|
print_start_col = ?, print_end_col = ?
|
||||||
WHERE id = ?
|
WHERE id = ?
|
||||||
''', [rows_per_page, detail_start_row, process_id])
|
''', [rows_per_page, detail_start_row, page_height, print_start_col, print_end_col, process_id])
|
||||||
|
|
||||||
flash('Settings updated successfully!', 'success')
|
flash('Settings updated successfully!', 'success')
|
||||||
return redirect(url_for('cons_sheets.process_template', process_id=process_id))
|
return redirect(url_for('cons_sheets.process_template', process_id=process_id))
|
||||||
|
|
||||||
|
|
||||||
@cons_sheets_bp.route('/admin/consumption-sheets/<int:process_id>/template/download')
|
@cons_sheets_bp.route('/admin/consumption-sheets/<int:process_id>/template/download')
|
||||||
@role_required('owner', 'admin')
|
@role_required('owner', 'admin')
|
||||||
def download_template(process_id):
|
def download_template(process_id):
|
||||||
@@ -905,22 +951,59 @@ def archive_session(session_id):
|
|||||||
|
|
||||||
return jsonify({'success': True})
|
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
|
@login_required
|
||||||
def export_session(session_id):
|
def download_import_template(session_id):
|
||||||
"""Export session to Excel using the process template"""
|
"""Generate a blank Excel template for bulk import"""
|
||||||
from flask import Response
|
from flask import Response # <--- ADDED THIS
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
import openpyxl
|
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('''
|
sess = query_db('''
|
||||||
SELECT cs.*, cp.process_name, cp.process_key, cp.id as process_id,
|
SELECT cs.*, cp.process_key
|
||||||
cp.template_file, cp.template_filename, cp.rows_per_page, cp.detail_start_row
|
|
||||||
FROM cons_sessions cs
|
FROM cons_sessions cs
|
||||||
JOIN cons_processes cp ON cs.process_id = cp.id
|
JOIN cons_processes cp ON cs.process_id = cp.id
|
||||||
WHERE cs.id = ?
|
WHERE cs.id = ?
|
||||||
@@ -930,11 +1013,124 @@ def export_session(session_id):
|
|||||||
flash('Session not found', 'danger')
|
flash('Session not found', 'danger')
|
||||||
return redirect(url_for('cons_sheets.index'))
|
return redirect(url_for('cons_sheets.index'))
|
||||||
|
|
||||||
if not sess['template_file']:
|
# 2. Check File
|
||||||
flash('No template configured for this process', 'danger')
|
if 'file' not in request.files:
|
||||||
|
flash('No file uploaded', 'danger')
|
||||||
return redirect(url_for('cons_sheets.scan_session', session_id=session_id))
|
return redirect(url_for('cons_sheets.scan_session', session_id=session_id))
|
||||||
|
|
||||||
# Get header fields and values
|
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
|
||||||
|
|
||||||
|
# --- 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('''
|
header_fields = query_db('''
|
||||||
SELECT cpf.field_name, cpf.excel_cell, cshv.field_value
|
SELECT cpf.field_name, cpf.excel_cell, cshv.field_value
|
||||||
FROM cons_process_fields cpf
|
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
|
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']])
|
''', [session_id, sess['process_id']])
|
||||||
|
|
||||||
# Get detail fields with their column mappings
|
|
||||||
detail_fields = query_db('''
|
detail_fields = query_db('''
|
||||||
SELECT field_name, excel_cell, field_type
|
SELECT field_name, excel_cell, field_type
|
||||||
FROM cons_process_fields
|
FROM cons_process_fields
|
||||||
@@ -950,169 +1145,94 @@ def export_session(session_id):
|
|||||||
ORDER BY sort_order, id
|
ORDER BY sort_order, id
|
||||||
''', [sess['process_id']])
|
''', [sess['process_id']])
|
||||||
|
|
||||||
# Get all scanned details
|
table_name = f'cons_proc_{sess["process_key"]}_details'
|
||||||
table_name = get_detail_table_name(sess['process_key'])
|
|
||||||
scans = query_db(f'''
|
scans = query_db(f'''
|
||||||
SELECT * FROM {table_name}
|
SELECT * FROM {table_name}
|
||||||
WHERE session_id = ? AND is_deleted = 0
|
WHERE session_id = ? AND is_deleted = 0
|
||||||
ORDER BY scanned_at ASC
|
ORDER BY scanned_at ASC
|
||||||
''', [session_id])
|
''', [session_id])
|
||||||
|
|
||||||
# Load the template
|
# Setup Excel
|
||||||
template_bytes = BytesIO(sess['template_file'])
|
wb = openpyxl.load_workbook(BytesIO(sess['template_file']))
|
||||||
wb = openpyxl.load_workbook(template_bytes)
|
|
||||||
ws = wb.active
|
ws = wb.active
|
||||||
|
|
||||||
rows_per_page = sess['rows_per_page'] or 30
|
# Clear existing breaks
|
||||||
detail_start_row = sess['detail_start_row'] or 11
|
ws.row_breaks.brk = []
|
||||||
|
ws.col_breaks.brk = []
|
||||||
|
|
||||||
# Calculate how many pages we need
|
# Calculate Pages Needed
|
||||||
total_scans = len(scans) if scans else 0
|
total_items = len(scans)
|
||||||
num_pages = max(1, (total_scans + rows_per_page - 1) // rows_per_page) if total_scans > 0 else 1
|
total_pages = math.ceil(total_items / rows_per_page) if total_items > 0 else 1
|
||||||
|
|
||||||
# Helper function to fill header values on a sheet
|
# --- MAIN LOOP ---
|
||||||
def fill_header(worksheet, header_fields):
|
for page_idx in range(total_pages):
|
||||||
|
|
||||||
|
# 1. Fill Header
|
||||||
for field in header_fields:
|
for field in header_fields:
|
||||||
if field['excel_cell'] and field['field_value']:
|
if field['excel_cell'] and field['field_value']:
|
||||||
try:
|
try:
|
||||||
worksheet[field['excel_cell']] = field['field_value']
|
col_letter, row_str = coordinate_from_string(field['excel_cell'])
|
||||||
except:
|
base_row = int(row_str)
|
||||||
pass # Skip invalid cell references
|
target_row = base_row + (page_idx * page_height)
|
||||||
|
ws[f"{col_letter}{target_row}"] = field['field_value']
|
||||||
|
except: pass
|
||||||
|
|
||||||
# Helper function to clear detail rows on a sheet
|
# 2. Fill Details
|
||||||
def clear_details(worksheet, detail_fields, start_row, num_rows):
|
start_idx = page_idx * rows_per_page
|
||||||
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
|
|
||||||
end_idx = start_idx + rows_per_page
|
end_idx = start_idx + rows_per_page
|
||||||
page_scans = scans[start_idx:end_idx]
|
page_scans = scans[start_idx:end_idx]
|
||||||
fill_details(new_ws, page_scans, detail_fields, detail_start_row)
|
|
||||||
|
|
||||||
# Rename first sheet if we have multiple pages
|
for i, scan in enumerate(page_scans):
|
||||||
if num_pages > 1:
|
target_row = detail_start_row + (page_idx * page_height) + i
|
||||||
ws.title = "Page 1"
|
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
|
||||||
|
|
||||||
# Save to BytesIO
|
# 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
|
||||||
|
|
||||||
|
for row_num in range(last_used_row + 1, SAFE_MAX_ROW):
|
||||||
|
ws.row_dimensions[row_num].hidden = True
|
||||||
|
|
||||||
|
# --- FINAL POLISH (Manual Widths) ---
|
||||||
|
|
||||||
|
# --- 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()
|
output = BytesIO()
|
||||||
wb.save(output)
|
wb.save(output)
|
||||||
output.seek(0)
|
output.seek(0)
|
||||||
|
|
||||||
# Generate filename
|
|
||||||
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
||||||
base_filename = f"{sess['process_key']}_{session_id}_{timestamp}"
|
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(
|
return Response(
|
||||||
output.getvalue(),
|
output.getvalue(),
|
||||||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||||
|
|||||||
@@ -10,6 +10,50 @@ def get_active_session(session_id):
|
|||||||
return None
|
return None
|
||||||
return sess
|
return sess
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@counting_bp.route('/counts/admin')
|
||||||
|
@login_required
|
||||||
|
def admin_dashboard():
|
||||||
|
"""Admin dashboard for Counts module"""
|
||||||
|
# Security check: Ensure user is admin/owner
|
||||||
|
if session.get('role') not in ['owner', 'admin']:
|
||||||
|
flash('Access denied. Admin role required.', 'danger')
|
||||||
|
return redirect(url_for('counting.index'))
|
||||||
|
|
||||||
|
show_archived = request.args.get('show_archived', '0') == '1'
|
||||||
|
|
||||||
|
# This SQL was moved from app.py
|
||||||
|
if show_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:
|
||||||
|
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('counts/admin_dashboard.html', sessions=sessions_list, show_archived=show_archived)
|
||||||
|
|
||||||
|
|
||||||
@counting_bp.route('/counts')
|
@counting_bp.route('/counts')
|
||||||
@login_required
|
@login_required
|
||||||
def index():
|
def index():
|
||||||
@@ -33,7 +77,7 @@ def index():
|
|||||||
ORDER BY created_timestamp DESC
|
ORDER BY created_timestamp DESC
|
||||||
''')
|
''')
|
||||||
|
|
||||||
return render_template('staff_dashboard.html', sessions=active_sessions)
|
return render_template('counts/staff_dashboard.html', sessions=active_sessions)
|
||||||
|
|
||||||
|
|
||||||
@counting_bp.route('/count/<int:session_id>')
|
@counting_bp.route('/count/<int:session_id>')
|
||||||
@@ -72,11 +116,18 @@ def my_counts(session_id):
|
|||||||
FROM LocationCounts lc
|
FROM LocationCounts lc
|
||||||
LEFT JOIN ScanEntries se ON lc.location_count_id = se.location_count_id AND se.is_deleted = 0
|
LEFT JOIN ScanEntries se ON lc.location_count_id = se.location_count_id AND se.is_deleted = 0
|
||||||
WHERE lc.session_id = ?
|
WHERE lc.session_id = ?
|
||||||
AND lc.counted_by = ?
|
|
||||||
AND lc.status = 'in_progress'
|
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
|
GROUP BY lc.location_count_id
|
||||||
ORDER BY lc.start_timestamp DESC
|
ORDER BY lc.start_timestamp DESC
|
||||||
''', [session_id, session['user_id']])
|
''', [session_id, session['user_id'], session['user_id']])
|
||||||
|
|
||||||
# Get this user's completed bins
|
# Get this user's completed bins
|
||||||
completed_bins = query_db('''
|
completed_bins = query_db('''
|
||||||
@@ -85,13 +136,19 @@ def my_counts(session_id):
|
|||||||
FROM LocationCounts lc
|
FROM LocationCounts lc
|
||||||
LEFT JOIN ScanEntries se ON lc.location_count_id = se.location_count_id AND se.is_deleted = 0
|
LEFT JOIN ScanEntries se ON lc.location_count_id = se.location_count_id AND se.is_deleted = 0
|
||||||
WHERE lc.session_id = ?
|
WHERE lc.session_id = ?
|
||||||
AND lc.counted_by = ?
|
|
||||||
AND lc.status = 'completed'
|
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
|
GROUP BY lc.location_count_id
|
||||||
ORDER BY lc.end_timestamp DESC
|
ORDER BY lc.start_timestamp DESC
|
||||||
''', [session_id, session['user_id']])
|
''', [session_id, session['user_id'], session['user_id']])
|
||||||
|
|
||||||
return render_template('my_counts.html',
|
return render_template('counts/my_counts.html',
|
||||||
count_session=sess,
|
count_session=sess,
|
||||||
active_bins=active_bins,
|
active_bins=active_bins,
|
||||||
completed_bins=completed_bins)
|
completed_bins=completed_bins)
|
||||||
@@ -100,7 +157,7 @@ def my_counts(session_id):
|
|||||||
@counting_bp.route('/session/<int:session_id>/start-bin', methods=['POST'])
|
@counting_bp.route('/session/<int:session_id>/start-bin', methods=['POST'])
|
||||||
@login_required
|
@login_required
|
||||||
def start_bin_count(session_id):
|
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)
|
sess = get_active_session(session_id)
|
||||||
if not sess:
|
if not sess:
|
||||||
flash('Session not found or archived', 'warning')
|
flash('Session not found or archived', 'warning')
|
||||||
@@ -115,6 +172,20 @@ def start_bin_count(session_id):
|
|||||||
flash('Bin number is required', 'danger')
|
flash('Bin number is required', 'danger')
|
||||||
return redirect(url_for('counting.my_counts', session_id=session_id))
|
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
|
# Count expected lots from MASTER baseline for this location
|
||||||
expected_lots = query_db('''
|
expected_lots = query_db('''
|
||||||
SELECT COUNT(DISTINCT lot_number) as count
|
SELECT COUNT(DISTINCT lot_number) as count
|
||||||
@@ -124,7 +195,7 @@ def start_bin_count(session_id):
|
|||||||
|
|
||||||
expected_count = expected_lots['count'] if expected_lots else 0
|
expected_count = expected_lots['count'] if expected_lots else 0
|
||||||
|
|
||||||
# Create new location count
|
# Create new location count if none existed
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
|
|
||||||
@@ -140,7 +211,6 @@ def start_bin_count(session_id):
|
|||||||
flash(f'Started counting bin: {location_name}', 'success')
|
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))
|
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'])
|
@counting_bp.route('/location/<int:location_count_id>/complete', methods=['POST'])
|
||||||
@login_required
|
@login_required
|
||||||
def complete_location(location_count_id):
|
def complete_location(location_count_id):
|
||||||
@@ -219,7 +289,7 @@ def count_location(session_id, location_count_id):
|
|||||||
ORDER BY lot_number
|
ORDER BY lot_number
|
||||||
''', [session_id, location['location_name'], location_count_id])
|
''', [session_id, location['location_name'], location_count_id])
|
||||||
|
|
||||||
return render_template('count_location.html',
|
return render_template('counts/count_location.html',
|
||||||
session_id=session_id,
|
session_id=session_id,
|
||||||
location=location,
|
location=location,
|
||||||
scans=scans,
|
scans=scans,
|
||||||
@@ -468,7 +538,7 @@ def scan_lot(session_id, location_count_id):
|
|||||||
def delete_scan(entry_id):
|
def delete_scan(entry_id):
|
||||||
"""Soft delete a scan and recalculate duplicate statuses"""
|
"""Soft delete a scan and recalculate duplicate statuses"""
|
||||||
# Get the scan being deleted
|
# 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:
|
if not scan:
|
||||||
return jsonify({'success': False, 'message': 'Scan not found'})
|
return jsonify({'success': False, 'message': 'Scan not found'})
|
||||||
@@ -528,7 +598,7 @@ def update_scan(entry_id):
|
|||||||
comment = data.get('comment', '')
|
comment = data.get('comment', '')
|
||||||
|
|
||||||
# Get the scan
|
# 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:
|
if not scan:
|
||||||
return jsonify({'success': False, 'message': 'Scan not found'})
|
return jsonify({'success': False, 'message': 'Scan not found'})
|
||||||
@@ -549,7 +619,7 @@ def update_scan(entry_id):
|
|||||||
actual_weight = ?,
|
actual_weight = ?,
|
||||||
comment = ?,
|
comment = ?,
|
||||||
modified_timestamp = CURRENT_TIMESTAMP
|
modified_timestamp = CURRENT_TIMESTAMP
|
||||||
WHERE entry_id = ?
|
WHERE entry_id = ? and is_deleted = 0
|
||||||
''', [item, weight, comment, entry_id])
|
''', [item, weight, comment, entry_id])
|
||||||
|
|
||||||
return jsonify({'success': True, 'message': 'Scan updated'})
|
return jsonify({'success': True, 'message': 'Scan updated'})
|
||||||
@@ -581,7 +651,7 @@ def recalculate_duplicate_status(session_id, lot_number, current_location):
|
|||||||
duplicate_info = NULL,
|
duplicate_info = NULL,
|
||||||
comment = NULL,
|
comment = NULL,
|
||||||
modified_timestamp = CURRENT_TIMESTAMP
|
modified_timestamp = CURRENT_TIMESTAMP
|
||||||
WHERE entry_id = ?
|
WHERE entry_id = ? and is_deleted = 0
|
||||||
''', [scan['entry_id']])
|
''', [scan['entry_id']])
|
||||||
updated_entries.append({
|
updated_entries.append({
|
||||||
'entry_id': scan['entry_id'],
|
'entry_id': scan['entry_id'],
|
||||||
@@ -626,7 +696,7 @@ def recalculate_duplicate_status(session_id, lot_number, current_location):
|
|||||||
duplicate_info = ?,
|
duplicate_info = ?,
|
||||||
comment = ?,
|
comment = ?,
|
||||||
modified_timestamp = CURRENT_TIMESTAMP
|
modified_timestamp = CURRENT_TIMESTAMP
|
||||||
WHERE entry_id = ?
|
WHERE entry_id = ? and is_deleted = 0
|
||||||
''', [duplicate_status, duplicate_info, duplicate_info, scan['entry_id']])
|
''', [duplicate_status, duplicate_info, duplicate_info, scan['entry_id']])
|
||||||
|
|
||||||
# Update our tracking list
|
# Update our tracking list
|
||||||
@@ -645,7 +715,7 @@ def recalculate_duplicate_status(session_id, lot_number, current_location):
|
|||||||
duplicate_info = ?,
|
duplicate_info = ?,
|
||||||
comment = ?,
|
comment = ?,
|
||||||
modified_timestamp = CURRENT_TIMESTAMP
|
modified_timestamp = CURRENT_TIMESTAMP
|
||||||
WHERE entry_id = ?
|
WHERE entry_id = ? and is_deleted = 0
|
||||||
''', [duplicate_status, duplicate_info, duplicate_info, prev_scan['entry_id']])
|
''', [duplicate_status, duplicate_info, duplicate_info, prev_scan['entry_id']])
|
||||||
|
|
||||||
# Update tracking for previous scans
|
# Update tracking for previous scans
|
||||||
@@ -711,3 +781,56 @@ def finish_location(session_id, location_count_id):
|
|||||||
'success': True,
|
'success': True,
|
||||||
'redirect': url_for('counting.count_session', session_id=session_id)
|
'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.'})
|
||||||
@@ -24,7 +24,7 @@ def create_session():
|
|||||||
flash(f'Session "{session_name}" created successfully!', 'success')
|
flash(f'Session "{session_name}" created successfully!', 'success')
|
||||||
return redirect(url_for('sessions.session_detail', session_id=session_id))
|
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>')
|
@sessions_bp.route('/session/<int:session_id>')
|
||||||
@@ -54,24 +54,38 @@ def session_detail(session_id):
|
|||||||
''', [session_id], one=True)
|
''', [session_id], one=True)
|
||||||
|
|
||||||
# Get location progress
|
# Get location progress
|
||||||
|
# We add a subquery to count the actual missing lots for each bin
|
||||||
locations = query_db('''
|
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
|
FROM LocationCounts lc
|
||||||
LEFT JOIN Users u ON lc.counted_by = u.user_id
|
LEFT JOIN Users u ON lc.counted_by = u.user_id
|
||||||
WHERE lc.session_id = ?
|
WHERE lc.session_id = ?
|
||||||
|
AND lc.is_deleted = 0
|
||||||
ORDER BY lc.status DESC, lc.location_name
|
ORDER BY lc.status DESC, lc.location_name
|
||||||
''', [session_id])
|
''', [session_id])
|
||||||
|
|
||||||
# Get active counters
|
# Get active counters
|
||||||
active_counters = query_db('''
|
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
|
FROM LocationCounts lc
|
||||||
JOIN Users u ON lc.counted_by = u.user_id
|
JOIN Users u ON lc.counted_by = u.user_id
|
||||||
WHERE lc.session_id = ? AND lc.status = 'in_progress'
|
WHERE lc.session_id = ?
|
||||||
ORDER BY lc.start_timestamp DESC
|
AND lc.status = 'in_progress'
|
||||||
|
AND lc.is_deleted = 0
|
||||||
|
GROUP BY u.user_id
|
||||||
|
ORDER BY start_timestamp DESC
|
||||||
''', [session_id])
|
''', [session_id])
|
||||||
|
|
||||||
return render_template('session_detail.html',
|
return render_template('/counts/session_detail.html',
|
||||||
count_session=sess,
|
count_session=sess,
|
||||||
stats=stats,
|
stats=stats,
|
||||||
locations=locations,
|
locations=locations,
|
||||||
@@ -98,6 +112,7 @@ def get_status_details(session_id, status):
|
|||||||
WHERE se.session_id = ?
|
WHERE se.session_id = ?
|
||||||
AND se.master_status = 'match'
|
AND se.master_status = 'match'
|
||||||
AND se.duplicate_status = '00'
|
AND se.duplicate_status = '00'
|
||||||
|
AND se.master_variance_lbs = 0
|
||||||
AND se.is_deleted = 0
|
AND se.is_deleted = 0
|
||||||
ORDER BY se.scan_timestamp DESC
|
ORDER BY se.scan_timestamp DESC
|
||||||
''', [session_id])
|
''', [session_id])
|
||||||
@@ -184,20 +199,21 @@ def get_status_details(session_id, status):
|
|||||||
# Missing lots (in master but not scanned)
|
# Missing lots (in master but not scanned)
|
||||||
items = query_db('''
|
items = query_db('''
|
||||||
SELECT
|
SELECT
|
||||||
bim.lot_number,
|
ml.lot_number,
|
||||||
bim.item,
|
ml.item,
|
||||||
bim.description,
|
bim.description,
|
||||||
bim.system_bin,
|
ml.master_expected_location as system_bin,
|
||||||
bim.system_quantity
|
ml.master_expected_quantity as system_quantity
|
||||||
FROM BaselineInventory_Master bim
|
FROM MissingLots ml
|
||||||
WHERE bim.session_id = ?
|
LEFT JOIN BaselineInventory_Master bim ON
|
||||||
AND bim.lot_number NOT IN (
|
ml.lot_number = bim.lot_number AND
|
||||||
SELECT lot_number
|
ml.item = bim.item AND
|
||||||
FROM ScanEntries
|
ml.master_expected_location = bim.system_bin AND
|
||||||
WHERE session_id = ? AND is_deleted = 0
|
ml.session_id = bim.session_id
|
||||||
)
|
WHERE ml.session_id = ?
|
||||||
ORDER BY bim.system_bin, bim.lot_number
|
GROUP BY ml.lot_number, ml.item, ml.master_expected_location
|
||||||
''', [session_id, session_id])
|
ORDER BY ml.master_expected_location, ml.lot_number
|
||||||
|
''', [session_id])
|
||||||
else:
|
else:
|
||||||
return jsonify({'success': False, 'message': 'Invalid status'})
|
return jsonify({'success': False, 'message': 'Invalid status'})
|
||||||
|
|
||||||
@@ -242,3 +258,39 @@ def activate_session(session_id):
|
|||||||
execute_db('UPDATE CountSessions SET status = ? WHERE session_id = ?', ['active', 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)
|
||||||
|
|||||||
@@ -166,6 +166,38 @@ def init_database():
|
|||||||
)
|
)
|
||||||
''')
|
''')
|
||||||
|
|
||||||
|
# ============================================
|
||||||
|
# MODULE SYSTEM TABLES
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
# Modules Table - Available feature modules
|
||||||
|
cursor.execute('''
|
||||||
|
CREATE TABLE IF NOT EXISTS Modules (
|
||||||
|
module_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
module_name TEXT NOT NULL,
|
||||||
|
module_key TEXT UNIQUE NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
icon TEXT,
|
||||||
|
is_active INTEGER DEFAULT 1,
|
||||||
|
display_order INTEGER DEFAULT 0
|
||||||
|
)
|
||||||
|
''')
|
||||||
|
|
||||||
|
# UserModules Table - Module access per user
|
||||||
|
cursor.execute('''
|
||||||
|
CREATE TABLE IF NOT EXISTS UserModules (
|
||||||
|
user_module_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
user_id INTEGER NOT NULL,
|
||||||
|
module_id INTEGER NOT NULL,
|
||||||
|
granted_by INTEGER,
|
||||||
|
granted_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY (user_id) REFERENCES Users(user_id),
|
||||||
|
FOREIGN KEY (module_id) REFERENCES Modules(module_id),
|
||||||
|
FOREIGN KEY (granted_by) REFERENCES Users(user_id),
|
||||||
|
UNIQUE(user_id, module_id)
|
||||||
|
)
|
||||||
|
''')
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# CONSUMPTION SHEETS MODULE TABLES
|
# CONSUMPTION SHEETS MODULE TABLES
|
||||||
# ============================================
|
# ============================================
|
||||||
@@ -295,6 +327,52 @@ def create_default_users():
|
|||||||
conn.close()
|
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__':
|
if __name__ == '__main__':
|
||||||
init_database()
|
init_database()
|
||||||
create_default_users()
|
create_default_users()
|
||||||
|
create_default_modules()
|
||||||
300
migrations.py
Normal file
300
migrations.py
Normal file
@@ -0,0 +1,300 @@
|
|||||||
|
"""
|
||||||
|
ScanLook 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
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
import os
|
||||||
|
|
||||||
|
DB_PATH = os.path.join(os.path.dirname(__file__), 'database', 'scanlook.db')
|
||||||
|
|
||||||
|
|
||||||
|
def get_db():
|
||||||
|
"""Get database connection"""
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
def init_migrations_table():
|
||||||
|
"""Create the migrations tracking table if it doesn't exist"""
|
||||||
|
conn = get_db()
|
||||||
|
conn.execute('''
|
||||||
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
version INTEGER PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
''')
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_applied_migrations():
|
||||||
|
"""Get list of already-applied migration versions"""
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
rows = conn.execute('SELECT version FROM schema_migrations ORDER BY version').fetchall()
|
||||||
|
return [row['version'] for row in rows]
|
||||||
|
except:
|
||||||
|
return []
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def record_migration(version, name):
|
||||||
|
"""Record that a migration was applied"""
|
||||||
|
conn = get_db()
|
||||||
|
conn.execute('INSERT INTO schema_migrations (version, name) VALUES (?, ?)', [version, name])
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def column_exists(table, column):
|
||||||
|
"""Check if a column exists in a table"""
|
||||||
|
conn = get_db()
|
||||||
|
cursor = conn.execute(f'PRAGMA table_info({table})')
|
||||||
|
columns = [row[1] for row in cursor.fetchall()]
|
||||||
|
conn.close()
|
||||||
|
return column in columns
|
||||||
|
|
||||||
|
|
||||||
|
def table_exists(table):
|
||||||
|
"""Check if a table exists"""
|
||||||
|
conn = get_db()
|
||||||
|
cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", [table])
|
||||||
|
exists = cursor.fetchone() is not None
|
||||||
|
conn.close()
|
||||||
|
return exists
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================
|
||||||
|
# MIGRATIONS
|
||||||
|
# ============================================
|
||||||
|
# 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)
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
def migration_001_add_modules_tables():
|
||||||
|
"""Add Modules and UserModules tables"""
|
||||||
|
conn = get_db()
|
||||||
|
|
||||||
|
if not table_exists('Modules'):
|
||||||
|
conn.execute('''
|
||||||
|
CREATE TABLE Modules (
|
||||||
|
module_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
module_name TEXT NOT NULL,
|
||||||
|
module_key TEXT UNIQUE NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
icon TEXT,
|
||||||
|
is_active INTEGER DEFAULT 1,
|
||||||
|
display_order INTEGER DEFAULT 0
|
||||||
|
)
|
||||||
|
''')
|
||||||
|
print(" Created Modules table")
|
||||||
|
|
||||||
|
if not table_exists('UserModules'):
|
||||||
|
conn.execute('''
|
||||||
|
CREATE TABLE UserModules (
|
||||||
|
user_module_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
user_id INTEGER NOT NULL,
|
||||||
|
module_id INTEGER NOT NULL,
|
||||||
|
granted_by INTEGER,
|
||||||
|
granted_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY (user_id) REFERENCES Users(user_id),
|
||||||
|
FOREIGN KEY (module_id) REFERENCES Modules(module_id),
|
||||||
|
FOREIGN KEY (granted_by) REFERENCES Users(user_id),
|
||||||
|
UNIQUE(user_id, module_id)
|
||||||
|
)
|
||||||
|
''')
|
||||||
|
print(" Created UserModules table")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def migration_002_add_usermodules_granted_columns():
|
||||||
|
"""Add granted_by and granted_timestamp to UserModules if missing"""
|
||||||
|
conn = get_db()
|
||||||
|
|
||||||
|
if table_exists('UserModules'):
|
||||||
|
if not column_exists('UserModules', 'granted_by'):
|
||||||
|
conn.execute('ALTER TABLE UserModules ADD COLUMN granted_by INTEGER')
|
||||||
|
print(" Added granted_by column to UserModules")
|
||||||
|
|
||||||
|
if not column_exists('UserModules', 'granted_timestamp'):
|
||||||
|
conn.execute('ALTER TABLE UserModules ADD COLUMN granted_timestamp DATETIME')
|
||||||
|
print(" Added granted_timestamp column to UserModules")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def migration_003_add_default_modules():
|
||||||
|
"""Add default modules if they don't exist"""
|
||||||
|
conn = get_db()
|
||||||
|
|
||||||
|
# Check if modules exist
|
||||||
|
existing = conn.execute('SELECT COUNT(*) as cnt FROM Modules').fetchone()
|
||||||
|
|
||||||
|
if existing['cnt'] == 0:
|
||||||
|
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)
|
||||||
|
''')
|
||||||
|
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")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def migration_004_assign_modules_to_admins():
|
||||||
|
"""Auto-assign all modules to owner and admin users"""
|
||||||
|
conn = get_db()
|
||||||
|
|
||||||
|
# Get admin users
|
||||||
|
admins = conn.execute('SELECT user_id FROM Users WHERE role IN ("owner", "admin")').fetchall()
|
||||||
|
modules = conn.execute('SELECT module_id FROM Modules').fetchall()
|
||||||
|
|
||||||
|
for user in admins:
|
||||||
|
for module in modules:
|
||||||
|
try:
|
||||||
|
conn.execute('''
|
||||||
|
INSERT INTO UserModules (user_id, module_id)
|
||||||
|
VALUES (?, ?)
|
||||||
|
''', [user['user_id'], module['module_id']])
|
||||||
|
except sqlite3.IntegrityError:
|
||||||
|
pass # Already assigned
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
print(" Assigned modules to admin users")
|
||||||
|
|
||||||
|
|
||||||
|
def migration_005_add_cons_process_fields_duplicate_key():
|
||||||
|
"""Add is_duplicate_key column to cons_process_fields if missing"""
|
||||||
|
conn = get_db()
|
||||||
|
|
||||||
|
if table_exists('cons_process_fields'):
|
||||||
|
if not column_exists('cons_process_fields', 'is_duplicate_key'):
|
||||||
|
conn.execute('ALTER TABLE cons_process_fields ADD COLUMN is_duplicate_key INTEGER DEFAULT 0')
|
||||||
|
print(" Added is_duplicate_key column to cons_process_fields")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def migration_006_add_is_deleted_to_locationcounts():
|
||||||
|
"""Add is_deleted column to LocationCounts table"""
|
||||||
|
conn = get_db()
|
||||||
|
|
||||||
|
if table_exists('LocationCounts'):
|
||||||
|
if not column_exists('LocationCounts', 'is_deleted'):
|
||||||
|
conn.execute('ALTER TABLE LocationCounts ADD COLUMN is_deleted INTEGER DEFAULT 0')
|
||||||
|
print(" Added is_deleted column to LocationCounts")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def migration_007_add_detail_end_row():
|
||||||
|
"""Add detail_end_row column to cons_processes table"""
|
||||||
|
conn = get_db()
|
||||||
|
|
||||||
|
if table_exists('cons_processes'):
|
||||||
|
if not column_exists('cons_processes', 'detail_end_row'):
|
||||||
|
conn.execute('ALTER TABLE cons_processes ADD COLUMN detail_end_row INTEGER')
|
||||||
|
print(" Added detail_end_row column to cons_processes")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def migration_008_add_page_height():
|
||||||
|
"""Add page_height column to cons_processes table"""
|
||||||
|
conn = get_db()
|
||||||
|
|
||||||
|
if table_exists('cons_processes'):
|
||||||
|
if not column_exists('cons_processes', 'page_height'):
|
||||||
|
conn.execute('ALTER TABLE cons_processes ADD COLUMN page_height INTEGER')
|
||||||
|
print(" Added page_height column to cons_processes")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def migration_009_add_print_columns():
|
||||||
|
"""Add print_start_col and print_end_col to cons_processes"""
|
||||||
|
conn = get_db()
|
||||||
|
if table_exists('cons_processes'):
|
||||||
|
if not column_exists('cons_processes', 'print_start_col'):
|
||||||
|
conn.execute('ALTER TABLE cons_processes ADD COLUMN print_start_col TEXT DEFAULT "A"')
|
||||||
|
print(" Added print_start_col")
|
||||||
|
if not column_exists('cons_processes', 'print_end_col'):
|
||||||
|
conn.execute('ALTER TABLE cons_processes ADD COLUMN print_end_col TEXT')
|
||||||
|
print(" Added print_end_col")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
# List of all migrations in order
|
||||||
|
MIGRATIONS = [
|
||||||
|
(1, 'add_modules_tables', migration_001_add_modules_tables),
|
||||||
|
(2, 'add_usermodules_granted_columns', migration_002_add_usermodules_granted_columns),
|
||||||
|
(3, 'add_default_modules', migration_003_add_default_modules),
|
||||||
|
(4, 'assign_modules_to_admins', migration_004_assign_modules_to_admins),
|
||||||
|
(5, 'add_cons_process_fields_duplicate_key', migration_005_add_cons_process_fields_duplicate_key),
|
||||||
|
(6, 'add_is_deleted_to_locationcounts', migration_006_add_is_deleted_to_locationcounts),
|
||||||
|
(7, 'add_detail_end_row', migration_007_add_detail_end_row),
|
||||||
|
(8, 'add_page_height', migration_008_add_page_height),
|
||||||
|
(9, 'add_print_columns', migration_009_add_print_columns),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations():
|
||||||
|
"""Run all pending migrations"""
|
||||||
|
print("🔄 Checking database migrations...")
|
||||||
|
|
||||||
|
# Make sure migrations table exists
|
||||||
|
init_migrations_table()
|
||||||
|
|
||||||
|
# Get already-applied migrations
|
||||||
|
applied = get_applied_migrations()
|
||||||
|
|
||||||
|
# Run pending 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")
|
||||||
|
return
|
||||||
|
|
||||||
|
print(f"📦 Running {len(pending)} migration(s)...")
|
||||||
|
|
||||||
|
for version, name, func in pending:
|
||||||
|
print(f"\n Migration {version}: {name}")
|
||||||
|
try:
|
||||||
|
func()
|
||||||
|
record_migration(version, name)
|
||||||
|
print(f" ✅ Migration {version} complete")
|
||||||
|
except Exception as e:
|
||||||
|
print(f" ❌ Migration {version} failed: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
print("\n✅ All migrations complete")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run_migrations()
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
Flask==3.1.2
|
Flask==3.1.2
|
||||||
Werkzeug==3.1.5
|
Werkzeug==3.1.5
|
||||||
openpyxl
|
openpyxl
|
||||||
|
Pillow
|
||||||
@@ -2283,3 +2283,22 @@ body {
|
|||||||
background: var(--color-primary);
|
background: var(--color-primary);
|
||||||
color: var(--color-bg);
|
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);
|
||||||
|
}
|
||||||
@@ -4,121 +4,28 @@
|
|||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="dashboard-container">
|
<div class="dashboard-container">
|
||||||
<!-- Mode Selector -->
|
<div class="dashboard-header" style="margin-top: var(--space-lg);">
|
||||||
<div class="mode-selector">
|
<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">
|
<a href="{{ url_for('home') }}" class="btn btn-secondary btn-sm">
|
||||||
<i class="fa-solid fa-arrow-left"></i> Back to Home
|
<i class="fa-solid fa-arrow-left"></i> Back to Home
|
||||||
</a>
|
</a>
|
||||||
<button class="mode-btn mode-btn-active" data-href="{{ url_for('admin_dashboard') }}">
|
<h1 class="page-title" style="margin-bottom: 0;">Admin Dashboard</h1>
|
||||||
👔 Admin Console
|
</div>
|
||||||
</button>
|
|
||||||
<button class="mode-btn" data-href="{{ url_for('staff_mode') }}">
|
|
||||||
📦 Scanning Mode
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
|
||||||
document.querySelectorAll('.mode-selector button').forEach(btn => {
|
|
||||||
btn.addEventListener('click', function() {
|
|
||||||
window.location.href = this.getAttribute('data-href');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="dashboard-header">
|
|
||||||
<div class="header-left">
|
|
||||||
<h1 class="page-title">Admin Dashboard</h1>
|
|
||||||
<label class="filter-toggle">
|
|
||||||
<input type="checkbox" id="showArchived" {% if show_archived %}checked{% endif %} onchange="toggleArchived()">
|
|
||||||
<span class="filter-label">Show Archived</span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<a href="{{ url_for('sessions.create_session') }}" class="btn btn-primary">
|
|
||||||
<span class="btn-icon">+</span> New Session
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
function toggleArchived() {
|
|
||||||
const checked = document.getElementById('showArchived').checked;
|
|
||||||
window.location.href = '{{ url_for("admin_dashboard") }}' + (checked ? '?show_archived=1' : '');
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<!-- Modules Section -->
|
|
||||||
<div class="modules-section">
|
<div class="modules-section">
|
||||||
<h2 class="section-title">Modules</h2>
|
<h2 class="section-title">Modules</h2>
|
||||||
<div class="modules-grid">
|
<div class="modules-grid">
|
||||||
<div class="module-card module-card-active">
|
<a href="{{ url_for('counting.admin_dashboard') }}" class="module-card">
|
||||||
<div class="module-icon">📋</div>
|
<div class="module-icon">📊</div> <h3 class="module-name">Counts</h3>
|
||||||
<h3 class="module-name">Counts</h3>
|
|
||||||
<p class="module-desc">Cycle counts & physical inventory</p>
|
<p class="module-desc">Cycle counts & physical inventory</p>
|
||||||
</div>
|
</a>
|
||||||
|
|
||||||
<a href="{{ url_for('cons_sheets.admin_processes') }}" class="module-card module-card-link">
|
<a href="{{ url_for('cons_sheets.admin_processes') }}" class="module-card module-card-link">
|
||||||
<div class="module-icon">📝</div>
|
<div class="module-icon">📝</div> <h3 class="module-name">Consumption Sheets</h3>
|
||||||
<h3 class="module-name">Consumption Sheets</h3>
|
|
||||||
<p class="module-desc">Production consumption tracking</p>
|
<p class="module-desc">Production consumption tracking</p>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{% if sessions %}
|
|
||||||
<div class="sessions-grid">
|
|
||||||
{% for session in sessions %}
|
|
||||||
<div class="session-card {% if session.status == 'archived' %}session-archived{% endif %}">
|
|
||||||
<div class="session-card-header">
|
|
||||||
<h3 class="session-name">
|
|
||||||
{{ session.session_name }}
|
|
||||||
{% if session.status == 'archived' %}<span class="archived-badge">ARCHIVED</span>{% endif %}
|
|
||||||
</h3>
|
|
||||||
<span class="session-type-badge session-type-{{ session.session_type }}">
|
|
||||||
{{ 'Full Physical' if session.session_type == 'full_physical' else 'Cycle Count' }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="session-stats">
|
|
||||||
<div class="stat-item">
|
|
||||||
<div class="stat-value">{{ session.total_locations or 0 }}</div>
|
|
||||||
<div class="stat-label">Total Locations</div>
|
|
||||||
</div>
|
|
||||||
<div class="stat-item">
|
|
||||||
<div class="stat-value">{{ session.completed_locations or 0 }}</div>
|
|
||||||
<div class="stat-label">Completed</div>
|
|
||||||
</div>
|
|
||||||
<div class="stat-item">
|
|
||||||
<div class="stat-value">{{ session.in_progress_locations or 0 }}</div>
|
|
||||||
<div class="stat-label">In Progress</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="session-meta">
|
|
||||||
<div class="meta-item">
|
|
||||||
<span class="meta-label">Created:</span>
|
|
||||||
<span class="meta-value">{{ session.created_timestamp[:16] }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="meta-item">
|
|
||||||
<span class="meta-label">By:</span>
|
|
||||||
<span class="meta-value">{{ session.created_by_name }}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="session-actions">
|
|
||||||
<a href="{{ url_for('sessions.session_detail', session_id=session.session_id) }}" class="btn btn-secondary btn-block">
|
|
||||||
View Details
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{% endfor %}
|
|
||||||
</div>
|
|
||||||
{% else %}
|
|
||||||
<div class="empty-state">
|
|
||||||
<div class="empty-icon">📋</div>
|
|
||||||
<h2 class="empty-title">No Active Sessions</h2>
|
|
||||||
<p class="empty-text">Create a new count session to get started</p>
|
|
||||||
<a href="{{ url_for('sessions.create_session') }}" class="btn btn-primary">
|
|
||||||
Create First Session
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -4,18 +4,31 @@
|
|||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="dashboard-container">
|
<div class="dashboard-container">
|
||||||
<!-- Back to Admin Dashboard -->
|
<div class="dashboard-header" style="margin-top: var(--space-lg);">
|
||||||
<div class="mode-selector">
|
<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">
|
<a href="{{ url_for('admin_dashboard') }}" class="btn btn-secondary btn-sm">
|
||||||
<i class="fa-solid fa-arrow-left"></i> Back to Admin
|
<i class="fa-solid fa-arrow-left"></i> Back to Admin
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<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>
|
</div>
|
||||||
|
|
||||||
<div class="dashboard-header">
|
|
||||||
<div class="header-left">
|
|
||||||
<h1 class="page-title">Consumption Sheets</h1>
|
|
||||||
<p class="page-subtitle">Manage process types and templates</p>
|
|
||||||
</div>
|
|
||||||
<a href="{{ url_for('cons_sheets.create_process') }}" class="btn btn-primary">
|
<a href="{{ url_for('cons_sheets.create_process') }}" class="btn btn-primary">
|
||||||
<span class="btn-icon">+</span> New Process
|
<span class="btn-icon">+</span> New Process
|
||||||
</a>
|
</a>
|
||||||
@@ -25,13 +38,34 @@
|
|||||||
<div class="sessions-grid">
|
<div class="sessions-grid">
|
||||||
{% for process in processes %}
|
{% for process in processes %}
|
||||||
<div class="session-card">
|
<div class="session-card">
|
||||||
<div class="session-card-header">
|
<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>
|
<h3 class="session-name">{{ process.process_name }}</h3>
|
||||||
<span class="session-type-badge">
|
<span class="session-type-badge">
|
||||||
{{ process.field_count or 0 }} fields
|
{{ process.field_count or 0 }} fields
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</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="session-meta">
|
||||||
<div class="meta-item">
|
<div class="meta-item">
|
||||||
<span class="meta-label">Key:</span>
|
<span class="meta-label">Key:</span>
|
||||||
@@ -57,6 +91,8 @@
|
|||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
|
|||||||
@@ -49,7 +49,13 @@
|
|||||||
<td>{{ field.excel_cell or '—' }}</td>
|
<td>{{ field.excel_cell or '—' }}</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="{{ url_for('cons_sheets.edit_field', process_id=process.id, field_id=field.id) }}" class="btn btn-secondary btn-sm">Edit</a>
|
<a href="{{ url_for('cons_sheets.edit_field', process_id=process.id, field_id=field.id) }}" class="btn btn-secondary btn-sm">Edit</a>
|
||||||
<button onclick="confirmDelete({{ field.id }}, '{{ field.field_label }}')" class="btn btn-sm" style="background: var(--color-danger); color: white;">Delete</button>
|
<button onclick="confirmDelete(this)"
|
||||||
|
data-id="{{ field.id }}"
|
||||||
|
data-label="{{ field.field_label }}"
|
||||||
|
class="btn btn-sm"
|
||||||
|
style="background: var(--color-danger); color: white;">
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
@@ -95,7 +101,13 @@
|
|||||||
<td>{{ field.excel_cell or '—' }}</td>
|
<td>{{ field.excel_cell or '—' }}</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="{{ url_for('cons_sheets.edit_field', process_id=process.id, field_id=field.id) }}" class="btn btn-secondary btn-sm">Edit</a>
|
<a href="{{ url_for('cons_sheets.edit_field', process_id=process.id, field_id=field.id) }}" class="btn btn-secondary btn-sm">Edit</a>
|
||||||
<button onclick="confirmDelete({{ field.id }}, '{{ field.field_label }}')" class="btn btn-sm" style="background: var(--color-danger); color: white;">Delete</button>
|
<button onclick="confirmDelete(this)"
|
||||||
|
data-id="{{ field.id }}"
|
||||||
|
data-label="{{ field.field_label }}"
|
||||||
|
class="btn btn-sm"
|
||||||
|
style="background: var(--color-danger); color: white;">
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
@@ -138,7 +150,11 @@
|
|||||||
</style>
|
</style>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
function confirmDelete(fieldId, fieldLabel) {
|
function confirmDelete(btn) {
|
||||||
|
// Read values from data attributes
|
||||||
|
const fieldId = btn.dataset.id;
|
||||||
|
const fieldLabel = btn.dataset.label;
|
||||||
|
|
||||||
if (confirm('Delete field "' + fieldLabel + '"?\n\nThis will soft-delete the field (data preserved but hidden).')) {
|
if (confirm('Delete field "' + fieldLabel + '"?\n\nThis will soft-delete the field (data preserved but hidden).')) {
|
||||||
fetch('{{ url_for("cons_sheets.delete_field", process_id=process.id, field_id=0) }}'.replace('0', fieldId), {
|
fetch('{{ url_for("cons_sheets.delete_field", process_id=process.id, field_id=0) }}'.replace('0', fieldId), {
|
||||||
method: 'POST'
|
method: 'POST'
|
||||||
|
|||||||
@@ -50,16 +50,40 @@
|
|||||||
|
|
||||||
<form method="POST" action="{{ url_for('cons_sheets.update_template_settings', process_id=process.id) }}">
|
<form method="POST" action="{{ url_for('cons_sheets.update_template_settings', process_id=process.id) }}">
|
||||||
<div class="form-group">
|
<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"
|
<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">
|
value="{{ process.rows_per_page or 30 }}" min="1" max="5000" class="form-input">
|
||||||
<p class="form-hint">Max detail rows before starting a new page</p>
|
<p class="form-hint">How many items fit in the grid before we need a new page?</p>
|
||||||
</div>
|
</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">
|
<div class="form-group">
|
||||||
<label for="detail_start_row" class="form-label">Detail Start Row</label>
|
<label for="detail_start_row" class="form-label">Detail Start Row</label>
|
||||||
<input type="number" id="detail_start_row" name="detail_start_row"
|
<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>
|
<p class="form-hint">Excel row number where detail data begins</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -101,9 +101,16 @@
|
|||||||
<div class="scans-header">
|
<div class="scans-header">
|
||||||
<h3 class="scans-title">Scanned Items (<span id="scanListCount">{{ scans|length }}</span>)</h3>
|
<h3 class="scans-title">Scanned Items (<span id="scanListCount">{{ scans|length }}</span>)</h3>
|
||||||
</div>
|
</div>
|
||||||
<div id="scansList" class="scans-grid">
|
<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 %}
|
{% for scan in scans %}
|
||||||
<div class="scan-row scan-row-{{ scan.duplicate_status }}" data-detail-id="{{ scan.id }}" onclick="openScanDetail({{ scan.id }})">
|
<div class="scan-row scan-row-{{ scan.duplicate_status }}"
|
||||||
|
data-detail-id="{{ scan.id }}"
|
||||||
|
onclick="openScanDetail(this.dataset.detailId)">
|
||||||
{% for field in detail_fields %}
|
{% for field in detail_fields %}
|
||||||
<div class="scan-row-cell">{% if field.field_type == 'REAL' %}{{ '%.1f'|format(scan[field.field_name]|float) if scan[field.field_name] else '-' }}{% else %}{{ scan[field.field_name] or '-' }}{% endif %}</div>
|
<div class="scan-row-cell">{% if field.field_type == 'REAL' %}{{ '%.1f'|format(scan[field.field_name]|float) if scan[field.field_name] else '-' }}{% else %}{{ scan[field.field_name] or '-' }}{% endif %}</div>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
@@ -135,11 +142,44 @@
|
|||||||
</div>
|
</div>
|
||||||
</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'">×</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>
|
<style>
|
||||||
.header-values { display: flex; flex-wrap: wrap; gap: var(--space-sm); margin: var(--space-sm) 0; }
|
.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); }
|
.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); }
|
||||||
.header-pill strong { color: var(--color-text); }
|
.header-pill strong { color: var(--color-text); }
|
||||||
.scan-row { display: grid; grid-template-columns: repeat({{ detail_fields|length }}, 1fr) auto; gap: var(--space-sm); padding: var(--space-md); background: var(--color-surface); border: 2px solid var(--color-border); border-radius: var(--radius-md); margin-bottom: var(--space-sm); cursor: pointer; transition: var(--transition); }
|
.scan-row { display: grid; grid-template-columns: repeat(var(--field-count), 1fr) auto; gap: var(--space-sm); padding: var(--space-md); background: var(--color-surface); border: 2px solid var(--color-border); border-radius: var(--radius-md); margin-bottom: var(--space-sm); cursor: pointer; transition: var(--transition); }
|
||||||
.scan-row:hover { border-color: var(--color-primary); }
|
.scan-row:hover { border-color: var(--color-primary); }
|
||||||
.scan-row-cell { font-size: 0.9rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
.scan-row-cell { font-size: 0.9rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
.scan-row-dup_same_session { border-left: 4px solid var(--color-duplicate) !important; background: rgba(0, 163, 255, 0.1) !important; }
|
.scan-row-dup_same_session { border-left: 4px solid var(--color-duplicate) !important; background: rgba(0, 163, 255, 0.1) !important; }
|
||||||
@@ -151,11 +191,22 @@
|
|||||||
.duplicate-message { color: var(--color-text-muted); margin-bottom: var(--space-lg); }
|
.duplicate-message { color: var(--color-text-muted); margin-bottom: var(--space-lg); }
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<script>
|
<script id="session-data" type="application/json">
|
||||||
const detailFields = {{ detail_fields|tojson|safe }};
|
{
|
||||||
const dupKeyFieldName = {{ (dup_key_field.field_name if dup_key_field else '')|tojson|safe }};
|
"detailFields": {{ detail_fields|tojson|safe }},
|
||||||
const sessionId = {{ session.id }};
|
"dupKeyFieldName": {{ (dup_key_field.field_name if dup_key_field else '')|tojson|safe }},
|
||||||
|
"sessionId": {{ session.id }}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// Read data from the JSON block above
|
||||||
|
const sessionData = JSON.parse(document.getElementById('session-data').textContent);
|
||||||
|
const detailFields = sessionData.detailFields;
|
||||||
|
const dupKeyFieldName = sessionData.dupKeyFieldName;
|
||||||
|
const sessionId = sessionData.sessionId;
|
||||||
|
|
||||||
|
// Standard variables
|
||||||
let currentDupKeyValue = '';
|
let currentDupKeyValue = '';
|
||||||
let currentDuplicateStatus = '';
|
let currentDuplicateStatus = '';
|
||||||
let isDuplicateConfirmed = false;
|
let isDuplicateConfirmed = false;
|
||||||
|
|||||||
@@ -47,7 +47,7 @@
|
|||||||
<span class="arrow-icon">→</span>
|
<span class="arrow-icon">→</span>
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</a>
|
||||||
<button class="btn-archive" onclick="archiveSession({{ s.id }}, '{{ s.process_name }}')" title="Archive this session">
|
<button class="btn-archive" onclick="archiveSession(this)" data-id="{{ s.id }}" data-name="{{ s.process_name }}" title="Archive this session">
|
||||||
🗑️
|
🗑️
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
102
templates/counts/admin_dashboard.html
Normal file
102
templates/counts/admin_dashboard.html
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Inventory Counts - ScanLook{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="dashboard-container">
|
||||||
|
<div class="dashboard-header">
|
||||||
|
<div class="header-left">
|
||||||
|
<a href="{{ url_for('admin_dashboard') }}" class="btn btn-secondary btn-sm" style="margin-right: var(--space-md);">
|
||||||
|
<i class="fa-solid fa-arrow-left"></i> Back to Admin
|
||||||
|
</a>
|
||||||
|
<div>
|
||||||
|
<h1 class="page-title">Inventory Counts</h1>
|
||||||
|
<p class="page-subtitle">Manage cycle counts and physical inventory</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="header-right">
|
||||||
|
<label class="filter-toggle" style="margin-right: var(--space-lg);">
|
||||||
|
<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">
|
||||||
|
<span class="btn-icon">+</span> New Session
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if sessions %}
|
||||||
|
<div class="sessions-grid">
|
||||||
|
{% for session in sessions %}
|
||||||
|
<div class="session-card {% if session.status == 'archived' %}session-archived{% endif %}">
|
||||||
|
<div class="session-card-header">
|
||||||
|
<h3 class="session-name">
|
||||||
|
{{ session.session_name }}
|
||||||
|
{% if session.status == 'archived' %}<span class="archived-badge">ARCHIVED</span>{% endif %}
|
||||||
|
</h3>
|
||||||
|
<span class="session-type-badge session-type-{{ session.session_type }}">
|
||||||
|
{{ 'Full Physical' if session.session_type == 'full_physical' else 'Cycle Count' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="session-stats">
|
||||||
|
<div class="stat-item">
|
||||||
|
<div class="stat-value">{{ session.total_locations or 0 }}</div>
|
||||||
|
<div class="stat-label">Total Locations</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-item">
|
||||||
|
<div class="stat-value">{{ session.completed_locations or 0 }}</div>
|
||||||
|
<div class="stat-label">Completed</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-item">
|
||||||
|
<div class="stat-value">{{ session.in_progress_locations or 0 }}</div>
|
||||||
|
<div class="stat-label">In Progress</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="session-meta">
|
||||||
|
<div class="meta-item">
|
||||||
|
<span class="meta-label">Created:</span>
|
||||||
|
<span class="meta-value">{{ session.created_timestamp[:16] }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="meta-item">
|
||||||
|
<span class="meta-label">By:</span>
|
||||||
|
<span class="meta-value">{{ session.created_by_name }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="session-actions">
|
||||||
|
<a href="{{ url_for('sessions.session_detail', session_id=session.session_id) }}" class="btn btn-secondary btn-block">
|
||||||
|
View Details
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="empty-state">
|
||||||
|
<div class="empty-icon">📋</div>
|
||||||
|
<h2 class="empty-title">No Active Sessions</h2>
|
||||||
|
<p class="empty-text">Create a new count session to get started</p>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function toggleArchived() {
|
||||||
|
const checked = document.getElementById('showArchived').checked;
|
||||||
|
window.location.href = '{{ url_for("counting.admin_dashboard") }}' + (checked ? '?show_archived=1' : '');
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.dashboard-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: var(--space-xl);
|
||||||
|
}
|
||||||
|
.header-left { display: flex; align-items: center; }
|
||||||
|
.header-right { display: flex; align-items: center; }
|
||||||
|
</style>
|
||||||
|
{% endblock %}
|
||||||
@@ -163,9 +163,7 @@
|
|||||||
<a href="{{ url_for('counting.my_counts', session_id=session_id) }}" class="btn btn-secondary btn-block btn-lg">
|
<a href="{{ url_for('counting.my_counts', session_id=session_id) }}" class="btn btn-secondary btn-block btn-lg">
|
||||||
← Back to My Counts
|
← Back to My Counts
|
||||||
</a>
|
</a>
|
||||||
<button id="finishBtn" class="btn btn-success btn-block btn-lg" onclick="finishLocation()">
|
{# Finish button moved to Admin Dashboard #}
|
||||||
✓ Finish Location
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button class="scroll-to-top" onclick="window.scrollTo({top: 0, behavior: 'smooth'})">
|
<button class="scroll-to-top" onclick="window.scrollTo({top: 0, behavior: 'smooth'})">
|
||||||
@@ -49,14 +49,6 @@
|
|||||||
<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('counting.count_location', session_id=count_session.session_id, location_count_id=bin.location_count_id) }}" class="btn btn-primary btn-block">
|
||||||
Resume Counting
|
Resume Counting
|
||||||
</a>
|
</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>
|
||||||
</div>
|
</div>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
12
templates/counts/partials/_active_counters.html
Normal file
12
templates/counts/partials/_active_counters.html
Normal 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>
|
||||||
@@ -72,42 +72,42 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Statistics Section -->
|
<!-- Statistics Section -->
|
||||||
<div class="section-card">
|
<div class="section-card">
|
||||||
<h2 class="section-title">Real-Time Statistics</h2>
|
<h2 class="section-title">Real-Time Statistics</h2>
|
||||||
|
|
||||||
<div class="stats-grid">
|
<div class="stats-grid">
|
||||||
<div class="stat-card stat-match" onclick="showStatusDetails('match')">
|
<div class="stat-card stat-match" onclick="showStatusDetails('match')">
|
||||||
<div class="stat-number">{{ stats.matched or 0 }}</div>
|
<div class="stat-number" id="count-matched">{{ stats.matched or 0 }}</div>
|
||||||
<div class="stat-label">✓ Matched</div>
|
<div class="stat-label">✓ Matched</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="stat-card stat-duplicate" onclick="showStatusDetails('duplicates')">
|
<div class="stat-card stat-duplicate" onclick="showStatusDetails('duplicates')">
|
||||||
<div class="stat-number">{{ stats.duplicates or 0 }}</div>
|
<div class="stat-number" id="count-duplicates">{{ stats.duplicates or 0 }}</div>
|
||||||
<div class="stat-label">🔵 Duplicates</div>
|
<div class="stat-label">🔵 Duplicates</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="stat-card stat-weight-disc" onclick="showStatusDetails('weight_discrepancy')">
|
<div class="stat-card stat-weight-disc" onclick="showStatusDetails('weight_discrepancy')">
|
||||||
<div class="stat-number">{{ stats.weight_discrepancy or 0 }}</div>
|
<div class="stat-number" id="count-discrepancy">{{ stats.weight_discrepancy or 0 }}</div>
|
||||||
<div class="stat-label">⚖️ Weight Discrepancy</div>
|
<div class="stat-label">⚖️ Weight Discrepancy</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="stat-card stat-wrong" onclick="showStatusDetails('wrong_location')">
|
<div class="stat-card stat-wrong" onclick="showStatusDetails('wrong_location')">
|
||||||
<div class="stat-number">{{ stats.wrong_location or 0 }}</div>
|
<div class="stat-number" id="count-wrong">{{ stats.wrong_location or 0 }}</div>
|
||||||
<div class="stat-label">⚠ Wrong Location</div>
|
<div class="stat-label">⚠ Wrong Location</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="stat-card stat-ghost" onclick="showStatusDetails('ghost_lot')">
|
<div class="stat-card stat-ghost" onclick="showStatusDetails('ghost_lot')">
|
||||||
<div class="stat-number">{{ stats.ghost_lots or 0 }}</div>
|
<div class="stat-number" id="count-ghost">{{ stats.ghost_lots or 0 }}</div>
|
||||||
<div class="stat-label">🟣 Ghost Lots</div>
|
<div class="stat-label">🟣 Ghost Lots</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="stat-card stat-missing" onclick="showStatusDetails('missing')">
|
<div class="stat-card stat-missing" onclick="showStatusDetails('missing')">
|
||||||
<div class="stat-number">{{ stats.missing_lots or 0 }}</div>
|
<div class="stat-number" id="count-missing">{{ stats.missing_lots or 0 }}</div>
|
||||||
<div class="stat-label">🔴 Missing</div>
|
<div class="stat-label">🔴 Missing</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Active Counters Section -->
|
<!-- Active Counters Section -->
|
||||||
{% if active_counters %}
|
{% if active_counters %}
|
||||||
<div class="section-card">
|
<div class="section-card">
|
||||||
<h2 class="section-title">Active Counters</h2>
|
<h2 class="section-title">Active Counters</h2>
|
||||||
<div class="counter-list">
|
<div id="active-counters-container"> <div class="counter-list">
|
||||||
{% for counter in active_counters %}
|
{% for counter in active_counters %}
|
||||||
<div class="counter-item">
|
<div class="counter-item">
|
||||||
<div class="counter-avatar">{{ counter.full_name[0] }}</div>
|
<div class="counter-avatar">{{ counter.full_name[0] }}</div>
|
||||||
@@ -125,7 +125,12 @@
|
|||||||
<!-- Location Progress Section -->
|
<!-- Location Progress Section -->
|
||||||
{% if locations %}
|
{% if locations %}
|
||||||
<div class="section-card">
|
<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">
|
<div class="location-table">
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
@@ -157,7 +162,7 @@
|
|||||||
<td>{{ loc.counter_name or '-' }}</td>
|
<td>{{ loc.counter_name or '-' }}</td>
|
||||||
<td>{{ loc.expected_lots_master }}</td>
|
<td>{{ loc.expected_lots_master }}</td>
|
||||||
<td>{{ loc.lots_found }}</td>
|
<td>{{ loc.lots_found }}</td>
|
||||||
<td>{{ loc.lots_missing }}</td>
|
<td>{{ loc.lots_missing_calc }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -198,6 +203,9 @@
|
|||||||
<button id="reopenLocationBtn" class="btn btn-warning btn-sm" style="display: none;" onclick="showReopenConfirm()">
|
<button id="reopenLocationBtn" class="btn btn-warning btn-sm" style="display: none;" onclick="showReopenConfirm()">
|
||||||
🔓 Reopen Location
|
🔓 Reopen Location
|
||||||
</button>
|
</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()">
|
<button class="btn btn-secondary btn-sm" onclick="exportLocationToCSV()">
|
||||||
📥 Export CSV
|
📥 Export CSV
|
||||||
</button>
|
</button>
|
||||||
@@ -460,6 +468,9 @@ function showLocationDetails(locationCountId, locationName, status) {
|
|||||||
// Show finalize or reopen button based on status
|
// Show finalize or reopen button based on status
|
||||||
const finalizeBtn = document.getElementById('finalizeLocationBtn');
|
const finalizeBtn = document.getElementById('finalizeLocationBtn');
|
||||||
const reopenBtn = document.getElementById('reopenLocationBtn');
|
const reopenBtn = document.getElementById('reopenLocationBtn');
|
||||||
|
const deleteBtn = document.getElementById('deleteLocationBtn'); // ADD THIS LINE
|
||||||
|
|
||||||
|
deleteBtn.style.display = 'block';
|
||||||
|
|
||||||
if (status === 'in_progress') {
|
if (status === 'in_progress') {
|
||||||
finalizeBtn.style.display = 'block';
|
finalizeBtn.style.display = 'block';
|
||||||
@@ -621,8 +632,8 @@ function closeFinalizeConfirm() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function confirmFinalize() {
|
function confirmFinalize() {
|
||||||
// Note: The /complete endpoint is handled by blueprints/counting.py
|
// Correctly points to the /finish route to trigger Missing Lot calculations
|
||||||
fetch(`/location/${currentLocationId}/complete`, {
|
fetch(`/count/${CURRENT_SESSION_ID}/location/${currentLocationId}/finish`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
@@ -633,16 +644,18 @@ function confirmFinalize() {
|
|||||||
if (data.success) {
|
if (data.success) {
|
||||||
closeFinalizeConfirm();
|
closeFinalizeConfirm();
|
||||||
closeLocationModal();
|
closeLocationModal();
|
||||||
location.reload(); // Reload to show updated status
|
location.reload(); // Reload to show updated status and Missing counts
|
||||||
} else {
|
} else {
|
||||||
alert(data.message || 'Error finalizing location');
|
alert(data.message || 'Error finalizing location');
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
|
console.error('Finalize Error:', error);
|
||||||
alert('Error: ' + error.message);
|
alert('Error: ' + error.message);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function showReopenConfirm() {
|
function showReopenConfirm() {
|
||||||
document.getElementById('reopenBinName').textContent = currentLocationName;
|
document.getElementById('reopenBinName').textContent = currentLocationName;
|
||||||
document.getElementById('reopenConfirmModal').style.display = 'flex';
|
document.getElementById('reopenConfirmModal').style.display = 'flex';
|
||||||
@@ -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(`/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(`/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(`/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(`/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>
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
Reference in New Issue
Block a user