File size: 4,255 Bytes
5617381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pandas as pd
import warnings
import os
from huggingface_hub import hf_hub_download
warnings.filterwarnings('ignore')

backlog_df = None

def initialize_data():
    global backlog_df
    
    try:
        print("Checking for data files...")
        
        repo_id = os.environ.get("SPACE_ID", "Niketha123/open-order-quantity")
        print(f"Repository: {repo_id}")
        
        try:
            print("Downloading BACKLOG.xlsx from Hugging Face...")
            file_path = hf_hub_download(
                repo_id=repo_id,
                filename="BACKLOG.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}")
            file_path = "BACKLOG.xlsx"
        
        print(f"Loading data from: {file_path}")
        backlog_df = pd.read_excel(file_path)
        print(f"βœ… Successfully loaded {len(backlog_df):,} rows")
        print(f"Columns: {list(backlog_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_open_quantity_orders():
    if backlog_df is None:
        return pd.DataFrame({"Message": ["⚠️ Data not loaded. Check logs for details."]})
    
    try:
        open_orders = []
        
        print(f"Processing {len(backlog_df):,} rows...")
        
        for idx, row in backlog_df.iterrows():
            open_qty = float(row.get('OPEN_QUANTITY_OF_SO', 0))
            unit_price = float(row.get('UNIT_PRICE', 0))
            
            if open_qty > 0:
                open_value = open_qty * unit_price
                
                open_orders.append({
                    'Sales Order': row.get('SALES_ORDER_NO', 'N/A'),
                    'Material ID': row.get('SAP_MATERIAL_NO', 'N/A'),
                    'Open Quantity': f"{open_qty:,.0f}",
                    'Open Value': f"${open_value:,.2f}",
                    'Supplier': row.get('SUPPLIER_NAME', 'N/A'),
                    'Sort_Value': open_value
                })
        
        print(f"βœ… Found {len(open_orders):,} open orders")
        
        df = pd.DataFrame(open_orders)
        
        if len(df) > 0:
            df = df.sort_values('Sort_Value', ascending=False)
            df = df.drop(columns=['Sort_Value'])
            df = df.reset_index(drop=True)
        
        return df if len(df) > 0 else pd.DataFrame({"Message": ["No open quantity 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 Open Order Quantity Dashboard...")
    print("=" * 60)
    
    data_loaded = initialize_data()
    print(f"Data loaded status: {data_loaded}")
    
    with gr.Blocks(title="Open Order Quantity", theme=gr.themes.Soft()) as dashboard:
        gr.Markdown("# πŸ“¦ Open Order Quantity")
        
        if not data_loaded:
            gr.Markdown("""
            ⚠️ **Error loading data files.**
            
            The data file may be in Git LFS. Check the Container logs for details.
            """)
        
        open_qty_table = gr.Dataframe(
            value=get_open_quantity_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_open_quantity_orders, outputs=open_qty_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="πŸ“Š Open Order Quantity - Enter Your Credentials"
    )