feat: Implement comprehensive database setup system

- Add complete database setup script (setup_complete_database.py)
- Add quick deployment script (quick_deploy.sh)
- Add comprehensive documentation (DATABASE_SETUP_README.md)
- Move individual db scripts to backup_db_scripts folder
- Update external_server.conf with correct database settings
- Clean up obsolete documentation files
- Streamline deployment process to single command

Features:
- One-script database creation for all tables and triggers
- Automated permissions and roles setup
- Complete verification and error handling
- Production-ready deployment workflow
- Maintains backward compatibility with individual scripts
This commit is contained in:
Quality System Admin
2025-10-11 21:45:37 +03:00
parent 05394697a0
commit af62fa478f
30 changed files with 924 additions and 679 deletions

View File

@@ -0,0 +1,110 @@
#!/usr/bin/env python3
import mariadb
import os
import sys
def get_external_db_connection():
"""Reads the external_server.conf file and returns a MariaDB database connection."""
# Get the instance folder path
current_dir = os.path.dirname(os.path.abspath(__file__))
instance_folder = os.path.join(current_dir, '../../instance')
settings_file = os.path.join(instance_folder, 'external_server.conf')
if not os.path.exists(settings_file):
raise FileNotFoundError(f"The external_server.conf file is missing: {settings_file}")
# Read settings from the configuration file
settings = {}
with open(settings_file, 'r') as f:
for line in f:
line = line.strip()
if line and '=' in line:
key, value = line.split('=', 1)
settings[key] = value
print(f"Connecting to MariaDB:")
print(f" Host: {settings.get('server_domain', 'N/A')}")
print(f" Port: {settings.get('port', 'N/A')}")
print(f" Database: {settings.get('database_name', 'N/A')}")
return mariadb.connect(
user=settings['username'],
password=settings['password'],
host=settings['server_domain'],
port=int(settings['port']),
database=settings['database_name']
)
def main():
try:
print("=== Adding Email Column to Users Table ===")
conn = get_external_db_connection()
cursor = conn.cursor()
# First, check the current table structure
print("\n1. Checking current table structure...")
cursor.execute("DESCRIBE users")
columns = cursor.fetchall()
has_email = False
for column in columns:
print(f" Column: {column[0]} ({column[1]})")
if column[0] == 'email':
has_email = True
if not has_email:
print("\n2. Adding email column...")
cursor.execute("ALTER TABLE users ADD COLUMN email VARCHAR(255)")
conn.commit()
print(" ✓ Email column added successfully")
else:
print("\n2. Email column already exists")
# Now check and display all users
print("\n3. Current users in database:")
cursor.execute("SELECT id, username, role, email FROM users")
users = cursor.fetchall()
if users:
print(f" Found {len(users)} users:")
for user in users:
email = user[3] if user[3] else "No email"
print(f" - ID: {user[0]}, Username: {user[1]}, Role: {user[2]}, Email: {email}")
else:
print(" No users found - creating test users...")
# Create some test users
test_users = [
('admin_user', 'admin123', 'admin', 'admin@company.com'),
('manager_user', 'manager123', 'manager', 'manager@company.com'),
('warehouse_user', 'warehouse123', 'warehouse_manager', 'warehouse@company.com'),
('quality_user', 'quality123', 'quality_manager', 'quality@company.com')
]
for username, password, role, email in test_users:
try:
cursor.execute("""
INSERT INTO users (username, password, role, email)
VALUES (%s, %s, %s, %s)
""", (username, password, role, email))
print(f" ✓ Created user: {username} ({role})")
except mariadb.IntegrityError as e:
print(f" ⚠ User {username} already exists: {e}")
conn.commit()
print(" ✓ Test users created successfully")
conn.close()
print("\n=== Database Update Complete ===")
except Exception as e:
print(f"❌ Error: {e}")
import traceback
traceback.print_exc()
return 1
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,105 @@
#!/usr/bin/env python3
import mariadb
import os
import sys
def get_external_db_connection():
"""Reads the external_server.conf file and returns a MariaDB database connection."""
# Get the instance folder path
current_dir = os.path.dirname(os.path.abspath(__file__))
instance_folder = os.path.join(current_dir, '../../instance')
settings_file = os.path.join(instance_folder, 'external_server.conf')
if not os.path.exists(settings_file):
raise FileNotFoundError(f"The external_server.conf file is missing: {settings_file}")
# Read settings from the configuration file
settings = {}
with open(settings_file, 'r') as f:
for line in f:
line = line.strip()
if line and '=' in line:
key, value = line.split('=', 1)
settings[key] = value
print(f"Connecting to MariaDB with settings:")
print(f" Host: {settings.get('server_domain', 'N/A')}")
print(f" Port: {settings.get('port', 'N/A')}")
print(f" Database: {settings.get('database_name', 'N/A')}")
print(f" Username: {settings.get('username', 'N/A')}")
# Create a database connection
return mariadb.connect(
user=settings['username'],
password=settings['password'],
host=settings['server_domain'],
port=int(settings['port']),
database=settings['database_name']
)
def main():
try:
print("=== Checking External MariaDB Database ===")
conn = get_external_db_connection()
cursor = conn.cursor()
# Create users table if it doesn't exist
print("\n1. Creating/verifying users table...")
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
role VARCHAR(50) NOT NULL,
email VARCHAR(255)
)
''')
print(" ✓ Users table created/verified")
# Check existing users
print("\n2. Checking existing users...")
cursor.execute("SELECT id, username, role, email FROM users")
users = cursor.fetchall()
if users:
print(f" Found {len(users)} existing users:")
for user in users:
email = user[3] if user[3] else "No email"
print(f" - ID: {user[0]}, Username: {user[1]}, Role: {user[2]}, Email: {email}")
else:
print(" No users found in external database")
# Create some test users
print("\n3. Creating test users...")
test_users = [
('admin_user', 'admin123', 'admin', 'admin@company.com'),
('manager_user', 'manager123', 'manager', 'manager@company.com'),
('warehouse_user', 'warehouse123', 'warehouse_manager', 'warehouse@company.com'),
('quality_user', 'quality123', 'quality_manager', 'quality@company.com')
]
for username, password, role, email in test_users:
try:
cursor.execute("""
INSERT INTO users (username, password, role, email)
VALUES (%s, %s, %s, %s)
""", (username, password, role, email))
print(f" ✓ Created user: {username} ({role})")
except mariadb.IntegrityError as e:
print(f" ⚠ User {username} already exists: {e}")
conn.commit()
print(" ✓ Test users created successfully")
conn.close()
print("\n=== Database Check Complete ===")
except Exception as e:
print(f"❌ Error: {e}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,60 @@
import mariadb
import os
def get_external_db_connection():
"""Get MariaDB connection using external_server.conf"""
settings_file = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../instance/external_server.conf'))
settings = {}
with open(settings_file, 'r') as f:
for line in f:
key, value = line.strip().split('=', 1)
settings[key] = value
return mariadb.connect(
user=settings['username'],
password=settings['password'],
host=settings['server_domain'],
port=int(settings['port']),
database=settings['database_name']
)
def create_external_users_table():
"""Create users table and superadmin user in external MariaDB database"""
try:
conn = get_external_db_connection()
cursor = conn.cursor()
# Create users table if not exists (MariaDB syntax)
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
role VARCHAR(50) NOT NULL
)
''')
# Insert superadmin user if not exists
cursor.execute('''
INSERT IGNORE INTO users (username, password, role)
VALUES (%s, %s, %s)
''', ('superadmin', 'superadmin123', 'superadmin'))
# Check if user was created/exists
cursor.execute("SELECT username, password, role FROM users WHERE username = %s", ('superadmin',))
result = cursor.fetchone()
if result:
print(f"SUCCESS: Superadmin user exists in external database")
print(f"Username: {result[0]}, Password: {result[1]}, Role: {result[2]}")
else:
print("ERROR: Failed to create/find superadmin user")
conn.commit()
conn.close()
print("External MariaDB users table setup completed.")
except Exception as e:
print(f"ERROR: {e}")
if __name__ == "__main__":
create_external_users_table()

