Files
Webovka-pro-Jarmark/dashboard_app.py

545 lines
16 KiB
Python

import ctypes
import io
import math
import queue
import random
import sys
import threading
import time
import tkinter as tk
from datetime import datetime
from flask import Flask, jsonify, request
from PIL import Image, ImageTk
import requests
# ==============================================================================
# SÍŤOVÝ SERVER & GLOBÁLNÍ PAMĚŤ
# ==============================================================================
SPOTIFY_SERVER_URL = "http://localhost:8080/endpoint"
order_queue = queue.Queue()
ORDERS = {}
flask_app = Flask(__name__)
@flask_app.route('/api/order', methods=['POST'])
def receive_order():
"""Přijme novou objednávku a uloží ji."""
try:
data = request.json or {}
order_id = str(random.randint(1000, 9999))
data['id'] = order_id
data['status'] = 'čaká na potvrzení'
ORDERS[order_id] = data
order_queue.put(data)
return (
jsonify(
{'status': 'success', 'order_id': order_id, 'message': 'Doručeno'}
),
200,
)
except Exception as e:
return jsonify({'status': 'error', 'message': str(e)}), 500
@flask_app.route('/api/order/<order_id>/status', methods=['GET'])
def get_order_status(order_id):
"""Vzdálený PC zjišťuje, zda byla objednávka na stánku potvrzena."""
order = ORDERS.get(str(order_id))
if not order:
return jsonify({'error': 'Nenalezeno'}), 404
return jsonify({'order_id': order_id, 'status': order['status']})
def run_flask():
flask_app.run(host='0.0.0.0', port=5000, debug=False, use_reloader=False)
# ==============================================================================
# WINDOWS MULTIMEDIÁLNÍ KLÁVESY
# ==============================================================================
VK_MEDIA_NEXT = 0xB0
VK_MEDIA_PREV = 0xB1
VK_MEDIA_PLAY_PAUSE = 0xCD
KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
def send_media_key(key_code):
"""Simuluje stisknutí hardwarové klávesy ve Windows."""
if sys.platform == 'win32':
ctypes.windll.user32.keybd_event(key_code, 0, KEYEVENTF_EXTENDEDKEY, 0)
ctypes.windll.user32.keybd_event(
key_code, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0
)
# ==============================================================================
# MAIN DASHBOARD GUI
# ==============================================================================
class ParticleDashboard(tk.Tk):
def __init__(self):
super().__init__()
self.title("Příchozí Objednávky & Spotify Dashboard")
self.attributes("-fullscreen", True)
self.configure(bg="#0a0e17")
self.bind("<Escape>", lambda e: self.attributes("-fullscreen", False))
self.bind(
"<F11>",
lambda e: self.attributes(
"-fullscreen", not self.attributes("-fullscreen")
),
)
self.width = self.winfo_screenwidth()
self.height = self.winfo_screenheight()
self.canvas = tk.Canvas(
self,
width=self.width,
height=self.height,
bg="#0a0e17",
highlightthickness=0,
)
self.canvas.pack(fill="both", expand=True)
# Částice na pozadí
self.num_particles = 50
self.particles = []
colors = ["#00f2fe", "#4facfe", "#1db954", "#7b2cbf", "#38bdf8"]
for _ in range(self.num_particles):
self.particles.append({
"x": random.uniform(0, self.width),
"y": random.uniform(0, self.height),
"vx": random.uniform(-0.5, 0.5),
"vy": random.uniform(-0.5, 0.5),
"radius": random.uniform(2, 4),
"color": random.choice(colors),
})
self.orders_list = []
self.current_img_url = None
self.cover_photo = None
self.is_running = True
self.create_ui_overlays()
self.animate_particles()
self.update_clock()
self.check_new_orders()
# Vlákno pro Spotify polling
threading.Thread(target=self._spotify_poll_loop, daemon=True).start()
def create_ui_overlays(self):
self.main_container = tk.Frame(self.canvas, bg="#0a0e17")
self.canvas.create_window(
self.width // 2,
self.height // 2,
window=self.main_container,
width=self.width - 60,
height=self.height - 60,
)
self.main_container.columnconfigure(0, weight=3)
self.main_container.columnconfigure(1, weight=1)
self.main_container.rowconfigure(1, weight=1)
# HEADER
header = tk.Frame(
self.main_container,
bg="#111827",
highlightbackground="#1f2937",
highlightthickness=1,
)
header.grid(
row=0, column=0, columnspan=2, sticky="ew", pady=(0, 15), ipady=10
)
title = tk.Label(
header,
text="⚡ PŘÍCHOZÍ OBJEDNÁVKY (STÁNEK)",
font=("Segoe UI", 20, "bold"),
fg="#00f2fe",
bg="#111827",
)
title.pack(side="left", padx=20)
self.time_lbl = tk.Label(
header, text="", font=("Segoe UI", 15, "bold"), fg="#9ca3af", bg="#111827"
)
self.time_lbl.pack(side="right", padx=20)
# LEVÝ PANEL - FRONTA OBJEDNÁVEK
self.orders_box = tk.Frame(
self.main_container,
bg="#111827",
highlightbackground="#1f2937",
highlightthickness=1,
)
self.orders_box.grid(row=1, column=0, sticky="nsew", padx=(0, 12))
tk.Label(
self.orders_box,
text="AKTUÁLNÍ FRONTA ZÁSILEK (ŽIVĚ)",
font=("Segoe UI", 11, "bold"),
fg="#6b7280",
bg="#111827",
).pack(anchor="w", padx=20, pady=(15, 10))
self.orders_scroll = tk.Frame(self.orders_box, bg="#111827")
self.orders_scroll.pack(fill="both", expand=True, padx=15, pady=5)
self.empty_lbl = tk.Label(
self.orders_scroll,
text="⏳ Čekám na první příchozí objednávku...",
font=("Segoe UI", 13, "italic"),
fg="#4b5563",
bg="#111827",
)
self.empty_lbl.pack(pady=50)
# PRAVÝ PANEL - STATISTIKY & SPOTIFY
right_panel = tk.Frame(self.main_container, bg="#0a0e17")
right_panel.grid(row=1, column=1, sticky="nsew")
stats_card = tk.Frame(
right_panel,
bg="#111827",
highlightbackground="#1f2937",
highlightthickness=1,
)
stats_card.pack(fill="x", pady=(0, 15), ipady=10)
tk.Label(
stats_card,
text="DNEŠNÍ PŘEHLED",
font=("Segoe UI", 11, "bold"),
fg="#6b7280",
bg="#111827",
).pack(anchor="w", padx=15, pady=(5, 5))
self.stats_total_lbl = tk.Label(
stats_card,
text="Celkem objednávek: 0 ks",
font=("Segoe UI", 13),
fg="#e5e7eb",
bg="#111827",
)
self.stats_total_lbl.pack(anchor="w", padx=15)
self.stats_money_lbl = tk.Label(
stats_card,
text="Tržba celkem: 0 Kč",
font=("Segoe UI", 13, "bold"),
fg="#38bdf8",
bg="#111827",
)
self.stats_money_lbl.pack(anchor="w", padx=15)
# SPOTIFY WIDGET
sp_card = tk.Frame(
right_panel,
bg="#121212",
highlightbackground="#1db954",
highlightthickness=1,
)
sp_card.pack(fill="x", side="bottom", ipady=10)
sp_head = tk.Frame(sp_card, bg="#121212")
sp_head.pack(fill="x", padx=15, pady=(10, 5))
tk.Label(
sp_head,
text="♫ SPOTIFY PLAYER",
font=("Segoe UI", 11, "bold"),
fg="#1db954",
bg="#121212",
).pack(side="left")
info_frame = tk.Frame(sp_card, bg="#121212")
info_frame.pack(fill="x", padx=15, pady=5)
self.sp_title_lbl = tk.Label(
info_frame,
text="Načítám Spotify...",
font=("Segoe UI", 15, "bold"),
fg="#ffffff",
bg="#121212",
anchor="w",
)
self.sp_title_lbl.pack(fill="x")
self.sp_artist_lbl = tk.Label(
info_frame,
text="Připojování k serveru",
font=("Segoe UI", 11),
fg="#b3b3b3",
bg="#121212",
anchor="w",
)
self.sp_artist_lbl.pack(fill="x")
self.sp_progress_lbl = tk.Label(
info_frame,
text="0:00 / 0:00",
font=("Segoe UI", 9),
fg="#6b7280",
bg="#121212",
anchor="w",
)
self.sp_progress_lbl.pack(fill="x", pady=(2, 0))
ctrls = tk.Frame(sp_card, bg="#121212")
ctrls.pack(pady=10)
tk.Button(
ctrls,
text="⏮",
font=("Segoe UI", 14),
fg="#ffffff",
bg="#282828",
bd=0,
padx=12,
cursor="hand2",
command=lambda: send_media_key(VK_MEDIA_PREV),
).pack(side="left", padx=8)
tk.Button(
ctrls,
text="⏯",
font=("Segoe UI", 16, "bold"),
fg="#000000",
bg="#1db954",
bd=0,
padx=14,
pady=2,
cursor="hand2",
command=lambda: send_media_key(VK_MEDIA_PLAY_PAUSE),
).pack(side="left", padx=8)
tk.Button(
ctrls,
text="⏭",
font=("Segoe UI", 14),
fg="#ffffff",
bg="#282828",
bd=0,
padx=12,
cursor="hand2",
command=lambda: send_media_key(VK_MEDIA_NEXT),
).pack(side="left", padx=8)
# ==========================================================================
# LOGIKA OBJEDNÁVEK A POTVRZOVÁNÍ
# ==========================================================================
def add_order_to_ui(self, order_data):
if self.empty_lbl:
self.empty_lbl.destroy()
self.empty_lbl = None
order_id = str(order_data.get("id"))
customer = order_data.get("customer", "Neznámý")
product = order_data.get("product", "Zboží")
quantity = order_data.get("quantity", 1)
price_unit = order_data.get("price", 0)
dobirka = order_data.get("dobirka", 0)
time_str = order_data.get("time", datetime.now().strftime("%H:%M:%S"))
total_price = quantity * price_unit
self.orders_list.append({"total": total_price, "qty": quantity})
# Řádek objednávky
row = tk.Frame(
self.orders_scroll,
bg="#1f2937",
highlightbackground="#374151",
highlightthickness=1,
)
row.pack(fill="x", pady=4, ipady=6)
left_info = tk.Frame(row, bg="#1f2937")
left_info.pack(side="left", padx=10)
tk.Label(
left_info,
text=f"#{order_id}",
font=("Segoe UI", 13, "bold"),
fg="#00f2fe",
bg="#1f2937",
).pack(anchor="w")
tk.Label(
left_info,
text=time_str,
font=("Segoe UI", 10),
fg="#9ca3af",
bg="#1f2937",
).pack(anchor="w")
mid_info = tk.Frame(row, bg="#1f2937")
mid_info.pack(side="left", padx=15, fill="x", expand=True)
title_text = f"{customer} • {quantity}x {product}"
tk.Label(
mid_info,
text=title_text,
font=("Segoe UI", 12, "bold"),
fg="#f3f4f6",
bg="#1f2937",
anchor="w",
).pack(fill="x")
detail_text = f"Celkem: {total_price:.0f} Kč ({price_unit:.0f} Kč/ks)"
if dobirka > 0:
detail_text += f" | ⚠️ Dobírka: {dobirka:.0f} Kč"
else:
detail_text += " | Zaplaceno"
tk.Label(
mid_info,
text=detail_text,
font=("Segoe UI", 11),
fg="#38bdf8" if dobirka == 0 else "#fbbf24",
bg="#1f2937",
anchor="w",
).pack(fill="x")
# Odznak stavu + Tlačítko Potvrdit
badge = tk.Label(
row,
text="ČEKÁ",
font=("Segoe UI", 10, "bold"),
fg="#ffffff",
bg="#ef4444",
padx=10,
pady=4,
)
badge.pack(side="right", padx=(5, 12))
btn_confirm = tk.Button(
row,
text="POTVRDIT",
font=("Segoe UI", 10, "bold"),
fg="#ffffff",
bg="#10b981",
activebackground="#059669",
activeforeground="#ffffff",
bd=0,
padx=10,
pady=3,
cursor="hand2",
)
btn_confirm.pack(side="right", padx=5)
def confirm_action():
ORDERS[order_id]["status"] = "potvrzeno"
badge.config(text="POTVRZENO", bg="#10b981")
btn_confirm.config(
text="✓ HOTOVO", bg="#374151", state="disabled", cursor="default"
)
btn_confirm.config(command=confirm_action)
# Aktualizace statistik
total_cnt = len(self.orders_list)
sum_money = sum(o["total"] for o in self.orders_list)
self.stats_total_lbl.config(text=f"Celkem objednávek: {total_cnt} ks")
self.stats_money_lbl.config(text=f"Tržba celkem: {sum_money:.0f} Kč")
def check_new_orders(self):
while not order_queue.empty():
order = order_queue.get()
self.add_order_to_ui(order)
self.after(300, self.check_new_orders)
# ==========================================================================
# SPOTIFY POLLING LOGIKA
# ==========================================================================
def _spotify_poll_loop(self):
while self.is_running:
try:
res = requests.get(SPOTIFY_SERVER_URL, timeout=2)
if res.status_code == 200:
data = res.json()
artist = str(data.get("artist", "Neznámý interpret")).strip()
title = str(data.get("title", "Žádná skladba")).strip()
progress = str(data.get("progressTime", "0:00 / 0:00"))
def apply():
self.sp_title_lbl.config(text=title if title else "Žádná skladba")
self.sp_artist_lbl.config(
text=artist if artist else "Spotify nehraje"
)
self.sp_progress_lbl.config(text=progress)
self.after(0, apply)
except Exception:
def apply_err():
self.sp_title_lbl.config(text="Spotify odpojeno")
self.sp_artist_lbl.config(text="Nelze načíst z localhost:8080")
self.after(0, apply_err)
time.sleep(1)
# ==========================================================================
# ANIMACE ČÁSTIC A HODINY
# ==========================================================================
def animate_particles(self):
self.canvas.delete("particle")
self.canvas.delete("line")
for p in self.particles:
p["x"] += p["vx"]
p["y"] += p["vy"]
if p["x"] <= 0 or p["x"] >= self.width:
p["vx"] *= -1
if p["y"] <= 0 or p["y"] >= self.height:
p["vy"] *= -1
x, y, r = p["x"], p["y"], p["radius"]
self.canvas.create_oval(
x - r,
y - r,
x + r,
y + r,
fill=p["color"],
outline="",
tags="particle",
)
for i in range(len(self.particles)):
for j in range(i + 1, len(self.particles)):
p1 = self.particles[i]
p2 = self.particles[j]
dist = math.hypot(p1["x"] - p2["x"], p1["y"] - p2["y"])
if dist < 110:
self.canvas.create_line(
p1["x"],
p1["y"],
p2["x"],
p2["y"],
fill="#1e293b",
width=1,
tags="line",
)
self.after(25, self.animate_particles)
def update_clock(self):
now = datetime.now().strftime("%H:%M:%S | %d.%m.%Y")
self.time_lbl.config(text=now)
self.after(1000, self.update_clock)
if __name__ == "__main__":
# 1. Spuštění Flasku v pozadí
t = threading.Thread(target=run_flask, daemon=True)
t.start()
# 2. Spuštění Tkinter GUI
app = ParticleDashboard()
app.mainloop()