correct update to the database and database created for scan

This commit is contained in:
2025-04-22 16:12:17 +03:00
parent e51e4bf2bb
commit 1d6eadf540
9 changed files with 246 additions and 36 deletions

View 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}")

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

@@ -1,5 +1,5 @@
import os import os
import pyodbc import mariadb
from flask import Blueprint, render_template, redirect, url_for, request, flash, session, current_app from flask import Blueprint, render_template, redirect, url_for, request, flash, session, current_app
from .models import User from .models import User
from . import db from . import db
@@ -7,7 +7,7 @@ from . import db
bp = Blueprint('main', __name__) bp = Blueprint('main', __name__)
def get_db_connection(): 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') settings_file = os.path.join(current_app.instance_path, 'external_server.conf')
if not os.path.exists(settings_file): if not os.path.exists(settings_file):
raise FileNotFoundError("The external_server.conf file is missing in the instance folder.") 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) key, value = line.strip().split('=', 1)
settings[key] = value settings[key] = value
# Create a database connection string # Create a database connection
connection_string = ( return mariadb.connect(
f"DRIVER={{ODBC Driver 17 for SQL Server}};" user=settings['username'],
f"SERVER={settings['server_domain']},{settings['port']};" password=settings['password'],
f"DATABASE={settings['database_name']};" host=settings['server_domain'],
f"UID={settings['username']};" port=int(settings['port']),
f"PWD={settings['password']};" database=settings['database_name']
) )
return pyodbc.connect(connection_string)
@bp.route('/login', methods=['GET', 'POST']) @bp.route('/login', methods=['GET', 'POST'])
def login(): def login():
@@ -99,18 +98,37 @@ def scan():
date = request.form.get('date') date = request.form.get('date')
time = request.form.get('time') 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: try:
# Connect to the database
conn = get_db_connection() conn = get_db_connection()
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute(
"INSERT INTO scanare (operator_code, cp_code, oc1_code, oc2_code, defect_code, date, time, quantity) " # Insert query
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)", insert_query = """
operator_code, cp_code, oc1_code, oc2_code, defect_code, date, time, 1 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.commit()
conn.close() conn.close()
flash('Scan data saved successfully.') 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}") flash(f"Error saving scan data: {e}")
# Fetch the latest scan data for display # Fetch the latest scan data for display
@@ -118,10 +136,16 @@ def scan():
try: try:
conn = get_db_connection() conn = get_db_connection()
cursor = conn.cursor() 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() scan_data = cursor.fetchall()
conn.close() 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}") flash(f"Error fetching scan data: {e}")
return render_template('scan.html', scan_data=scan_data) return render_template('scan.html', scan_data=scan_data)

View File

@@ -10,7 +10,7 @@
<input type="text" id="operator_code" name="operator_code" maxlength="4" required> <input type="text" id="operator_code" name="operator_code" maxlength="4" required>
<label for="cp_code">CP Code:</label> <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> <label for="oc1_code">OC1 Code:</label>
<input type="text" id="oc1_code" name="oc1_code" maxlength="4" required> <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> <input type="text" id="defect_code" name="defect_code" maxlength="4" required>
<label for="date">Date:</label> <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> <label for="time">Time:</label>
<input type="text" id="time" name="time" value="{{ now().strftime('%H:%M:%S') }}" readonly> <input type="text" id="time" name="time" value="{{ now().strftime('%H:%M:%S') }}" readonly>
@@ -38,28 +38,30 @@
<thead> <thead>
<tr> <tr>
<th>ID</th> <th>ID</th>
<th>Operator Code</th> <th>Op Code</th>
<th>CP Code</th> <th>CP Code</th>
<th>OC1 Code</th> <th>OC1 Code</th>
<th>OC2 Code</th> <th>OC2 Code</th>
<th>Defect Code</th> <th>Defect Code</th>
<th>Date</th> <th>Date</th>
<th>Time</th> <th>Time</th>
<th>Quantity</th> <th>Apr. Quantity</th>
<th>Rejec. Quantity</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for row in scan_data %} {% for row in scan_data %}
<tr> <tr>
<td>{{ row.id }}</td> <td>{{ row[0] }}</td> <!-- Id -->
<td>{{ row.operator_code }}</td> <td>{{ row[1] }}</td> <!-- operator_code -->
<td>{{ row.cp_code }}</td> <td>{{ row[2] }}</td> <!-- CP_full_code -->
<td>{{ row.oc1_code }}</td> <td>{{ row[3] }}</td> <!-- OC1_code -->
<td>{{ row.oc2_code }}</td> <td>{{ row[4] }}</td> <!-- OC2_code -->
<td>{{ row.defect_code }}</td> <td>{{ row[5] }}</td> <!-- quality_code -->
<td>{{ row.date }}</td> <td>{{ row[6] }}</td> <!-- date -->
<td>{{ row.time }}</td> <td>{{ row[7] }}</td> <!-- time -->
<td>{{ row.quantity }}</td> <td>{{ row[8] }}</td> <!-- approved_quantity -->
<td>{{ row[9] }}</td> <!-- rejected_quantity -->
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>

37
py_app/app/test.py Normal file
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}")

View File

@@ -1,5 +1,5 @@
server_domain=testserver.com server_domain=localhost
port=3602 port=3602
database_name=recticel database_name=trasabilitate_database
username=test1 username=trasabilitate
password=12345678 password=Initial01!

View File

@@ -2,4 +2,12 @@ python3 -m venv recticel
source recticel/bin/activate source recticel/bin/activate
python /home/ske087/quality_recticel/py_app/run.py python /home/ske087/quality_recticel/py_app/run.py
sudo mysql -u root -p
root password : Initaial01!
CREATE DATABASE trasabilitate_database;
CREATE USER 'trasabilitate'@'localhost' IDENTIFIED BY 'Initial01!';
GRANT ALL PRIVILEGES ON trasabilitate_database.* TO 'trasabilitate'@'localhost';
FLUSH PRIVILEGES;
EXIT