View File

@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""
Database script to create the order_for_labels table
This table will store order information for label generation
"""
import sys
import os
import mariadb
from flask import Flask
# Add the app directory to the path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def get_db_connection():
"""Get database connection using settings from external_server.conf"""
# Go up two levels from this script to reach py_app directory, then to instance
app_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
settings_file = os.path.join(app_root, 'instance', 'external_server.conf')
settings = {}
with open(settings_file, 'r') as f:
for line in f:
key, value = line.strip().split('=', 1)
settings[key] = value
return mariadb.connect(
user=settings['username'],
password=settings['password'],
host=settings['server_domain'],
port=int(settings['port']),
database=settings['database_name']
)
def create_order_for_labels_table():
"""
Creates the order_for_labels table with the specified structure
"""
try:
conn = get_db_connection()
cursor = conn.cursor()
# First check if table already exists
cursor.execute("SHOW TABLES LIKE 'order_for_labels'")
result = cursor.fetchone()
if result:
print("Table 'order_for_labels' already exists.")
# Show current structure
cursor.execute("DESCRIBE order_for_labels")
columns = cursor.fetchall()
print("\nCurrent table structure:")
for col in columns:
print(f" {col[0]} - {col[1]} {'NULL' if col[2] == 'YES' else 'NOT NULL'}")
else:
# Create the table
create_table_sql = """
CREATE TABLE order_for_labels (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique identifier',
comanda_productie VARCHAR(15) NOT NULL COMMENT 'Production Order',
cod_articol VARCHAR(15) COMMENT 'Article Code',
descr_com_prod VARCHAR(50) NOT NULL COMMENT 'Production Order Description',
cantitate INT(3) NOT NULL COMMENT 'Quantity',
com_achiz_client VARCHAR(25) COMMENT 'Client Purchase Order',
nr_linie_com_client INT(3) COMMENT 'Client Order Line Number',
customer_name VARCHAR(50) COMMENT 'Customer Name',
customer_article_number VARCHAR(25) COMMENT 'Customer Article Number',
open_for_order VARCHAR(25) COMMENT 'Open for Order Status',
line_number INT(3) COMMENT 'Line Number',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Record creation timestamp',
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Record update timestamp'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Table for storing order information for label generation'
"""
cursor.execute(create_table_sql)
conn.commit()
print("✅ Table 'order_for_labels' created successfully!")
# Show the created structure
cursor.execute("DESCRIBE order_for_labels")
columns = cursor.fetchall()
print("\n📋 Table structure:")
for col in columns:
null_info = 'NULL' if col[2] == 'YES' else 'NOT NULL'
default_info = f" DEFAULT {col[4]}" if col[4] else ""
print(f" 📌 {col[0]:<25} {col[1]:<20} {null_info}{default_info}")
conn.close()
except mariadb.Error as e:
print(f"❌ Database error: {e}")
return False
except Exception as e:
print(f"❌ Error: {e}")
return False
return True
if __name__ == "__main__":
print("🏗️ Creating order_for_labels table...")
print("="*50)
success = create_order_for_labels_table()
if success:
print("\n✅ Database setup completed successfully!")
else:
print("\n❌ Database setup failed!")
print("="*50)

View File

@@ -0,0 +1,141 @@
#!/usr/bin/env python3
import mariadb
import os
import sys
def get_external_db_connection():
"""Reads the external_server.conf file and returns a MariaDB database connection."""
# Get the instance folder path
current_dir = os.path.dirname(os.path.abspath(__file__))
instance_folder = os.path.join(current_dir, '../../instance')
settings_file = os.path.join(instance_folder, 'external_server.conf')
if not os.path.exists(settings_file):
raise FileNotFoundError(f"The external_server.conf file is missing: {settings_file}")
# Read settings from the configuration file
settings = {}
with open(settings_file, 'r') as f:
for line in f:
line = line.strip()
if line and '=' in line:
key, value = line.split('=', 1)
settings[key] = value
return mariadb.connect(
user=settings['username'],
password=settings['password'],
host=settings['server_domain'],
port=int(settings['port']),
database=settings['database_name']
)
def main():
try:
print("=== Creating Permission Management Tables ===")
conn = get_external_db_connection()
cursor = conn.cursor()
# 1. Create permissions table
print("\n1. Creating permissions table...")
cursor.execute('''
CREATE TABLE IF NOT EXISTS permissions (
id INT AUTO_INCREMENT PRIMARY KEY,
permission_key VARCHAR(255) UNIQUE NOT NULL,
page VARCHAR(100) NOT NULL,
page_name VARCHAR(255) NOT NULL,
section VARCHAR(100) NOT NULL,
section_name VARCHAR(255) NOT NULL,
action VARCHAR(50) NOT NULL,
action_name VARCHAR(255) NOT NULL,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
''')
print(" ✓ Permissions table created/verified")
# 2. Create role_permissions table
print("\n2. Creating role_permissions table...")
cursor.execute('''
CREATE TABLE IF NOT EXISTS role_permissions (
id INT AUTO_INCREMENT PRIMARY KEY,
role VARCHAR(50) NOT NULL,
permission_key VARCHAR(255) NOT NULL,
granted BOOLEAN DEFAULT TRUE,
granted_by VARCHAR(50),
granted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY unique_role_permission (role, permission_key),
FOREIGN KEY (permission_key) REFERENCES permissions(permission_key) ON DELETE CASCADE
)
''')
print(" ✓ Role permissions table created/verified")
# 3. Create role_hierarchy table for role management
print("\n3. Creating role_hierarchy table...")
cursor.execute('''
CREATE TABLE IF NOT EXISTS role_hierarchy (
id INT AUTO_INCREMENT PRIMARY KEY,
role_name VARCHAR(50) UNIQUE NOT NULL,
display_name VARCHAR(255) NOT NULL,
description TEXT,
level INT DEFAULT 0,
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
''')
print(" ✓ Role hierarchy table created/verified")
# 4. Create permission_audit_log table for tracking changes
print("\n4. Creating permission_audit_log table...")
cursor.execute('''
CREATE TABLE IF NOT EXISTS permission_audit_log (
id INT AUTO_INCREMENT PRIMARY KEY,
role VARCHAR(50) NOT NULL,
permission_key VARCHAR(255) NOT NULL,
action ENUM('granted', 'revoked') NOT NULL,
changed_by VARCHAR(50) NOT NULL,
changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
reason TEXT,
ip_address VARCHAR(45)
)
''')
print(" ✓ Permission audit log table created/verified")
conn.commit()
# 5. Check if we need to populate initial data
print("\n5. Checking for existing data...")
cursor.execute("SELECT COUNT(*) FROM permissions")
permission_count = cursor.fetchone()[0]
if permission_count == 0:
print(" No permissions found - will need to populate with default data")
print(" Run 'populate_permissions.py' to initialize the permission system")
else:
print(f" Found {permission_count} existing permissions")
cursor.execute("SELECT COUNT(*) FROM role_hierarchy")
role_count = cursor.fetchone()[0]
if role_count == 0:
print(" No roles found - will need to populate with default roles")
else:
print(f" Found {role_count} existing roles")
conn.close()
print("\n=== Permission Database Schema Created Successfully ===")
except Exception as e:
print(f"❌ Error: {e}")
import traceback
traceback.print_exc()
return 1
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,45 @@
import sqlite3
import os
def create_roles_and_users_tables(db_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Create users table if not exists
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
role TEXT NOT NULL
)
''')
# Insert superadmin user if not exists (default password: 'admin', change after first login)
cursor.execute('''
INSERT OR IGNORE INTO users (username, password, role)
VALUES (?, ?, ?)
''', ('superadmin', 'superadmin123', 'superadmin'))
# Create roles table if not exists
cursor.execute('''
CREATE TABLE IF NOT EXISTS roles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
access_level TEXT NOT NULL,
description TEXT
)
''')
# Insert superadmin role if not exists
cursor.execute('''
INSERT OR IGNORE INTO roles (name, access_level, description)
VALUES (?, ?, ?)
''', ('superadmin', 'full', 'Full access to all app areas and functions'))
conn.commit()
conn.close()
if __name__ == "__main__":
# Default path to users.db in instance folder
instance_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../instance'))
if not os.path.exists(instance_folder):
os.makedirs(instance_folder)
db_path = os.path.join(instance_folder, 'users.db')
create_roles_and_users_tables(db_path)
print("Roles and users tables created. Superadmin user and role initialized.")

View File

@@ -0,0 +1,42 @@
import mariadb
# Database connection credentials
db_config = {
"user": "trasabilitate",
"password": "Initial01!",
"host": "localhost",
"database": "trasabilitate"
}
# Connect to the database
try:
conn = mariadb.connect(**db_config)
cursor = conn.cursor()
print("Connected to the database successfully!")
# Create the scan1_orders table
create_table_query = """
CREATE TABLE IF NOT EXISTS scan1_orders (
Id INT AUTO_INCREMENT PRIMARY KEY, -- Auto-incremented ID with 6 digits
operator_code VARCHAR(4) NOT NULL, -- Operator code with 4 characters
CP_full_code VARCHAR(15) NOT NULL UNIQUE, -- Full CP code with up to 15 characters
OC1_code VARCHAR(4) NOT NULL, -- OC1 code with 4 characters
OC2_code VARCHAR(4) NOT NULL, -- OC2 code with 4 characters
CP_base_code VARCHAR(10) GENERATED ALWAYS AS (LEFT(CP_full_code, 10)) STORED, -- Auto-generated base code (first 10 characters of CP_full_code)
quality_code INT(3) NOT NULL, -- Quality code with 3 digits
date DATE NOT NULL, -- Date in format dd-mm-yyyy
time TIME NOT NULL, -- Time in format hh:mm:ss
approved_quantity INT DEFAULT 0, -- Auto-incremented quantity for quality_code = 000
rejected_quantity INT DEFAULT 0 -- Auto-incremented quantity for quality_code != 000
);
"""
cursor.execute(create_table_query)
print("Table 'scan1_orders' created successfully!")
# Commit changes and close the connection
conn.commit()
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error connecting to the database: {e}")

View File

@@ -0,0 +1,41 @@
import mariadb
# Database connection credentials
# (reuse from create_scan_1db.py or update as needed)
db_config = {
"user": "trasabilitate",
"password": "Initial01!",
"host": "localhost",
"database": "trasabilitate"
}
try:
conn = mariadb.connect(**db_config)
cursor = conn.cursor()
print("Connected to the database successfully!")
# Create the scanfg_orders table (same structure as scan1_orders)
create_table_query = """
CREATE TABLE IF NOT EXISTS scanfg_orders (
Id INT AUTO_INCREMENT PRIMARY KEY,
operator_code VARCHAR(4) NOT NULL,
CP_full_code VARCHAR(15) NOT NULL UNIQUE,
OC1_code VARCHAR(4) NOT NULL,
OC2_code VARCHAR(4) NOT NULL,
CP_base_code VARCHAR(10) GENERATED ALWAYS AS (LEFT(CP_full_code, 10)) STORED,
quality_code INT(3) NOT NULL,
date DATE NOT NULL,
time TIME NOT NULL,
approved_quantity INT DEFAULT 0,
rejected_quantity INT DEFAULT 0
);
"""
cursor.execute(create_table_query)
print("Table 'scanfg_orders' created successfully!")
conn.commit()
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error connecting to the database: {e}")

View File

@@ -0,0 +1,70 @@
import mariadb
# Database connection credentials
db_config = {
"user": "trasabilitate",
"password": "Initial01!",
"host": "localhost",
"database": "trasabilitate"
}
# Connect to the database
try:
conn = mariadb.connect(**db_config)
cursor = conn.cursor()
print("Connected to the database successfully!")
# Delete old triggers if they exist
try:
cursor.execute("DROP TRIGGER IF EXISTS increment_approved_quantity;")
print("Old trigger 'increment_approved_quantity' deleted successfully.")
except mariadb.Error as e:
print(f"Error deleting old trigger 'increment_approved_quantity': {e}")
try:
cursor.execute("DROP TRIGGER IF EXISTS increment_rejected_quantity;")
print("Old trigger 'increment_rejected_quantity' deleted successfully.")
except mariadb.Error as e:
print(f"Error deleting old trigger 'increment_rejected_quantity': {e}")
# Create corrected trigger for approved_quantity
create_approved_trigger = """
CREATE TRIGGER increment_approved_quantity
BEFORE INSERT ON scan1_orders
FOR EACH ROW
BEGIN
IF NEW.quality_code = 000 THEN
SET NEW.approved_quantity = (
SELECT COUNT(*)
FROM scan1_orders
WHERE CP_base_code = NEW.CP_base_code AND quality_code = 000
) + 1;
SET NEW.rejected_quantity = (
SELECT COUNT(*)
FROM scan1_orders
WHERE CP_base_code = NEW.CP_base_code AND quality_code != 000
);
ELSE
SET NEW.approved_quantity = (
SELECT COUNT(*)
FROM scan1_orders
WHERE CP_base_code = NEW.CP_base_code AND quality_code = 000
);
SET NEW.rejected_quantity = (
SELECT COUNT(*)
FROM scan1_orders
WHERE CP_base_code = NEW.CP_base_code AND quality_code != 000
) + 1;
END IF;
END;
"""
cursor.execute(create_approved_trigger)
print("Trigger 'increment_approved_quantity' created successfully!")
# Commit changes and close the connection
conn.commit()
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error connecting to the database or creating triggers: {e}")

View File

@@ -0,0 +1,73 @@
import mariadb
# Database connection credentials
db_config = {
"user": "trasabilitate",
"password": "Initial01!",
"host": "localhost",
"database": "trasabilitate"
}
# Connect to the database
try:
conn = mariadb.connect(**db_config)
cursor = conn.cursor()
print("Connected to the database successfully!")
# Delete old triggers if they exist
try:
cursor.execute("DROP TRIGGER IF EXISTS increment_approved_quantity_fg;")
print("Old trigger 'increment_approved_quantity_fg' deleted successfully.")
except mariadb.Error as e:
print(f"Error deleting old trigger 'increment_approved_quantity_fg': {e}")
try:
cursor.execute("DROP TRIGGER IF EXISTS increment_rejected_quantity_fg;")
print("Old trigger 'increment_rejected_quantity_fg' deleted successfully.")
except mariadb.Error as e:
print(f"Error deleting old trigger 'increment_rejected_quantity_fg': {e}")
# Create corrected trigger for approved_quantity in scanfg_orders
create_approved_trigger_fg = """
CREATE TRIGGER increment_approved_quantity_fg
BEFORE INSERT ON scanfg_orders
FOR EACH ROW
BEGIN
IF NEW.quality_code = 000 THEN
SET NEW.approved_quantity = (
SELECT COUNT(*)
FROM scanfg_orders
WHERE CP_base_code = NEW.CP_base_code AND quality_code = 000
) + 1;
SET NEW.rejected_quantity = (
SELECT COUNT(*)
FROM scanfg_orders
WHERE CP_base_code = NEW.CP_base_code AND quality_code != 000
);
ELSE
SET NEW.approved_quantity = (
SELECT COUNT(*)
FROM scanfg_orders
WHERE CP_base_code = NEW.CP_base_code AND quality_code = 000
);
SET NEW.rejected_quantity = (
SELECT COUNT(*)
FROM scanfg_orders
WHERE CP_base_code = NEW.CP_base_code AND quality_code != 000
) + 1;
END IF;
END;
"""
cursor.execute(create_approved_trigger_fg)
print("Trigger 'increment_approved_quantity_fg' created successfully for scanfg_orders table!")
# Commit changes and close the connection
conn.commit()
cursor.close()
conn.close()
print("\n✅ All triggers for scanfg_orders table created successfully!")
print("The approved_quantity and rejected_quantity will now be calculated automatically.")
except mariadb.Error as e:
print(f"Error connecting to the database or creating triggers: {e}")

View File

@@ -0,0 +1,25 @@
import mariadb
from app.warehouse import get_db_connection
from flask import Flask
import os
def create_warehouse_locations_table():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS warehouse_locations (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
location_code VARCHAR(12) NOT NULL UNIQUE,
size INT,
description VARCHAR(250)
)
''')
conn.commit()
conn.close()
if __name__ == "__main__":
instance_path = os.path.abspath("instance")
app = Flask(__name__, instance_path=instance_path)
with app.app_context():
create_warehouse_locations_table()
print("warehouse_locations table created or already exists.")

View File

@@ -0,0 +1,30 @@
import mariadb
# Database connection credentials
def get_db_connection():
return mariadb.connect(
user="trasabilitate", # Replace with your username
password="Initial01!", # Replace with your password
host="localhost", # Replace with your host
port=3306, # Default MariaDB port
database="trasabilitate_database" # Replace with your database name
)
try:
# Connect to the database
conn = get_db_connection()
cursor = conn.cursor()
# Delete query
delete_query = "DELETE FROM scan1_orders"
cursor.execute(delete_query)
conn.commit()
print("All data from the 'scan1_orders' table has been deleted successfully.")
# Close the connection
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error deleting data: {e}")

View File

@@ -0,0 +1,26 @@
import mariadb
import os
def get_external_db_connection():
settings_file = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../instance/external_server.conf'))
settings = {}
with open(settings_file, 'r') as f:
for line in f:
key, value = line.strip().split('=', 1)
settings[key] = value
return mariadb.connect(
user=settings['username'],
password=settings['password'],
host=settings['server_domain'],
port=int(settings['port']),
database=settings['database_name']
)
if __name__ == "__main__":
conn = get_external_db_connection()
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS users")
cursor.execute("DROP TABLE IF EXISTS roles")
conn.commit()
conn.close()
print("Dropped users and roles tables from external database.")

View File

@@ -0,0 +1,53 @@
import sqlite3
import os
def check_database(db_path, description):
"""Check if a database exists and show its users."""
if os.path.exists(db_path):
print(f"\n{description}: FOUND at {db_path}")
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Check if users table exists
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'")
if cursor.fetchone():
cursor.execute("SELECT id, username, password, role FROM users")
users = cursor.fetchall()
if users:
print("Users in this database:")
for user in users:
print(f" ID: {user[0]}, Username: {user[1]}, Password: {user[2]}, Role: {user[3]}")
else:
print(" Users table exists but is empty")
else:
print(" No users table found")
conn.close()
except Exception as e:
print(f" Error reading database: {e}")
else:
print(f"\n{description}: NOT FOUND at {db_path}")
if __name__ == "__main__":
# Check different possible locations for users.db
# 1. Root quality_recticel/instance/users.db
root_instance = "/home/ske087/quality_recticel/instance/users.db"
check_database(root_instance, "Root instance users.db")
# 2. App instance folder
app_instance = "/home/ske087/quality_recticel/py_app/instance/users.db"
check_database(app_instance, "App instance users.db")
# 3. Current working directory
cwd_db = "/home/ske087/quality_recticel/py_app/users.db"
check_database(cwd_db, "Working directory users.db")
# 4. Flask app database (relative to py_app)
flask_db = "/home/ske087/quality_recticel/py_app/app/users.db"
check_database(flask_db, "Flask app users.db")
print("\n" + "="*50)
print("RECOMMENDATION:")
print("The login should use the external MariaDB database.")
print("Make sure you have created the superadmin user in MariaDB using create_roles_table.py")

View File

@@ -0,0 +1,143 @@
#!/usr/bin/env python3
import mariadb
import os
import sys
# Add the app directory to the path so we can import our permissions module
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from permissions import APP_PERMISSIONS, ROLE_HIERARCHY, ACTIONS, get_all_permissions, get_default_permissions_for_role
def get_external_db_connection():
"""Reads the external_server.conf file and returns a MariaDB database connection."""
current_dir = os.path.dirname(os.path.abspath(__file__))
instance_folder = os.path.join(current_dir, '../../instance')
settings_file = os.path.join(instance_folder, 'external_server.conf')
if not os.path.exists(settings_file):
raise FileNotFoundError(f"The external_server.conf file is missing: {settings_file}")
settings = {}
with open(settings_file, 'r') as f:
for line in f:
line = line.strip()
if line and '=' in line:
key, value = line.split('=', 1)
settings[key] = value
return mariadb.connect(
user=settings['username'],
password=settings['password'],
host=settings['server_domain'],
port=int(settings['port']),
database=settings['database_name']
)
def main():
try:
print("=== Populating Permission System ===")
conn = get_external_db_connection()
cursor = conn.cursor()
# 1. Populate all permissions
print("\n1. Populating permissions...")
permissions = get_all_permissions()
for perm in permissions:
try:
cursor.execute('''
INSERT INTO permissions (permission_key, page, page_name, section, section_name, action, action_name)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
page_name = VALUES(page_name),
section_name = VALUES(section_name),
action_name = VALUES(action_name),
updated_at = CURRENT_TIMESTAMP
''', (
perm['key'],
perm['page'],
perm['page_name'],
perm['section'],
perm['section_name'],
perm['action'],
perm['action_name']
))
except Exception as e:
print(f" ⚠ Error inserting permission {perm['key']}: {e}")
conn.commit()
print(f" ✓ Populated {len(permissions)} permissions")
# 2. Populate role hierarchy
print("\n2. Populating role hierarchy...")
for role_name, role_data in ROLE_HIERARCHY.items():
try:
cursor.execute('''
INSERT INTO role_hierarchy (role_name, display_name, description, level)
VALUES (%s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
display_name = VALUES(display_name),
description = VALUES(description),
level = VALUES(level),
updated_at = CURRENT_TIMESTAMP
''', (
role_name,
role_data['name'],
role_data['description'],
role_data['level']
))
except Exception as e:
print(f" ⚠ Error inserting role {role_name}: {e}")
conn.commit()
print(f" ✓ Populated {len(ROLE_HIERARCHY)} roles")
# 3. Set default permissions for each role
print("\n3. Setting default role permissions...")
for role_name in ROLE_HIERARCHY.keys():
default_permissions = get_default_permissions_for_role(role_name)
print(f" Setting permissions for {role_name}: {len(default_permissions)} permissions")
for permission_key in default_permissions:
try:
cursor.execute('''
INSERT INTO role_permissions (role, permission_key, granted, granted_by)
VALUES (%s, %s, TRUE, 'system')
ON DUPLICATE KEY UPDATE
granted = TRUE,
updated_at = CURRENT_TIMESTAMP
''', (role_name, permission_key))
except Exception as e:
print(f" ⚠ Error setting permission {permission_key} for {role_name}: {e}")
conn.commit()
# 4. Show summary
print("\n4. Permission Summary:")
cursor.execute('''
SELECT r.role_name, r.display_name, COUNT(rp.permission_key) as permission_count
FROM role_hierarchy r
LEFT JOIN role_permissions rp ON r.role_name = rp.role AND rp.granted = TRUE
GROUP BY r.role_name, r.display_name
ORDER BY r.level DESC
''')
results = cursor.fetchall()
for role_name, display_name, count in results:
print(f" {display_name} ({role_name}): {count} permissions")
conn.close()
print("\n=== Permission System Initialization Complete ===")
except Exception as e:
print(f"❌ Error: {e}")
import traceback
traceback.print_exc()
return 1
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,30 @@
import sqlite3
import os
instance_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../instance'))
db_path = os.path.join(instance_folder, 'users.db')
if not os.path.exists(db_path):
print("users.db not found at", db_path)
exit(1)
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Check if users table exists
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'")
if not cursor.fetchone():
print("No users table found in users.db.")
conn.close()
exit(1)
# Print all users
cursor.execute("SELECT id, username, password, role FROM users")
rows = cursor.fetchall()
if not rows:
print("No users found in users.db.")
else:
print("Users in users.db:")
for row in rows:
print(f"id={row[0]}, username={row[1]}, password={row[2]}, role={row[3]}")
conn.close()

View File

@@ -0,0 +1,34 @@
import mariadb
# Database connection credentials
db_config = {
"user": "trasabilitate",
"password": "Initial01!",
"host": "localhost",
"database": "trasabilitate_database"
}
try:
# Connect to the database
conn = mariadb.connect(**db_config)
cursor = conn.cursor()
# Query to fetch all records from the scan1 table
query = "SELECT * FROM scan1_orders ORDER BY Id DESC LIMIT 15"
cursor.execute(query)
# Fetch and print the results
rows = cursor.fetchall()
if rows:
print("Records in the 'scan1_orders' table:")
for row in rows:
print(row)
else:
print("No records found in the 'scan1_orders' table.")
# Close the connection
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error connecting to the database: {e}")

View File

@@ -0,0 +1,50 @@
import mariadb
# Database connection credentials
DB_CONFIG = {
"user": "sa",
"password": "12345678",
"host": "localhost",
"database": "recticel"
}
def recreate_order_for_labels_table():
conn = mariadb.connect(**DB_CONFIG)
cursor = conn.cursor()
print("Connected to the database successfully!")
# Drop the table if it exists
cursor.execute("DROP TABLE IF EXISTS order_for_labels")
print("Dropped existing 'order_for_labels' table.")
# Create the table with the new unique constraint
create_table_sql = """
CREATE TABLE order_for_labels (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique identifier',
comanda_productie VARCHAR(15) NOT NULL UNIQUE COMMENT 'Production Order (unique)',
cod_articol VARCHAR(15) COMMENT 'Article Code',
descr_com_prod VARCHAR(50) NOT NULL COMMENT 'Production Order Description',
cantitate INT(3) NOT NULL COMMENT 'Quantity',
data_livrare DATE COMMENT 'Delivery date',
dimensiune VARCHAR(20) COMMENT 'Dimensions',
com_achiz_client VARCHAR(25) COMMENT 'Client Purchase Order',
nr_linie_com_client INT(3) COMMENT 'Client Order Line Number',
customer_name VARCHAR(50) COMMENT 'Customer Name',
customer_article_number VARCHAR(25) COMMENT 'Customer Article Number',
open_for_order VARCHAR(25) COMMENT 'Open for Order Status',
line_number INT(3) COMMENT 'Line Number',
printed_labels TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Boolean flag: 0=labels not printed, 1=labels printed',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Record creation timestamp',
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Record update timestamp'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Table for storing order information for label generation';
"""
cursor.execute(create_table_sql)
print("Created new 'order_for_labels' table with unique comanda_productie.")
conn.commit()
cursor.close()
conn.close()
print("Done.")
if __name__ == "__main__":
recreate_order_for_labels_table()

View File

@@ -0,0 +1,34 @@
import sqlite3
import os
from flask import Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key' # Use the same key as in __init__.py
instance_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../instance'))
if not os.path.exists(instance_folder):
os.makedirs(instance_folder)
db_path = os.path.join(instance_folder, 'users.db')
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Create users table if not exists
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
role TEXT NOT NULL
)
''')
# Insert superadmin user if not exists
cursor.execute('''
INSERT OR IGNORE INTO users (username, password, role)
VALUES (?, ?, ?)
''', ('superadmin', 'superadmin123', 'superadmin'))
conn.commit()
conn.close()
print("Internal users.db seeded with superadmin user.")

View File

@@ -0,0 +1,37 @@
import mariadb
# Database connection credentials
def get_db_connection():
return mariadb.connect(
user="trasabilitate", # Replace with your username
password="Initial01!", # Replace with your password
host="localhost", # Replace with your host
port=3306, # Default MariaDB port
database="trasabilitate_database" # Replace with your database name
)
try:
# Connect to the database
conn = get_db_connection()
cursor = conn.cursor()
# Insert query
insert_query = """
INSERT INTO scan1_orders (operator_code, CP_full_code, OC1_code, OC2_code, quality_code, date, time)
VALUES (?, ?, ?, ?, ?, ?, ?)
"""
# Values to insert
values = ('OP01', 'CP12345678-0002', 'OC11', 'OC22', 000, '2025-04-22', '14:30:00')
# Execute the query
cursor.execute(insert_query, values)
conn.commit()
print("Test data inserted successfully into scan1_orders.")
# Close the connection
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error inserting data: {e}")