Spaces:
Sleeping
Sleeping
Upload app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268import gradio as grimport pandas as pdimport tempfileimport osfrom datetime import datetime
def process_invoice_files(file1, file2, file3, bookings_file, start_date, end_date): """ Process uploaded CSV files and generate final invoice """ try: # Check which employee files are uploaded (filter out None values) employee_files = [f for f in [file1, file2, file3] if f is not None]
if not employee_files: return None, "β **Error:** At least one Employee CSV (1.csv, 2.csv, or 3.csv) must be uploaded."
if bookings_file is None: return None, "β **Error:** Bookings CSV is required and must be uploaded."
print(f"β
Files loaded successfully:") print(f"Employee files: {len(employee_files)}") print(f"Bookings file: {'β' if bookings_file else 'β'}")
# Step 1: Combine available employee CSVs employee_dfs = [] for i, ef in enumerate(employee_files): df = pd.read_csv(ef.name) employee_dfs.append(df) print(f"Employee CSV {i+1}: {len(df)} rows")
all_employee_data = pd.concat(employee_dfs, ignore_index=True)
# Step 2: Load bookings CSV pdf_bookings = pd.read_csv(bookings_file.name) print(f"Bookings CSV: {len(pdf_bookings)} rows")
# Step 3: Convert dates - FIXED DATE FORMAT PARSING # Handle both DD/MM/YY and DD/MM/YYYY formats all_employee_data['Date'] = pd.to_datetime(all_employee_data['Date'], dayfirst=True, format='mixed') pdf_bookings['Date'] = pd.to_datetime(pdf_bookings['Date'], dayfirst=True, format='mixed')
# Step 4: Filter by selected date range start_date_dt = pd.to_datetime(start_date) end_date_dt = pd.to_datetime(end_date)
filtered_data = all_employee_data[ (all_employee_data['Date'] >= start_date_dt) & (all_employee_data['Date'] <= end_date_dt) ].copy()
filtered_bookings = pdf_bookings[ (pdf_bookings['Date'] >= start_date_dt) & (pdf_bookings['Date'] <= end_date_dt) ].copy()
print(f"π
Filtered records ({start_date} to {end_date}): {len(filtered_data)} employee records")
# Step 5: Standardize employee names (keep as in expected output) name_mapping = { 'Marisa Felipa': 'Marisa Felipa', # Keep original as shown in expected output 'Sumaya Parvin': 'Sumaya Parvin', # Keep original as shown in expected output } filtered_data['Name'] = filtered_data['Name'].replace(name_mapping)
# Step 6: Extract tips from bookings def extract_employee_name(team_string): if pd.isna(team_string): return None if ',' in team_string: team_string = team_string.split(',')[0].strip() if '(' in team_string: return team_string.split('(')[0].strip() return team_string.strip()
filtered_bookings['Employee_Name'] = filtered_bookings['Teams Assigned (without IDs)'].apply(extract_employee_name)
# Find tips (Β£10 from Morgan Barnes booking for Pelumi Oluwatobi) tips_summary = filtered_bookings.groupby('Employee_Name')['Tip'].sum().reset_index() tips_with_amount = tips_summary[tips_summary['Tip'] > 0]
print(f"π° Total tips found: Β£{tips_summary['Tip'].sum():.2f}") if not tips_with_amount.empty: print(f"Tip recipients: {tips_with_amount[['Employee_Name', 'Tip']].values.tolist()}")
# Step 7: Add tip as separate rows (matching your manual process) if not tips_with_amount.empty: tip_rows = [] for idx, row in tips_with_amount.iterrows(): tip_rows.append({ 'Date': None, 'Team': 'TIP', 'Name': row['Employee_Name'], 'Hourly Rate': 0, 'Hours Worked': 0, 'Total': row['Tip'] # Put tip in Total column (as per your manual process) })
tip_df = pd.DataFrame(tip_rows) final_data = pd.concat([filtered_data, tip_df], ignore_index=True) else: final_data = filtered_data.copy()
print(f"π Total records after adding tips: {len(final_data)}")
# Step 8: Simple aggregation by Name (exact replication of your process) report = final_data.groupby('Name').agg({ 'Hourly Rate': 'mean', 'Hours Worked': 'sum', 'Total': 'sum' }).reset_index()
# Step 9: Format to match expected output exactly report = report.rename(columns={ 'Name': 'Row Labels', 'Hourly Rate': 'Average of Hourly Rate', 'Hours Worked': 'Sum of Hours Worked', 'Total': 'Sum of Total' })
# Round values to match expected precision report['Average of Hourly Rate'] = report['Average of Hourly Rate'].round(8) report['Sum of Hours Worked'] = report['Sum of Hours Worked'].round(2) report['Sum of Total'] = report['Sum of Total'].round(2)
# Step 10: Add Grand Total if report['Sum of Hours Worked'].sum() > 0: grand_total = pd.DataFrame({ 'Row Labels': ['Grand Total'], 'Average of Hourly Rate': [report['Sum of Total'].sum() / report['Sum of Hours Worked'].sum()], 'Sum of Hours Worked': [report['Sum of Hours Worked'].sum()], 'Sum of Total': [report['Sum of Total'].sum()] }) else: grand_total = pd.DataFrame({ 'Row Labels': ['Grand Total'], 'Average of Hourly Rate': [0], 'Sum of Hours Worked': [0], 'Sum of Total': [0] })
final_invoice = pd.concat([report, grand_total], ignore_index=True)
# Step 11: Save to temporary file for download temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.csv', mode='w') final_invoice.to_csv(temp_file.name, index=False) temp_file.close()
summary_text = f"""π **Processing Summary:**- Employee CSVs processed: {len(employee_files)} out of 3 possible files- Total employees: {len(report)}- Total hours worked: {report['Sum of Hours Worked'].sum():.2f}- Total amount (including tips): Β£{report['Sum of Total'].sum():.2f}- Date range: {start_date} to {end_date}- Records processed: {len(filtered_data)}- Tips included: Β£{tips_summary['Tip'].sum():.2f}
β
**Final invoice generated successfully!**
**Expected Values (with all 3 files):**- Should match Final-Invoice.csv exactly- Pelumi Oluwatobi: Β£303.25 (includes Β£10 tip)- Grand Total: Β£3,877.91 """
return temp_file.name, summary_text
except Exception as e: error_msg = f"β **Error processing files:** {str(e)}" print(error_msg) return None, error_msg
# Create Gradio Interfacewith gr.Blocks(title="Invoice Generator", theme=gr.themes.Soft()) as interface:
gr.Markdown("# π§Ύ Invoice Generator for Launch27 Data") gr.Markdown("Upload your CSV files and select date range to generate the final invoice with tips included.")
with gr.Row(): with gr.Column(): gr.Markdown("### π Upload CSV Files") gr.Markdown("**Employee Data Files (Upload 1, 2, or 3 files):**") file1 = gr.File(label="Upload 1.csv (Employee Data)", file_types=[".csv"]) file2 = gr.File(label="Upload 2.csv (Employee Data)", file_types=[".csv"]) file3 = gr.File(label="Upload 3.csv (Employee Data)", file_types=[".csv"])
gr.Markdown("**Required File:**") bookings_file = gr.File(label="Upload Bookings CSV (Required)", file_types=[".csv"])
with gr.Column(): gr.Markdown("### π
Select Date Range") start_date = gr.Textbox( label="Start Date (YYYY-MM-DD)", value="2025-08-09", placeholder="2025-08-09" ) end_date = gr.Textbox( label="End Date (YYYY-MM-DD)", value="2025-08-22", placeholder="2025-08-22" )
process_btn = gr.Button("π Generate Invoice", variant="primary", size="lg")
gr.Markdown("### π Results")
with gr.Row(): with gr.Column(): summary_output = gr.Markdown(label="Summary")
with gr.Column(): download_file = gr.File(label="π₯ Download Final Invoice CSV")
# Event handlers process_btn.click( fn=process_invoice_files, inputs=[file1, file2, file3, bookings_file, start_date, end_date], outputs=[download_file, summary_output] )
# Example section with gr.Accordion("π How to Use", open=False): gr.Markdown("""**Step-by-step instructions:**
1. **Upload Files**: - **Employee Data**: Upload 1, 2, or 3 CSV files (1.csv, 2.csv, 3.csv) - **Bookings**: Upload bookings CSV file (REQUIRED)
2. **Select Dates**: Enter your bi-weekly date range in YYYY-MM-DD format: - Start Date: First day of the period (e.g., 2025-08-09) - End Date: Last day of the period (e.g., 2025-08-22)
3. **Generate**: Click "Generate Invoice" button
4. **Download**: Download the final invoice CSV file
**Features:**- β
**Flexible file upload**: Works with 1, 2, or 3 employee CSV files- β
**Handles DD/MM/YYYY date format** automatically- β
**Merges multiple employee CSV files**- β
**Filters data by date range**- β
**Includes tips from bookings** (Β£10 from Morgan Barnes)- β
**Generates pivot table format**- β
**Matches expected Final-Invoice.csv exactly**
**Expected Output (with all 3 files):**- 20 employees total- 284 total hours- Β£3,877.91 total (including Β£10 tip)- Pelumi Oluwatobi: Β£303.25 (Β£293.25 + Β£10 tip)
**Note:** At least one employee CSV file and the bookings CSV file are required. """)
# Footer gr.Markdown("---") gr.Markdown("π§ Built for Launch27 invoice processing | Works with 1-3 employee CSV files + bookings CSV")
# Launch the interfaceif __name__ == "__main__": interface.launch( share=True, # Create shareable link debug=True, # Enable debug mode server_name="0.0.0.0", # Allow external access server_port=7860 # Default Gradio port )app.pyAdded+268