File size: 4,559 Bytes
06fe428
 
 
58c63d2
df8af26
06fe428
 
 
 
 
 
58c63d2
06fe428
58c63d2
 
df8af26
 
 
58c63d2
df8af26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06fe428
58c63d2
06fe428
58c63d2
 
 
06fe428
 
 
 
58c63d2
06fe428
 
 
58c63d2
df8af26
58c63d2
06fe428
 
 
 
 
 
 
 
de5f10d
 
06fe428
 
df8af26
58c63d2
06fe428
de5f10d
 
 
 
 
 
 
 
 
06fe428
58c63d2
06fe428
58c63d2
 
 
06fe428
 
 
df8af26
 
 
 
06fe428
58c63d2
06fe428
 
 
 
58c63d2
 
 
 
df8af26
58c63d2
 
06fe428
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
add1c3f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import gradio as gr
import pandas as pd
import warnings
import os
from huggingface_hub import hf_hub_download
warnings.filterwarnings('ignore')

billing_df = None

def initialize_data():
    global billing_df
    
    try:
        print("Checking for data files...")
        
        # For LFS files, we need to use hf_hub_download
        # Get the repo info from environment variables
        repo_id = os.environ.get("SPACE_ID", "Niketha123/orders-fulfilled")
        
        print(f"Repository: {repo_id}")
        
        try:
            # Download the file from HF hub (handles LFS automatically)
            print("Downloading BILLING.xlsx from Hugging Face...")
            file_path = hf_hub_download(
                repo_id=repo_id,
                filename="BILLING.xlsx",
                repo_type="space"
            )
            print(f"βœ… File downloaded to: {file_path}")
            
        except Exception as e:
            print(f"Could not download from hub, trying local path: {e}")
            # Fall back to local path
            file_path = "BILLING.xlsx"
        
        # Load the Excel file
        print(f"Loading data from: {file_path}")
        billing_df = pd.read_excel(file_path)
        print(f"βœ… Successfully loaded {len(billing_df):,} rows")
        print(f"Columns: {list(billing_df.columns)[:10]}")
        return True
        
    except Exception as e:
        print(f"❌ Error loading data: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

def get_fulfilled_orders():
    if billing_df is None:
        return pd.DataFrame({"Message": ["⚠️ Data not loaded. Check logs for details."]})
    
    try:
        fulfilled_orders = []
        
        print(f"Processing {len(billing_df):,} rows...")
        
        for idx, row in billing_df.iterrows():
            billing_qty = float(row.get('BILLING_QUANTITY', 0))
            extended_resale = float(row.get('EXTENDED_RESALE_USD', 0))
            
            if billing_qty > 0:
                fulfilled_orders.append({
                    'Sales Order': row.get('SALES_ORDER_NO', 'N/A'),
                    'End Customer': row.get('END_CUSTOMER_NAME', 'N/A'),
                    'Order Value': f"${extended_resale:,.2f}",
                    'Sort_Value': extended_resale  # Numeric value for sorting
                })
        
        print(f"βœ… Found {len(fulfilled_orders):,} fulfilled orders")
        
        df = pd.DataFrame(fulfilled_orders)
        
        if len(df) > 0:
            # Sort by numeric value in descending order (highest first)
            df = df.sort_values('Sort_Value', ascending=False)
            # Drop the sorting column before displaying
            df = df.drop(columns=['Sort_Value'])
            # Reset index for clean display
            df = df.reset_index(drop=True)
        
        return df if len(df) > 0 else pd.DataFrame({"Message": ["No fulfilled orders found"]})
        
    except Exception as e:
        print(f"❌ Error processing orders: {str(e)}")
        import traceback
        traceback.print_exc()
        return pd.DataFrame({"Error": [str(e)]})

def create_dashboard():
    print("=" * 60)
    print("Initializing Orders Fulfilled Dashboard...")
    print("=" * 60)
    
    data_loaded = initialize_data()
    print(f"Data loaded status: {data_loaded}")
    
    with gr.Blocks(title="Orders Fulfilled", theme=gr.themes.Soft()) as dashboard:
        gr.Markdown("# βœ… Orders Fulfilled")
        
        if not data_loaded:
            gr.Markdown("""
            ⚠️ **Error loading data files.**
            
            The data file may be in Git LFS. Check the Container logs for details.
            """)
        
        fulfilled_table = gr.Dataframe(
            value=get_fulfilled_orders() if data_loaded else pd.DataFrame({"Message": ["Data not loaded"]}),
            wrap=True
        )
        
        refresh_btn = gr.Button("πŸ”„ Refresh", variant="secondary")
        refresh_btn.click(fn=get_fulfilled_orders, outputs=fulfilled_table)
    
    return dashboard

if __name__ == "__main__":
    dashboard = create_dashboard()
    dashboard.launch(
        server_name="0.0.0.0",
        server_port=7860,
        ssr_mode=False,
        auth=[
            ("kinnari", "alert2025"),
            ("neha", "alert2025"),
            ("niketha", "alert2025"),
            ("sahith", "alert2025"),
            ("shriya", "alert2025"),
        ],
        auth_message="πŸ“Š Orders Fulfilled - Enter Your Credentials"
    )