Reports-Visual/sites/server.py

136 lines
4.6 KiB
Python

import streamlit as st
import pandas as pd
import mysql.connector
from datetime import datetime
import os
from dotenv import load_dotenv
load_dotenv()
def get_filtered_server(customer_ids, service_id, service_status, os_type, reporting):
mydb = mysql.connector.connect(
host=os.getenv("MYSQL_HOST"),
user=os.getenv("MYSQL_USER"),
password=os.getenv("MYSQL_PASSWORD"),
database=os.getenv("MYSQL_DATABASE")
)
# Prepare the base query
query = f"""
select s.hostname, s.privat_ipaddress, s.public_ipaddress, s.ram, s.createdate, s.disabledate, s.os, s.customer_ID, s.server_ID, hc.name, hc.core
from Kunden.server s
join Kunden.`hardware.cpu` hc ON hc.cpu_ID = s.cpu_ID
WHERE 1=1
"""
# If multiple customers are selected, use the IN clause
if customer_ids:
customer_ids_str = ', '.join([str(id) for id in customer_ids])
query += f" AND s.customer_ID IN ({customer_ids_str})"
if service_id:
query += f" AND s.service_ID = {service_id}"
if service_status:
query += f" AND s.status = {service_status}"
if os_type:
query += f" AND s.os = '{os_type}'"
if reporting == "True":
query += f" AND licensekey IS NOT NULL"
users = pd.read_sql_query(query, mydb)
mydb.close()
return users
def get_initial_data():
mydb = mysql.connector.connect(
host=os.getenv("MYSQL_HOST"),
user=os.getenv("MYSQL_USER"),
password=os.getenv("MYSQL_PASSWORD"),
database=os.getenv("MYSQL_DATABASE")
)
# Fetch unique service IDs and names
service_id_query = """
SELECT DISTINCT s.service_ID, s.name
FROM Kunden.services s
"""
service_ids = pd.read_sql_query(service_id_query, mydb)
# Fetch customer information
customer_query = """
SELECT DISTINCT c.customer_ID, c.customer, co.companyname
FROM Kunden.company co
JOIN Kunden.customers c ON co.customer_ID = c.customer_ID
"""
customers = pd.read_sql_query(customer_query, mydb)
mydb.close()
return service_ids, customers
def server_filter():
st.title("Server Filter :mag_right:")
# Get initial data for widgets
initial_service_ids, customers = get_initial_data()
# Combine service_ID and name for display
service_options = initial_service_ids.apply(lambda row: f"{row['service_ID']} - {row['name']}", axis=1)
# Create a dictionary for customer selection
customer_dict = {f"{row['companyname']} - {row['customer']}": row['customer_ID'] for _, row in customers.iterrows()}
# Use multiselect for multiple customer selection
selected_customers = st.multiselect(
'Select Customer(s)',
list(customer_dict.keys()) # Display only companyname and customer
)
# Get the corresponding customer IDs
selected_customer_ids = [customer_dict[customer] for customer in selected_customers]
# Add selection widget for service ID
selected_service = st.selectbox(
'Select Service',
["All"] + service_options.tolist()
)
# Extract service_ID from selected option
selected_service_id = None if selected_service == "All" else int(selected_service.split(' - ')[0])
# Add selection widget for service status
selected_status = st.selectbox(
'Select Service Status',
["All", "1 - Active", "0 - Inactive"]
)
# Extract status from selected option
service_status = None if selected_status == "All" else int(selected_status.split(' - ')[0])
# Add SPLA server selection
reporting_box = st.selectbox(
'Select SPLA Server',
["Nein", "Ja"]
)
# Extract reporting status
reporting = None if reporting_box == "Nein" else "True"
# Add OS type selection
os_box = st.selectbox(
'Select OS Type',
["All", "Linux", "Windows"]
)
# Extract OS type
os_type = None if os_box == "All" else os_box
# Add a button to apply filters
if st.button('Apply Filters'):
# Fetch filtered data from the database
filtered_data = get_filtered_server(selected_customer_ids, selected_service_id, service_status, os_type, reporting)
# Display the filtered data
if not filtered_data.empty:
st.dataframe(filtered_data)
st.text(f"CPU SUMME = {sum(filtered_data['core'])}" )
st.text(f"Berechung der Core-Pakete: Anzahl der Cores({filtered_data['core'].count()}) * Core-Pakete aus SPLA (8) / 2")
st.text(f"Reporting Core-Pakete = {(filtered_data['core'].count())*8/2}".split('.')[0])
else:
st.write("No data available for the selected filters.")