Compare commits

..

No commits in common. "aeee08c4c9ea52218613745811ae1cde5e794c64" and "379998a4592171eb67bc556a14ce50efc5fcfaed" have entirely different histories.

2 changed files with 38 additions and 50 deletions

View File

@ -18,4 +18,4 @@ EXPOSE 80
HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
ENTRYPOINT ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"] ENTRYPOINT ["streamlit", "run", "app.py", "--server.port=80", "--server.address=0.0.0.0"]

View File

@ -2,14 +2,14 @@ import streamlit as st
import pandas as pd import pandas as pd
import subprocess import subprocess
import mysql.connector import mysql.connector
from datetime import datetime, timedelta from datetime import datetime
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
load_dotenv() load_dotenv()
total_time_unit = [] total_time_unit = []
def get_filtered_users(customer_id, start_date, end_date): def get_filtered_users(customer_id):
mydb = mysql.connector.connect( mydb = mysql.connector.connect(
host=os.getenv("MYSQL_HOST"), host=os.getenv("MYSQL_HOST"),
user=os.getenv("MYSQL_USER"), user=os.getenv("MYSQL_USER"),
@ -17,28 +17,24 @@ def get_filtered_users(customer_id, start_date, end_date):
database=os.getenv("MYSQL_DATABASE") database=os.getenv("MYSQL_DATABASE")
) )
# Prepare the base query with date filter # Prepare the base query
query = f""" query = f"""
SELECT number,title,createdate,time FROM Kunden.tickets SELECT number,title,createdate,time FROM Kunden.tickets
WHERE createdate BETWEEN '{start_date}' AND '{end_date}' WHERE 1=1
""" """
if customer_id: if customer_id:
query += f" AND customer_ID = {customer_id}" query += f"AND customer_ID = {customer_id} order by createdate"
query += " ORDER BY createdate"
users = pd.read_sql_query(query, mydb) users = pd.read_sql_query(query, mydb)
mydb.close() mydb.close()
# Format date columns
for column in users.select_dtypes(include=['datetime64[ns]', 'datetime64[ns, UTC]']).columns: for column in users.select_dtypes(include=['datetime64[ns]', 'datetime64[ns, UTC]']).columns:
users[column] = users[column].dt.strftime('%d.%m.%Y') users[column] = users[column].dt.strftime('%d.%m.%Y')
# Convert 'time' to integer
users.iloc[:, 3] = users.iloc[:, 3].str.split('.').str[0] users.iloc[:, 3] = users.iloc[:, 3].str.split('.').str[0]
users['time'] = users['time'].astype(int) users['time'] = users['time'].astype(int)
# Create hyperlink for ticket number base_url = "https://ticket.stines.de/#ticket/zoom/number/" # Replace with your actual base URL
base_url = "https://ticket.stines.de/#ticket/zoom/number/"
users['Link'] = users['number'].apply(lambda x: f'<a href="{base_url}{x}" target="_blank">{x}</a>') users['Link'] = users['number'].apply(lambda x: f'<a href="{base_url}{x}" target="_blank">{x}</a>')
return users return users
@ -69,28 +65,28 @@ def get_initial_data():
return service_ids, customers return service_ids, customers
def run_script_and_list_documents(): def run_script_and_list_documents():
output_area = st.empty() # Placeholder for output output_area = st.empty() # Platzhalter für die Ausgabe
document_paths = [] # List to store generated document paths document_paths = [] # Liste der erstellten Dokumente
# Directory where the script should be run # Verzeichnis, in dem das Skript ausgeführt werden soll
working_directory = "apps/ticket_export/exports" working_directory = "apps/ticket_export/exports"
# Run the script in the specified directory # Führe das Skript in dem angegebenen Verzeichnis aus
result = subprocess.run( result = subprocess.run(
["python3", "apps/ticket_export/main.py"], ["python3", "apps/ticket_export/main.py"],
capture_output=True, capture_output=True,
text=True text=True
) )
# Search for generated documents in the working directory # Suche nach den erstellten Dokumenten im Arbeitsverzeichnis
for filename in os.listdir(working_directory): for filename in os.listdir("apps/ticket_export/exports"):
if filename.endswith(".docx"): if filename.endswith(".docx"):
full_path = os.path.join(working_directory, filename) full_path = os.path.join(working_directory, filename)
document_paths.append(full_path) document_paths.append(full_path)
# Display the list of generated documents and offer them for download # Zeige die Liste der erstellten Dokumente an und biete sie zum Download an
if document_paths: if document_paths:
st.write("Generated Documents:") st.write("Erstellte Dokumente:")
for doc_path in document_paths: for doc_path in document_paths:
with open(doc_path, "rb") as file: with open(doc_path, "rb") as file:
st.download_button( st.download_button(
@ -100,7 +96,7 @@ def run_script_and_list_documents():
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document" mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
) )
else: else:
st.write("No documents found.") st.write("Keine Dokumente gefunden.")
def ticket_filter(): def ticket_filter():
st.title("Ticket Filter :mag_right:") st.title("Ticket Filter :mag_right:")
@ -116,22 +112,16 @@ def ticket_filter():
# Extract customer_ID from selected option # Extract customer_ID from selected option
selected_customer_id = None if selected_customer == "All" else int(selected_customer.split(' - ')[0]) selected_customer_id = None if selected_customer == "All" else int(selected_customer.split(' - ')[0])
# Add date range picker if st.button("Rechnung erstellen"):
start_date = st.date_input("Start Date", datetime.now() - timedelta(days=30)) st.write("Das Skript wird ausgeführt...")
end_date = st.date_input("End Date", datetime.now())
if st.button("Create Invoice"):
st.write("Running the script...")
run_script_and_list_documents() run_script_and_list_documents()
# Add a button to apply filters # Add a button to apply filters
if st.button('Apply Filters'): if st.button('Apply Filters'):
if start_date > end_date:
st.error("Error: End date must be greater than or equal to start date.")
else:
# Fetch filtered data from the database # Fetch filtered data from the database
filtered_data = get_filtered_users(selected_customer_id, start_date, end_date) filtered_data = get_filtered_users(selected_customer_id)
if not filtered_data.empty: if not filtered_data.empty:
# st.dataframe(filtered_data,hide_index=True)
st.markdown(filtered_data.to_html(escape=False), unsafe_allow_html=True) st.markdown(filtered_data.to_html(escape=False), unsafe_allow_html=True)
# Convert DataFrame to CSV # Convert DataFrame to CSV
csv = filtered_data.drop(columns=['Link']).to_csv(index=False) csv = filtered_data.drop(columns=['Link']).to_csv(index=False)
@ -145,8 +135,6 @@ def ticket_filter():
file_name=f"filtered_data_{selected_customer}.csv", # Custom file name file_name=f"filtered_data_{selected_customer}.csv", # Custom file name
mime='text/csv', mime='text/csv',
) )
else: else:
st.write("No data available for the selected filters.") st.write("No data available for the selected filters.")
if __name__ == "__main__":
ticket_filter()