correct update to the database and database created for scan
This commit is contained in:
Binary file not shown.
42
py_app/app/db_create_scripts/create_scan_1db.py
Normal file
42
py_app/app/db_create_scripts/create_scan_1db.py
Normal file
@@ -0,0 +1,42 @@
|
||||
import mariadb
|
||||
|
||||
# Database connection credentials
|
||||
db_config = {
|
||||
"user": "trasabilitate",
|
||||
"password": "Initial01!",
|
||||
"host": "localhost",
|
||||
"database": "trasabilitate_database"
|
||||
}
|
||||
|
||||
# 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, -- 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}")
|
||||
63
py_app/app/db_create_scripts/create_triggers.py
Normal file
63
py_app/app/db_create_scripts/create_triggers.py
Normal file
@@ -0,0 +1,63 @@
|
||||
import mariadb
|
||||
|
||||
# Database connection credentials
|
||||
db_config = {
|
||||
"user": "trasabilitate",
|
||||
"password": "Initial01!",
|
||||
"host": "localhost",
|
||||
"database": "trasabilitate_database"
|
||||
}
|
||||
|
||||
# Connect to the database
|
||||
try:
|
||||
conn = mariadb.connect(**db_config)
|
||||
cursor = conn.cursor()
|
||||
print("Connected to the database successfully!")
|
||||
|
||||
# Create trigger for approved_quantity
|
||||
create_approved_trigger = """
|
||||
DELIMITER //
|
||||
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 IFNULL(MAX(approved_quantity), 0) + 1
|
||||
FROM scan1_orders
|
||||
WHERE CP_base_code = NEW.CP_base_code
|
||||
);
|
||||
END IF;
|
||||
END//
|
||||
DELIMITER ;
|
||||
"""
|
||||
cursor.execute(create_approved_trigger)
|
||||
print("Trigger 'increment_approved_quantity' created successfully!")
|
||||
|
||||
# Create trigger for rejected_quantity
|
||||
create_rejected_trigger = """
|
||||
DELIMITER //
|
||||
CREATE TRIGGER increment_rejected_quantity
|
||||
BEFORE INSERT ON scan1_orders
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
IF NEW.quality_code != 000 THEN
|
||||
SET NEW.rejected_quantity = (
|
||||
SELECT IFNULL(MAX(rejected_quantity), 0) + 1
|
||||
FROM scan1_orders
|
||||
WHERE CP_base_code = NEW.CP_base_code
|
||||
);
|
||||
END IF;
|
||||
END//
|
||||
DELIMITER ;
|
||||
"""
|
||||
cursor.execute(create_rejected_trigger)
|
||||
print("Trigger 'increment_rejected_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}")
|
||||
34
py_app/app/query.py
Normal file
34
py_app/app/query.py
Normal 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}")
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import pyodbc
|
||||
import mariadb
|
||||
from flask import Blueprint, render_template, redirect, url_for, request, flash, session, current_app
|
||||
from .models import User
|
||||
from . import db
|
||||
@@ -7,7 +7,7 @@ from . import db
|
||||
bp = Blueprint('main', __name__)
|
||||
|
||||
def get_db_connection():
|
||||
"""Reads the external_server.conf file and returns a database connection."""
|
||||
"""Reads the external_server.conf file and returns a MariaDB database connection."""
|
||||
settings_file = os.path.join(current_app.instance_path, 'external_server.conf')
|
||||
if not os.path.exists(settings_file):
|
||||
raise FileNotFoundError("The external_server.conf file is missing in the instance folder.")
|
||||
@@ -19,15 +19,14 @@ def get_db_connection():
|
||||
key, value = line.strip().split('=', 1)
|
||||
settings[key] = value
|
||||
|
||||
# Create a database connection string
|
||||
connection_string = (
|
||||
f"DRIVER={{ODBC Driver 17 for SQL Server}};"
|
||||
f"SERVER={settings['server_domain']},{settings['port']};"
|
||||
f"DATABASE={settings['database_name']};"
|
||||
f"UID={settings['username']};"
|
||||
f"PWD={settings['password']};"
|
||||
# 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']
|
||||
)
|
||||
return pyodbc.connect(connection_string)
|
||||
|
||||
@bp.route('/login', methods=['GET', 'POST'])
|
||||
def login():
|
||||
@@ -99,18 +98,37 @@ def scan():
|
||||
date = request.form.get('date')
|
||||
time = request.form.get('time')
|
||||
|
||||
# Print the values to the terminal for debugging with single quotes
|
||||
print("Values to be inserted:")
|
||||
print(f"Operator Code: '{operator_code}'")
|
||||
print(f"CP Code: '{cp_code}'")
|
||||
print(f"OC1 Code: '{oc1_code}'")
|
||||
print(f"OC2 Code: '{oc2_code}'")
|
||||
print(f"Defect Code: '{defect_code}'")
|
||||
print(f"Date: '{date}'")
|
||||
print(f"Time: '{time}'")
|
||||
|
||||
try:
|
||||
# Connect to the database
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
"INSERT INTO scanare (operator_code, cp_code, oc1_code, oc2_code, defect_code, date, time, quantity) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
operator_code, cp_code, oc1_code, oc2_code, defect_code, date, time, 1
|
||||
)
|
||||
|
||||
# Insert query
|
||||
insert_query = """
|
||||
INSERT INTO scan1_orders (operator_code, CP_full_code, OC1_code, OC2_code, quality_code, date, time)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
"""
|
||||
print(f"Executing query: {insert_query}")
|
||||
print(f"With values: ('{operator_code}', '{cp_code}', '{oc1_code}', '{oc2_code}', '{defect_code}', '{date}', '{time}')")
|
||||
|
||||
# Execute the query
|
||||
cursor.execute(insert_query, (operator_code, cp_code, oc1_code, oc2_code, defect_code, date, time))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
flash('Scan data saved successfully.')
|
||||
except Exception as e:
|
||||
except mariadb.Error as e:
|
||||
print(f"Error saving scan data: {e}")
|
||||
flash(f"Error saving scan data: {e}")
|
||||
|
||||
# Fetch the latest scan data for display
|
||||
@@ -118,10 +136,16 @@ def scan():
|
||||
try:
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT TOP 14 * FROM scanare ORDER BY id DESC")
|
||||
cursor.execute("""
|
||||
SELECT Id, operator_code, CP_full_code, OC1_code, OC2_code, quality_code, date, time, approved_quantity, rejected_quantity
|
||||
FROM scan1_orders
|
||||
ORDER BY Id DESC
|
||||
LIMIT 15
|
||||
""")
|
||||
scan_data = cursor.fetchall()
|
||||
conn.close()
|
||||
except Exception as e:
|
||||
except mariadb.Error as e:
|
||||
print(f"Error fetching scan data: {e}")
|
||||
flash(f"Error fetching scan data: {e}")
|
||||
|
||||
return render_template('scan.html', scan_data=scan_data)
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<input type="text" id="operator_code" name="operator_code" maxlength="4" required>
|
||||
|
||||
<label for="cp_code">CP Code:</label>
|
||||
<input type="text" id="cp_code" name="cp_code" maxlength="14" required>
|
||||
<input type="text" id="cp_code" name="cp_code" maxlength="15" required>
|
||||
|
||||
<label for="oc1_code">OC1 Code:</label>
|
||||
<input type="text" id="oc1_code" name="oc1_code" maxlength="4" required>
|
||||
@@ -22,7 +22,7 @@
|
||||
<input type="text" id="defect_code" name="defect_code" maxlength="4" required>
|
||||
|
||||
<label for="date">Date:</label>
|
||||
<input type="text" id="date" name="date" value="{{ now().strftime('%Y-%m-%d') }}" readonly>
|
||||
<input type="text" id="date" name="date" value="{{ now().strftime('%Y-%m-%d') }}" placeholder="yyyy-mm-dd" pattern="\d{4}-\d{2}-\d{2}" required>
|
||||
|
||||
<label for="time">Time:</label>
|
||||
<input type="text" id="time" name="time" value="{{ now().strftime('%H:%M:%S') }}" readonly>
|
||||
@@ -38,28 +38,30 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Operator Code</th>
|
||||
<th>Op Code</th>
|
||||
<th>CP Code</th>
|
||||
<th>OC1 Code</th>
|
||||
<th>OC2 Code</th>
|
||||
<th>Defect Code</th>
|
||||
<th>Date</th>
|
||||
<th>Time</th>
|
||||
<th>Quantity</th>
|
||||
<th>Apr. Quantity</th>
|
||||
<th>Rejec. Quantity</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in scan_data %}
|
||||
<tr>
|
||||
<td>{{ row.id }}</td>
|
||||
<td>{{ row.operator_code }}</td>
|
||||
<td>{{ row.cp_code }}</td>
|
||||
<td>{{ row.oc1_code }}</td>
|
||||
<td>{{ row.oc2_code }}</td>
|
||||
<td>{{ row.defect_code }}</td>
|
||||
<td>{{ row.date }}</td>
|
||||
<td>{{ row.time }}</td>
|
||||
<td>{{ row.quantity }}</td>
|
||||
<td>{{ row[0] }}</td> <!-- Id -->
|
||||
<td>{{ row[1] }}</td> <!-- operator_code -->
|
||||
<td>{{ row[2] }}</td> <!-- CP_full_code -->
|
||||
<td>{{ row[3] }}</td> <!-- OC1_code -->
|
||||
<td>{{ row[4] }}</td> <!-- OC2_code -->
|
||||
<td>{{ row[5] }}</td> <!-- quality_code -->
|
||||
<td>{{ row[6] }}</td> <!-- date -->
|
||||
<td>{{ row[7] }}</td> <!-- time -->
|
||||
<td>{{ row[8] }}</td> <!-- approved_quantity -->
|
||||
<td>{{ row[9] }}</td> <!-- rejected_quantity -->
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
|
||||
37
py_app/app/test.py
Normal file
37
py_app/app/test.py
Normal 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}")
|
||||
Reference in New Issue
Block a user