diff --git "a/app.py" "b/app.py"
deleted file mode 100644--- "a/app.py"
+++ /dev/null
@@ -1,4382 +0,0 @@
-# -*- coding: utf-8 -*-
-"""Final File prior to User Access
-
-Automatically generated by Colab.
-
-Original file is located at
- https://colab.research.google.com/drive/1zKH9cRk6FxYky5m1T6CjN7OYSrnZUyAl
-"""
-
-# Pink Blossoms Brewing - Keg Management System
-import subprocess
-import sys
-
-def install_packages():
- packages = ['gradio', 'pandas', 'numpy', 'plotly', 'requests', 'pytz']
- for package in packages:
- try:
- __import__(package)
- print(f"✓ {package} already installed")
- except ImportError:
- print(f"Installing {package}...")
- subprocess.check_call([sys.executable, "-m", "pip", "install", package])
- print(f"✓ {package} installed successfully")
-
-install_packages()
-
-import gradio as gr
-import sqlite3
-import pandas as pd
-import numpy as np
-from datetime import datetime, timedelta, date
-import plotly.express as px
-import plotly.graph_objects as go
-from plotly.subplots import make_subplots
-import json
-import re
-import pytz
-import os
-import requests
-from typing import List, Dict, Optional, Tuple
-import warnings
-warnings.filterwarnings('ignore')
-
-# Clean CSS styling
-enhanced_css = """
-:root {
- --pb-primary: #DD1B52;
- --pb-light: #F5A5C7;
- --pb-dark: #000000;
- --pb-pantone: #C8102E;
- --white: #ffffff;
- --gray-50: #fafafa;
- --gray-100: #f5f5f5;
- --gray-200: #eeeeee;
- --gray-300: #e0e0e0;
- --gray-600: #757575;
- --gray-800: #424242;
- --success: #4caf50;
- --warning: #ff9800;
- --error: #f44336;
- --archived: #9e9e9e;
- --compact-spacing: 8px;
- --compact-padding: 12px;
-}
-
-.gradio-container {
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
- background: var(--white);
- color: var(--gray-800);
- max-width: 1400px;
- margin: 0 auto;
- padding: 20px;
- line-height: 1.6;
-}
-
-.gradio-container h1 {
- color: var(--pb-primary);
- font-weight: 700;
- font-size: 2.5rem;
- text-align: center;
- margin: 0 0 30px 0;
- text-shadow: 1px 1px 2px rgba(221, 27, 82, 0.1);
- border-bottom: 3px solid var(--pb-light);
- padding-bottom: 15px;
-}
-
-.gradio-container h2 {
- color: var(--pb-primary);
- font-weight: 600;
- font-size: 1.75rem;
- margin: 30px 0 20px 0;
- border-bottom: 2px solid var(--pb-light);
- padding-bottom: 10px;
-}
-
-.gradio-container h3 {
- color: var(--pb-dark);
- font-weight: 600;
- font-size: 1.5rem;
- margin: 25px 0 15px 0;
-}
-
-.gradio-container h4 {
- color: var(--pb-primary);
- font-weight: 500;
- font-size: 1.25rem;
- margin: 20px 0 10px 0;
-}
-
-.compact-row {
- gap: var(--compact-spacing) !important;
- margin: var(--compact-spacing) 0 !important;
-}
-
-.compact-section {
- margin: var(--compact-spacing) 0 !important;
- padding: var(--compact-padding) !important;
-}
-
-.gradio-container .tab-nav button {
- background: transparent !important;
- color: var(--gray-600) !important;
- border: none !important;
- border-bottom: 3px solid transparent !important;
- border-radius: 0 !important;
- font-weight: 600 !important;
- padding: 15px 20px !important;
- transition: all 0.3s ease !important;
- font-size: 16px !important;
-}
-
-.gradio-container .tab-nav button:hover {
- color: var(--pb-primary) !important;
- border-bottom-color: var(--pb-light) !important;
- background: rgba(245, 165, 199, 0.1) !important;
-}
-
-.gradio-container .tab-nav button.selected {
- color: var(--pb-primary) !important;
- border-bottom-color: var(--pb-primary) !important;
- background: rgba(245, 165, 199, 0.15) !important;
-}
-
-.gradio-group {
- background: var(--white);
- border: 2px solid var(--pb-light);
- border-radius: 12px;
- padding: 20px;
- margin: 15px 0;
- box-shadow: 0 4px 12px rgba(221, 27, 82, 0.08);
- transition: box-shadow 0.3s ease;
-}
-
-.gradio-group:hover {
- box-shadow: 0 6px 16px rgba(221, 27, 82, 0.12);
-}
-
-input, textarea, select {
- border: 2px solid var(--gray-300) !important;
- border-radius: 8px !important;
- padding: 10px 12px !important;
- font-size: 14px !important;
- background: var(--white) !important;
- transition: all 0.3s ease !important;
- min-height: 35px !important;
-}
-
-input:focus, textarea:focus, select:focus {
- border-color: var(--pb-primary) !important;
- box-shadow: 0 0 0 4px rgba(221, 27, 82, 0.15) !important;
- outline: none !important;
-}
-
-.gradio-button {
- background: var(--pb-primary) !important;
- color: var(--white) !important;
- border: none !important;
- border-radius: 8px !important;
- padding: 10px 18px !important;
- font-weight: 600 !important;
- font-size: 14px !important;
- transition: all 0.3s ease !important;
- cursor: pointer !important;
- min-height: 35px !important;
- display: flex !important;
- align-items: center !important;
- justify-content: center !important;
-}
-
-.gradio-button:hover {
- background: var(--pb-pantone) !important;
- transform: translateY(-2px) !important;
- box-shadow: 0 4px 12px rgba(221, 27, 82, 0.25) !important;
-}
-
-.gradio-dataframe {
- border: 2px solid var(--pb-light);
- border-radius: 12px;
- overflow: hidden;
- background: var(--white);
- box-shadow: 0 4px 12px rgba(221, 27, 82, 0.08);
-}
-
-.gradio-dataframe table {
- border-collapse: collapse;
- width: 100%;
-}
-
-.gradio-dataframe th {
- background: linear-gradient(135deg, var(--pb-primary), var(--pb-pantone)) !important;
- color: var(--white) !important;
- font-weight: 700 !important;
- padding: 12px 16px !important;
- text-align: left !important;
- font-size: 13px !important;
- text-transform: uppercase !important;
- letter-spacing: 0.5px !important;
-}
-
-.gradio-dataframe td {
- padding: 10px 16px !important;
- border-bottom: 1px solid var(--pb-light) !important;
- font-size: 13px !important;
-}
-
-.gradio-dataframe tr:nth-child(even) {
- background: rgba(245, 165, 199, 0.05) !important;
-}
-
-.gradio-dataframe tr:hover {
- background: rgba(245, 165, 199, 0.15) !important;
-}
-
-.gradio-plot {
- border: 2px solid var(--pb-light);
- border-radius: 12px;
- overflow: hidden;
- background: var(--white);
- box-shadow: 0 4px 12px rgba(221, 27, 82, 0.08);
- margin: var(--compact-spacing) 0 !important;
-}
-
-label {
- font-weight: 600 !important;
- color: var(--pb-dark) !important;
- font-size: 14px !important;
- margin-bottom: 6px !important;
- display: block !important;
-}
-
-.gradio-container .gr-markdown {
- color: var(--gray-800);
-}
-
-.gradio-container .gr-markdown h4 {
- color: var(--pb-primary);
- font-weight: 600;
- margin: var(--compact-spacing) 0 !important;
-}
-
-.gradio-container .gr-markdown strong {
- color: var(--pb-primary);
-}
-
-@media (max-width: 768px) {
- .gradio-container {
- padding: 12px;
- }
- .gradio-container h1 {
- font-size: 1.8rem;
- }
- input, textarea, select {
- font-size: 16px !important;
- padding: 8px 10px !important;
- }
- .gradio-group {
- padding: 15px;
- }
-}
-
-::-webkit-scrollbar {
- width: 8px;
-}
-
-::-webkit-scrollbar-track {
- background: var(--gray-100);
- border-radius: 4px;
-}
-
-::-webkit-scrollbar-thumb {
- background: var(--pb-light);
- border-radius: 4px;
-}
-
-::-webkit-scrollbar-thumb:hover {
- background: var(--pb-primary);
-}
-"""
-
-# Core configuration
-SINGAPORE_TZ = pytz.timezone('Asia/Singapore')
-UTC_TZ = pytz.UTC
-SHOPIFY_SHOP_DOMAIN = "pink-blossoms-brewing"
-PRIMARY_LOCATIONS = ["BT1", "BT2", "Tasting Room"]
-LOCATION_KEG_LIMITS = {
- "BT1": 10,
- "BT2": 10,
- "Tasting Room": 18
-}
-
-def get_singapore_now():
- return datetime.now(SINGAPORE_TZ)
-
-def get_utc_now():
- return datetime.now(UTC_TZ)
-
-def singapore_to_utc(sg_datetime):
- if isinstance(sg_datetime, str):
- dt = datetime.strptime(sg_datetime, '%Y-%m-%d %H:%M:%S')
- dt = SINGAPORE_TZ.localize(dt)
- return dt.astimezone(UTC_TZ)
- elif sg_datetime.tzinfo is None:
- sg_datetime = SINGAPORE_TZ.localize(sg_datetime)
- return sg_datetime.astimezone(UTC_TZ)
-
-def utc_to_singapore(utc_datetime):
- if isinstance(utc_datetime, str):
- utc_datetime = datetime.strptime(utc_datetime, '%Y-%m-%d %H:%M:%S')
- if utc_datetime.tzinfo is None:
- utc_datetime = UTC_TZ.localize(utc_datetime)
- elif utc_datetime.tzinfo != UTC_TZ:
- utc_datetime = utc_datetime.astimezone(UTC_TZ)
- return utc_datetime.astimezone(SINGAPORE_TZ)
-
-def format_singapore_time(dt):
- if isinstance(dt, str):
- dt = utc_to_singapore(dt)
- elif dt.tzinfo is None:
- dt = SINGAPORE_TZ.localize(dt)
- elif dt.tzinfo != SINGAPORE_TZ:
- dt = dt.astimezone(SINGAPORE_TZ)
- return dt.strftime('%Y-%m-%d %H:%M:%S SGT')
-
-def parse_event_date(event_date_str: str, default_date: date = None) -> date:
- if not event_date_str or not event_date_str.strip():
- return default_date if default_date else get_singapore_now().date()
- try:
- return datetime.strptime(event_date_str.strip(), '%Y-%m-%d').date()
- except ValueError:
- return default_date if default_date else get_singapore_now().date()
-
-def create_singapore_datetime(event_date: date, time_str: str = "00:00") -> datetime:
- try:
- if time_str == "23:59:59":
- time_obj = datetime.strptime(time_str, '%H:%M:%S').time()
- else:
- time_obj = datetime.strptime(time_str, '%H:%M').time()
- dt = datetime.combine(event_date, time_obj)
- return SINGAPORE_TZ.localize(dt)
- except ValueError:
- dt = datetime.combine(event_date, datetime.min.time())
- return SINGAPORE_TZ.localize(dt)
-
-def create_empty_plot(title="Click button to load data", height=350):
- fig = go.Figure()
- fig.add_annotation(
- text=title, x=0.5, y=0.5, showarrow=False,
- font=dict(size=14, color="#757575", family="system-ui, sans-serif")
- )
- fig.update_layout(
- title="", xaxis=dict(visible=False), yaxis=dict(visible=False),
- template="plotly_white", height=height, margin=dict(t=20, b=20, l=20, r=20),
- plot_bgcolor='rgba(245, 165, 199, 0.05)', paper_bgcolor='white'
- )
- return fig
-
-def create_error_plot(error_message, height=350):
- fig = go.Figure()
- fig.add_annotation(
- text=f"Error: {error_message}", x=0.5, y=0.5, showarrow=False,
- font=dict(size=14, color="#f44336", family="system-ui, sans-serif")
- )
- fig.update_layout(
- title="Error Loading Data", xaxis=dict(visible=False), yaxis=dict(visible=False),
- template="plotly_white", height=height, margin=dict(t=20, b=20, l=20, r=20)
- )
- return fig
-
-def create_draw_down_bar_chart(df):
- try:
- if df.empty:
- return create_empty_plot("No draw down data available for selected filters")
-
- df['beer_size_combo'] = df['beer_code'] + ' (' + df['keg_size_value'].astype(str) + 'L)'
- combo_counts = df['beer_size_combo'].value_counts().sort_index()
-
- color_map = {
- 'LOM': '#DD1B52', 'DSB': '#F5A5C7', 'HY': '#ff9800',
- 'NSG': '#4caf50', 'WAT': '#9c27b0', 'DIA': '#607d8b'
- }
-
- colors = []
- for combo in combo_counts.index:
- beer_code = combo.split(' (')[0]
- colors.append(color_map.get(beer_code, '#424242'))
-
- fig = go.Figure(data=[go.Bar(
- x=combo_counts.index, y=combo_counts.values, marker_color=colors,
- text=[f"{count} kegs" for count in combo_counts.values], textposition='auto',
- hovertemplate='%{x}
Draw Downs: %{y}
'
- )])
-
- fig.update_layout(
- title="Draw Down Analysis by Beer Code & Size",
- xaxis_title="Beer Code & Size",
- yaxis_title="Number of Draw Downs",
- template="plotly_white", height=400,
- font=dict(family="system-ui, sans-serif", size=11),
- title_font=dict(size=16, color="#DD1B52"),
- plot_bgcolor='rgba(245, 165, 199, 0.1)',
- paper_bgcolor='white', margin=dict(t=60, b=60, l=60, r=60),
- showlegend=False
- )
- fig.update_xaxes(tickangle=45)
- return fig
- except Exception as e:
- return create_error_plot(f"Chart Error: {str(e)}")
-
-class ShopifyOrdersAPIClient:
- def __init__(self, access_token=None, db_conn=None):
- self.shop_domain = SHOPIFY_SHOP_DOMAIN
- self.access_token = access_token or os.getenv('SHOPIFY_ACCESS_TOKEN', '')
- self.base_url = f"https://{self.shop_domain}.myshopify.com" if self.shop_domain else None
- self.headers = {
- 'X-Shopify-Access-Token': self.access_token,
- 'Content-Type': 'application/json'
- } if self.access_token else {}
- self.api_version = '2024-10'
- self.db_conn = db_conn
- self.location_id_mapping = {}
- self.inventory_to_pos_mapping = {}
- self._load_location_mappings()
-
- def _load_location_mappings(self):
- """Load location mappings from database"""
- if not self.db_conn:
- self.location_id_mapping = {
- '67045785765': 'Beer Truck 1',
- '67805577381': 'Beer Truck 2',
- '15546056802': '50 Ubi Ave 3',
- }
- self.inventory_to_pos_mapping = {
- 'BT1': 'Beer Truck 1',
- 'BT2': 'Beer Truck 2',
- 'Tasting Room': '50 Ubi Ave 3'
- }
- return
-
- try:
- cursor = self.db_conn.cursor()
-
- cursor.execute('''
- SELECT lm.shopify_location_id, lm.pos_location_name
- FROM location_mapping lm
- WHERE lm.is_active = TRUE
- AND lm.is_archived = FALSE
- AND lm.shopify_location_id IS NOT NULL
- AND lm.shopify_location_id != ''
- ''')
-
- self.location_id_mapping = {}
- for shopify_id, pos_name in cursor.fetchall():
- self.location_id_mapping[str(shopify_id)] = pos_name
-
- cursor.execute('''
- SELECT l.location_name, lm.pos_location_name
- FROM location_mapping lm
- JOIN locations l ON lm.location_id = l.location_id
- WHERE lm.is_active = TRUE
- AND lm.is_archived = FALSE
- ''')
-
- self.inventory_to_pos_mapping = {}
- for inv_name, pos_name in cursor.fetchall():
- self.inventory_to_pos_mapping[inv_name] = pos_name
-
- if not self.inventory_to_pos_mapping:
- self.inventory_to_pos_mapping = {
- 'BT1': 'Beer Truck 1',
- 'BT2': 'Beer Truck 2',
- 'Tasting Room': '50 Ubi Ave 3'
- }
-
- if not self.location_id_mapping:
- self.location_id_mapping = {
- '67045785765': 'Beer Truck 1',
- '67805577381': 'Beer Truck 2',
- '15546056802': '50 Ubi Ave 3',
- }
-
- except Exception as e:
- print(f"Error loading location mappings: {e}")
- self.location_id_mapping = {
- '67045785765': 'Beer Truck 1',
- '67805577381': 'Beer Truck 2',
- '15546056802': '50 Ubi Ave 3',
- }
- self.inventory_to_pos_mapping = {
- 'BT1': 'Beer Truck 1',
- 'BT2': 'Beer Truck 2',
- 'Tasting Room': '50 Ubi Ave 3'
- }
-
- def refresh_location_mappings(self):
- """Refresh location mappings from database"""
- self._load_location_mappings()
-
- def test_connection(self):
- if not self.base_url or not self.access_token:
- return False, "Missing Shopify access token"
- try:
- response = requests.get(f"{self.base_url}/admin/api/{self.api_version}/shop.json",
- headers=self.headers, timeout=10)
- if response.status_code == 200:
- shop_data = response.json()
- shop_name = shop_data.get('shop', {}).get('name', 'Unknown')
- return True, f"Connected to: {shop_name}"
- else:
- return False, f"API Error: {response.status_code} - {response.text}"
- except requests.exceptions.RequestException as e:
- return False, f"Connection Error: {str(e)}"
-
- def get_orders_for_keg_yield(self, beer_code, location, tap_in_date, tap_in_time,
- tap_out_date=None, tap_out_time=None, debug_mode=False):
- if not self.base_url or not self.access_token:
- return None, "API not configured"
-
- try:
- self._load_location_mappings()
-
- tap_in_sg = create_singapore_datetime(parse_event_date(tap_in_date), tap_in_time)
- if tap_out_date and tap_out_time:
- tap_out_sg = create_singapore_datetime(parse_event_date(tap_out_date), tap_out_time)
- else:
- tap_out_sg = get_singapore_now()
-
- target_pos_location = self._get_pos_location_for_inventory_location(location)
- target_location_id = self._get_location_id_for_pos_location(target_pos_location)
-
- if debug_mode:
- print(f"Target location: {target_pos_location} (ID: {target_location_id})")
-
- start_date = tap_in_sg.date()
- end_date = tap_out_sg.date()
-
- all_daily_line_items = []
- daily_summaries = []
-
- current_date = start_date
- while current_date <= end_date:
- if current_date == start_date and current_date == end_date:
- daily_start_sg = tap_in_sg
- daily_end_sg = tap_out_sg
- period_type = "Same Day"
- elif current_date == start_date:
- daily_start_sg = tap_in_sg
- daily_end_sg = create_singapore_datetime(current_date, "23:59:59")
- period_type = "First Day"
- elif current_date == end_date:
- daily_start_sg = create_singapore_datetime(current_date, "00:00")
- daily_end_sg = tap_out_sg
- period_type = "Last Day"
- else:
- daily_start_sg = create_singapore_datetime(current_date, "00:00")
- daily_end_sg = create_singapore_datetime(current_date, "23:59:59")
- period_type = "Full Day"
-
- daily_start_utc = daily_start_sg.astimezone(pytz.UTC)
- daily_end_utc = daily_end_sg.astimezone(pytz.UTC)
-
- daily_orders = self._fetch_orders_from_api(daily_start_utc, daily_end_utc)
-
- if not daily_orders:
- daily_summaries.append({
- 'date': current_date.strftime('%Y-%m-%d'),
- 'period_type': period_type,
- 'start_time': daily_start_sg.strftime('%H:%M:%S'),
- 'end_time': daily_end_sg.strftime('%H:%M:%S'),
- 'orders_count': 0, 'items_count': 0, 'volume': 0.0
- })
- current_date += timedelta(days=1)
- continue
-
- orders_with_location = self._apply_location_id_fallback(daily_orders)
- filtered_by_time = self._filter_orders_by_time_range(orders_with_location, daily_start_utc, daily_end_utc)
- location_filtered_orders = self._filter_orders_by_location_id(filtered_by_time, target_location_id)
- daily_beer_line_items = self._extract_matching_line_items(location_filtered_orders, beer_code, target_pos_location)
-
- daily_items = len(daily_beer_line_items)
- daily_volume = sum(self._calculate_item_volume(item) for item in daily_beer_line_items)
-
- daily_summaries.append({
- 'date': current_date.strftime('%Y-%m-%d'),
- 'period_type': period_type,
- 'start_time': daily_start_sg.strftime('%H:%M:%S'),
- 'end_time': daily_end_sg.strftime('%H:%M:%S'),
- 'orders_count': len(location_filtered_orders),
- 'items_count': daily_items,
- 'volume': daily_volume
- })
-
- for item in daily_beer_line_items:
- item['calculation_date'] = current_date.strftime('%Y-%m-%d')
- item['period_type'] = period_type
- all_daily_line_items.extend(daily_beer_line_items)
-
- current_date += timedelta(days=1)
-
- if not all_daily_line_items:
- return pd.DataFrame(), f"No matching products found for {beer_code} at {location} across {len(daily_summaries)} days"
-
- combined_df = pd.DataFrame(all_daily_line_items)
- combined_df['calculation_method'] = 'daily_breakdown'
- combined_df['daily_summaries'] = str(daily_summaries)
-
- return combined_df, None
-
- except requests.exceptions.RequestException as e:
- return None, f"Request Error: {str(e)}"
- except Exception as e:
- return None, f"Unexpected Error: {str(e)}"
-
- def get_orders_for_location_analysis(self, beer_code, location, tap_in_date, tap_in_time,
- tap_out_date=None, tap_out_time=None, debug_mode=False):
- """
- New method for location-based analysis without keg dependency
- Returns sales data for a beer code at a location during a time period
- """
- if not self.base_url or not self.access_token:
- return None, "API not configured"
-
- try:
- self._load_location_mappings()
-
- tap_in_sg = create_singapore_datetime(parse_event_date(tap_in_date), tap_in_time)
- if tap_out_date and tap_out_time:
- tap_out_sg = create_singapore_datetime(parse_event_date(tap_out_date), tap_out_time)
- else:
- tap_out_sg = get_singapore_now()
-
- target_pos_location = self._get_pos_location_for_inventory_location(location)
- target_location_id = self._get_location_id_for_pos_location(target_pos_location)
-
- if debug_mode:
- print(f"Analyzing sales for {beer_code} at {target_pos_location} (ID: {target_location_id})")
-
- start_date = tap_in_sg.date()
- end_date = tap_out_sg.date()
-
- all_daily_line_items = []
- daily_summaries = []
-
- current_date = start_date
- while current_date <= end_date:
- if current_date == start_date and current_date == end_date:
- daily_start_sg = tap_in_sg
- daily_end_sg = tap_out_sg
- period_type = "Same Day"
- elif current_date == start_date:
- daily_start_sg = tap_in_sg
- daily_end_sg = create_singapore_datetime(current_date, "23:59:59")
- period_type = "First Day"
- elif current_date == end_date:
- daily_start_sg = create_singapore_datetime(current_date, "00:00")
- daily_end_sg = tap_out_sg
- period_type = "Last Day"
- else:
- daily_start_sg = create_singapore_datetime(current_date, "00:00")
- daily_end_sg = create_singapore_datetime(current_date, "23:59:59")
- period_type = "Full Day"
-
- daily_start_utc = daily_start_sg.astimezone(pytz.UTC)
- daily_end_utc = daily_end_sg.astimezone(pytz.UTC)
-
- daily_orders = self._fetch_orders_from_api(daily_start_utc, daily_end_utc)
-
- if not daily_orders:
- daily_summaries.append({
- 'date': current_date.strftime('%Y-%m-%d'),
- 'period_type': period_type,
- 'start_time': daily_start_sg.strftime('%H:%M:%S'),
- 'end_time': daily_end_sg.strftime('%H:%M:%S'),
- 'orders_count': 0, 'items_count': 0, 'volume': 0.0
- })
- current_date += timedelta(days=1)
- continue
-
- orders_with_location = self._apply_location_id_fallback(daily_orders)
- filtered_by_time = self._filter_orders_by_time_range(orders_with_location, daily_start_utc, daily_end_utc)
- location_filtered_orders = self._filter_orders_by_location_id(filtered_by_time, target_location_id)
- daily_beer_line_items = self._extract_matching_line_items(location_filtered_orders, beer_code, target_pos_location)
-
- daily_items = len(daily_beer_line_items)
- daily_volume = sum(self._calculate_item_volume(item) for item in daily_beer_line_items)
-
- daily_summaries.append({
- 'date': current_date.strftime('%Y-%m-%d'),
- 'period_type': period_type,
- 'start_time': daily_start_sg.strftime('%H:%M:%S'),
- 'end_time': daily_end_sg.strftime('%H:%M:%S'),
- 'orders_count': len(location_filtered_orders),
- 'items_count': daily_items,
- 'volume': daily_volume
- })
-
- for item in daily_beer_line_items:
- item['calculation_date'] = current_date.strftime('%Y-%m-%d')
- item['period_type'] = period_type
- all_daily_line_items.extend(daily_beer_line_items)
-
- current_date += timedelta(days=1)
-
- return all_daily_line_items, daily_summaries, None
-
- except requests.exceptions.RequestException as e:
- return None, None, f"Request Error: {str(e)}"
- except Exception as e:
- return None, None, f"Unexpected Error: {str(e)}"
-
- def _calculate_item_volume(self, item):
- try:
- quantity = int(item.get('net_quantity', 0))
- if quantity <= 0:
- return 0.0
- product_title = str(item.get('full_product_title', '')).lower()
- volume_per_item = self._extract_volume_from_product_title(product_title)
- return quantity * volume_per_item
- except:
- return 0.0
-
- def _get_pos_location_for_inventory_location(self, inventory_location):
- self._load_location_mappings()
- return self.inventory_to_pos_mapping.get(inventory_location, inventory_location)
-
- def _get_location_id_for_pos_location(self, pos_location):
- for location_id, mapped_location in self.location_id_mapping.items():
- if mapped_location.lower() == pos_location.lower():
- return location_id
- return None
-
- def _fetch_orders_from_api(self, start_utc, end_utc):
- def _fetch_with_params(params, method_name):
- all_orders = []
- since_id = None
- page_count = 0
- max_pages = 100
-
- while page_count < max_pages:
- current_params = params.copy()
- if since_id:
- current_params['since_id'] = since_id
-
- try:
- response = requests.get(
- f"{self.base_url}/admin/api/{self.api_version}/orders.json",
- headers=self.headers, params=current_params, timeout=60
- )
-
- if response.status_code == 429:
- retry_after = response.headers.get('Retry-After', '2')
- import time
- time.sleep(int(retry_after))
- continue
- elif response.status_code == 422:
- break
- elif response.status_code != 200:
- break
-
- data = response.json()
- orders = data.get('orders', [])
- all_orders.extend(orders)
- page_count += 1
-
- if len(orders) < 250:
- break
-
- since_id = orders[-1]['id']
-
- except requests.exceptions.Timeout:
- break
- except requests.exceptions.RequestException as e:
- break
-
- return all_orders
-
- processed_at_min = start_utc.strftime('%Y-%m-%dT%H:%M:%S+00:00')
- processed_at_max = end_utc.strftime('%Y-%m-%dT%H:%M:%S+00:00')
-
- params_processed = {
- 'limit': 250, 'status': 'any',
- 'processed_at_min': processed_at_min, 'processed_at_max': processed_at_max,
- 'fields': 'id,created_at,processed_at,line_items,source_name,location_id,name,financial_status,fulfillment_status'
- }
-
- created_at_min = start_utc.strftime('%Y-%m-%dT%H:%M:%S+00:00')
- created_at_max = end_utc.strftime('%Y-%m-%dT%H:%M:%S+00:00')
-
- params_created = {
- 'limit': 250, 'status': 'any',
- 'created_at_min': created_at_min, 'created_at_max': created_at_max,
- 'fields': 'id,created_at,processed_at,line_items,source_name,location_id,name,financial_status,fulfillment_status'
- }
-
- orders_by_processed = _fetch_with_params(params_processed, "processed_at")
- orders_by_created = _fetch_with_params(params_created, "created_at")
-
- all_orders = {}
- for order in orders_by_processed:
- all_orders[order['id']] = order
- for order in orders_by_created:
- all_orders[order['id']] = order
-
- return list(all_orders.values())
-
- def _apply_location_id_fallback(self, orders):
- name_to_location_id = {}
- for order in orders:
- location_id = order.get('location_id')
- name = order.get('name', '').strip()
- if location_id and name:
- if name not in name_to_location_id:
- name_to_location_id[name] = location_id
-
- for order in orders:
- if not order.get('location_id'):
- name = order.get('name', '').strip()
- if name and name in name_to_location_id:
- order['location_id'] = name_to_location_id[name]
- return orders
-
- def _filter_orders_by_time_range(self, orders, start_utc, end_utc):
- filtered_orders = []
- for order in orders:
- order_timestamp_str = order.get('processed_at') or order.get('created_at')
- if not order_timestamp_str:
- continue
- try:
- order_timestamp_utc = datetime.fromisoformat(order_timestamp_str.replace('Z', '+00:00'))
- if start_utc <= order_timestamp_utc <= end_utc:
- filtered_orders.append(order)
- except:
- continue
- return filtered_orders
-
- def _filter_orders_by_location_id(self, orders, target_location_id):
- if not target_location_id:
- return []
- filtered_orders = []
- for order in orders:
- source = (order.get('source_name') or '').lower()
- if not ('pos' in source or 'point' in source):
- continue
- financial_status = (order.get('financial_status') or '').lower()
- if financial_status not in ['paid', 'authorized', 'partially_paid']:
- continue
- order_location_id = str(order.get('location_id', ''))
- if order_location_id == target_location_id:
- filtered_orders.append(order)
- return filtered_orders
-
- def _extract_matching_line_items(self, orders, beer_code, target_pos_location):
- matching_line_items = []
- beer_keywords = self._get_beer_keywords_from_db(beer_code)
- exclude_keywords = self._get_exclude_keywords_from_db()
-
- seen_orders = set()
- unique_orders = []
- for order in orders:
- order_id = order.get('id')
- if order_id not in seen_orders:
- seen_orders.add(order_id)
- unique_orders.append(order)
-
- for order in unique_orders:
- line_items = order.get('line_items', [])
- order_date = order.get('processed_at') or order.get('created_at')
- order_id = order.get('id')
- order_location_id = order.get('location_id')
- order_location_name = self.location_id_mapping.get(str(order_location_id), 'Unknown')
-
- for item in line_items:
- product_title = (item.get('title') or '').lower()
- variant_title = (item.get('variant_title') or '').lower()
- net_quantity = item.get('quantity', 0)
- full_product_title = f"{product_title} {variant_title}".strip()
-
- if self._matches_beer_product(full_product_title, beer_keywords, exclude_keywords):
- if order_location_name.lower() == target_pos_location.lower():
- matching_line_items.append({
- 'order_id': order_id, 'created_at': order_date,
- 'product_title': item.get('title') or '',
- 'net_quantity': net_quantity, 'variant_title': variant_title,
- 'sku': item.get('sku') or '', 'vendor': item.get('vendor') or '',
- 'full_product_title': full_product_title,
- 'pos_location_name': order_location_name,
- 'location_id': order_location_id
- })
- return matching_line_items
-
- def _get_beer_keywords_from_db(self, beer_code):
- if not self.db_conn:
- default_keywords = {
- 'LOM': ['lean on me'], 'DSB': ['believing'], 'HY': ['hundred years'],
- 'WAT': ['watermelon'], 'DIA': ['diana'], 'NSG': ['never say goodbye']
- }
- return default_keywords.get(beer_code.upper(), [beer_code.lower()])
- try:
- cursor = self.db_conn.cursor()
- cursor.execute('SELECT keyword FROM beer_keywords WHERE beer_code = ? AND is_active = TRUE', (beer_code.upper(),))
- keywords = [row[0].lower() for row in cursor.fetchall()]
- return keywords if keywords else [beer_code.lower()]
- except Exception:
- return [beer_code.lower()]
-
- def _get_exclude_keywords_from_db(self):
- if not self.db_conn:
- return ['6 pack', 'minikeg']
- try:
- cursor = self.db_conn.cursor()
- cursor.execute('SELECT keyword FROM exclude_keywords WHERE is_active = TRUE')
- return [row[0].lower() for row in cursor.fetchall()]
- except Exception:
- return ['6 pack', 'minikeg']
-
- def _matches_beer_product(self, product_title, beer_keywords, exclude_keywords):
- for exclude_keyword in exclude_keywords:
- if exclude_keyword.lower() in product_title.lower():
- return False
- for keyword in beer_keywords:
- if keyword.lower() in product_title.lower():
- return True
- return False
-
- def _extract_volume_from_product_title(self, product_title):
- ml_match = re.search(r'(\d+(?:\.\d+)?)\s*ml', product_title)
- if ml_match:
- ml_value = float(ml_match.group(1))
- return ml_value / 1000
- oz_match = re.search(r'(\d+(?:\.\d+)?)\s*oz', product_title)
- if oz_match:
- oz_value = float(oz_match.group(1))
- ml_value = oz_value * 29.5735
- return ml_value / 1000
- if 'pint' in product_title:
- if 'half' in product_title:
- return 0.237
- else:
- return 0.473
- return 0.473
-
-class BreweryKegInventorySystem:
- def __init__(self, db_name=None):
- self.db_name = db_name or 'brewery_keg_system.db'
- self.conn = sqlite3.connect(self.db_name, check_same_thread=False)
- self.create_tables()
- self.shopify_client = None
-
- def set_shopify_access_token(self, access_token):
- if access_token:
- self.shopify_client = ShopifyOrdersAPIClient(access_token=access_token, db_conn=self.conn)
- return "Shopify client initialized successfully"
- else:
- return "Access token is required"
-
- def create_tables(self):
- cursor = self.conn.cursor()
-
- # Core tables
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS keg_form_state (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- keg_id TEXT NOT NULL,
- location TEXT NOT NULL,
- tap_in_date TEXT,
- tap_in_time TEXT,
- tap_out_date TEXT,
- tap_out_time TEXT,
- last_updated DATETIME DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(keg_id, location)
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS api_tokens (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- service_name TEXT UNIQUE NOT NULL,
- token_value TEXT NOT NULL,
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS event_dates (
- event_id INTEGER PRIMARY KEY AUTOINCREMENT,
- event_date DATE NOT NULL,
- event_time TIME DEFAULT '00:00:00',
- event_datetime_utc DATETIME NOT NULL,
- event_datetime_singapore TEXT NOT NULL,
- created_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(event_date, event_time)
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS beer_codes (
- beer_code TEXT PRIMARY KEY,
- description TEXT,
- is_active BOOLEAN DEFAULT TRUE,
- created_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS locations (
- location_id INTEGER PRIMARY KEY AUTOINCREMENT,
- location_name TEXT UNIQUE NOT NULL,
- is_active BOOLEAN DEFAULT TRUE,
- created_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS users (
- user_id INTEGER PRIMARY KEY AUTOINCREMENT,
- username TEXT UNIQUE NOT NULL,
- role TEXT DEFAULT 'user',
- is_active BOOLEAN DEFAULT TRUE,
- created_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS user_preferences (
- user_id TEXT PRIMARY KEY,
- default_tap_in_time TEXT DEFAULT '10:00',
- default_tap_out_time TEXT DEFAULT '22:00',
- preferred_date_format TEXT DEFAULT 'YYYY-MM-DD',
- auto_refresh_interval INTEGER DEFAULT 300,
- created_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP,
- updated_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS transaction_types (
- transaction_type_id INTEGER PRIMARY KEY AUTOINCREMENT,
- transaction_type_code TEXT UNIQUE NOT NULL,
- transaction_type_name TEXT NOT NULL,
- is_active BOOLEAN DEFAULT TRUE
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS kegs (
- keg_id TEXT PRIMARY KEY,
- beer_code TEXT NOT NULL,
- tank TEXT,
- keg_size_value REAL NOT NULL,
- keg_size_unit TEXT DEFAULT 'L',
- keg_number TEXT,
- production_event_id INTEGER,
- created_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP,
- created_by_user_id INTEGER,
- FOREIGN KEY (beer_code) REFERENCES beer_codes (beer_code),
- FOREIGN KEY (production_event_id) REFERENCES event_dates (event_id),
- FOREIGN KEY (created_by_user_id) REFERENCES users (user_id)
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS keg_transactions (
- transaction_id INTEGER PRIMARY KEY AUTOINCREMENT,
- keg_id TEXT NOT NULL,
- transaction_type_id INTEGER NOT NULL,
- event_id INTEGER NOT NULL,
- location_id INTEGER,
- status_after TEXT NOT NULL,
- previous_status TEXT,
- quantity_sold REAL,
- quantity_unit TEXT,
- remaining_volume REAL,
- days_outstanding REAL,
- performed_by_user_id INTEGER,
- notes TEXT,
- metadata_json TEXT,
- created_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (keg_id) REFERENCES kegs (keg_id),
- FOREIGN KEY (transaction_type_id) REFERENCES transaction_types (transaction_type_id),
- FOREIGN KEY (event_id) REFERENCES event_dates (event_id),
- FOREIGN KEY (location_id) REFERENCES locations (location_id),
- FOREIGN KEY (performed_by_user_id) REFERENCES users (user_id)
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS keg_yield (
- yield_id INTEGER PRIMARY KEY AUTOINCREMENT,
- keg_id TEXT NOT NULL,
- tap_in_event_id INTEGER NOT NULL,
- tap_out_event_id INTEGER,
- location_id INTEGER,
- keg_volume REAL,
- shopify_query TEXT,
- total_sales_volume REAL,
- keg_yield_percentage REAL,
- total_items_sold INTEGER DEFAULT 0,
- data_source TEXT,
- api_error TEXT,
- tap_period_sequence INTEGER DEFAULT 1,
- calculation_method TEXT DEFAULT 'single_call',
- daily_breakdown_json TEXT,
- created_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (keg_id) REFERENCES kegs (keg_id),
- FOREIGN KEY (tap_in_event_id) REFERENCES event_dates (event_id),
- FOREIGN KEY (tap_out_event_id) REFERENCES event_dates (event_id),
- FOREIGN KEY (location_id) REFERENCES locations (location_id)
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS location_sales_analysis (
- analysis_id INTEGER PRIMARY KEY AUTOINCREMENT,
- beer_code TEXT NOT NULL,
- location_id INTEGER NOT NULL,
- tap_in_event_id INTEGER NOT NULL,
- tap_out_event_id INTEGER,
- total_sales_volume REAL,
- total_items_sold INTEGER DEFAULT 0,
- data_source TEXT,
- api_error TEXT,
- calculation_method TEXT DEFAULT 'location_analysis',
- daily_breakdown_json TEXT,
- created_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (beer_code) REFERENCES beer_codes (beer_code),
- FOREIGN KEY (location_id) REFERENCES locations (location_id),
- FOREIGN KEY (tap_in_event_id) REFERENCES event_dates (event_id),
- FOREIGN KEY (tap_out_event_id) REFERENCES event_dates (event_id)
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS beer_keywords (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- beer_code TEXT NOT NULL,
- keyword TEXT NOT NULL,
- is_active BOOLEAN DEFAULT TRUE,
- created_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP,
- created_by_user_id INTEGER,
- FOREIGN KEY (beer_code) REFERENCES beer_codes (beer_code),
- FOREIGN KEY (created_by_user_id) REFERENCES users (user_id),
- UNIQUE(beer_code, keyword)
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS location_mapping (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- location_id INTEGER NOT NULL,
- pos_location_name TEXT NOT NULL,
- shopify_location_id TEXT,
- is_active BOOLEAN DEFAULT TRUE,
- is_archived BOOLEAN DEFAULT FALSE,
- created_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP,
- updated_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP,
- created_by_user_id INTEGER,
- FOREIGN KEY (location_id) REFERENCES locations (location_id),
- FOREIGN KEY (created_by_user_id) REFERENCES users (user_id),
- UNIQUE(location_id, pos_location_name)
- )
- ''')
-
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS exclude_keywords (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- keyword TEXT UNIQUE NOT NULL,
- is_active BOOLEAN DEFAULT TRUE,
- created_at_utc DATETIME DEFAULT CURRENT_TIMESTAMP,
- created_by_user_id INTEGER,
- FOREIGN KEY (created_by_user_id) REFERENCES users (user_id)
- )
- ''')
-
- # Initialize transaction types
- transaction_types = [
- ('CREATE', 'Keg Creation'),
- ('DRAW_DOWN', 'Draw Down'),
- ('RETURN', 'Return Empty'),
- ('RETURN_PARTIAL', 'Return Partial'),
- ('INTERNAL_TRANSFER', 'Internal Transfer'),
- ('DELETE', 'Delete Keg')
- ]
-
- for code, name in transaction_types:
- cursor.execute('INSERT OR IGNORE INTO transaction_types (transaction_type_code, transaction_type_name) VALUES (?, ?)', (code, name))
-
- # Create indexes
- indexes = [
- 'CREATE INDEX IF NOT EXISTS idx_keg_transactions_keg_id ON keg_transactions(keg_id)',
- 'CREATE INDEX IF NOT EXISTS idx_keg_transactions_event_id ON keg_transactions(event_id)',
- 'CREATE INDEX IF NOT EXISTS idx_keg_yield_keg_id ON keg_yield(keg_id)',
- 'CREATE INDEX IF NOT EXISTS idx_beer_keywords_code ON beer_keywords(beer_code)',
- 'CREATE INDEX IF NOT EXISTS idx_location_mapping_location ON location_mapping(location_id)',
- 'CREATE INDEX IF NOT EXISTS idx_event_dates_date ON event_dates(event_date)',
- 'CREATE INDEX IF NOT EXISTS idx_location_sales_analysis ON location_sales_analysis(beer_code, location_id)'
- ]
-
- for index_sql in indexes:
- cursor.execute(index_sql)
-
- self._initialize_default_data()
- self.conn.commit()
-
- def _initialize_default_data(self):
- cursor = self.conn.cursor()
- cursor.execute('INSERT OR IGNORE INTO users (username, role) VALUES ("system", "admin")')
- cursor.execute('INSERT OR IGNORE INTO users (username, role) VALUES ("admin", "admin")')
- cursor.execute('INSERT OR IGNORE INTO users (username, role) VALUES ("web_user", "user")')
-
- cursor.execute('SELECT user_id FROM users WHERE username = "system"')
- system_user_result = cursor.fetchone()
- system_user_id = system_user_result[0] if system_user_result else None
-
- # Default beer codes
- default_beer_codes = [
- ('LOM', 'Lean On Me'), ('HY', 'Hundred Years'), ('DSB', 'Believing'),
- ('NSG', 'Never Say Goodbye'), ('WAT', 'Watermelon Wheat'), ('DIA', 'Diana')
- ]
- for code, desc in default_beer_codes:
- cursor.execute('INSERT OR IGNORE INTO beer_codes (beer_code, description) VALUES (?, ?)', (code, desc))
-
- # Default locations
- default_locations = [
- 'BT2', 'BT1', 'Tasting Room', 'LittlePartCafe', 'SGTaps',
- 'UpwardConsulting', 'Cold Room', 'Brewery'
- ]
- for location in default_locations:
- cursor.execute('INSERT OR IGNORE INTO locations (location_name) VALUES (?)', (location,))
-
- cursor.execute('INSERT OR IGNORE INTO user_preferences (user_id, default_tap_in_time, default_tap_out_time) VALUES ("web_user", "10:00", "22:00")')
-
- if system_user_id:
- # Beer keywords
- cursor.execute('DELETE FROM beer_keywords WHERE created_by_user_id = ?', (system_user_id,))
- default_beer_keywords = [
- ('LOM', 'lean on me'), ('DSB', 'believing'), ('HY', 'hundred years'),
- ('WAT', 'watermelon'), ('DIA', 'diana'), ('NSG', 'never say goodbye')
- ]
- for beer_code, keyword in default_beer_keywords:
- cursor.execute('INSERT INTO beer_keywords (beer_code, keyword, created_by_user_id) VALUES (?, ?, ?)', (beer_code, keyword, system_user_id))
-
- # Location mappings
- location_mappings_data = [
- ('BT1', 'Beer Truck 1', '67045785765'),
- ('BT2', 'Beer Truck 2', '67805577381'),
- ('Tasting Room', '50 Ubi Ave 3', '15546056802')
- ]
- for location_name, pos_name, shopify_id in location_mappings_data:
- cursor.execute('SELECT location_id FROM locations WHERE location_name = ?', (location_name,))
- location_result = cursor.fetchone()
- if location_result:
- location_id = location_result[0]
- cursor.execute('''
- INSERT OR REPLACE INTO location_mapping
- (location_id, pos_location_name, shopify_location_id, created_by_user_id)
- VALUES (?, ?, ?, ?)
- ''', (location_id, pos_name, shopify_id, system_user_id))
-
- # Exclude keywords
- cursor.execute('DELETE FROM exclude_keywords WHERE created_by_user_id = ?', (system_user_id,))
- default_exclude_keywords = ['6 pack', 'minikeg']
- for keyword in default_exclude_keywords:
- cursor.execute('INSERT INTO exclude_keywords (keyword, created_by_user_id) VALUES (?, ?)', (keyword, system_user_id))
-
- # Form persistence methods
- def save_keg_form_state(self, keg_id, location, tap_in_date, tap_in_time, tap_out_date, tap_out_time):
- try:
- cursor = self.conn.cursor()
- cursor.execute('''
- INSERT OR REPLACE INTO keg_form_state
- (keg_id, location, tap_in_date, tap_in_time, tap_out_date, tap_out_time, last_updated)
- VALUES (?, ?, ?, ?, ?, ?, ?)
- ''', (keg_id, location, tap_in_date, tap_in_time, tap_out_date, tap_out_time, get_utc_now()))
- self.conn.commit()
- return True
- except Exception as e:
- print(f"Error saving form state: {e}")
- return False
-
- def load_keg_form_state(self, keg_id, location):
- try:
- cursor = self.conn.cursor()
- cursor.execute('''
- SELECT tap_in_date, tap_in_time, tap_out_date, tap_out_time
- FROM keg_form_state
- WHERE keg_id = ? AND location = ?
- ''', (keg_id, location))
- result = cursor.fetchone()
- if result:
- return {
- 'tap_in_date': result[0], 'tap_in_time': result[1],
- 'tap_out_date': result[2], 'tap_out_time': result[3]
- }
- return None
- except Exception as e:
- print(f"Error loading form state: {e}")
- return None
-
- # API token methods
- def save_api_token(self, service_name, token):
- try:
- cursor = self.conn.cursor()
- cursor.execute('''
- INSERT OR REPLACE INTO api_tokens (service_name, token_value, updated_at)
- VALUES (?, ?, ?)
- ''', (service_name, token, get_utc_now()))
- self.conn.commit()
-
- if service_name == 'shopify':
- self.set_shopify_access_token(token)
-
- return True
- except Exception as e:
- print(f"Error saving token: {e}")
- return False
-
- def load_api_token(self, service_name):
- try:
- cursor = self.conn.cursor()
- cursor.execute('SELECT token_value FROM api_tokens WHERE service_name = ?', (service_name,))
- result = cursor.fetchone()
- return result[0] if result else None
- except Exception as e:
- print(f"Error loading token: {e}")
- return None
-
- def save_user_preferences(self, user_id, tap_in_time=None, tap_out_time=None):
- try:
- cursor = self.conn.cursor()
- current_prefs = self.load_user_preferences(user_id)
- final_tap_in = tap_in_time or current_prefs['tap_in_time']
- final_tap_out = tap_out_time or current_prefs['tap_out_time']
- cursor.execute('''
- INSERT OR REPLACE INTO user_preferences
- (user_id, default_tap_in_time, default_tap_out_time, updated_at_utc)
- VALUES (?, ?, ?, ?)
- ''', (user_id, final_tap_in, final_tap_out, get_utc_now()))
- self.conn.commit()
- return True
- except Exception as e:
- print(f"Error saving preferences: {e}")
- return False
-
- def load_user_preferences(self, user_id):
- try:
- cursor = self.conn.cursor()
- cursor.execute('SELECT default_tap_in_time, default_tap_out_time FROM user_preferences WHERE user_id = ?', (user_id,))
- result = cursor.fetchone()
- if result:
- return {'tap_in_time': result[0], 'tap_out_time': result[1]}
- else:
- self.save_user_preferences(user_id, '10:00', '22:00')
- return {'tap_in_time': '10:00', 'tap_out_time': '22:00'}
- except Exception as e:
- print(f"Error loading preferences: {e}")
- return {'tap_in_time': '10:00', 'tap_out_time': '22:00'}
-
- def create_event_date(self, event_date: date, event_time: str = "00:00") -> int:
- cursor = self.conn.cursor()
- sg_datetime = create_singapore_datetime(event_date, event_time)
- utc_datetime = sg_datetime.astimezone(UTC_TZ)
- sg_datetime_str = format_singapore_time(sg_datetime)
-
- cursor.execute('SELECT event_id FROM event_dates WHERE event_date = ? AND event_time = ?', (event_date.isoformat(), event_time))
- existing = cursor.fetchone()
- if existing:
- return existing[0]
-
- cursor.execute('''
- INSERT INTO event_dates (event_date, event_time, event_datetime_utc, event_datetime_singapore)
- VALUES (?, ?, ?, ?)
- ''', (event_date.isoformat(), event_time, utc_datetime, sg_datetime_str))
- self.conn.commit()
- return cursor.lastrowid
-
- def get_location_id(self, location_name: str) -> int:
- if not location_name:
- return None
- cursor = self.conn.cursor()
- cursor.execute('SELECT location_id FROM locations WHERE location_name = ?', (location_name,))
- result = cursor.fetchone()
- return result[0] if result else None
-
- def get_user_id(self, username: str) -> int:
- if not username:
- return None
- cursor = self.conn.cursor()
- cursor.execute('SELECT user_id FROM users WHERE username = ?', (username,))
- result = cursor.fetchone()
- return result[0] if result else None
-
- def get_transaction_type_id(self, transaction_type_code: str) -> int:
- cursor = self.conn.cursor()
- cursor.execute('SELECT transaction_type_id FROM transaction_types WHERE transaction_type_code = ?', (transaction_type_code,))
- result = cursor.fetchone()
- return result[0] if result else None
-
- def get_beer_codes(self):
- cursor = self.conn.cursor()
- cursor.execute('SELECT beer_code FROM beer_codes WHERE is_active = TRUE ORDER BY beer_code')
- return [row[0] for row in cursor.fetchall()]
-
- def add_beer_code(self, code, description=''):
- try:
- cursor = self.conn.cursor()
- cursor.execute('INSERT OR IGNORE INTO beer_codes (beer_code, description) VALUES (?, ?)', (code.upper(), description))
- self.conn.commit()
- return f"Beer code '{code}' added successfully!"
- except Exception as e:
- return f"Error: {str(e)}"
-
- def get_locations(self):
- cursor = self.conn.cursor()
- cursor.execute('SELECT location_name FROM locations WHERE is_active = TRUE ORDER BY location_name')
- return [row[0] for row in cursor.fetchall()]
-
- def get_locations_excluding_brewery(self):
- cursor = self.conn.cursor()
- cursor.execute('SELECT location_name FROM locations WHERE is_active = TRUE AND location_name != "Brewery" ORDER BY location_name')
- return [row[0] for row in cursor.fetchall()]
-
- def get_retail_wholesale_locations(self):
- cursor = self.conn.cursor()
- cursor.execute('SELECT location_name FROM locations WHERE is_active = TRUE AND location_name NOT IN ("Brewery", "Cold Room") ORDER BY location_name')
- return [row[0] for row in cursor.fetchall()]
-
- def get_locations_with_shopify_mapping(self):
- try:
- cursor = self.conn.cursor()
- cursor.execute('''
- SELECT DISTINCT l.location_name
- FROM locations l
- JOIN location_mapping lm ON l.location_id = lm.location_id
- WHERE l.is_active = TRUE
- AND lm.is_active = TRUE
- AND lm.is_archived = FALSE
- AND lm.shopify_location_id IS NOT NULL
- AND lm.shopify_location_id != ''
- ORDER BY l.location_name
- ''')
- return [row[0] for row in cursor.fetchall()]
- except Exception as e:
- print(f"Error getting locations with Shopify mapping: {e}")
- return []
-
- def get_locations_by_category(self):
- """Get locations categorized by primary and others"""
- try:
- all_shopify_locations = self.get_locations_with_shopify_mapping()
- primary_locations = [loc for loc in all_shopify_locations if loc in PRIMARY_LOCATIONS]
- other_locations = [loc for loc in all_shopify_locations if loc not in PRIMARY_LOCATIONS]
-
- return {
- 'primary': primary_locations,
- 'others': other_locations,
- 'all_with_shopify': all_shopify_locations
- }
- except Exception as e:
- print(f"Error categorizing locations: {e}")
- return {'primary': [], 'others': [], 'all_with_shopify': []}
-
- def add_location(self, location_name):
- try:
- cursor = self.conn.cursor()
- cursor.execute('INSERT OR IGNORE INTO locations (location_name) VALUES (?)', (location_name,))
- self.conn.commit()
- return f"Location '{location_name}' added successfully!"
- except Exception as e:
- return f"Error: {str(e)}"
-
- def generate_keg_id(self, beer_code, keg_size_value, event_date=None, keg_number=None):
- if event_date:
- date_str = event_date.strftime('%Y%m%d') if isinstance(event_date, date) else event_date
- else:
- date_str = get_singapore_now().strftime('%Y%m%d')
-
- if keg_number is not None:
- return f'{date_str}{beer_code}{keg_size_value:g}L{keg_number:03d}'
- else:
- cursor = self.conn.cursor()
- cursor.execute('SELECT COUNT(*) FROM kegs WHERE keg_id LIKE ?', (f'{date_str}{beer_code}{keg_size_value}%',))
- sequence = cursor.fetchone()[0] + 1
- return f'{date_str}{beer_code}{keg_size_value:g}L{sequence:03d}'
-
- def parse_keg_range(self, keg_range_str):
- try:
- if '-' in keg_range_str:
- start, end = keg_range_str.split('-')
- start_num = int(start.strip())
- end_num = int(end.strip())
- return list(range(start_num, end_num + 1))
- else:
- return [int(keg_range_str.strip())]
- except:
- return []
-
- def create_transaction(self, keg_id: str, transaction_type_code: str, status_after: str,
- event_date: date, event_time: str = "00:00", previous_status: str = None,
- location_name: str = None, quantity_sold: float = None, quantity_unit: str = None,
- remaining_volume: float = None, username: str = None, metadata: dict = None, notes: str = None):
- event_id = self.create_event_date(event_date, event_time)
- transaction_type_id = self.get_transaction_type_id(transaction_type_code)
- location_id = self.get_location_id(location_name) if location_name else None
- user_id = self.get_user_id(username) if username else self.get_user_id('system')
-
- days_outstanding = None
- if metadata and 'days_outstanding' in metadata:
- days_outstanding = metadata['days_outstanding']
-
- cursor = self.conn.cursor()
- cursor.execute('''
- INSERT INTO keg_transactions
- (keg_id, transaction_type_id, event_id, location_id, status_after,
- previous_status, quantity_sold, quantity_unit, remaining_volume,
- days_outstanding, performed_by_user_id, notes, metadata_json)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ''', (keg_id, transaction_type_id, event_id, location_id, status_after,
- previous_status, quantity_sold, quantity_unit, remaining_volume,
- days_outstanding, user_id, notes, json.dumps(metadata) if metadata else None))
- self.conn.commit()
- return cursor.lastrowid
-
- def calculate_remaining_volume(self, keg_size_value, quantity_sold, quantity_unit):
- if not quantity_sold:
- return keg_size_value
- conversions = {'pint': 0.473, 'half_pint': 0.237, '330ml': 0.33}
- litres_sold = quantity_sold * conversions.get(quantity_unit, 0)
- remaining = keg_size_value - litres_sold
- return max(0, remaining)
-
- def add_keg(self, beer_code, tank, keg_size_value, keg_number, event_date, performed_by='user'):
- try:
- keg_id = self.generate_keg_id(beer_code, keg_size_value, event_date, keg_number)
- production_event_id = self.create_event_date(event_date)
- user_id = self.get_user_id(performed_by) or self.get_user_id('system')
-
- cursor = self.conn.cursor()
- cursor.execute('''
- INSERT INTO kegs (keg_id, beer_code, tank, keg_size_value,
- keg_number, production_event_id, created_by_user_id)
- VALUES (?, ?, ?, ?, ?, ?, ?)
- ''', (keg_id, beer_code, tank, keg_size_value, str(keg_number), production_event_id, user_id))
-
- metadata = {'initial_creation': True, 'production_date': event_date.isoformat()}
- self.create_transaction(
- keg_id=keg_id, transaction_type_code='CREATE', status_after='In Storage',
- event_date=event_date, previous_status=None, location_name='Cold Room',
- remaining_volume=keg_size_value, username=performed_by, metadata=metadata,
- notes=f'Keg created: {beer_code} {keg_size_value}L from tank {tank}'
- )
- return f"Success! Keg added with ID: {keg_id}"
- except sqlite3.IntegrityError as e:
- return f"Error: {str(e)}"
- except Exception as e:
- return f"Error: {str(e)}"
-
- def bulk_add_kegs(self, keg_batches, event_date, performed_by='user'):
- results = []
- success_count = 0
- error_count = 0
- keg_ids = []
-
- try:
- kegs_to_add = []
- for batch in keg_batches:
- beer_code = batch['beer_code']
- tank = batch['tank']
- keg_size_value = batch['keg_size_value']
- keg_range = batch['keg_range']
-
- keg_numbers = self.parse_keg_range(keg_range)
- if not keg_numbers:
- results.append(f"Invalid keg range: {keg_range}")
- error_count += 1
- continue
-
- for keg_number in keg_numbers:
- keg_id = self.generate_keg_id(beer_code, keg_size_value, event_date, keg_number)
- cursor = self.conn.cursor()
- cursor.execute('SELECT COUNT(*) FROM kegs WHERE keg_id = ?', (keg_id,))
- if cursor.fetchone()[0] > 0:
- results.append(f"{beer_code} keg {keg_number:02d}: Duplicate ID detected")
- error_count += 1
- continue
-
- kegs_to_add.append({
- 'keg_id': keg_id, 'beer_code': beer_code, 'tank': tank,
- 'keg_size_value': keg_size_value, 'keg_number': keg_number, 'event_date': event_date
- })
-
- for keg_data in kegs_to_add:
- try:
- result = self.add_keg(
- beer_code=keg_data['beer_code'], tank=keg_data['tank'],
- keg_size_value=keg_data['keg_size_value'], keg_number=keg_data['keg_number'],
- event_date=event_date, performed_by=performed_by
- )
- if "Success!" in result:
- success_count += 1
- keg_ids.append(keg_data['keg_id'])
- else:
- results.append(f"{keg_data['beer_code']} keg {keg_data['keg_number']:02d}: {result}")
- error_count += 1
- except Exception as e:
- results.append(f"Error adding {keg_data['beer_code']} keg {keg_data['keg_number']:02d}: {str(e)}")
- error_count += 1
-
- sg_time = format_singapore_time(get_singapore_now())
- summary = f"Bulk Add Complete! ({sg_time})\n"
- summary += f"Production Date: {event_date.strftime('%Y-%m-%d')}\n\n"
- summary += f"Successfully added: {success_count} kegs\nErrors: {error_count}\n\n"
-
- if keg_ids:
- summary += f"Generated Keg IDs ({len(keg_ids)}):\n"
- ids_by_beer = {}
- for keg_id in keg_ids:
- beer_part = keg_id[8:]
- beer_key = beer_part.split('L')[0]
- if beer_key not in ids_by_beer:
- ids_by_beer[beer_key] = []
- ids_by_beer[beer_key].append(keg_id)
-
- for beer_key, ids in ids_by_beer.items():
- summary += f" • {beer_key}: {', '.join(ids)}\n"
-
- if results:
- summary += f"\nIssues:\n"
- for result in results[:10]:
- summary += f" • {result}\n"
- if len(results) > 10:
- summary += f" • ... and {len(results) - 10} more issues\n"
-
- return summary
- except Exception as e:
- return f"Bulk add failed: {str(e)}"
-
- def bulk_delete_kegs(self, keg_ids_list, performed_by='user'):
- try:
- success_count = 0
- error_count = 0
- results = []
- current_date = get_singapore_now().date()
-
- for keg_id in keg_ids_list:
- try:
- current_status_df = self.get_current_keg_status(keg_id.strip())
- if current_status_df.empty:
- results.append(f"Keg {keg_id} not found")
- error_count += 1
- continue
-
- current_status = current_status_df.iloc[0]['status']
- self.create_transaction(
- keg_id=keg_id.strip(), transaction_type_code='DELETE', status_after='Deleted',
- event_date=current_date, previous_status=current_status,
- username=performed_by, notes=f'Keg bulk deleted by {performed_by}'
- )
- success_count += 1
- except Exception as e:
- results.append(f"Error deleting {keg_id}: {str(e)}")
- error_count += 1
-
- sg_time = format_singapore_time(get_singapore_now())
- summary = f"Bulk Delete Complete! ({sg_time})\n\n"
- summary += f"Successfully deleted: {success_count} kegs\nErrors: {error_count}\n\n"
-
- if results:
- summary += f"Issues:\n"
- for result in results[:10]:
- summary += f" • {result}\n"
- return summary
- except Exception as e:
- return f"Bulk delete failed: {str(e)}"
-
- def get_current_keg_status(self, keg_id: str = None):
- if keg_id:
- query = '''
- WITH latest_transactions AS (
- SELECT kt.keg_id, MAX(kt.created_at_utc) as latest_timestamp
- FROM keg_transactions kt WHERE kt.keg_id = ? GROUP BY kt.keg_id
- )
- SELECT k.keg_id, k.beer_code, k.tank, k.keg_size_value, k.keg_size_unit, k.keg_number,
- ed_prod.event_date as production_date, ed_trans.event_datetime_singapore as singapore_timestamp,
- kt.created_at_utc as action_timestamp, COALESCE(l.location_name, 'Cold Room') as location,
- kt.status_after as status, kt.quantity_sold, kt.quantity_unit,
- COALESCE(kt.remaining_volume, k.keg_size_value) as remaining_volume,
- kt.days_outstanding, u.username as performed_by, kt.notes,
- tt.transaction_type_name as transaction_type, kt.metadata_json
- FROM kegs k
- JOIN latest_transactions lt ON k.keg_id = lt.keg_id
- JOIN keg_transactions kt ON k.keg_id = kt.keg_id AND kt.created_at_utc = lt.latest_timestamp
- LEFT JOIN event_dates ed_prod ON k.production_event_id = ed_prod.event_id
- LEFT JOIN event_dates ed_trans ON kt.event_id = ed_trans.event_id
- LEFT JOIN locations l ON kt.location_id = l.location_id
- LEFT JOIN users u ON kt.performed_by_user_id = u.user_id
- LEFT JOIN transaction_types tt ON kt.transaction_type_id = tt.transaction_type_id
- '''
- return pd.read_sql_query(query, self.conn, params=[keg_id])
- else:
- query = '''
- WITH latest_transactions AS (
- SELECT kt.keg_id, MAX(kt.created_at_utc) as latest_timestamp
- FROM keg_transactions kt GROUP BY kt.keg_id
- )
- SELECT k.keg_id, k.beer_code, k.tank, k.keg_size_value, k.keg_size_unit, k.keg_number,
- ed_prod.event_date as production_date, ed_trans.event_datetime_singapore as singapore_timestamp,
- kt.created_at_utc as action_timestamp, COALESCE(l.location_name, 'Cold Room') as location,
- kt.status_after as status, kt.quantity_sold, kt.quantity_unit,
- COALESCE(kt.remaining_volume, k.keg_size_value) as remaining_volume,
- kt.days_outstanding, u.username as performed_by, kt.notes,
- tt.transaction_type_name as transaction_type, kt.metadata_json
- FROM kegs k
- JOIN latest_transactions lt ON k.keg_id = lt.keg_id
- JOIN keg_transactions kt ON k.keg_id = kt.keg_id AND kt.created_at_utc = lt.latest_timestamp
- LEFT JOIN event_dates ed_prod ON k.production_event_id = ed_prod.event_id
- LEFT JOIN event_dates ed_trans ON kt.event_id = ed_trans.event_id
- LEFT JOIN locations l ON kt.location_id = l.location_id
- LEFT JOIN users u ON kt.performed_by_user_id = u.user_id
- LEFT JOIN transaction_types tt ON kt.transaction_type_id = tt.transaction_type_id
- ORDER BY kt.created_at_utc DESC
- '''
- return pd.read_sql_query(query, self.conn)
-
- def get_active_kegs_for_dropdowns(self):
- try:
- df = self.get_current_keg_status()
- if df.empty:
- return ["No kegs available - Add kegs first"]
-
- keg_list = []
- for _, row in df.iterrows():
- if row.get('status') in ['Deleted', 'Returned'] or row.get('location') == 'Brewery':
- continue
-
- location = row.get('location', 'Unknown')
- if location == 'Cold Room':
- location_display = 'Storage'
- else:
- location_display = location
- volume = f"{row.get('remaining_volume', row['keg_size_value']):.1f}L"
- label = f"{row['keg_id']} - {row['beer_code']} ({volume}, {location_display})"
- keg_list.append(label)
- return keg_list if keg_list else ["No active kegs available"]
- except Exception as e:
- return [f"Error loading kegs: {str(e)}"]
-
- def get_all_keg_list(self):
- try:
- query = '''
- WITH latest_transactions AS (
- SELECT kt.keg_id, MAX(kt.created_at_utc) as latest_timestamp
- FROM keg_transactions kt GROUP BY kt.keg_id
- )
- SELECT k.keg_id, k.beer_code, k.keg_size_value,
- COALESCE(l.location_name, 'Storage') as current_location
- FROM kegs k
- LEFT JOIN latest_transactions lt ON k.keg_id = lt.keg_id
- LEFT JOIN keg_transactions kt ON k.keg_id = kt.keg_id AND kt.created_at_utc = lt.latest_timestamp
- LEFT JOIN locations l ON kt.location_id = l.location_id
- ORDER BY k.created_at_utc DESC
- '''
- df = pd.read_sql_query(query, self.conn)
- if df.empty:
- return ["No kegs found"]
-
- keg_list = []
- for _, row in df.iterrows():
- location = row['current_location']
- if location == 'Cold Room':
- location = 'Storage'
- label = f"{row['keg_id']} - {row['beer_code']} ({row['keg_size_value']}L, {location})"
- keg_list.append(label)
- return keg_list
- except Exception as e:
- return [f"Error loading kegs: {str(e)}"]
-
- def get_keg_item_code_from_label(self, label):
- try:
- if " - " in label:
- return label.split(" - ")[0]
- return label
- except:
- return label
-
- def get_kegs_at_retail_location(self, location):
- try:
- df = self.get_current_keg_status()
- if df.empty:
- return pd.DataFrame()
-
- location_kegs = df[
- (df['location'] == location) &
- (~df['status'].isin(['Deleted', 'Returned'])) &
- (df['location'] != 'Brewery')
- ].copy()
-
- if location_kegs.empty:
- return pd.DataFrame()
-
- location_kegs['transfer_volume'] = location_kegs['remaining_volume']
- location_kegs['days_at_location'] = (
- pd.to_datetime('now') - pd.to_datetime(location_kegs['singapore_timestamp'])
- ).dt.days
-
- display_cols = [
- 'keg_id', 'beer_code', 'transfer_volume', 'status',
- 'days_at_location', 'singapore_timestamp'
- ]
-
- result = location_kegs[display_cols].copy()
- result.columns = [
- 'Keg ID', 'Beer Code', 'Transfer Volume (L)', 'Status',
- 'Days at Location', 'Last Updated (SGT)'
- ]
- return result.sort_values('Last Updated (SGT)', ascending=False)
- except Exception as e:
- print(f"Error getting kegs for {location}: {str(e)}")
- return pd.DataFrame()
-
- def get_draw_down_transactions_by_date_range(self, start_date: str, end_date: str, location_filter: str = None, beer_filter: str = None):
- try:
- query = '''
- SELECT kt.keg_id, k.beer_code, k.keg_size_value, k.keg_size_unit, l.location_name,
- ed.event_date, ed.event_time, ed.event_datetime_singapore, kt.remaining_volume,
- tt.transaction_type_name, kt.created_at_utc, kt.notes
- FROM keg_transactions kt
- JOIN kegs k ON kt.keg_id = k.keg_id
- JOIN transaction_types tt ON kt.transaction_type_id = tt.transaction_type_id
- LEFT JOIN locations l ON kt.location_id = l.location_id
- LEFT JOIN event_dates ed ON kt.event_id = ed.event_id
- WHERE tt.transaction_type_code = 'DRAW_DOWN'
- AND ed.event_date >= ? AND ed.event_date <= ?
- '''
- params = [start_date, end_date]
-
- if location_filter and location_filter != "All Locations":
- query += ' AND l.location_name = ?'
- params.append(location_filter)
- if beer_filter and beer_filter != "All Beer Codes":
- query += ' AND k.beer_code = ?'
- params.append(beer_filter)
-
- query += ' ORDER BY ed.event_date ASC, ed.event_time ASC'
- return pd.read_sql_query(query, self.conn, params=params)
- except Exception as e:
- print(f"Error getting draw down transactions: {str(e)}")
- return pd.DataFrame()
-
- def get_draw_down_summary_stats(self, df):
- if df.empty:
- return {'total_draw_downs': 0, 'unique_locations': 0, 'unique_beer_codes': 0, 'total_volume': 0, 'date_range': 'No data'}
- try:
- # Create combined breakdown: Location, Beer Code (Size)
- combined_breakdown = {}
- for _, row in df.iterrows():
- location = row.get('location_name', 'Unknown')
- beer_code = row.get('beer_code', 'Unknown')
- size = row.get('keg_size_value', 0)
-
- # Format: "Location, Beer Code (Size)"
- breakdown_key = f"{location}, {beer_code} ({size}L)"
- combined_breakdown[breakdown_key] = combined_breakdown.get(breakdown_key, 0) + 1
-
- return {
- 'total_draw_downs': len(df),
- 'unique_locations': df['location_name'].nunique(),
- 'unique_beer_codes': df['beer_code'].nunique(),
- 'total_volume': df['keg_size_value'].sum(),
- 'avg_keg_size': df['keg_size_value'].mean(),
- 'date_range': f"{df['event_date'].min()} to {df['event_date'].max()}",
- 'combined_breakdown': combined_breakdown
- }
- except Exception as e:
- return {'error': str(e)}
-
- def update_keg_status(self, keg_id, action, event_date, event_time="00:00", username=None, **kwargs):
- try:
- if isinstance(event_date, str):
- event_date = parse_event_date(event_date)
-
- current_status_df = self.get_current_keg_status(keg_id)
- if current_status_df.empty:
- return f"Keg {keg_id} not found"
-
- current_status = current_status_df.iloc[0]['status']
- current_location = current_status_df.iloc[0].get('location', 'Unknown')
- current_volume = current_status_df.iloc[0].get('remaining_volume', current_status_df.iloc[0]['keg_size_value'])
-
- if action == 'draw_down':
- metadata = {'previous_location': current_location}
- self.create_transaction(
- keg_id=keg_id, transaction_type_code='DRAW_DOWN', status_after='Drawn Down',
- event_date=event_date, event_time=event_time, previous_status=current_status,
- location_name=kwargs.get('location'), remaining_volume=current_volume,
- username=username, metadata=metadata,
- notes=f"Drawn down to {kwargs.get('location')} by {username or 'system'}"
- )
- elif action == 'return':
- self.create_transaction(
- keg_id=keg_id, transaction_type_code='RETURN', status_after='Returned',
- event_date=event_date, event_time=event_time, previous_status=current_status,
- location_name='Brewery', remaining_volume=current_volume, username=username,
- notes=f"Full keg returned to brewery by {username or 'system'}"
- )
- elif action == 'return_partial':
- quantity_sold = kwargs.get('quantity_sold', 0)
- quantity_unit = kwargs.get('quantity_unit', 'pint')
- remaining_volume = self.calculate_remaining_volume(current_volume, quantity_sold, quantity_unit)
- metadata = {'partial_return': True}
- self.create_transaction(
- keg_id=keg_id, transaction_type_code='RETURN_PARTIAL', status_after='Partial Return',
- event_date=event_date, event_time=event_time, previous_status=current_status,
- location_name='Cold Room', quantity_sold=quantity_sold, quantity_unit=quantity_unit,
- remaining_volume=remaining_volume, username=username, metadata=metadata,
- notes=f"Partial keg returned: {quantity_sold} {quantity_unit} sold, {remaining_volume:.2f}L remaining by {username or 'system'}"
- )
- elif action == 'internal_transfer':
- quantity_sold = kwargs.get('quantity_sold', 0)
- quantity_unit = kwargs.get('quantity_unit', 'pint')
- remaining_volume = self.calculate_remaining_volume(current_volume, quantity_sold, quantity_unit)
- metadata = {'internal_transfer': True, 'previous_location': current_location}
- self.create_transaction(
- keg_id=keg_id, transaction_type_code='INTERNAL_TRANSFER', status_after='Transferred',
- event_date=event_date, event_time=event_time, previous_status=current_status,
- location_name=kwargs.get('location'), quantity_sold=quantity_sold,
- quantity_unit=quantity_unit, remaining_volume=remaining_volume,
- username=username, metadata=metadata,
- notes=f"Internal transfer to {kwargs.get('location')}: {quantity_sold} {quantity_unit} sold, {remaining_volume:.2f}L remaining by {username or 'system'}"
- )
-
- return f"Success! Keg {keg_id} {action.replace('_', ' ').title()} on {event_date} at {event_time}"
- except Exception as e:
- return f"Error: {str(e)}"
-
- def calculate_keg_yield_for_period(self, keg_id, tap_in_date, tap_in_time, tap_out_date, tap_out_time, tap_period_sequence=1, debug_mode=True):
- try:
- keg_info_df = self.get_current_keg_status(keg_id)
- if keg_info_df.empty:
- return "Error: Keg not found"
-
- keg_info = keg_info_df.iloc[0]
- beer_code = keg_info['beer_code']
- keg_volume = keg_info['remaining_volume']
- location = keg_info.get('location', 'Unknown')
-
- tap_in_event_id = self.create_event_date(parse_event_date(tap_in_date), tap_in_time)
- tap_out_event_id = None
- if tap_out_date:
- tap_out_event_id = self.create_event_date(parse_event_date(tap_out_date), tap_out_time)
-
- total_sales_volume = 0
- total_items_sold = 0
- yield_percentage = 0
- data_source = "No Data"
- api_error = None
- order_details = []
- daily_breakdown = []
-
- if self.shopify_client:
- try:
- orders_df, error = self.shopify_client.get_orders_for_keg_yield(
- beer_code, location, tap_in_date, tap_in_time, tap_out_date, tap_out_time, debug_mode=debug_mode
- )
-
- if error:
- api_error = error
- data_source = f"API Error: {error}"
- elif orders_df is not None and not orders_df.empty:
- total_sales_volume, total_items_sold, order_details = self._process_orders_sales_data(orders_df)
- data_source = "Shopify Orders API (Daily Breakdown)"
-
- if 'daily_summaries' in orders_df.columns and not orders_df.empty:
- try:
- daily_breakdown = eval(orders_df.iloc[0]['daily_summaries'])
- except:
- daily_breakdown = []
- else:
- data_source = "API - No Data"
- except Exception as e:
- api_error = str(e)
- data_source = f"API Exception: {str(e)}"
- else:
- data_source = "No API Configuration"
-
- yield_percentage = (total_sales_volume / keg_volume) * 100 if keg_volume > 0 else 0
- location_id = self.get_location_id(location)
-
- cursor = self.conn.cursor()
- cursor.execute('''
- INSERT INTO keg_yield (keg_id, tap_in_event_id, tap_out_event_id, location_id,
- keg_volume, total_sales_volume, total_items_sold,
- keg_yield_percentage, data_source, api_error, tap_period_sequence,
- calculation_method, daily_breakdown_json)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ''', (keg_id, tap_in_event_id, tap_out_event_id, location_id, keg_volume,
- total_sales_volume, total_items_sold, yield_percentage,
- data_source, api_error, tap_period_sequence,
- 'daily_breakdown', json.dumps(daily_breakdown) if daily_breakdown else None))
- self.conn.commit()
-
- return {
- 'keg_id': keg_id, 'beer_code': beer_code, 'location': location, 'keg_volume': keg_volume,
- 'total_sales_volume': total_sales_volume, 'total_items_sold': total_items_sold,
- 'yield_percentage': yield_percentage, 'tap_in_datetime': f"{tap_in_date} {tap_in_time}",
- 'tap_out_datetime': f"{tap_out_date} {tap_out_time}" if tap_out_date else "Ongoing",
- 'tap_period_sequence': tap_period_sequence, 'data_source': data_source,
- 'api_error': api_error, 'order_details': order_details,
- 'daily_breakdown': daily_breakdown, 'calculation_method': 'daily_breakdown'
- }
- except Exception as e:
- return f"Error calculating yield: {str(e)}"
-
- def calculate_location_sales_analysis(self, beer_code, location, tap_in_date, tap_in_time, tap_out_date=None, tap_out_time=None, debug_mode=True):
- """
- New method for location-based sales analysis without keg dependency
- """
- try:
- if not beer_code or not location:
- return "Error: Beer code and location are required"
-
- if not tap_in_date:
- return "Error: Tap in date is required"
-
- tap_in_event_id = self.create_event_date(parse_event_date(tap_in_date), tap_in_time)
- tap_out_event_id = None
- if tap_out_date:
- tap_out_event_id = self.create_event_date(parse_event_date(tap_out_date), tap_out_time)
-
- total_sales_volume = 0
- total_items_sold = 0
- data_source = "No Data"
- api_error = None
- order_details = []
- daily_breakdown = []
-
- if self.shopify_client:
- try:
- line_items, daily_summaries, error = self.shopify_client.get_orders_for_location_analysis(
- beer_code, location, tap_in_date, tap_in_time, tap_out_date, tap_out_time, debug_mode=debug_mode
- )
-
- if error:
- api_error = error
- data_source = f"API Error: {error}"
- elif line_items is not None:
- # Process the line items to calculate totals
- for item in line_items:
- try:
- quantity = int(item.get('net_quantity', 0))
- if quantity <= 0:
- continue
-
- total_items_sold += quantity
- product_title = str(item.get('full_product_title', '')).lower()
- volume_per_item = self._extract_volume_from_product_title(product_title)
- volume = quantity * volume_per_item
- total_sales_volume += volume
-
- order_details.append({
- 'order_id': item.get('order_id', 'Unknown'),
- 'product': item.get('product_title', product_title),
- 'qty': quantity, 'volume': volume, 'unit_volume': volume_per_item,
- 'location': item.get('pos_location_name', 'Unknown'),
- 'date': item.get('calculation_date', 'Unknown')
- })
- except (ValueError, TypeError):
- continue
-
- data_source = "Shopify Orders API (Location Analysis)"
- daily_breakdown = daily_summaries if daily_summaries else []
- else:
- data_source = "API - No Data"
- except Exception as e:
- api_error = str(e)
- data_source = f"API Exception: {str(e)}"
- else:
- data_source = "No API Configuration"
-
- location_id = self.get_location_id(location)
-
- # Save to location_sales_analysis table
- cursor = self.conn.cursor()
- cursor.execute('''
- INSERT INTO location_sales_analysis (beer_code, location_id, tap_in_event_id, tap_out_event_id,
- total_sales_volume, total_items_sold, data_source, api_error,
- calculation_method, daily_breakdown_json)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ''', (beer_code, location_id, tap_in_event_id, tap_out_event_id,
- total_sales_volume, total_items_sold, data_source, api_error,
- 'location_analysis', json.dumps(daily_breakdown) if daily_breakdown else None))
- self.conn.commit()
-
- return {
- 'beer_code': beer_code, 'location': location,
- 'total_sales_volume': total_sales_volume, 'total_items_sold': total_items_sold,
- 'tap_in_datetime': f"{tap_in_date} {tap_in_time}",
- 'tap_out_datetime': f"{tap_out_date} {tap_out_time}" if tap_out_date else "Ongoing",
- 'data_source': data_source, 'api_error': api_error, 'order_details': order_details,
- 'daily_breakdown': daily_breakdown, 'calculation_method': 'location_analysis'
- }
- except Exception as e:
- return f"Error calculating location sales: {str(e)}"
-
- def _process_orders_sales_data(self, orders_df):
- try:
- total_volume = 0
- net_items_sold = 0
- order_details = []
-
- for _, row in orders_df.iterrows():
- try:
- quantity = int(row.get('net_quantity', 0))
- if quantity <= 0:
- continue
-
- net_items_sold += quantity
- product_title = str(row.get('full_product_title', '')).lower()
- volume_per_item = self._extract_volume_from_product_title(product_title)
- volume = quantity * volume_per_item
- total_volume += volume
-
- order_details.append({
- 'order_id': row.get('order_id', 'Unknown'),
- 'product': row.get('product_title', product_title),
- 'qty': quantity, 'volume': volume, 'unit_volume': volume_per_item,
- 'location': row.get('pos_location_name', 'Unknown'),
- 'date': row.get('calculation_date', 'Unknown')
- })
- except (ValueError, TypeError) as e:
- continue
- return total_volume, net_items_sold, order_details
- except Exception as e:
- print(f"Error processing Orders API sales data: {e}")
- return 0, 0, []
-
- def _extract_volume_from_product_title(self, product_title):
- ml_match = re.search(r'(\d+(?:\.\d+)?)\s*ml', product_title)
- if ml_match:
- ml_value = float(ml_match.group(1))
- return ml_value / 1000
- oz_match = re.search(r'(\d+(?:\.\d+)?)\s*oz', product_title)
- if oz_match:
- oz_value = float(oz_match.group(1))
- ml_value = oz_value * 29.5735
- return ml_value / 1000
- if 'pint' in product_title:
- if 'half' in product_title:
- return 0.237
- else:
- return 0.473
- return 0.473
-
- def get_keg_history(self, keg_id: str):
- query = '''
- SELECT kt.*, k.beer_code, k.tank, k.keg_size_value, tt.transaction_type_name,
- ed.event_datetime_singapore, l.location_name, u.username as performed_by_name
- FROM keg_transactions kt
- JOIN kegs k ON kt.keg_id = k.keg_id
- LEFT JOIN transaction_types tt ON kt.transaction_type_id = tt.transaction_type_id
- LEFT JOIN event_dates ed ON kt.event_id = ed.event_id
- LEFT JOIN locations l ON kt.location_id = l.location_id
- LEFT JOIN users u ON kt.performed_by_user_id = u.user_id
- WHERE kt.keg_id = ? ORDER BY kt.created_at_utc ASC
- '''
- return pd.read_sql_query(query, self.conn, params=[keg_id])
-
- def get_transactions_report(self, start_date: str = None, end_date: str = None, user_filter: str = None, location_filter: str = None, transaction_type_filter: str = None):
- query = '''
- SELECT kt.transaction_id, kt.keg_id, k.beer_code, k.keg_size_value, tt.transaction_type_name as transaction_type,
- ed.event_datetime_singapore as singapore_timestamp, kt.created_at_utc as action_timestamp,
- l.location_name as location, kt.status_after, kt.quantity_sold, kt.quantity_unit,
- kt.remaining_volume, u.username as performed_by, kt.notes
- FROM keg_transactions kt
- JOIN kegs k ON kt.keg_id = k.keg_id
- LEFT JOIN transaction_types tt ON kt.transaction_type_id = tt.transaction_type_id
- LEFT JOIN event_dates ed ON kt.event_id = ed.event_id
- LEFT JOIN locations l ON kt.location_id = l.location_id
- LEFT JOIN users u ON kt.performed_by_user_id = u.user_id
- WHERE 1=1
- '''
- params = []
-
- if start_date:
- query += ' AND DATE(kt.created_at_utc) >= ?'
- params.append(start_date)
- if end_date:
- query += ' AND DATE(kt.created_at_utc) <= ?'
- params.append(end_date)
- if user_filter and user_filter != 'All Users':
- query += ' AND u.username = ?'
- params.append(user_filter)
- if location_filter and location_filter != 'All Locations':
- query += ' AND l.location_name = ?'
- params.append(location_filter)
- if transaction_type_filter and transaction_type_filter != 'All Transaction Types':
- query += ' AND tt.transaction_type_name = ?'
- params.append(transaction_type_filter)
-
- query += ' ORDER BY kt.created_at_utc DESC'
- return pd.read_sql_query(query, self.conn, params=params)
-
- def get_transaction_types(self):
- cursor = self.conn.cursor()
- cursor.execute('SELECT transaction_type_name FROM transaction_types WHERE is_active = TRUE ORDER BY transaction_type_name')
- return [row[0] for row in cursor.fetchall()]
-
- def get_users(self):
- cursor = self.conn.cursor()
- cursor.execute('SELECT username FROM users WHERE is_active = TRUE ORDER BY username')
- return [row[0] for row in cursor.fetchall()]
-
- def add_user(self, username, role='user'):
- try:
- cursor = self.conn.cursor()
- cursor.execute('INSERT OR IGNORE INTO users (username, role) VALUES (?, ?)', (username, role))
- self.conn.commit()
- return f"User '{username}' added successfully!"
- except Exception as e:
- return f"Error: {str(e)}"
-
- def add_beer_keyword(self, beer_code, keyword):
- try:
- system_user_id = self.get_user_id('system')
- cursor = self.conn.cursor()
- cursor.execute('INSERT INTO beer_keywords (beer_code, keyword, created_by_user_id) VALUES (?, ?, ?)', (beer_code.upper(), keyword.lower(), system_user_id))
- self.conn.commit()
- return f"Added keyword '{keyword}' for beer code '{beer_code}'"
- except Exception as e:
- return f"Error: {str(e)}"
-
- def get_beer_keywords(self, beer_code=None):
- try:
- cursor = self.conn.cursor()
- if beer_code:
- cursor.execute('SELECT beer_code, keyword FROM beer_keywords WHERE beer_code = ? AND is_active = TRUE ORDER BY beer_code, keyword', (beer_code.upper(),))
- else:
- cursor.execute('SELECT beer_code, keyword FROM beer_keywords WHERE is_active = TRUE ORDER BY beer_code, keyword')
- return cursor.fetchall()
- except Exception as e:
- return []
-
- def add_location_mapping(self, inventory_location, pos_location, shopify_location_id=None):
- try:
- location_id = self.get_location_id(inventory_location)
- if not location_id:
- return f"Error: Location '{inventory_location}' not found"
-
- system_user_id = self.get_user_id('system')
- cursor = self.conn.cursor()
-
- cursor.execute('''
- INSERT OR REPLACE INTO location_mapping
- (location_id, pos_location_name, shopify_location_id, created_by_user_id, updated_at_utc)
- VALUES (?, ?, ?, ?, ?)
- ''', (location_id, pos_location, shopify_location_id, system_user_id, get_utc_now()))
- self.conn.commit()
-
- if self.shopify_client:
- self.shopify_client.refresh_location_mappings()
-
- mapping_info = f"'{inventory_location}' → '{pos_location}'"
- if shopify_location_id:
- mapping_info += f" (ID: {shopify_location_id})"
-
- return f"Added mapping: {mapping_info}"
- except Exception as e:
- return f"Error: {str(e)}"
-
- def archive_location_mapping(self, inventory_location, archive=True):
- try:
- location_id = self.get_location_id(inventory_location)
- if not location_id:
- return f"Error: Location '{inventory_location}' not found"
-
- cursor = self.conn.cursor()
- cursor.execute('''
- UPDATE location_mapping
- SET is_archived = ?, updated_at_utc = ?
- WHERE location_id = ?
- ''', (archive, get_utc_now(), location_id))
- self.conn.commit()
-
- if self.shopify_client:
- self.shopify_client.refresh_location_mappings()
-
- action = "archived" if archive else "activated"
- return f"Location '{inventory_location}' {action} successfully"
- except Exception as e:
- return f"Error: {str(e)}"
-
- def get_location_mappings(self):
- try:
- cursor = self.conn.cursor()
- cursor.execute('''
- SELECT l.location_name, lm.pos_location_name, lm.shopify_location_id,
- lm.is_active, lm.is_archived, lm.updated_at_utc
- FROM location_mapping lm
- JOIN locations l ON lm.location_id = l.location_id
- WHERE lm.is_active = TRUE
- ORDER BY lm.is_archived ASC, l.location_name
- ''')
- return cursor.fetchall()
- except Exception as e:
- return []
-
- def add_exclude_keyword(self, keyword):
- try:
- system_user_id = self.get_user_id('system')
- cursor = self.conn.cursor()
- cursor.execute('INSERT INTO exclude_keywords (keyword, created_by_user_id) VALUES (?, ?)', (keyword.lower(), system_user_id))
- self.conn.commit()
- return f"Added exclude keyword: '{keyword}'"
- except Exception as e:
- return f"Error: {str(e)}"
-
- def get_exclude_keywords(self):
- try:
- cursor = self.conn.cursor()
- cursor.execute('SELECT keyword FROM exclude_keywords WHERE is_active = TRUE ORDER BY keyword')
- return [row[0] for row in cursor.fetchall()]
- except Exception as e:
- return []
-
- def get_location_sales_history(self):
- """Get history of location sales analyses"""
- try:
- query = '''
- SELECT lsa.beer_code, l.location_name as location,
- ed_in.event_date as tap_in_date, ed_in.event_time as tap_in_time,
- ed_out.event_date as tap_out_date, ed_out.event_time as tap_out_time,
- lsa.total_sales_volume, lsa.total_items_sold,
- lsa.data_source, lsa.calculation_method, lsa.created_at_utc
- FROM location_sales_analysis lsa
- LEFT JOIN locations l ON lsa.location_id = l.location_id
- LEFT JOIN event_dates ed_in ON lsa.tap_in_event_id = ed_in.event_id
- LEFT JOIN event_dates ed_out ON lsa.tap_out_event_id = ed_out.event_id
- ORDER BY lsa.created_at_utc DESC LIMIT 50
- '''
- return pd.read_sql_query(query, self.conn)
- except Exception as e:
- return pd.DataFrame()
-
-# Helper functions
-def get_keg_tap_dates_for_location(keg_id, location, keg_system):
- try:
- history_df = keg_system.get_keg_history(keg_id)
- if history_df.empty:
- return {'tap_in_date': None, 'tap_in_time': None, 'tap_out_date': None, 'tap_out_time': None}
-
- tap_in_transaction = None
- tap_out_transaction = None
-
- for idx, row in history_df.iterrows():
- transaction_type = row.get('transaction_type_name', '')
- current_location = row.get('location_name', '')
-
- if current_location == location and transaction_type in ['Draw Down', 'Internal Transfer']:
- if not tap_in_transaction:
- tap_in_transaction = row
- elif tap_in_transaction and current_location != location and transaction_type in ['Return Empty', 'Return Partial', 'Internal Transfer']:
- tap_out_transaction = row
- break
-
- tap_in_date = None
- tap_in_time = None
- tap_out_date = None
- tap_out_time = None
-
- if tap_in_transaction is not None:
- event_datetime_str = tap_in_transaction.get('event_datetime_singapore', '')
- if event_datetime_str:
- try:
- dt_part = event_datetime_str.replace(' SGT', '').strip()
- dt = datetime.strptime(dt_part, '%Y-%m-%d %H:%M:%S')
- tap_in_date = dt.strftime('%Y-%m-%d')
- tap_in_time = dt.strftime('%H:%M')
- except:
- pass
-
- if tap_out_transaction is not None:
- event_datetime_str = tap_out_transaction.get('event_datetime_singapore', '')
- if event_datetime_str:
- try:
- dt_part = event_datetime_str.replace(' SGT', '').strip()
- dt = datetime.strptime(dt_part, '%Y-%m-%d %H:%M:%S')
- tap_out_date = dt.strftime('%Y-%m-%d')
- tap_out_time = dt.strftime('%H:%M')
- except:
- pass
-
- return {'tap_in_date': tap_in_date, 'tap_in_time': tap_in_time, 'tap_out_date': tap_out_date, 'tap_out_time': tap_out_time}
- except Exception as e:
- return {'tap_in_date': None, 'tap_in_time': None, 'tap_out_date': None, 'tap_out_time': None}
-
-def get_keg_volume_when_tapped(keg_id, location, keg_system):
- try:
- history_df = keg_system.get_keg_history(keg_id)
- if history_df.empty:
- return None
- for _, row in history_df.iterrows():
- transaction_type = row.get('transaction_type_name', '')
- current_location = row.get('location_name', '')
- if current_location == location and transaction_type in ['Draw Down', 'Internal Transfer']:
- return row.get('remaining_volume', None)
- return None
- except Exception as e:
- return None
-
-def validate_date(date_str):
- try:
- return datetime.strptime(date_str, "%Y-%m-%d").date()
- except:
- return None
-
-def parse_keg_size(keg_size_input):
- if keg_size_input in ['20L', '30L']:
- return float(keg_size_input.replace('L', ''))
- elif keg_size_input == 'Other':
- return None
- else:
- try:
- return float(keg_size_input)
- except:
- return None
-
-def create_excel_copy_text(df_data):
- if df_data is None or len(df_data) == 0:
- return ""
- try:
- df = pd.DataFrame(df_data)
- lines = []
- headers = [str(col) for col in df.columns]
- lines.append("\t".join(headers))
-
- for _, row in df.iterrows():
- row_values = []
- for val in row.values:
- if pd.isna(val) or val is None:
- row_values.append("")
- else:
- row_values.append(str(val))
- lines.append("\t".join(row_values))
- return "\n".join(lines)
- except Exception as e:
- return f"Error formatting data: {str(e)}"
-
-def generate_draw_down_summary_text(stats):
- if 'error' in stats:
- return f"Error generating summary: {stats['error']}"
-
- if stats['total_draw_downs'] == 0:
- return "**No draw down transactions found**\n\nTry expanding the date range or adjusting filters."
-
- summary = f"## Draw Down Analysis Summary\n\n"
- summary += f"**Overview:** {stats['total_draw_downs']} draw downs | {stats['unique_locations']} locations | {stats['unique_beer_codes']} beer codes\n"
- summary += f"**Period:** {stats['date_range']}\n"
- summary += f"**Total Volume:** {stats['total_volume']:.1f}L\n"
- summary += f"**Average Keg Size:** {stats.get('avg_keg_size', 0):.1f}L\n\n"
-
- # Combined breakdown by location, beer code, and size
- if 'combined_breakdown' in stats and stats['combined_breakdown']:
- summary += f"**Breakdown:**\n"
- for breakdown_key, count in sorted(stats['combined_breakdown'].items()):
- summary += f"• {breakdown_key}: {count} kegs\n"
-
- return summary
-
-def prepare_draw_down_display_table(df):
- if df.empty:
- return pd.DataFrame()
- try:
- df = df.copy()
-
- if 'created_at_utc' in df.columns:
- df['action_time_formatted'] = pd.to_datetime(df['created_at_utc']).apply(
- lambda x: format_singapore_time(x) if pd.notnull(x) else ''
- )
- else:
- df['action_time_formatted'] = ''
-
- display_columns = ['keg_id', 'beer_code', 'keg_size_value', 'location_name', 'event_datetime_singapore', 'action_time_formatted', 'remaining_volume', 'notes']
- display_df = df[display_columns].copy()
- display_df.columns = ['Keg ID', 'Beer Code', 'Size (L)', 'Location', 'Event Time (SGT)', 'Action Time (SGT)', 'Remaining Vol (L)', 'Notes']
- return display_df.sort_values('Event Time (SGT)', ascending=False)
- except Exception as e:
- return pd.DataFrame([{'Error': f'Failed to prepare display table: {str(e)}'}])
-
-def initialize_system():
- print("Initializing Pink Blossoms Brewing System...")
- try:
- keg_system = BreweryKegInventorySystem()
-
- saved_token = keg_system.load_api_token('shopify')
- if saved_token:
- keg_system.set_shopify_access_token(saved_token)
- print("✓ Shopify API token auto-loaded from database")
-
- print("✓ Database initialized successfully")
- print("✓ Form persistence enabled")
- print("✓ API token persistence enabled")
- print("✓ Location mapping with Shopify IDs")
- print(f"✓ Singapore Time: {format_singapore_time(get_singapore_now())}")
- print("✓ System ready!")
- return keg_system
- except Exception as e:
- print(f"✗ Initialization failed: {str(e)}")
- return None
-
-# Initialize the system
-keg_system = initialize_system()
-CURRENT_USER = "web_user"
-
-def setup_shopify_with_token():
- # First try to load saved token from database
- saved_token = keg_system.load_api_token('shopify')
-
- if saved_token:
- # Use saved token from database
- token = saved_token
- result = keg_system.set_shopify_access_token(token)
- return f"✓ Shopify API configured using saved token\n{result}"
- else:
- # Fall back to hardcoded token only if no saved token exists
- token = "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"
- keg_system.save_api_token('shopify', token)
- result = keg_system.set_shopify_access_token(token)
- return f"✓ Shopify API configured with default token\n{result}"
-
-def refresh_kegs_and_locations():
- """Function to refresh both keg and location dropdowns"""
- updated_keg_list = keg_system.get_active_kegs_for_dropdowns()
- updated_location_list = keg_system.get_retail_wholesale_locations()
-
- updates = []
- for i in range(5):
- updates.append(gr.update(choices=updated_keg_list, value=None))
- updates.append(gr.update(choices=updated_location_list, value=None))
-
- return updates
-
-def create_web_interface():
- with gr.Blocks(
- title="Pink Blossoms Brewing - Keg Management System",
- theme=gr.themes.Soft(primary_hue="pink", secondary_hue="gray", neutral_hue="gray"),
- css=enhanced_css
- ) as app:
-
- gr.Markdown("# 🌸 Pink Blossoms Brewing - Keg Management System")
-
- with gr.Tabs():
-
- # Tab 1: Add Kegs
- with gr.TabItem("🏭 Add Kegs"):
- gr.Markdown("### Add New Kegs to Inventory")
-
- with gr.Group():
- gr.Markdown("**Production Date:**")
- bulk_event_date = gr.Textbox(
- label="Production Date (YYYY-MM-DD)",
- value=get_singapore_now().date().strftime("%Y-%m-%d"),
- placeholder="2025-08-29",
- info="Date when kegs were produced"
- )
-
- with gr.Group():
- gr.Markdown("**Batch 1:**")
- with gr.Row():
- batch1_beer_code = gr.Dropdown(choices=keg_system.get_beer_codes() + ["+ Add New"], label="Beer Code", value=None)
- batch1_new_code = gr.Textbox(label="New Code", placeholder="Enter new code", visible=False)
- batch1_tank = gr.Dropdown(choices=["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8"], label="Tank", value=None)
- batch1_keg_size = gr.Dropdown(choices=["20L", "30L", "Other"], label="Size", value="30L")
- batch1_custom_size = gr.Number(label="Custom Size (L)", visible=False)
- batch1_keg_range = gr.Textbox(label="Keg Range", placeholder="1-30 or 001-030", info="Range of keg numbers")
-
- with gr.Group():
- gr.Markdown("**Batch 2:** (Optional)")
- with gr.Row():
- batch2_beer_code = gr.Dropdown(choices=keg_system.get_beer_codes() + ["+ Add New"], label="Beer Code", value=None)
- batch2_new_code = gr.Textbox(label="New Code", placeholder="Enter new code", visible=False)
- batch2_tank = gr.Dropdown(choices=["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8"], label="Tank", value=None)
- batch2_keg_size = gr.Dropdown(choices=["20L", "30L", "Other"], label="Size", value="30L")
- batch2_custom_size = gr.Number(label="Custom Size (L)", visible=False)
- batch2_keg_range = gr.Textbox(label="Keg Range", placeholder="31-60")
-
- with gr.Row():
- generate_preview_btn = gr.Button("Check Conflicts", variant="primary")
- clear_fields_btn = gr.Button("Clear Fields", variant="primary")
- add_kegs_btn = gr.Button("Add Kegs", variant="primary")
-
- gr.Markdown("---")
- with gr.Group():
- gr.Markdown("**Delete Kegs:**")
- with gr.Row():
- refresh_delete_dropdowns_btn = gr.Button("Refresh Lists", variant="primary")
-
- with gr.Row():
- delete_dropdown1 = gr.Dropdown(choices=keg_system.get_active_kegs_for_dropdowns(), label="Delete Keg 1", value=None)
- delete_dropdown2 = gr.Dropdown(choices=keg_system.get_active_kegs_for_dropdowns(), label="Delete Keg 2", value=None)
- delete_dropdown3 = gr.Dropdown(choices=keg_system.get_active_kegs_for_dropdowns(), label="Delete Keg 3", value=None)
-
- gr.Markdown("**Range Deletion:**")
- with gr.Row():
- range_date_input = gr.Textbox(label="Date (YYYYMMDD)", placeholder="20250827", info="Format: YYYYMMDD")
- range_beer_code_input = gr.Textbox(label="Beer Code", placeholder="DSB", info="Beer code")
- range_size_input = gr.Textbox(label="Size", placeholder="30L", info="Size without unit")
- range_numbers_input = gr.Textbox(label="Numbers", placeholder="1-5,6,11", info="Ranges and individual")
-
- with gr.Row():
- preview_range_btn = gr.Button("Preview Range", variant="primary")
- bulk_delete_btn = gr.Button("Delete Selected Kegs", variant="primary")
-
- range_preview_output = gr.Textbox(label="Range Preview", interactive=False, lines=3, placeholder="Click 'Preview Range' to see which kegs will be deleted")
-
- conflict_check_output = gr.Textbox(label="Status Messages", interactive=False, lines=4)
- bulk_results = gr.Textbox(label="Operation Results", interactive=False, lines=6)
-
- # Event handlers for Add Kegs tab
- def toggle_new_code_field(beer_code_selection):
- return gr.update(visible=(beer_code_selection == "+ Add New"))
-
- def toggle_custom_size_field(keg_size_selection):
- return gr.update(visible=(keg_size_selection == "Other"))
-
- def check_for_conflicts(event_date_str, b1_beer_code, b1_new_code, b1_tank, b1_keg_size, b1_custom_size, b1_keg_range, b2_beer_code, b2_new_code, b2_tank, b2_keg_size, b2_custom_size, b2_keg_range):
- try:
- conflicts = []
- check_date = parse_event_date(event_date_str, get_singapore_now().date())
- date_str = check_date.strftime('%Y%m%d')
-
- for batch_num, (beer_code, new_code, tank, keg_size, custom_size, keg_range) in enumerate([
- (b1_beer_code, b1_new_code, b1_tank, b1_keg_size, b1_custom_size, b1_keg_range),
- (b2_beer_code, b2_new_code, b2_tank, b2_keg_size, b2_custom_size, b2_keg_range)
- ], 1):
-
- if beer_code and keg_range and tank:
- beer_code_final = new_code if beer_code == "+ Add New" else beer_code
- if beer_code_final:
- keg_size_value = custom_size if keg_size == "Other" else parse_keg_size(keg_size)
- if keg_size_value:
- keg_numbers = keg_system.parse_keg_range(keg_range.strip())
- for keg_num in keg_numbers[:5]:
- potential_id = f'{date_str}{beer_code_final}{keg_size_value:g}L{keg_num:03d}'
- cursor = keg_system.conn.cursor()
- cursor.execute('SELECT COUNT(*) FROM kegs WHERE keg_id = ?', (potential_id,))
- if cursor.fetchone()[0] > 0:
- conflicts.append(f"CONFLICT: {potential_id} already exists!")
-
- result = f"Conflict Check - {format_singapore_time(get_singapore_now())}\n"
- result += f"Production Date: {date_str} ({check_date.strftime('%Y-%m-%d')})\n\n"
-
- if conflicts:
- result += f"CONFLICTS FOUND ({len(conflicts)}):\n"
- for conflict in conflicts[:10]:
- result += f"{conflict}\n"
- result += "\nUse different keg numbers or production date\n"
- else:
- result += f"No conflicts - Ready to proceed!\n"
-
- return result
- except Exception as e:
- return f"Error checking conflicts: {str(e)}"
-
- def process_bulk_add_form(event_date_str, b1_beer_code, b1_new_code, b1_tank, b1_keg_size, b1_custom_size, b1_keg_range, b2_beer_code, b2_new_code, b2_tank, b2_keg_size, b2_custom_size, b2_keg_range):
- try:
- event_date = parse_event_date(event_date_str, get_singapore_now().date())
- batches = []
-
- for beer_code, new_code, tank, keg_size, custom_size, keg_range in [
- (b1_beer_code, b1_new_code, b1_tank, b1_keg_size, b1_custom_size, b1_keg_range),
- (b2_beer_code, b2_new_code, b2_tank, b2_keg_size, b2_custom_size, b2_keg_range)
- ]:
- if keg_range and tank:
- beer_code_final = new_code.upper().strip() if beer_code == "+ Add New" else beer_code
- if not beer_code_final:
- continue
-
- if beer_code == "+ Add New" and new_code:
- keg_system.add_beer_code(new_code.upper().strip())
-
- keg_size_value = custom_size if keg_size == "Other" else parse_keg_size(keg_size)
- if not keg_size_value:
- continue
-
- batches.append({
- 'beer_code': beer_code_final.upper(),
- 'tank': tank.upper().strip(),
- 'keg_size_value': keg_size_value,
- 'keg_range': keg_range.strip()
- })
-
- if not batches:
- return "No valid batches to process."
-
- return keg_system.bulk_add_kegs(batches, event_date, performed_by='web_user')
- except Exception as e:
- return f"Error processing bulk add: {str(e)}"
-
- def process_bulk_delete(dropdown1, dropdown2, dropdown3, date_str, beer_code, size_str, numbers_str):
- keg_ids = []
- for dropdown in [dropdown1, dropdown2, dropdown3]:
- if dropdown and dropdown.strip() and not dropdown.startswith("No kegs") and not dropdown.startswith("Select"):
- keg_id = keg_system.get_keg_item_code_from_label(dropdown)
- if keg_id:
- keg_ids.append(keg_id.strip())
-
- if date_str and beer_code and size_str and numbers_str:
- try:
- range_keg_ids = generate_keg_ids_from_range(date_str.strip(), beer_code.strip().upper(), size_str.strip(), numbers_str.strip())
- keg_ids.extend(range_keg_ids)
- except Exception as e:
- return f"Error processing range: {str(e)}"
-
- keg_ids = list(dict.fromkeys(keg_ids))
- if not keg_ids:
- return "Please select kegs from dropdowns OR enter range details"
- return keg_system.bulk_delete_kegs(keg_ids, performed_by='web_user')
-
- def generate_keg_ids_from_range(date_str, beer_code, size_str, numbers_str):
- size_value = size_str.replace('L', '').strip()
- keg_numbers = []
- for part in numbers_str.split(','):
- part = part.strip()
- if '-' in part:
- start, end = part.split('-')
- keg_numbers.extend(range(int(start), int(end) + 1))
- else:
- keg_numbers.append(int(part))
- keg_ids = []
- for num in keg_numbers:
- keg_id = f"{date_str}{beer_code}{size_value}L{num:03d}"
- keg_ids.append(keg_id)
- return keg_ids
-
- def preview_range_deletion(date_str, beer_code, size_str, numbers_str):
- if not (date_str and beer_code and size_str and numbers_str):
- return "Please fill in all range fields to preview"
- try:
- keg_ids = generate_keg_ids_from_range(date_str.strip(), beer_code.strip().upper(), size_str.strip(), numbers_str.strip())
- existing_kegs = []
- missing_kegs = []
-
- for keg_id in keg_ids:
- keg_status_df = keg_system.get_current_keg_status(keg_id)
- if not keg_status_df.empty:
- status = keg_status_df.iloc[0]['status']
- existing_kegs.append(f"{keg_id} ({status})")
- else:
- missing_kegs.append(keg_id)
-
- result = f"Range Preview: {date_str}{beer_code}{size_str.replace('L', '')} numbers {numbers_str}\n\n"
-
- if existing_kegs:
- result += f"EXISTING KEGS TO DELETE ({len(existing_kegs)}):\n"
- for keg in existing_kegs:
- result += f"✓ {keg}\n"
-
- if missing_kegs:
- result += f"\nMISSING KEGS ({len(missing_kegs)}):\n"
- for keg in missing_kegs[:5]:
- result += f"✗ {keg}\n"
- if len(missing_kegs) > 5:
- result += f"... and {len(missing_kegs) - 5} more missing kegs\n"
-
- if not existing_kegs:
- result += "\n⚠️ No existing kegs found in this range!"
- return result
- except Exception as e:
- return f"Error in range preview: {str(e)}"
-
- def clear_all_fields():
- return [
- get_singapore_now().date().strftime("%Y-%m-%d"),
- None, "", None, "30L", None, "",
- None, "", None, "30L", None, "",
- None, None, None, "", "",
- gr.update(visible=False), gr.update(visible=False),
- gr.update(visible=False), gr.update(visible=False),
- ]
-
- def refresh_delete_dropdowns():
- keg_list = keg_system.get_active_kegs_for_dropdowns()
- return [gr.update(choices=keg_list, value=None)] * 3
-
- # Wire up event handlers
- batch1_beer_code.change(toggle_new_code_field, batch1_beer_code, batch1_new_code)
- batch1_keg_size.change(toggle_custom_size_field, batch1_keg_size, batch1_custom_size)
- batch2_beer_code.change(toggle_new_code_field, batch2_beer_code, batch2_new_code)
- batch2_keg_size.change(toggle_custom_size_field, batch2_keg_size, batch2_custom_size)
-
- generate_preview_btn.click(
- check_for_conflicts,
- inputs=[bulk_event_date, batch1_beer_code, batch1_new_code, batch1_tank, batch1_keg_size, batch1_custom_size, batch1_keg_range, batch2_beer_code, batch2_new_code, batch2_tank, batch2_keg_size, batch2_custom_size, batch2_keg_range],
- outputs=conflict_check_output
- )
-
- clear_fields_btn.click(
- clear_all_fields,
- outputs=[bulk_event_date, batch1_beer_code, batch1_new_code, batch1_tank, batch1_keg_size, batch1_custom_size, batch1_keg_range, batch2_beer_code, batch2_new_code, batch2_tank, batch2_keg_size, batch2_custom_size, batch2_keg_range, delete_dropdown1, delete_dropdown2, delete_dropdown3, conflict_check_output, bulk_results, batch1_new_code, batch1_custom_size, batch2_new_code, batch2_custom_size]
- )
-
- add_kegs_btn.click(
- process_bulk_add_form,
- inputs=[bulk_event_date, batch1_beer_code, batch1_new_code, batch1_tank, batch1_keg_size, batch1_custom_size, batch1_keg_range, batch2_beer_code, batch2_new_code, batch2_tank, batch2_keg_size, batch2_custom_size, batch2_keg_range],
- outputs=bulk_results
- )
-
- refresh_delete_dropdowns_btn.click(refresh_delete_dropdowns, outputs=[delete_dropdown1, delete_dropdown2, delete_dropdown3])
- bulk_delete_btn.click(process_bulk_delete, inputs=[delete_dropdown1, delete_dropdown2, delete_dropdown3, range_date_input, range_beer_code_input, range_size_input, range_numbers_input], outputs=bulk_results)
- preview_range_btn.click(preview_range_deletion, inputs=[range_date_input, range_beer_code_input, range_size_input, range_numbers_input], outputs=range_preview_output)
-
- # Tab 2: Keg Actions
- with gr.TabItem("🎯 Keg Actions"):
- gr.Markdown("### Manage Keg Locations and Status")
-
- with gr.Row():
- action_event_date = gr.Textbox(
- label="Date (YYYY-MM-DD)",
- value=get_singapore_now().date().strftime("%Y-%m-%d"),
- scale=1
- )
- action_event_time = gr.Textbox(
- label="Time (HH:MM)",
- value=get_singapore_now().strftime("%H:%M"),
- scale=1
- )
- refresh_keg_btn = gr.Button("Refresh Lists", variant="primary", scale=1)
- clear_all_inventory_btn = gr.Button("Clear All", variant="primary", scale=1)
- execute_all_actions_btn = gr.Button("Execute Actions", variant="primary", scale=1)
- auto_time_btn = gr.Button("Current Time", variant="primary", scale=1)
-
- with gr.Group():
- gr.Markdown("**Keg Actions:**")
- action_choices = [
- ("Draw Down", "draw_down"),
- ("Return Empty Keg", "return"),
- ("Return Partial Keg", "return_partial"),
- ("Internal Transfer", "internal_transfer")
- ]
-
- action_components = []
- for i in range(1, 6):
- with gr.Row():
- keg_dropdown = gr.Dropdown(choices=keg_system.get_active_kegs_for_dropdowns(), label=f"Keg {i}", value=None)
- action_dropdown = gr.Dropdown(choices=action_choices, label="Action", value="draw_down")
- quantity_input = gr.Number(label="Qty Sold", value=0, minimum=0, visible=False)
- unit_dropdown = gr.Dropdown(choices=["half_pint", "330ml", "pint"], label="Unit", value="half_pint", visible=False)
- location_dropdown = gr.Dropdown(choices=keg_system.get_retail_wholesale_locations(), label="Location", value=None)
-
- action_components.append({
- 'keg': keg_dropdown, 'action': action_dropdown, 'quantity': quantity_input,
- 'unit': unit_dropdown, 'location': location_dropdown
- })
-
- action_output = gr.Textbox(label="Action Results", interactive=False, lines=6)
-
- def update_field_visibility_and_location(action_type):
- show_quantity = action_type in ['return_partial', 'internal_transfer']
-
- # Updated unit choices order: half_pint, 330ml, pint
- if action_type in ['return_partial', 'internal_transfer']:
- unit_choices = ["half_pint", "330ml", "pint"]
- unit_value = "half_pint" # Default to half_pint
- else:
- unit_choices = ["pint", "half_pint", "330ml"]
- unit_value = "pint"
-
- if action_type == 'draw_down':
- location_choices = keg_system.get_retail_wholesale_locations()
- location_value = None
- location_visible = True
- elif action_type == 'return':
- location_choices = ["Brewery"]
- location_value = "Brewery"
- location_visible = True
- elif action_type == 'return_partial':
- location_choices = ["Cold Room"]
- location_value = "Cold Room"
- location_visible = True
- elif action_type == 'internal_transfer':
- # Only show locations with active Shopify mappings for internal transfer
- location_choices = keg_system.get_locations_with_shopify_mapping()
- location_value = None
- location_visible = True
- else:
- location_choices = keg_system.get_retail_wholesale_locations()
- location_value = None
- location_visible = True
-
- return (
- gr.update(visible=show_quantity),
- gr.update(visible=show_quantity, choices=unit_choices, value=unit_value),
- gr.update(choices=location_choices, value=location_value, visible=location_visible)
- )
-
- for comp in action_components:
- comp['action'].change(
- update_field_visibility_and_location,
- comp['action'],
- [comp['quantity'], comp['unit'], comp['location']]
- )
-
- def execute_multiple_keg_actions(action_event_date, action_event_time, *args):
- results = []
- success_count = 0
- event_date = parse_event_date(action_event_date, get_singapore_now().date())
-
- for i in range(0, len(args), 5):
- keg_label = args[i]
- action_type = args[i+1]
- quantity_sold = args[i+2]
- quantity_unit = args[i+3]
- location = args[i+4]
-
- if keg_label and not keg_label.startswith("No kegs") and not keg_label.startswith("Select"):
- try:
- keg_id = keg_system.get_keg_item_code_from_label(keg_label)
- if not keg_id:
- continue
-
- kwargs = {}
- if location:
- kwargs['location'] = location
- if action_type in ['return_partial', 'internal_transfer']:
- kwargs['quantity_sold'] = quantity_sold or 0
- kwargs['quantity_unit'] = quantity_unit
-
- result = keg_system.update_keg_status(
- keg_id, action_type, event_date, action_event_time,
- username='web_user', **kwargs
- )
- results.append(f"{keg_id}: {result}")
- success_count += 1
- except Exception as e:
- results.append(f"Error with {keg_label}: {str(e)}")
-
- if results:
- summary = f"Executed {success_count} actions on {event_date} at {action_event_time}:\n\n" + "\n".join(results)
- else:
- summary = "No valid kegs selected for actions."
- return summary
-
- def update_to_current_time():
- return get_singapore_now().strftime("%H:%M")
-
- def clear_all_action_fields():
- updates = []
- for i in range(5):
- updates.append(gr.update(value=None))
- updates.append(gr.update(value="draw_down"))
- updates.append(gr.update(value=0, visible=False))
- updates.append(gr.update(value="half_pint", visible=False, choices=["half_pint", "330ml", "pint"]))
- updates.append(gr.update(value=None, choices=keg_system.get_retail_wholesale_locations()))
- updates.append("")
- return updates
-
- execute_inputs = [action_event_date, action_event_time]
- for comp in action_components:
- execute_inputs.extend([comp['keg'], comp['action'], comp['quantity'], comp['unit'], comp['location']])
-
- clear_all_outputs = []
- for comp in action_components:
- clear_all_outputs.extend([comp['keg'], comp['action'], comp['quantity'], comp['unit'], comp['location']])
- clear_all_outputs.append(action_output)
-
- refresh_outputs = []
- for comp in action_components:
- refresh_outputs.append(comp['keg'])
- refresh_outputs.append(comp['location'])
-
- execute_all_actions_btn.click(execute_multiple_keg_actions, inputs=execute_inputs, outputs=action_output)
- auto_time_btn.click(update_to_current_time, outputs=[action_event_time])
- refresh_keg_btn.click(refresh_kegs_and_locations, outputs=refresh_outputs)
- clear_all_inventory_btn.click(clear_all_action_fields, outputs=clear_all_outputs)
-
- # Tab 3: Inventory Overview
- with gr.TabItem("📊 Inventory Overview"):
- gr.Markdown("### Inventory Analysis Dashboard")
-
- with gr.Tabs():
- with gr.TabItem("Current Status"):
- gr.Markdown("### Current Inventory Status")
- gr.Markdown("*Note: Only deleted kegs and fully returned kegs are excluded from this overview*")
-
- with gr.Row():
- beer_code_filter = gr.Dropdown(
- choices=["All Beer Codes"] + keg_system.get_beer_codes(),
- label="Filter Beer Code", value="All Beer Codes", interactive=True
- )
- location_filter = gr.Dropdown(
- choices=["All Locations"] + keg_system.get_locations_excluding_brewery(),
- label="Filter Location", value="All Locations", interactive=True
- )
- status_filter = gr.Dropdown(
- choices=["All Status", "In Storage", "Drawn Down", "Transferred", "Partial Return"],
- label="Filter Status", value="All Status", interactive=True
- )
- refresh_overview_btn = gr.Button("Refresh Overview", variant="primary")
-
- with gr.Row():
- with gr.Column(scale=2):
- plot_state = gr.State(value=None)
- inventory_plot = gr.Plot(show_label=False)
- with gr.Column(scale=1):
- inventory_summary = gr.Markdown("Loading inventory data...")
-
- with gr.Row():
- copy_inventory_btn = gr.Button("Copy for Excel", variant="primary")
-
- inventory_table = gr.Dataframe(
- value=pd.DataFrame(), label="Complete Inventory", interactive=False, wrap=True
- )
- inventory_excel_output = gr.Textbox(
- label="Excel Format Data", value="", interactive=False, lines=4, visible=False
- )
-
- with gr.TabItem("Draw Down Analysis"):
- gr.Markdown("### Draw Down Analysis by Date Range")
- gr.Markdown("*Analyze keg draw downs by date range*")
-
- with gr.Group():
- gr.Markdown("**Analysis Period & Filters:**")
- with gr.Row():
- dd_start_date = gr.Textbox(
- label="Start Date (YYYY-MM-DD)",
- value=(get_singapore_now() - timedelta(days=30)).date().strftime("%Y-%m-%d"),
- placeholder="2025-07-30"
- )
- dd_end_date = gr.Textbox(
- label="End Date (YYYY-MM-DD)",
- value=get_singapore_now().date().strftime("%Y-%m-%d"),
- placeholder="2025-08-29"
- )
- dd_location_filter = gr.Dropdown(
- choices=["All Locations"] + keg_system.get_retail_wholesale_locations(),
- label="Filter by Location", value="All Locations", interactive=True
- )
- dd_beer_filter = gr.Dropdown(
- choices=["All Beer Codes"] + keg_system.get_beer_codes(),
- label="Filter by Beer Code", value="All Beer Codes", interactive=True
- )
-
- with gr.Row():
- generate_dd_analysis_btn = gr.Button("Generate Analysis", variant="primary")
- copy_dd_analysis_btn = gr.Button("Copy for Excel", variant="primary")
-
- with gr.Row():
- with gr.Column(scale=2):
- dd_plot_state = gr.State(value=None)
- dd_analysis_plot = gr.Plot(label="Draw Down Analysis", show_label=False)
- with gr.Column(scale=1):
- dd_summary_stats = gr.Markdown("Click 'Generate Analysis' to load data...")
-
- dd_analysis_table = gr.Dataframe(
- value=pd.DataFrame(), label="Draw Down Details", interactive=False, wrap=True
- )
- dd_excel_output = gr.Textbox(
- label="Excel Format Data", value="", interactive=False, lines=4, visible=False
- )
-
- def generate_draw_down_analysis(start_date, end_date, location_filter, beer_filter):
- try:
- dd_df = keg_system.get_draw_down_transactions_by_date_range(start_date, end_date, location_filter, beer_filter)
- if dd_df.empty:
- empty_fig = create_empty_plot("No draw down transactions found for selected period")
- summary = "**No draw down transactions found**\n\nTry expanding the date range or adjusting filters."
- return empty_fig, empty_fig, summary, pd.DataFrame()
-
- stats = keg_system.get_draw_down_summary_stats(dd_df)
- bar_chart_fig = create_draw_down_bar_chart(dd_df)
- summary = generate_draw_down_summary_text(stats)
- display_df = prepare_draw_down_display_table(dd_df)
- return bar_chart_fig, bar_chart_fig, summary, display_df
- except Exception as e:
- error_fig = create_error_plot(f"Error: {str(e)}")
- return error_fig, error_fig, f"Error: {str(e)}", pd.DataFrame()
-
- def copy_dd_analysis_for_excel(df_data):
- excel_text = create_excel_copy_text(df_data)
- if excel_text:
- return gr.update(visible=True, value=excel_text)
- else:
- return gr.update(visible=False, value="No data to copy")
-
- generate_dd_analysis_btn.click(
- generate_draw_down_analysis,
- inputs=[dd_start_date, dd_end_date, dd_location_filter, dd_beer_filter],
- outputs=[dd_analysis_plot, dd_plot_state, dd_summary_stats, dd_analysis_table]
- )
-
- dd_location_filter.change(
- generate_draw_down_analysis,
- inputs=[dd_start_date, dd_end_date, dd_location_filter, dd_beer_filter],
- outputs=[dd_analysis_plot, dd_plot_state, dd_summary_stats, dd_analysis_table]
- )
-
- dd_beer_filter.change(
- generate_draw_down_analysis,
- inputs=[dd_start_date, dd_end_date, dd_location_filter, dd_beer_filter],
- outputs=[dd_analysis_plot, dd_plot_state, dd_summary_stats, dd_analysis_table]
- )
-
- copy_dd_analysis_btn.click(copy_dd_analysis_for_excel, inputs=[dd_analysis_table], outputs=[dd_excel_output])
-
- def update_inventory_overview(beer_filter, location_filter, status_filter):
- try:
- df = keg_system.get_current_keg_status()
- if df.empty:
- empty_fig = create_empty_plot("No kegs found. Add kegs using the Add Kegs tab.")
- return empty_fig, empty_fig, "**No kegs found**\n\nAdd kegs using the Add Kegs tab.", pd.DataFrame()
-
- df = df[~df['status'].isin(['Deleted', 'Returned']) & (df['location'] != 'Brewery')]
-
- if beer_filter != "All Beer Codes":
- df = df[df['beer_code'] == beer_filter]
- if location_filter != "All Locations":
- df = df[df['location'] == location_filter]
- if status_filter != "All Status":
- df = df[df['status'] == status_filter]
-
- if df.empty:
- empty_fig = create_empty_plot("No kegs match current filters")
- return empty_fig, empty_fig, "**No kegs match current filters**", pd.DataFrame()
-
- df['beer_volume'] = df['beer_code'] + ' (' + df['remaining_volume'].round(1).astype(str) + 'L)'
- location_data = df.groupby(['location', 'beer_volume']).size().reset_index(name='count')
- locations = location_data['location'].unique()
-
- colors = ['#DD1B52', '#F5A5C7', '#424242', '#ff9800', '#4caf50', '#9c27b0', '#607d8b', '#795548']
-
- fig = go.Figure()
- for i, location in enumerate(locations):
- location_subset = location_data[location_data['location'] == location]
- fig.add_trace(go.Bar(
- x=location_subset['beer_volume'], y=location_subset['count'], name=location,
- marker_color=colors[i % len(colors)],
- text=[f"{count} kegs" for count in location_subset['count']], textposition='auto'
- ))
-
- fig.update_layout(
- title="Current Inventory by Location & Beer", xaxis_title="Beer Code & Volume",
- yaxis_title="Number of Kegs", template="plotly_white", height=350,
- font=dict(family="system-ui, sans-serif", size=10),
- title_font=dict(size=14, color="#DD1B52"),
- plot_bgcolor='rgba(245, 165, 199, 0.1)', paper_bgcolor='white',
- barmode='group', margin=dict(t=50, b=50, l=50, r=50)
- )
- fig.update_xaxes(tickangle=45)
-
- total_kegs = len(df)
- unique_beers = df['beer_code'].nunique()
- unique_locations = df['location'].nunique()
- total_volume = df['remaining_volume'].sum()
- focus_locations = keg_system.get_locations_with_shopify_mapping()
- focus_data = df[df['location'].isin(focus_locations)]
-
- summary = f"## Inventory Analysis\n\n"
- summary += f"**Status:** {total_kegs} kegs | {unique_beers} beer codes | {unique_locations} locations\n"
- summary += f"**Volume:** {total_volume:.1f}L remaining\n\n"
-
- # Cold Room Analysis
- cold_room_data = df[df['location'] == 'Cold Room']
- if not cold_room_data.empty:
- summary += f"**Cold Room Storage:**\n"
-
- # Group by beer code first, then by size
- beer_size_breakdown = {}
- for _, row in cold_room_data.iterrows():
- beer_code = row['beer_code']
- size = row['keg_size_value']
-
- if beer_code not in beer_size_breakdown:
- beer_size_breakdown[beer_code] = {}
-
- if size not in beer_size_breakdown[beer_code]:
- beer_size_breakdown[beer_code][size] = 0
-
- beer_size_breakdown[beer_code][size] += 1
-
- # Display in requested format: Beer: 30L - X, 20L - Y
- for beer_code in sorted(beer_size_breakdown.keys()):
- size_info = []
- for size in sorted(beer_size_breakdown[beer_code].keys(), reverse=True):
- count = beer_size_breakdown[beer_code][size]
- size_info.append(f"{size}L - {count}")
- summary += f"• {beer_code}: {', '.join(size_info)}\n"
-
- else:
- summary += f"**Cold Room Storage:** No kegs in storage\n"
-
- location_counts = df['location'].value_counts()
- summary += f"\n**All Locations:**\n"
- for location, count in location_counts.items():
- summary += f"• {location}: {count} kegs\n"
-
- display_df = df[['keg_id', 'beer_code', 'location', 'keg_size_value', 'remaining_volume', 'status', 'production_date', 'singapore_timestamp', 'action_timestamp']].copy()
-
- if 'action_timestamp' in display_df.columns:
- display_df['action_timestamp_formatted'] = pd.to_datetime(display_df['action_timestamp']).apply(
- lambda x: format_singapore_time(x) if pd.notnull(x) else ''
- )
-
- display_df.columns = ['Keg ID', 'Beer Code', 'Location', 'Size (L)', 'Volume (L)', 'Status', 'Production Date', 'Event Time (SGT)', 'Action Time', 'Action Time (SGT)']
- display_df = display_df.drop('Action Time', axis=1)
- return fig, fig, summary, display_df
- except Exception as e:
- error_fig = create_error_plot(f"Error: {str(e)}")
- return error_fig, error_fig, f"Error: {str(e)}", pd.DataFrame()
-
- def copy_inventory_for_excel(df_data):
- excel_text = create_excel_copy_text(df_data)
- if excel_text:
- return gr.update(visible=True, value=excel_text)
- else:
- return gr.update(visible=False, value="No data to copy")
-
- refresh_overview_btn.click(update_inventory_overview, inputs=[beer_code_filter, location_filter, status_filter], outputs=[inventory_plot, plot_state, inventory_summary, inventory_table])
- beer_code_filter.change(update_inventory_overview, inputs=[beer_code_filter, location_filter, status_filter], outputs=[inventory_plot, plot_state, inventory_summary, inventory_table])
- location_filter.change(update_inventory_overview, inputs=[beer_code_filter, location_filter, status_filter], outputs=[inventory_plot, plot_state, inventory_summary, inventory_table])
- status_filter.change(update_inventory_overview, inputs=[beer_code_filter, location_filter, status_filter], outputs=[inventory_plot, plot_state, inventory_summary, inventory_table])
- copy_inventory_btn.click(copy_inventory_for_excel, inputs=[inventory_table], outputs=[inventory_excel_output])
-
- # Tab 4: Keg Yield Analysis - UPDATED WITH CHANGES
- with gr.TabItem("📈 Keg Yield Analysis"):
- gr.Markdown("### Retail Keg Yield Analysis")
- gr.Markdown("*Analyze keg performance at locations with Shopify integration*")
-
- with gr.Tabs():
- with gr.TabItem("Retail Locations Analysis"):
- gr.Markdown("#### Individual Keg Controls by Location")
- gr.Markdown("*Only locations with active Shopify mappings and location IDs are shown*")
-
- dynamic_retail_location_selector = gr.CheckboxGroup(
- choices=[],
- label="Select Locations (Shopify-Connected Only)",
- value=[],
- scale=2
- )
-
- with gr.Row():
- refresh_shopify_locations_btn = gr.Button("Refresh Available Locations", variant="primary")
- load_kegs_btn = gr.Button("Load All Kegs", variant="primary")
- setup_shopify_btn = gr.Button("Connect to Shopify API", variant="primary")
-
- retail_status = gr.Textbox(label="Status", interactive=False, lines=2)
-
- # Primary location sections with individual calculate buttons
- location_sections = {}
- location_kegs = {}
-
- for location_code in PRIMARY_LOCATIONS:
- keg_limit = LOCATION_KEG_LIMITS.get(location_code, 18)
- with gr.Group(visible=False) as location_section:
- gr.Markdown(f"### {location_code} (Max: {keg_limit} kegs)")
- kegs_list = []
- for i in range(keg_limit):
- with gr.Group(visible=False) as keg_group:
- with gr.Row():
- keg_info = gr.Textbox(label=f"Keg {i+1}", interactive=False, scale=2)
- tap_in_date = gr.Textbox(label="Tap In Date", scale=1)
- tap_in_time = gr.Textbox(label="Tap In Time", scale=1)
- tap_out_date = gr.Textbox(label="Tap Out Date", scale=1)
- tap_out_time = gr.Textbox(label="Tap Out Time", scale=1)
- calculate_btn = gr.Button("Calculate", variant="primary", scale=1)
- result = gr.Textbox(label="Result", interactive=False, lines=1)
-
- kegs_list.append({
- 'group': keg_group, 'info': keg_info, 'tap_in_date': tap_in_date,
- 'tap_in_time': tap_in_time, 'tap_out_date': tap_out_date,
- 'tap_out_time': tap_out_time, 'calculate_btn': calculate_btn, 'result': result
- })
-
- location_sections[location_code] = location_section
- location_kegs[location_code] = kegs_list
-
- # Others section with individual calculate buttons
- with gr.Group(visible=False) as others_section:
- gr.Markdown("### Others")
-
- others_kegs_list = []
- for i in range(20):
- with gr.Group(visible=False) as others_keg_group:
- with gr.Row():
- others_keg_info = gr.Textbox(label=f"Keg {i+1}", interactive=False, scale=2)
- others_tap_in_date = gr.Textbox(label="Tap In Date", scale=1)
- others_tap_in_time = gr.Textbox(label="Tap In Time", scale=1)
- others_tap_out_date = gr.Textbox(label="Tap Out Date", scale=1)
- others_tap_out_time = gr.Textbox(label="Tap Out Time", scale=1)
- others_calculate_btn = gr.Button("Calculate", variant="primary", scale=1)
- others_result = gr.Textbox(label="Result", interactive=False, lines=1)
-
- others_kegs_list.append({
- 'group': others_keg_group, 'info': others_keg_info, 'tap_in_date': others_tap_in_date,
- 'tap_in_time': others_tap_in_time, 'tap_out_date': others_tap_out_date,
- 'tap_out_time': others_tap_out_time, 'calculate_btn': others_calculate_btn, 'result': others_result
- })
-
- location_sections["Others"] = others_section
- location_kegs["Others"] = others_kegs_list
-
- keg_metadata = gr.State(value={})
-
- def refresh_shopify_connected_locations():
- try:
- available_locations = keg_system.get_locations_with_shopify_mapping()
- if not available_locations:
- return gr.update(
- choices=[],
- value=[],
- label="No Locations Available (Configure Shopify mappings in Administration)"
- ), "⚠️ No locations with Shopify mapping found. Configure location mappings in Administration tab."
-
- return gr.update(
- choices=available_locations,
- value=available_locations,
- label=f"Select Locations (Shopify-Connected: {len(available_locations)})"
- ), f"✓ Found {len(available_locations)} locations with Shopify integration: {', '.join(available_locations)}"
-
- except Exception as e:
- return gr.update(choices=[], value=[]), f"Error loading Shopify locations: {str(e)}"
-
- def load_kegs_with_dynamic_locations(selected_locations):
- try:
- if not selected_locations:
- return generate_empty_keg_updates() + [{}, "No locations selected"]
-
- available_locations = keg_system.get_locations_with_shopify_mapping()
- valid_locations = [loc for loc in selected_locations if loc in available_locations]
-
- if not valid_locations:
- return generate_empty_keg_updates() + [{}, "Selected locations don't have Shopify mappings"]
-
- primary_locations = [loc for loc in valid_locations if loc in PRIMARY_LOCATIONS]
- other_locations = [loc for loc in valid_locations if loc not in PRIMARY_LOCATIONS]
-
- updates = []
- keg_data = {}
- user_prefs = keg_system.load_user_preferences(CURRENT_USER)
- total_kegs = 0
-
- # Handle primary locations
- for location_code in PRIMARY_LOCATIONS:
- keg_limit = LOCATION_KEG_LIMITS.get(location_code, 18)
- location_has_kegs = location_code in primary_locations
- updates.append(gr.update(visible=location_has_kegs))
-
- if location_has_kegs:
- kegs_df = keg_system.get_kegs_at_retail_location(location_code)
- keg_data[location_code] = []
-
- for i in range(keg_limit):
- if i < len(kegs_df):
- keg_row = kegs_df.iloc[i]
- keg_id = keg_row['Keg ID']
-
- saved_state = keg_system.load_keg_form_state(keg_id, location_code)
-
- if saved_state:
- tap_in_date = saved_state['tap_in_date']
- tap_in_time = saved_state['tap_in_time']
- tap_out_date = saved_state['tap_out_date']
- tap_out_time = saved_state['tap_out_time']
- else:
- tap_dates = get_keg_tap_dates_for_location(keg_id, location_code, keg_system)
- tap_in_date = tap_dates.get('tap_in_date', get_singapore_now().date().strftime("%Y-%m-%d"))
- tap_in_time = tap_dates.get('tap_in_time', user_prefs['tap_in_time'])
- tap_out_date = tap_dates.get('tap_out_date', '')
- tap_out_time = tap_dates.get('tap_out_time', user_prefs['tap_out_time'])
-
- volume_when_tapped = get_keg_volume_when_tapped(keg_id, location_code, keg_system)
-
- keg_data[location_code].append({
- 'keg_id': keg_id,
- 'beer_code': keg_row['Beer Code'],
- 'volume_when_tapped': volume_when_tapped or keg_row['Transfer Volume (L)'],
- 'location': location_code
- })
-
- updates.extend([
- gr.update(visible=True),
- f"{keg_id} - {keg_row['Beer Code']} ({volume_when_tapped or keg_row['Transfer Volume (L)']}L when tapped)",
- tap_in_date,
- tap_in_time,
- tap_out_date,
- tap_out_time,
- ""
- ])
- total_kegs += 1
- else:
- updates.extend([
- gr.update(visible=False),
- "", "", "", "", "", ""
- ])
- else:
- for i in range(keg_limit):
- updates.extend([
- gr.update(visible=False),
- "", "", "", "", "", ""
- ])
-
- # Handle Others section for non-primary locations
- others_visible = len(other_locations) > 0
- updates.append(gr.update(visible=others_visible))
-
- if others_visible:
- all_other_kegs = []
- keg_data["Others"] = []
-
- for location in other_locations:
- kegs_df = keg_system.get_kegs_at_retail_location(location)
- if not kegs_df.empty:
- for _, keg_row in kegs_df.iterrows():
- keg_id = keg_row['Keg ID']
-
- saved_state = keg_system.load_keg_form_state(keg_id, location)
-
- if saved_state:
- tap_in_date = saved_state['tap_in_date']
- tap_in_time = saved_state['tap_in_time']
- tap_out_date = saved_state['tap_out_date']
- tap_out_time = saved_state['tap_out_time']
- else:
- tap_dates = get_keg_tap_dates_for_location(keg_id, location, keg_system)
- tap_in_date = tap_dates.get('tap_in_date', get_singapore_now().date().strftime("%Y-%m-%d"))
- tap_in_time = tap_dates.get('tap_in_time', user_prefs['tap_in_time'])
- tap_out_date = tap_dates.get('tap_out_date', '')
- tap_out_time = tap_dates.get('tap_out_time', user_prefs['tap_out_time'])
-
- volume_when_tapped = get_keg_volume_when_tapped(keg_id, location, keg_system)
-
- all_other_kegs.append({
- 'keg_id': keg_id,
- 'beer_code': keg_row['Beer Code'],
- 'volume_when_tapped': volume_when_tapped or keg_row['Transfer Volume (L)'],
- 'location': location,
- 'tap_in_date': tap_in_date,
- 'tap_in_time': tap_in_time,
- 'tap_out_date': tap_out_date,
- 'tap_out_time': tap_out_time
- })
-
- # Fill Others section with kegs (up to 20)
- for i in range(20):
- if i < len(all_other_kegs):
- keg_info = all_other_kegs[i]
- keg_data["Others"].append({
- 'keg_id': keg_info['keg_id'],
- 'beer_code': keg_info['beer_code'],
- 'volume_when_tapped': keg_info['volume_when_tapped'],
- 'location': keg_info['location']
- })
-
- updates.extend([
- gr.update(visible=True),
- f"{keg_info['keg_id']} - {keg_info['beer_code']} ({keg_info['volume_when_tapped']}L) @ {keg_info['location']}",
- keg_info['tap_in_date'],
- keg_info['tap_in_time'],
- keg_info['tap_out_date'],
- keg_info['tap_out_time'],
- ""
- ])
- total_kegs += 1
- else:
- updates.extend([
- gr.update(visible=False),
- "", "", "", "", "", ""
- ])
- else:
- for i in range(20):
- updates.extend([
- gr.update(visible=False),
- "", "", "", "", "", ""
- ])
-
- updates.append(keg_data)
- status_msg = f"Loaded {total_kegs} kegs from {len(valid_locations)} Shopify-connected locations"
- if other_locations:
- status_msg += f" ({len(primary_locations)} primary + {len(other_locations)} others)"
- if len(valid_locations) < len(selected_locations):
- status_msg += f" (Some locations excluded - no Shopify mapping)"
- updates.append(status_msg)
- return updates
-
- except Exception as e:
- return generate_empty_keg_updates() + [{}, f"Error: {str(e)}"]
-
- def generate_empty_keg_updates():
- updates = []
- # Primary locations with different limits
- for location_code in PRIMARY_LOCATIONS:
- keg_limit = LOCATION_KEG_LIMITS.get(location_code, 18)
- updates.append(gr.update(visible=False)) # Location section visibility
- for keg in range(keg_limit):
- updates.extend([
- gr.update(visible=False),
- "", "", "", "", "", ""
- ])
- # Others section (20 kegs)
- updates.append(gr.update(visible=False))
- for keg in range(20):
- updates.extend([
- gr.update(visible=False),
- "", "", "", "", "", ""
- ])
- return updates
-
- def calculate_individual_retail_keg(location, keg_index, keg_data, tap_in_date, tap_in_time, tap_out_date, tap_out_time):
- try:
- if not keg_data or location not in keg_data or keg_index >= len(keg_data[location]):
- return "No keg data available"
-
- if not tap_in_date or not tap_in_time:
- return "Please enter tap in date and time"
-
- keg_info = keg_data[location][keg_index]
- keg_id = keg_info['keg_id']
- actual_location = keg_info['location']
- volume_when_tapped = keg_info['volume_when_tapped']
-
- keg_system.save_keg_form_state(keg_id, actual_location, tap_in_date, tap_in_time, tap_out_date, tap_out_time)
-
- yield_result = keg_system.calculate_keg_yield_for_period(
- keg_id, tap_in_date, tap_in_time,
- tap_out_date if tap_out_date else None,
- tap_out_time if tap_out_time else None,
- 1, debug_mode=False
- )
-
- if isinstance(yield_result, dict):
- sales_volume = yield_result['total_sales_volume']
- items_sold = yield_result['total_items_sold']
-
- if volume_when_tapped and volume_when_tapped > 0:
- yield_percentage = (sales_volume / volume_when_tapped) * 100
- else:
- yield_percentage = yield_result['yield_percentage']
-
- return f"Sales: {sales_volume:.2f}L | Yield: {yield_percentage:.1f}% | Items: {items_sold}"
- else:
- return f"Error: {str(yield_result)}"
-
- except Exception as e:
- return f"Error: {str(e)}"
-
- def create_auto_save_handler(location, keg_index):
- def save_timing_data(keg_data, tap_in_date, tap_in_time, tap_out_date, tap_out_time):
- try:
- if keg_data and location in keg_data and keg_index < len(keg_data[location]):
- keg_info = keg_data[location][keg_index]
- keg_id = keg_info['keg_id']
- actual_location = keg_info['location']
- keg_system.save_keg_form_state(keg_id, actual_location, tap_in_date, tap_in_time, tap_out_date, tap_out_time)
- return ""
- except Exception as e:
- return f"Auto-save error: {str(e)}"
- return save_timing_data
-
- def create_individual_calculate_handler(location, keg_index):
- def calculate_single_keg(keg_data, tap_in_date, tap_in_time, tap_out_date, tap_out_time):
- return calculate_individual_retail_keg(location, keg_index, keg_data, tap_in_date, tap_in_time, tap_out_date, tap_out_time)
- return calculate_single_keg
-
- refresh_shopify_locations_btn.click(
- refresh_shopify_connected_locations,
- outputs=[dynamic_retail_location_selector, retail_status]
- )
-
- # Load kegs outputs
- load_kegs_outputs = []
-
- # Primary locations outputs with different limits
- for location_code in PRIMARY_LOCATIONS:
- load_kegs_outputs.append(location_sections[location_code])
- keg_limit = LOCATION_KEG_LIMITS.get(location_code, 18)
- for keg in range(keg_limit):
- load_kegs_outputs.extend([location_kegs[location_code][keg]['group'],
- location_kegs[location_code][keg]['info'],
- location_kegs[location_code][keg]['tap_in_date'],
- location_kegs[location_code][keg]['tap_in_time'],
- location_kegs[location_code][keg]['tap_out_date'],
- location_kegs[location_code][keg]['tap_out_time'],
- location_kegs[location_code][keg]['result']])
-
- # Others section outputs
- load_kegs_outputs.append(location_sections["Others"])
- for keg in location_kegs["Others"]:
- load_kegs_outputs.extend([keg['group'], keg['info'], keg['tap_in_date'], keg['tap_in_time'], keg['tap_out_date'], keg['tap_out_time'], keg['result']])
-
- load_kegs_outputs.extend([keg_metadata, retail_status])
-
- load_kegs_btn.click(
- load_kegs_with_dynamic_locations,
- inputs=[dynamic_retail_location_selector],
- outputs=load_kegs_outputs
- )
-
- setup_shopify_btn.click(setup_shopify_with_token, outputs=[retail_status])
-
- # Individual calculate button handlers for primary locations
- for location_code in PRIMARY_LOCATIONS:
- keg_limit = LOCATION_KEG_LIMITS.get(location_code, 18)
- for i in range(keg_limit):
- keg = location_kegs[location_code][i]
- # Auto-save handler
- auto_save_handler = create_auto_save_handler(location_code, i)
- for field in [keg['tap_in_date'], keg['tap_in_time'], keg['tap_out_date'], keg['tap_out_time']]:
- field.change(
- auto_save_handler,
- inputs=[keg_metadata, keg['tap_in_date'], keg['tap_in_time'], keg['tap_out_date'], keg['tap_out_time']]
- )
-
- # Individual calculate button handler
- calculate_handler = create_individual_calculate_handler(location_code, i)
- keg['calculate_btn'].click(
- calculate_handler,
- inputs=[keg_metadata, keg['tap_in_date'], keg['tap_in_time'], keg['tap_out_date'], keg['tap_out_time']],
- outputs=[keg['result']]
- )
-
- # Individual calculate button handlers for Others section
- for i, keg in enumerate(location_kegs["Others"]):
- # Auto-save handler
- auto_save_handler = create_auto_save_handler("Others", i)
- for field in [keg['tap_in_date'], keg['tap_in_time'], keg['tap_out_date'], keg['tap_out_time']]:
- field.change(
- auto_save_handler,
- inputs=[keg_metadata, keg['tap_in_date'], keg['tap_in_time'], keg['tap_out_date'], keg['tap_out_time']]
- )
-
- # Individual calculate button handler
- calculate_handler = create_individual_calculate_handler("Others", i)
- keg['calculate_btn'].click(
- calculate_handler,
- inputs=[keg_metadata, keg['tap_in_date'], keg['tap_in_time'], keg['tap_out_date'], keg['tap_out_time']],
- outputs=[keg['result']]
- )
-
- # Updated Individual Keg Analysis tab (removed duplicate and modified)
- with gr.TabItem("Individual Sales Analysis"):
- gr.Markdown("#### Location Sales Analysis")
- gr.Markdown("*Analyze sales by beer code and location (independent of keg information)*")
-
- # Move buttons to top
- with gr.Row():
- refresh_sales_data_btn = gr.Button("Refresh Data", variant="primary")
- clear_sales_fields_btn = gr.Button("Clear", variant="primary")
- connect_shopify_sales_btn = gr.Button("Connect to Shopify API", variant="primary")
-
- with gr.Group():
- gr.Markdown("**Sales Analysis Parameters:**")
- with gr.Row():
- sales_beer_code = gr.Dropdown(
- choices=keg_system.get_beer_codes(),
- label="Beer Code",
- value=None, scale=1
- )
- sales_location = gr.Dropdown(
- choices=keg_system.get_locations_with_shopify_mapping(),
- label="Location",
- value=None, scale=1
- )
- sales_tap_in_date = gr.Textbox(
- label="Start Date (YYYY-MM-DD)",
- value=get_singapore_now().date().strftime("%Y-%m-%d"),
- placeholder="2025-08-29", scale=1
- )
- sales_tap_in_time = gr.Textbox(
- label="Start Time (HH:MM)",
- value="10:00",
- placeholder="10:00", scale=1
- )
- sales_tap_out_date = gr.Textbox(
- label="End Date (YYYY-MM-DD)",
- value="",
- placeholder="2025-08-29",
- info="Leave empty for current time", scale=1
- )
- sales_tap_out_time = gr.Textbox(
- label="End Time (HH:MM)",
- value="22:00",
- placeholder="22:00", scale=1
- )
- calculate_sales_btn = gr.Button("Calculate Sales", variant="primary", scale=1)
-
- sales_results = gr.Textbox(
- label="Sales Analysis Results",
- interactive=False, lines=12
- )
-
- sales_history_table = gr.Dataframe(
- label="Previous Sales Analyses",
- interactive=False
- )
-
- def refresh_sales_data():
- beer_codes = keg_system.get_beer_codes()
- shopify_locations = keg_system.get_locations_with_shopify_mapping()
- return gr.update(choices=beer_codes, value=None), gr.update(choices=shopify_locations, value=None)
-
- def calculate_location_sales_analysis_ui(beer_code, location, tap_in_date, tap_in_time, tap_out_date, tap_out_time):
- try:
- if not beer_code or not location:
- return "Please select both beer code and location first."
-
- if not tap_in_date:
- return "Start date is required."
-
- sales_result = keg_system.calculate_location_sales_analysis(
- beer_code, location, tap_in_date, tap_in_time,
- tap_out_date if tap_out_date else None,
- tap_out_time if tap_out_time else None,
- debug_mode=True
- )
-
- if isinstance(sales_result, str):
- return sales_result
-
- result_text = f"Location Sales Analysis Results:\n"
- result_text += f"Analysis Method: Shopify Orders API Integration\n\n"
-
- result_text += f"Beer Code: {sales_result['beer_code']}\n"
- result_text += f"Location: {sales_result['location']}\n"
- result_text += f"Analysis Period: {sales_result['tap_in_datetime']} to {sales_result['tap_out_datetime']}\n"
- result_text += f"Items Sold: {sales_result['total_items_sold']}\n"
- result_text += f"Total Sales Volume: {sales_result['total_sales_volume']:.2f}L\n\n"
-
- if 'daily_breakdown' in sales_result and sales_result['daily_breakdown']:
- result_text += f"DETAILED DAILY BREAKDOWN:\n"
- for day_data in sales_result['daily_breakdown']:
- result_text += f"📅 {day_data['date']} ({day_data.get('period_type', 'Full Day')}):\n"
- result_text += f" Time Range: {day_data['start_time']} - {day_data['end_time']}\n"
- result_text += f" Items: {day_data['items_count']} | Volume: {day_data['volume']:.3f}L\n"
- result_text += f" Orders Processed: {day_data['orders_count']}\n\n"
-
- if 'order_details' in sales_result and sales_result['order_details']:
- result_text += f"ORDER DETAILS ({len(sales_result['order_details'])}):\n"
- for i, order in enumerate(sales_result['order_details'], 1):
- result_text += f"{i:2d}. Order {order['order_id']} | {order['product']} | "
- result_text += f"Qty: {order['qty']} | Vol: {order['volume']:.3f}L"
- if 'date' in order:
- result_text += f" | Date: {order['date']}"
- result_text += "\n"
- result_text += "\n"
-
- result_text += f"Data Source: {sales_result.get('data_source', 'Unknown')}\n"
- if sales_result.get('api_error'):
- result_text += f"API Error: {sales_result['api_error']}\n"
-
- return result_text
- except Exception as e:
- return f"Error calculating sales: {str(e)}"
-
- def clear_sales_fields():
- return [
- None, None, get_singapore_now().date().strftime("%Y-%m-%d"),
- "10:00", "", "22:00", "",
- ]
-
- def get_sales_history():
- try:
- return keg_system.get_location_sales_history()
- except Exception as e:
- return pd.DataFrame()
-
- refresh_sales_data_btn.click(refresh_sales_data, outputs=[sales_beer_code, sales_location])
-
- calculate_sales_btn.click(
- calculate_location_sales_analysis_ui,
- inputs=[sales_beer_code, sales_location, sales_tap_in_date, sales_tap_in_time,
- sales_tap_out_date, sales_tap_out_time],
- outputs=sales_results
- )
-
- clear_sales_fields_btn.click(
- clear_sales_fields,
- outputs=[sales_beer_code, sales_location, sales_tap_in_date, sales_tap_in_time,
- sales_tap_out_date, sales_tap_out_time, sales_results]
- )
-
- connect_shopify_sales_btn.click(setup_shopify_with_token, outputs=[sales_results])
-
- app.load(get_sales_history, outputs=sales_history_table)
- app.load(refresh_shopify_connected_locations, outputs=[dynamic_retail_location_selector, retail_status])
-
- # Tab 5: Transaction History
- with gr.TabItem("📋 Transaction History"):
- gr.Markdown("### Transaction Reports")
-
- with gr.Row():
- report_start_date = gr.Textbox(
- label="Start Date (YYYY-MM-DD)",
- value=(get_singapore_now() - timedelta(days=7)).date().strftime("%Y-%m-%d"),
- scale=1
- )
- report_end_date = gr.Textbox(
- label="End Date (YYYY-MM-DD)",
- value=get_singapore_now().date().strftime("%Y-%m-%d"),
- scale=1
- )
-
- with gr.Row():
- user_filter_dropdown = gr.Dropdown(
- choices=["All Users"] + keg_system.get_users(),
- label="Filter by User",
- value="All Users",
- scale=1
- )
- location_filter_dropdown = gr.Dropdown(
- choices=["All Locations"] + keg_system.get_locations(),
- label="Filter by Location",
- value="All Locations",
- scale=1
- )
- transaction_type_filter_dropdown = gr.Dropdown(
- choices=["All Transaction Types"] + keg_system.get_transaction_types(),
- label="Filter by Transaction Type",
- value="All Transaction Types",
- scale=1
- )
-
- with gr.Row():
- generate_report_btn = gr.Button("Generate Report", variant="primary")
- copy_report_btn = gr.Button("Copy for Excel", variant="primary")
- clear_all_filters_btn = gr.Button("Clear Filters", variant="primary")
-
- report_table = gr.Dataframe(
- value=pd.DataFrame(), label="Transaction History Report", interactive=False, wrap=True
- )
-
- report_excel_output = gr.Textbox(
- label="Excel Format Data", value="", interactive=False, lines=4, visible=False
- )
-
- def generate_transaction_report(start_date, end_date, user_filter, location_filter, transaction_type_filter):
- try:
- final_user_filter = None if user_filter == "All Users" else user_filter
- final_location_filter = None if location_filter == "All Locations" else location_filter
- final_transaction_type_filter = None if transaction_type_filter == "All Transaction Types" else transaction_type_filter
-
- report_df = keg_system.get_transactions_report(
- start_date, end_date,
- final_user_filter,
- final_location_filter,
- final_transaction_type_filter
- )
-
- if 'action_timestamp' in report_df.columns and not report_df.empty:
- report_df['action_timestamp_formatted'] = pd.to_datetime(report_df['action_timestamp']).apply(
- lambda x: format_singapore_time(x) if pd.notnull(x) else ''
- )
- report_df = report_df.drop('action_timestamp', axis=1)
- report_df.rename(columns={'action_timestamp_formatted': 'Action Time (SGT)'}, inplace=True)
-
- return report_df
- except Exception as e:
- print(f"Error generating report: {str(e)}")
- return pd.DataFrame()
-
- def copy_report_for_excel(df_data):
- excel_text = create_excel_copy_text(df_data)
- if excel_text:
- return gr.update(visible=True, value=excel_text)
- else:
- return gr.update(visible=False, value="No data to copy")
-
- def clear_all_transaction_filters():
- return [
- (get_singapore_now() - timedelta(days=7)).date().strftime("%Y-%m-%d"),
- get_singapore_now().date().strftime("%Y-%m-%d"),
- "All Users",
- "All Locations",
- "All Transaction Types",
- pd.DataFrame(),
- gr.update(visible=False, value="")
- ]
-
- generate_report_btn.click(
- generate_transaction_report,
- inputs=[report_start_date, report_end_date, user_filter_dropdown, location_filter_dropdown, transaction_type_filter_dropdown],
- outputs=[report_table]
- )
-
- copy_report_btn.click(copy_report_for_excel, inputs=[report_table], outputs=[report_excel_output])
-
- clear_all_filters_btn.click(
- clear_all_transaction_filters,
- outputs=[report_start_date, report_end_date, user_filter_dropdown, location_filter_dropdown, transaction_type_filter_dropdown, report_table, report_excel_output]
- )
-
- # Tab 6: Administration
- with gr.TabItem("⚙️ Administration"):
- gr.Markdown("### System Administration")
-
- with gr.Tabs():
- with gr.TabItem("User Management"):
- gr.Markdown("#### User Management")
- with gr.Row():
- new_user_name = gr.Textbox(label="Username", placeholder="Enter username")
- new_user_role = gr.Dropdown(choices=["user", "admin"], label="Role", value="user")
- add_user_btn = gr.Button("Add User", variant="primary")
-
- user_add_output = gr.Textbox(label="Status", interactive=False, lines=2)
-
- def add_user_and_refresh(name, role):
- result = keg_system.add_user(name, role)
- return result
-
- add_user_btn.click(add_user_and_refresh, inputs=[new_user_name, new_user_role], outputs=[user_add_output])
-
- with gr.TabItem("Location Management"):
- gr.Markdown("#### Location Management")
- gr.Markdown("*Add locations for inventory management*")
-
- with gr.Row():
- new_location_name = gr.Textbox(label="Location Name", placeholder="Enter location name")
- add_location_btn = gr.Button("Add Location", variant="primary")
- view_locations_btn = gr.Button("View All Locations", variant="primary")
-
- location_add_output = gr.Textbox(label="Status", interactive=False, lines=2)
- locations_output = gr.Textbox(label="All Locations", interactive=False, lines=6)
-
- def get_all_locations():
- try:
- locations = keg_system.get_locations()
- shopify_locations = keg_system.get_locations_with_shopify_mapping()
-
- if not locations:
- return "No locations found."
-
- result = f"All Locations ({len(locations)}):\n\n"
-
- mapped_locations = []
- unmapped_locations = []
-
- for location in locations:
- if location in shopify_locations:
- mapped_locations.append(location)
- else:
- unmapped_locations.append(location)
-
- if mapped_locations:
- result += f"✓ Shopify-Connected ({len(mapped_locations)}):\n"
- result += f" {', '.join(mapped_locations)}\n\n"
-
- if unmapped_locations:
- result += f"⚠️ Not Shopify-Connected ({len(unmapped_locations)}):\n"
- result += f" {', '.join(unmapped_locations)}\n"
- result += f" (Wholesale/delivery locations - excluded from yield analysis)\n"
-
- return result
- except Exception as e:
- return f"Error getting locations: {str(e)}"
-
- def add_location_simple(location_name):
- if not location_name or not location_name.strip():
- return "Please enter a location name"
-
- result = keg_system.add_location(location_name.strip())
-
- if keg_system.shopify_client:
- keg_system.shopify_client.refresh_location_mappings()
-
- return result
-
- add_location_btn.click(add_location_simple, inputs=new_location_name, outputs=location_add_output)
- view_locations_btn.click(get_all_locations, outputs=locations_output)
-
- with gr.TabItem("Shopify API"):
- gr.Markdown("#### Shopify API Configuration")
- gr.Markdown("*Connect to Shopify for sales data and location management*")
-
- with gr.Group():
- gr.Markdown("**API Connection:**")
- with gr.Row():
- shopify_access_token = gr.Textbox(
- label="Shopify Access Token",
- value="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",
- placeholder="Enter your Shopify access token",
- type="password",
- info="Private app access token from Shopify admin"
- )
- save_token_btn = gr.Button("Save Token", variant="primary")
- test_connection_btn = gr.Button("Test Connection", variant="primary")
-
- connection_status = gr.Textbox(label="Connection Status", interactive=False, lines=3)
-
- gr.Markdown("---")
-
- with gr.Tabs():
- with gr.TabItem("Beer Keywords"):
- gr.Markdown("**Beer Keywords for Product Matching**")
-
- with gr.Row():
- refresh_beer_codes_btn = gr.Button("Refresh Beer Codes", variant="primary")
- view_keywords_btn = gr.Button("Refresh Keywords", variant="primary")
-
- with gr.Row():
- keyword_beer_code = gr.Dropdown(
- choices=keg_system.get_beer_codes(), label="Beer Code", value=None
- )
- keyword_text = gr.Textbox(label="Keyword", placeholder="Enter search keyword")
- add_keyword_btn = gr.Button("Add Keyword", variant="primary")
-
- keyword_add_output = gr.Textbox(label="Status", interactive=False, lines=2)
- keywords_display = gr.Textbox(label="Current Beer Keywords", interactive=False, lines=6)
-
- def add_beer_keyword_ui(beer_code, keyword):
- if not beer_code or not keyword:
- return "Please select beer code and enter keyword"
- return keg_system.add_beer_keyword(beer_code, keyword)
-
- def display_all_keywords():
- try:
- keywords = keg_system.get_beer_keywords()
- if not keywords:
- return "No keywords configured"
-
- result = "Beer Keywords Configuration:\n\n"
- current_beer = None
- for beer_code, keyword in keywords:
- if beer_code != current_beer:
- if current_beer is not None:
- result += "\n"
- result += f"{beer_code}:\n"
- current_beer = beer_code
- result += f" • {keyword}\n"
- return result
- except Exception as e:
- return f"Error loading keywords: {str(e)}"
-
- def refresh_beer_codes_dropdown():
- updated_choices = keg_system.get_beer_codes()
- return gr.update(choices=updated_choices, value=None)
-
- def refresh_keywords_and_beer_codes():
- keywords_text = display_all_keywords()
- updated_choices = keg_system.get_beer_codes()
- return keywords_text, gr.update(choices=updated_choices, value=None)
-
- add_keyword_btn.click(
- add_beer_keyword_ui,
- inputs=[keyword_beer_code, keyword_text],
- outputs=keyword_add_output
- )
-
- view_keywords_btn.click(
- refresh_keywords_and_beer_codes,
- outputs=[keywords_display, keyword_beer_code]
- )
-
- refresh_beer_codes_btn.click(refresh_beer_codes_dropdown, outputs=keyword_beer_code)
-
- with gr.TabItem("Exclude Keywords"):
- gr.Markdown("**Keywords to Exclude from Product Matching**")
-
- view_exclude_keywords_btn = gr.Button("Refresh Exclude Keywords", variant="primary")
-
- with gr.Row():
- exclude_keyword_text = gr.Textbox(
- label="Exclude Keyword",
- placeholder="Enter keyword to exclude"
- )
- add_exclude_keyword_btn = gr.Button("Add Exclude Keyword", variant="primary")
-
- exclude_add_output = gr.Textbox(label="Status", interactive=False, lines=2)
- exclude_keywords_display = gr.Textbox(
- label="Current Exclude Keywords", interactive=False, lines=4
- )
-
- def add_exclude_keyword_ui(keyword):
- if not keyword:
- return "Please enter keyword to exclude"
- return keg_system.add_exclude_keyword(keyword)
-
- def display_all_exclude_keywords():
- try:
- keywords = keg_system.get_exclude_keywords()
- if not keywords:
- return "No exclude keywords configured"
-
- result = "Exclude Keywords Configuration:\n\n"
- for keyword in keywords:
- result += f"• {keyword}\n"
- return result
- except Exception as e:
- return f"Error loading exclude keywords: {str(e)}"
-
- add_exclude_keyword_btn.click(
- add_exclude_keyword_ui,
- inputs=exclude_keyword_text,
- outputs=exclude_add_output
- )
-
- view_exclude_keywords_btn.click(
- display_all_exclude_keywords,
- outputs=exclude_keywords_display
- )
-
- with gr.TabItem("Location Mapping"):
- gr.Markdown("**Location Mapping Management**")
- gr.Markdown("*Configure location mappings with Shopify location IDs*")
-
- with gr.Row():
- view_mappings_btn = gr.Button("Refresh Mappings", variant="primary")
- refresh_location_choices_btn = gr.Button("Refresh Location Lists", variant="primary")
-
- with gr.Group():
- gr.Markdown("**Add New Location Mapping:**")
- with gr.Row():
- mapping_inventory_location = gr.Dropdown(
- choices=keg_system.get_locations(),
- label="Inventory Location", value=None
- )
- mapping_pos_location = gr.Textbox(
- label="Shopify POS Location",
- placeholder="Enter POS location name",
- info="Exact name as shown in Shopify POS"
- )
- mapping_shopify_id = gr.Textbox(
- label="Shopify Location ID",
- placeholder="Enter Shopify location ID",
- info="Numeric ID from Shopify admin"
- )
- add_mapping_btn = gr.Button("Add Mapping", variant="primary")
-
- with gr.Group():
- gr.Markdown("**Archive Management:**")
- with gr.Row():
- archive_location_dropdown = gr.Dropdown(
- choices=[],
- label="Select Location to Archive/Activate",
- value=None
- )
- archive_btn = gr.Button("Archive Location", variant="primary")
- activate_btn = gr.Button("Activate Location", variant="primary")
-
- mapping_add_output = gr.Textbox(label="Status", interactive=False, lines=3)
- archive_output = gr.Textbox(label="Archive Status", interactive=False, lines=2)
- mappings_display = gr.Textbox(label="Current Location Mappings", interactive=False, lines=10)
-
- def add_location_mapping_ui(inv_location, pos_location, shopify_id):
- if not inv_location or not pos_location:
- return "Please select inventory location and enter POS location"
-
- shopify_location_id = None
- if shopify_id and shopify_id.strip():
- shopify_location_id = shopify_id.strip()
-
- result = keg_system.add_location_mapping(inv_location, pos_location, shopify_location_id)
-
- if keg_system.shopify_client:
- keg_system.shopify_client.refresh_location_mappings()
-
- return result
-
- def display_all_mappings():
- try:
- mappings = keg_system.get_location_mappings()
- if not mappings:
- return "No location mappings configured"
-
- result = "Location Mapping Configuration:\n\n"
- active_count = 0
- archived_count = 0
-
- primary_mappings = []
- other_mappings = []
-
- for inv_loc, pos_loc, shopify_id, is_active, is_archived, updated_at in mappings:
- status_indicators = []
- if is_archived:
- status_indicators.append("ARCHIVED")
- archived_count += 1
- else:
- active_count += 1
-
- status_text = f" [{', '.join(status_indicators)}]" if status_indicators else ""
-
- mapping_line = f"• {inv_loc} → {pos_loc}"
- if shopify_id:
- mapping_line += f" (ID: {shopify_id})"
- mapping_line += status_text
-
- if inv_loc in PRIMARY_LOCATIONS:
- primary_mappings.append(mapping_line)
- else:
- other_mappings.append(mapping_line)
-
- if primary_mappings:
- result += "PRIMARY LOCATIONS:\n"
- for mapping in primary_mappings:
- result += f"{mapping}\n"
- result += "\n"
-
- if other_mappings:
- result += "OTHER LOCATIONS:\n"
- for mapping in other_mappings:
- result += f"{mapping}\n"
- result += "\n"
-
- result += f"Summary: {active_count} active, {archived_count} archived"
- return result
- except Exception as e:
- return f"Error loading mappings: {str(e)}"
-
- def refresh_archive_dropdown():
- try:
- mappings = keg_system.get_location_mappings()
- location_choices = []
- for inv_loc, pos_loc, shopify_id, is_active, is_archived, updated_at in mappings:
- status = "ARCHIVED" if is_archived else "ACTIVE"
- choice_label = f"{inv_loc} ({status})"
- location_choices.append(choice_label)
-
- return gr.update(choices=location_choices, value=None)
- except Exception as e:
- return gr.update(choices=[], value=None)
-
- def archive_location_action(selected_location, archive=True):
- if not selected_location:
- return "Please select a location"
-
- location_name = selected_location.split(' (')[0]
-
- result = keg_system.archive_location_mapping(location_name, archive)
- return result
-
- def refresh_all_location_data():
- mappings_text = display_all_mappings()
- updated_location_choices = keg_system.get_locations()
- updated_archive_choices = []
-
- try:
- mappings = keg_system.get_location_mappings()
- for inv_loc, pos_loc, shopify_id, is_active, is_archived, updated_at in mappings:
- status = "ARCHIVED" if is_archived else "ACTIVE"
- choice_label = f"{inv_loc} ({status})"
- updated_archive_choices.append(choice_label)
- except:
- pass
-
- return (
- mappings_text,
- gr.update(choices=updated_location_choices, value=None),
- gr.update(choices=updated_archive_choices, value=None)
- )
-
- add_mapping_btn.click(
- add_location_mapping_ui,
- inputs=[mapping_inventory_location, mapping_pos_location, mapping_shopify_id],
- outputs=mapping_add_output
- )
-
- view_mappings_btn.click(
- refresh_all_location_data,
- outputs=[mappings_display, mapping_inventory_location, archive_location_dropdown]
- )
-
- refresh_location_choices_btn.click(
- refresh_all_location_data,
- outputs=[mappings_display, mapping_inventory_location, archive_location_dropdown]
- )
-
- archive_btn.click(
- lambda loc: archive_location_action(loc, True),
- inputs=archive_location_dropdown,
- outputs=archive_output
- )
-
- activate_btn.click(
- lambda loc: archive_location_action(loc, False),
- inputs=archive_location_dropdown,
- outputs=archive_output
- )
-
- def save_shopify_token(access_token):
- if not access_token:
- return "Please enter an access token"
-
- # Save token to database (this will overwrite any existing token)
- keg_system.save_api_token('shopify', access_token)
-
- # Set the token for the current session
- result = keg_system.set_shopify_access_token(access_token)
-
- return f"✓ Token saved to database and activated\n{result}\n\nThis token will now be used by all 'Connect to Shopify API' buttons."
-
- def test_shopify_connection():
- if not keg_system.shopify_client:
- return "Please save an access token first"
-
- success, message = keg_system.shopify_client.test_connection()
-
- if success:
- return f"✅ CONNECTION SUCCESSFUL (API 2024-10)\n{message}\n\nShopify Orders API ready for yield calculations!"
- else:
- return f"❌ CONNECTION FAILED\n{message}\n\nPlease check your access token."
-
- save_token_btn.click(save_shopify_token, inputs=[shopify_access_token], outputs=connection_status)
- test_connection_btn.click(test_shopify_connection, outputs=connection_status)
-
- # Load initial data
- app.load(
- lambda: update_inventory_overview("All Beer Codes", "All Locations", "All Status"),
- outputs=[inventory_plot, plot_state, inventory_summary, inventory_table]
- )
-
- gr.Markdown("---")
- gr.Markdown("**Pink Blossoms Brewing - Keg Management System**")
-
- return app
-
-def main():
- if keg_system is None:
- print("❌ System initialization failed. Please check the error messages above.")
- return
-
- print("\n" + "="*80)
- print("🌸 PINK BLOSSOMS BREWING - KEG MANAGEMENT SYSTEM")
- print("="*80)
- print(f"✓ Database: {keg_system.db_name}")
- print(f"✓ Singapore Time: {format_singapore_time(get_singapore_now())}")
- print("✓ FEATURES:")
- print(" • Dynamic location support for Shopify integration")
- print(" • Form persistence with auto-save")
- print(" • Individual keg yield calculation buttons")
- print(" • Location-based sales analysis (independent of keg data)")
- print(" • Enhanced location mapping and management")
- print(" • Support for up to 20 kegs in Others section")
- print("="*80)
-
- try:
- app = create_web_interface()
- print("✓ Web interface created successfully")
-
- print("\n🚀 Launching Pink Blossoms Brewing System...")
-
- for port in range(7860, 7870):
- try:
- app.launch(
- server_name="0.0.0.0", server_port=port, share=True,
- inbrowser=True, show_error=True, debug=False
- )
- print(f"✅ Successfully launched on port {port}")
- break
- except Exception as e:
- if "port" in str(e).lower() or "address already in use" in str(e).lower():
- print(f"Port {port} busy, trying next...")
- continue
- else:
- raise e
- else:
- print("❌ Could not find available port")
-
- except Exception as e:
- print(f"❌ Launch failed: {str(e)}")
- print("\nTroubleshooting:")
- print("1. Make sure all required packages are installed")
- print("2. Check if another Gradio app is running")
- print("3. Restart the kernel and try again")
-
-if __name__ == "__main__":
- main()
\ No newline at end of file