Natwar commited on
Commit
402feb9
Β·
verified Β·
1 Parent(s): 2f7e39e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -63
app.py CHANGED
@@ -1,14 +1,29 @@
1
  import subprocess
2
  import sys
3
-
4
  # Install openpyxl if not available
5
  try:
6
  import openpyxl
7
  except ImportError:
8
  subprocess.check_call([sys.executable, "-m", "pip", "install", "openpyxl"])
9
  import openpyxl
10
-
11
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  import gradio as gr
14
  import pandas as pd
@@ -20,27 +35,23 @@ from openpyxl.drawing.image import Image as ExcelImage
20
  import random
21
  import base64
22
  from io import BytesIO
23
-
 
24
 
25
  def generate_random_invoice_number():
26
  """Generate random 6-digit invoice number"""
27
  return str(random.randint(100000, 999999))
28
 
29
-
30
  def create_professional_individual_invoice(workbook, employee_data, start_date, end_date):
31
  """Create individual invoice sheet with professional Glimmr template formatting and logo"""
32
-
33
  # --- PASTE YOUR CLEANED BASE64 STRING HERE ---
34
  GLIMMR_LOGO_BASE64 = """
35
  iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAnFBMVEX///8An9r/nzcAm9kAmdgAndkAl9fo8/rQ5/Vjt+L/myug0OzU6fb/yZzC4PIAldeBwudPsOCn1O05qd7/3MDk8fn/mSH/59Xd7vh6v+a73fFrvOWy2vD/nC74/P6Hx+n/qVP/rl3/0qshpdz/8ub//PlYteL/1rX/lACUy+r/o0L/5Mv/lxr/uXj/vYH/69r/w4z/t3Mfm83/y6CSnfTNAAAGLElEQVR4nO2cfXeiOBTGiXlBxRGF1iJabIeOHabOtLv9/t9tkxBAq+juWV4OOc/vn0ajOfcxbzf3hjoOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH0wSyd9m9AuCeUi7tuIVllyIqK+jWiTjBG+6duINokE4bxvI1qFyDE67tuINplwQtd9G/F/ePlxvX4rJyHpxpSWeH24Wu0KMvQx+uvpanUox+iiG0va4e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NupzqF+m45Go8fDx8dK/h1Nay/oNMumjBCagviisNoPc4WkyiDStMwC68fxxElDymUoi/rCjVYoNT7qP9NvnQicnWUGaxTOSoVHVHFvNq8UXqrXG6pRaFjVP7jRJJMiu0sL8y8rZMcKq14sU8I6ViPO6iuN4kzhoZt5WBgVBsG/Vkj3ZdabTIwGHW8zjfG0+N3k/CuC/6qtUqFccB4fn2/Z1ggzExZUjnVYzbirClV3FWbfO+O8Bb6vFMrGAlrqNnNVhToKhavPt9enn90M0q2xZPIfFKp0ofksc517E+hfVgrlqjOvfgzTFotKhVP9YNFrJwJLo7MuFXa0xORkxmjPeoX29mGxeKytVRgbS4i1Cu+LBT6zVWGxWxF5VCj2OMsUBmbLr/iicHdDoXtL4aZnhWUnli6kUrioFBpZtQqTWwoXfStMuDGmOAopheYuolIY+dcVmmK9QtNWfwrlj8zUMZwHxiodGV348jhMfRWe8PKiPOJmPlP40j1IRV6UCl2urtMydTrK65lsIc6L+mxv2pI/0befK0VHHukx0XwelT5qHvuNvMU6y3Muri4msjDOkbJmpqhvRse79cJTgR7z5rj66H3ZlsqivjzkXPmnDG1QhpHyCWNfNjD2zb071xyDrLtYoU73i3g8z0z4iNmWlI+ZXkdZEcSw7z88fb3z61txo/mY7Ul8LI+LWsZSlJExOSMHmZO/xXjDhdq/hQgtvNtkSKLxeGZdAg0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgMPwD+p9Y6vy1tXkAAAAASUVORK5CYII=
36
  """
37
-
38
  ws = workbook.create_sheet(title=employee_data['Row Labels'])
39
-
40
  column_widths = {'A': 25, 'B': 15, 'C': 15, 'D': 15, 'E': 15, 'F': 12, 'G': 12, 'H': 12, 'I': 12}
41
  for col, width in column_widths.items():
42
  ws.column_dimensions[col].width = width
43
-
44
  try:
45
  if GLIMMR_LOGO_BASE64.strip() and "PASTE" not in GLIMMR_LOGO_BASE64 and "YOUR BASE64" not in GLIMMR_LOGO_BASE64:
46
  logo_data = base64.b64decode(GLIMMR_LOGO_BASE64.strip())
@@ -51,11 +62,9 @@ def create_professional_individual_invoice(workbook, employee_data, start_date,
51
  ws.add_image(img, 'A1')
52
  except Exception as e:
53
  print(f"Logo embedding failed: {e}")
54
-
55
  # Company name
56
  ws['A6'] = 'Glimmr Ltd'
57
  ws['A6'].font = Font(bold=True, size=16)
58
-
59
  # --- CORRECTED HEADER STRUCTURE TO MATCH ORIGINAL ---
60
  # Main header spanning wider (extended one cell left)
61
  ws.merge_cells('E2:I2')
@@ -63,62 +72,52 @@ def create_professional_individual_invoice(workbook, employee_data, start_date,
63
  ws['E2'].font = Font(bold=True, size=14, color='FFFFFF')
64
  ws['E2'].alignment = Alignment(horizontal='center', vertical='center')
65
  ws['E2'].fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
66
-
67
  # Invoice # header (left side)
68
  ws.merge_cells('E6:F6')
69
  ws['E6'] = 'Invoice #'
70
  ws['E6'].font = Font(bold=True, color='FFFFFF')
71
  ws['E6'].fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
72
  ws['E6'].alignment = Alignment(horizontal='center', vertical='center')
73
-
74
  # Date header (right side)
75
  ws.merge_cells('G6:I6')
76
  ws['G6'] = 'Date'
77
  ws['G6'].font = Font(bold=True, color='FFFFFF')
78
  ws['G6'].fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
79
  ws['G6'].alignment = Alignment(horizontal='center', vertical='center')
80
-
81
  # Invoice # value (below header)
82
  ws.merge_cells('E7:F7')
83
  ws['E7'] = generate_random_invoice_number()
84
  ws['E7'].alignment = Alignment(horizontal='center', vertical='center')
85
-
86
  # Date value (below header)
87
  ws.merge_cells('G7:I7')
88
  ws['G7'] = datetime.now().strftime('%d/%m/%y')
89
  ws['G7'].alignment = Alignment(horizontal='center', vertical='center')
90
-
91
  # Company address
92
  ws['A8'] = '108 Westbourne Terrace'
93
  ws['A9'] = 'London'
94
  ws['A10'] = 'W2 6QJ'
95
  ws['A11'] = 'support@glimmr.co.uk'
96
  ws['A12'] = '020 8158 8505'
97
-
98
  # Payee information
99
  ws['A14'] = "Payee's Name"
100
  ws['A14'].font = Font(bold=True)
101
  ws['A15'] = employee_data['Row Labels']
102
  ws['A15'].font = Font(size=11)
103
-
104
  # Payment period header
105
  ws.merge_cells('A20:D20')
106
  ws['A20'] = 'Payment Period'
107
  ws['A20'].font = Font(bold=True, color='FFFFFF')
108
  ws['A20'].fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
109
  ws['A20'].alignment = Alignment(horizontal='center')
110
-
111
  # Table headers - adjusted positions
112
  ws['E20'] = 'Hours'
113
  ws['F20'] = 'Β£ / Hour'
114
  ws.merge_cells('G20:I20')
115
  ws['G20'] = 'Amount'
116
-
117
  for cell in ['E20', 'F20', 'G20']:
118
  ws[cell].font = Font(bold=True, color='FFFFFF')
119
  ws[cell].fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
120
  ws[cell].alignment = Alignment(horizontal='center')
121
-
122
  # Payment period data with center alignment
123
  ws.merge_cells('A21:D21')
124
  ws['A21'] = f"{start_date} to {end_date}"
@@ -127,17 +126,14 @@ def create_professional_individual_invoice(workbook, employee_data, start_date,
127
  ws['F21'] = f"Β£ {employee_data['Average of Hourly Rate']:.2f}"
128
  ws.merge_cells('G21:I21')
129
  ws['G21'] = f"Β£ {employee_data['Sum of Total']:.2f}"
130
-
131
  # Total sections - adjusted positions
132
  ws.merge_cells('F24:G24')
133
  ws['F24'] = 'Total Labor'
134
  ws['F24'].font = Font(bold=True)
135
  ws.merge_cells('H24:I24')
136
  ws['H24'] = f"Β£ {employee_data['Sum of Total']:.2f}"
137
-
138
  ws.merge_cells('F26:G26')
139
  ws['F26'] = 'Tax (Withholding)'
140
-
141
  # Payment due date and total
142
  due_date = (datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)).strftime('%d/%m/%Y')
143
  ws['A27'] = f'Payment is due on {due_date}'
@@ -147,31 +143,124 @@ def create_professional_individual_invoice(workbook, employee_data, start_date,
147
  ws.merge_cells('H27:I27')
148
  ws['H27'] = f"Β£ {employee_data['Sum of Total']:.2f}"
149
  ws['H27'].font = Font(bold=True)
150
-
151
  # Comments section
152
  ws['A28'] = 'Comments or Special Instructions:'
153
  ws['A28'].font = Font(bold=True)
154
  ws['A29'] = 'Payments to be made every other Saturday (or as close to these days).'
155
  ws['A30'] = 'Please let us know immediately if there are any issues.'
156
-
157
  # Apply borders - updated ranges
158
  thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
159
-
160
  # Border for payment period table
161
  for row in range(20, 22):
162
  for col in range(1, 10):
163
  ws.cell(row=row, column=col).border = thin_border
164
-
165
  # Border for header section
166
  for row in range(6, 8):
167
  for col_letter in ['E', 'F', 'G', 'H', 'I']:
168
  ws[f'{col_letter}{row}'].border = thin_border
169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
  def create_invoices_from_template_with_logo(report_data, start_date, end_date):
172
  wb = openpyxl.Workbook()
173
  wb.remove(wb.active)
174
-
175
  # Create Payments sheet
176
  payments_ws = wb.create_sheet(title="Payments")
177
  payments_ws['C1'] = 'DO NOT ALTER THIS TEMPLATE'
@@ -180,7 +269,6 @@ def create_invoices_from_template_with_logo(report_data, start_date, end_date):
180
  for col, header in enumerate(headers, 1):
181
  cell = payments_ws.cell(row=2, column=col, value=header)
182
  cell.font = Font(bold=True)
183
-
184
  for row_idx, employee in enumerate(report_data[report_data['Row Labels'] != 'Grand Total'].itertuples(), 3):
185
  name_parts = employee._1.split(' ', 1)
186
  first_name = name_parts[0] if name_parts else ''
@@ -191,7 +279,6 @@ def create_invoices_from_template_with_logo(report_data, start_date, end_date):
191
  payments_ws.cell(row=row_idx, column=4, value='')
192
  payments_ws.cell(row=row_idx, column=5, value=employee._4)
193
  payments_ws.cell(row=row_idx, column=6, value='')
194
-
195
  # Create Pivot sheet
196
  pivot_ws = wb.create_sheet(title="Pivot")
197
  pivot_ws['A1'] = f"{start_date} to {end_date}"
@@ -202,83 +289,76 @@ def create_invoices_from_template_with_logo(report_data, start_date, end_date):
202
  for col, header in enumerate(pivot_headers, 1):
203
  cell = pivot_ws.cell(row=3, column=col, value=header)
204
  cell.font = Font(bold=True)
205
-
206
  for row_idx, employee in enumerate(report_data.itertuples(), 4):
207
  pivot_ws.cell(row=row_idx, column=1, value=employee._1)
208
  pivot_ws.cell(row=row_idx, column=2, value=employee._2)
209
  pivot_ws.cell(row=row_idx, column=3, value=employee._3)
210
  pivot_ws.cell(row=row_idx, column=4, value=employee._4)
211
-
212
  # Create individual invoice sheets
213
  individual_employees = report_data[report_data['Row Labels'] != 'Grand Total']
214
  for _, employee in individual_employees.iterrows():
215
  create_professional_individual_invoice(wb, employee, start_date, end_date)
216
-
217
  return wb
218
 
219
-
220
  def process_invoice_files_with_professional_excel(file1, file2, file3, bookings_file, start_date, end_date):
221
  try:
222
  employee_files = [f for f in [file1, file2, file3] if f is not None]
223
  if not employee_files:
224
- return None, "❗ **Error:** At least one Employee CSV must be uploaded."
225
  if bookings_file is None:
226
- return None, "❗ **Error:** Bookings CSV is required."
227
-
228
  employee_dfs = [pd.read_csv(ef.name) for ef in employee_files]
229
  all_employee_data = pd.concat(employee_dfs, ignore_index=True)
230
  pdf_bookings = pd.read_csv(bookings_file.name)
231
-
232
  all_employee_data['Date'] = pd.to_datetime(all_employee_data['Date'], dayfirst=True, errors='coerce')
233
  pdf_bookings['Date'] = pd.to_datetime(pdf_bookings['Date'], dayfirst=True, errors='coerce')
234
-
235
  start_date_dt = pd.to_datetime(start_date)
236
  end_date_dt = pd.to_datetime(end_date)
237
-
238
  filtered_data = all_employee_data[(all_employee_data['Date'] >= start_date_dt) & (all_employee_data['Date'] <= end_date_dt)].copy()
239
  filtered_bookings = pdf_bookings[(pdf_bookings['Date'] >= start_date_dt) & (pdf_bookings['Date'] <= end_date_dt)].copy()
240
-
241
  def extract_employee_name(team_string):
242
  if pd.isna(team_string): return None
243
  name = team_string.split(',')[0].strip()
244
  return name.split('(')[0].strip()
245
-
246
  filtered_bookings['Employee_Name'] = filtered_bookings['Teams Assigned (without IDs)'].apply(extract_employee_name)
247
  tips_summary = filtered_bookings.groupby('Employee_Name')['Tip'].sum().reset_index()
248
  tips_with_amount = tips_summary[tips_summary['Tip'] > 0]
249
-
250
  if not tips_with_amount.empty:
251
  tip_rows = [{'Name': row['Employee_Name'], 'Hourly Rate': 0, 'Hours Worked': 0, 'Total': row['Tip']} for _, row in tips_with_amount.iterrows()]
252
  tip_df = pd.DataFrame(tip_rows)
253
  final_data = pd.concat([filtered_data, tip_df], ignore_index=True)
254
  else:
255
  final_data = filtered_data.copy()
256
-
257
  report = final_data.groupby('Name').agg({'Hourly Rate': 'mean', 'Hours Worked': 'sum', 'Total': 'sum'}).reset_index()
258
  report = report.rename(columns={'Name': 'Row Labels', 'Hourly Rate': 'Average of Hourly Rate', 'Hours Worked': 'Sum of Hours Worked', 'Total': 'Sum of Total'})
259
  report['Average of Hourly Rate'] = report['Average of Hourly Rate'].round(8)
260
  report['Sum of Hours Worked'] = report['Sum of Hours Worked'].round(2)
261
  report['Sum of Total'] = report['Sum of Total'].round(2)
262
-
263
  total_hours = report['Sum of Hours Worked'].sum()
264
  total_sum = report['Sum of Total'].sum()
265
  grand_total = pd.DataFrame({'Row Labels': ['Grand Total'], 'Average of Hourly Rate': [total_sum / total_hours if total_hours > 0 else 0], 'Sum of Hours Worked': [total_hours], 'Sum of Total': [total_sum]})
266
  final_invoice = pd.concat([report, grand_total], ignore_index=True)
267
-
268
  wb = create_invoices_from_template_with_logo(final_invoice, start_date, end_date)
269
-
270
  with tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx') as tmp:
271
  wb.save(tmp.name)
272
- temp_file_path = tmp.name
273
-
 
 
 
 
 
 
 
 
 
 
 
274
  individual_employees_count = len(report[report['Row Labels'] != 'Grand Total'])
275
- summary_text = f"πŸŽ‰ **Professional Invoice Generated Successfully!**\n\n- βœ… **Individual Professional Invoices** for each employee ({individual_employees_count} sheets)\n- βœ… **Payments Summary & Pivot Data** sheets included\n- βœ… **Glimmr Logo & Branding** applied\n\n**Summary for {start_date} to {end_date}:**\n- Total hours: {total_hours:.2f}\n- Total amount: Β£{total_sum:.2f}"
276
-
277
- return temp_file_path, summary_text
278
-
279
  except Exception as e:
280
- return None, f"❌ **An error occurred:**\n\n``````\n\nPlease check your input files and date formats (YYYY-MM-DD)."
281
-
282
 
283
  with gr.Blocks(title="Complete Professional Invoice Generator", theme=gr.themes.Soft()) as interface:
284
  gr.Markdown("# 🧾 Complete Professional Invoice Generator for Launch27 Data")
@@ -293,26 +373,30 @@ with gr.Blocks(title="Complete Professional Invoice Generator", theme=gr.themes.
293
  gr.Markdown("### πŸ“… Select Date Range")
294
  start_date = gr.Textbox(label="Start Date (YYYY-MM-DD)", value="2025-08-09")
295
  end_date = gr.Textbox(label="End Date (YYYY-MM-DD)", value="2025-08-22")
296
- process_btn = gr.Button("πŸš€ Generate Professional Invoice Excel", variant="primary", size="lg")
297
-
298
  gr.Markdown("---")
299
  gr.Markdown("### πŸ“‹ Results")
300
  with gr.Row():
301
  summary_output = gr.Markdown(label="Summary")
302
- download_file = gr.File(label="πŸ“₯ Download Professional Invoice Excel (.xlsx)")
303
-
 
304
  process_btn.click(
305
  fn=process_invoice_files_with_professional_excel,
306
  inputs=[file1, file2, file3, bookings_file, start_date, end_date],
307
- outputs=[download_file, summary_output]
308
  )
309
-
310
  with gr.Accordion("πŸ“– How to Use", open=False):
311
  gr.Markdown("""
312
  1. **Upload Files**: Upload 1-3 employee CSVs and the required bookings CSV.
313
  2. **Select Dates**: Enter the date range in YYYY-MM-DD format.
314
  3. **Generate**: Click the button.
315
- 4. **Download**: Your complete Excel file will appear for download.
 
 
 
 
 
316
  """)
317
 
318
  if __name__ == "__main__":
 
1
  import subprocess
2
  import sys
 
3
  # Install openpyxl if not available
4
  try:
5
  import openpyxl
6
  except ImportError:
7
  subprocess.check_call([sys.executable, "-m", "pip", "install", "openpyxl"])
8
  import openpyxl
9
+ # Install additional dependencies for PDF generation
10
+ try:
11
+ from reportlab.pdfgen import canvas
12
+ from reportlab.lib.pagesizes import A4
13
+ from reportlab.lib.units import inch
14
+ from reportlab.lib.colors import HexColor
15
+ from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, Image
16
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
17
+ from reportlab.lib import colors
18
+ except ImportError:
19
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "reportlab"])
20
+ from reportlab.pdfgen import canvas
21
+ from reportlab.lib.pagesizes import A4
22
+ from reportlab.lib.units import inch
23
+ from reportlab.lib.colors import HexColor
24
+ from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, Image
25
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
26
+ from reportlab.lib import colors
27
 
28
  import gradio as gr
29
  import pandas as pd
 
35
  import random
36
  import base64
37
  from io import BytesIO
38
+ import os
39
+ import zipfile
40
 
41
  def generate_random_invoice_number():
42
  """Generate random 6-digit invoice number"""
43
  return str(random.randint(100000, 999999))
44
 
 
45
  def create_professional_individual_invoice(workbook, employee_data, start_date, end_date):
46
  """Create individual invoice sheet with professional Glimmr template formatting and logo"""
 
47
  # --- PASTE YOUR CLEANED BASE64 STRING HERE ---
48
  GLIMMR_LOGO_BASE64 = """
49
  iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAnFBMVEX///8An9r/nzcAm9kAmdgAndkAl9fo8/rQ5/Vjt+L/myug0OzU6fb/yZzC4PIAldeBwudPsOCn1O05qd7/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dq/hQgtvNtkSKLxeGZdAg0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgMPwD+p9Y6vy1tXkAAAAASUVORK5CYII=
50
  """
 
51
  ws = workbook.create_sheet(title=employee_data['Row Labels'])
 
52
  column_widths = {'A': 25, 'B': 15, 'C': 15, 'D': 15, 'E': 15, 'F': 12, 'G': 12, 'H': 12, 'I': 12}
53
  for col, width in column_widths.items():
54
  ws.column_dimensions[col].width = width
 
55
  try:
56
  if GLIMMR_LOGO_BASE64.strip() and "PASTE" not in GLIMMR_LOGO_BASE64 and "YOUR BASE64" not in GLIMMR_LOGO_BASE64:
57
  logo_data = base64.b64decode(GLIMMR_LOGO_BASE64.strip())
 
62
  ws.add_image(img, 'A1')
63
  except Exception as e:
64
  print(f"Logo embedding failed: {e}")
 
65
  # Company name
66
  ws['A6'] = 'Glimmr Ltd'
67
  ws['A6'].font = Font(bold=True, size=16)
 
68
  # --- CORRECTED HEADER STRUCTURE TO MATCH ORIGINAL ---
69
  # Main header spanning wider (extended one cell left)
70
  ws.merge_cells('E2:I2')
 
72
  ws['E2'].font = Font(bold=True, size=14, color='FFFFFF')
73
  ws['E2'].alignment = Alignment(horizontal='center', vertical='center')
74
  ws['E2'].fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
 
75
  # Invoice # header (left side)
76
  ws.merge_cells('E6:F6')
77
  ws['E6'] = 'Invoice #'
78
  ws['E6'].font = Font(bold=True, color='FFFFFF')
79
  ws['E6'].fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
80
  ws['E6'].alignment = Alignment(horizontal='center', vertical='center')
 
81
  # Date header (right side)
82
  ws.merge_cells('G6:I6')
83
  ws['G6'] = 'Date'
84
  ws['G6'].font = Font(bold=True, color='FFFFFF')
85
  ws['G6'].fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
86
  ws['G6'].alignment = Alignment(horizontal='center', vertical='center')
 
87
  # Invoice # value (below header)
88
  ws.merge_cells('E7:F7')
89
  ws['E7'] = generate_random_invoice_number()
90
  ws['E7'].alignment = Alignment(horizontal='center', vertical='center')
 
91
  # Date value (below header)
92
  ws.merge_cells('G7:I7')
93
  ws['G7'] = datetime.now().strftime('%d/%m/%y')
94
  ws['G7'].alignment = Alignment(horizontal='center', vertical='center')
 
95
  # Company address
96
  ws['A8'] = '108 Westbourne Terrace'
97
  ws['A9'] = 'London'
98
  ws['A10'] = 'W2 6QJ'
99
  ws['A11'] = 'support@glimmr.co.uk'
100
  ws['A12'] = '020 8158 8505'
 
101
  # Payee information
102
  ws['A14'] = "Payee's Name"
103
  ws['A14'].font = Font(bold=True)
104
  ws['A15'] = employee_data['Row Labels']
105
  ws['A15'].font = Font(size=11)
 
106
  # Payment period header
107
  ws.merge_cells('A20:D20')
108
  ws['A20'] = 'Payment Period'
109
  ws['A20'].font = Font(bold=True, color='FFFFFF')
110
  ws['A20'].fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
111
  ws['A20'].alignment = Alignment(horizontal='center')
 
112
  # Table headers - adjusted positions
113
  ws['E20'] = 'Hours'
114
  ws['F20'] = 'Β£ / Hour'
115
  ws.merge_cells('G20:I20')
116
  ws['G20'] = 'Amount'
 
117
  for cell in ['E20', 'F20', 'G20']:
118
  ws[cell].font = Font(bold=True, color='FFFFFF')
119
  ws[cell].fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
120
  ws[cell].alignment = Alignment(horizontal='center')
 
121
  # Payment period data with center alignment
122
  ws.merge_cells('A21:D21')
123
  ws['A21'] = f"{start_date} to {end_date}"
 
126
  ws['F21'] = f"Β£ {employee_data['Average of Hourly Rate']:.2f}"
127
  ws.merge_cells('G21:I21')
128
  ws['G21'] = f"Β£ {employee_data['Sum of Total']:.2f}"
 
129
  # Total sections - adjusted positions
130
  ws.merge_cells('F24:G24')
131
  ws['F24'] = 'Total Labor'
132
  ws['F24'].font = Font(bold=True)
133
  ws.merge_cells('H24:I24')
134
  ws['H24'] = f"Β£ {employee_data['Sum of Total']:.2f}"
 
135
  ws.merge_cells('F26:G26')
136
  ws['F26'] = 'Tax (Withholding)'
 
137
  # Payment due date and total
138
  due_date = (datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)).strftime('%d/%m/%Y')
139
  ws['A27'] = f'Payment is due on {due_date}'
 
143
  ws.merge_cells('H27:I27')
144
  ws['H27'] = f"Β£ {employee_data['Sum of Total']:.2f}"
145
  ws['H27'].font = Font(bold=True)
 
146
  # Comments section
147
  ws['A28'] = 'Comments or Special Instructions:'
148
  ws['A28'].font = Font(bold=True)
149
  ws['A29'] = 'Payments to be made every other Saturday (or as close to these days).'
150
  ws['A30'] = 'Please let us know immediately if there are any issues.'
 
151
  # Apply borders - updated ranges
152
  thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
 
153
  # Border for payment period table
154
  for row in range(20, 22):
155
  for col in range(1, 10):
156
  ws.cell(row=row, column=col).border = thin_border
 
157
  # Border for header section
158
  for row in range(6, 8):
159
  for col_letter in ['E', 'F', 'G', 'H', 'I']:
160
  ws[f'{col_letter}{row}'].border = thin_border
161
 
162
+ def create_individual_pdf_invoice(employee_data, start_date, end_date, output_dir):
163
+ """Create individual PDF invoice for each cleaner"""
164
+ GLIMMR_LOGO_BASE64 = """
165
+ iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAnFBMVEX///8An9r/nzcAm9kAmdgAndkAl9fo8/rQ5/Vjt+L/myug0OzU6fb/yZzC4PIAldeBwudPsOCn1O05qd7/3MDk8fn/mSH/59Xd7vh6v+a73fFrvOWy2vD/nC74/P6Hx+n/qVP/rl3/0qshpdz/8ub//PlYteL/1rX/lACUy+r/o0L/5Mv/lxr/uXj/vYH/69r/w4z/t3Mfm83/y6CSnfTNAAAGLElEQVR4nO2cfXeiOBTGiXlBxRGF1iJabIeOHabOtLv9/t9tkxBAq+juWV4OOc/vn0ajOfcxb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XSMdOsk7lmUHlAo8UeillfK/9llgWaRhIh4Ax+Q11jy2ZCFVM82kacsrI+t5xlTPHxFJ+PeC6mD+C8fprupo+vzrO52G1OoxuPH3TGEuWb34i0DlB7p8qXCjfmvsqrO3pZVVMMhPCYIvEhIi5r7vJV9/nYl68S5O1MNupzqF+m45Go8fDx8dK/h1Nay/oNMumjBCagviisNoPc4WkyiDStMwC68fxxElDymUoi/rCjVYoNT7qP9NvnQicnWUGaxTOSoVHVHFvNq8UXqrXG6pRaFjVP7jRJJMiu0sL8y8rZMcKq14sU8I6ViPO6iuN4kzhoZt5WBgVBsG/Vkj3ZdabTIwGHW8zjfG0+N3k/CuC/6qtUqFccB4fn2/Z1ggzExZUjnVYzbirClV3FWbfO+O8Bb6vFMrGAlrqNnNVhToKhavPt9enn90M0q2xZPIfFKp0ofksc517E+hfVgrlqjOvfgzTFotKhVP9YNFrJwJLo7MuFXa0xORkxmjPeoX29mGxeKytVRgbS4i1Cu+LBT6zVWGxWxF5VCj2OMsUBmbLr/iicHdDoXtL4aZnhWUnli6kUrioFBpZtQqTWwoXfStMuDGmOAopheYuolIY+dcVmmK9QtNWfwrlj8zUMZwHxiodGV348jhMfRWe8PKiPOJmPlP40j1IRV6UCl2urtMydTrK65lsIc6L+mxv2pI/0befK0VHHukx0XwelT5qHvuNvMU6y3Muri4msjDOkbJmpqhvRse79cJTgR7z5rj66H3ZlsqivjzkXPmnDG1QhpHyCWNfNjD2zb071xyDrLtYoU73i3g8z0z4iNmWlI+ZXkdZEcSw7z88fb3z61txo/mY7Ul8LI+LWsZSlJExOSMHmZO/xXjDhdq/hQgtvNtkSKLxeGZdAg0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgMPwD+p9Y6vy1tXkAAAAASUVORK5CYII=
166
+ """
167
+ clean_name = "".join(c for c in employee_data['Row Labels'] if c.isalnum() or c in (' ', '-', '_')).rstrip()
168
+ clean_name = clean_name.replace(' ', '_')
169
+ start_dt = datetime.strptime(start_date, '%Y-%m-%d')
170
+ end_dt = datetime.strptime(end_date, '%Y-%m-%d')
171
+ date_period = f"{start_dt.strftime('%d%b%Y')}-{end_dt.strftime('%d%b%Y')}"
172
+ filename = f"{clean_name}_{date_period}_Glimmr_Invoice.pdf"
173
+ filepath = os.path.join(output_dir, filename)
174
+ doc = SimpleDocTemplate(filepath, pagesize=A4, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18)
175
+ story = []
176
+ try:
177
+ if GLIMMR_LOGO_BASE64.strip():
178
+ logo_data = base64.b64decode(GLIMMR_LOGO_BASE64.strip())
179
+ logo_stream = BytesIO(logo_data)
180
+ logo_img = Image(logo_stream)
181
+ logo_img.drawWidth = 2*inch
182
+ logo_img.drawHeight = 1*inch
183
+ story.append(logo_img)
184
+ story.append(Spacer(1, 12))
185
+ except Exception as e:
186
+ print(f"PDF Logo embedding failed: {e}")
187
+ styles = getSampleStyleSheet()
188
+ title_style = ParagraphStyle('CustomTitle', parent=styles['Heading1'], fontSize=18, spaceAfter=30, textColor=HexColor('#4472C4'), alignment=1)
189
+ header_style = ParagraphStyle('CustomHeader', parent=styles['Heading2'], fontSize=14, spaceAfter=12, textColor=HexColor('#4472C4'))
190
+ normal_style = styles['Normal']
191
+ story.append(Paragraph('<b>Glimmr Ltd</b>', title_style))
192
+ address_text = "108 Westbourne Terrace<br/>London<br/>W2 6QJ<br/>support@glimmr.co.uk<br/>020 8158 8505"
193
+ story.append(Paragraph(address_text, normal_style))
194
+ story.append(Spacer(1, 20))
195
+ invoice_number = generate_random_invoice_number()
196
+ current_date = datetime.now().strftime('%d/%m/%Y')
197
+ invoice_header_data = [['CLEANER INVOICE', ''], ['Invoice #: ' + invoice_number, 'Date: ' + current_date]]
198
+ invoice_header_table = Table(invoice_header_data, colWidths=[3*inch, 3*inch])
199
+ invoice_header_table.setStyle(TableStyle([
200
+ ('BACKGROUND', (0, 0), (-1, 0), HexColor('#4472C4')),
201
+ ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
202
+ ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
203
+ ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
204
+ ('FONTSIZE', (0, 0), (-1, 0), 14),
205
+ ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
206
+ ('FONTSIZE', (0, 1), (-1, -1), 12),
207
+ ('BOTTOMPADDING', (0, 0), (-1, -1), 12),
208
+ ('GRID', (0, 0), (-1, -1), 1, colors.black)
209
+ ]))
210
+ story.append(invoice_header_table)
211
+ story.append(Spacer(1, 20))
212
+ story.append(Paragraph('<b>Payee\'s Name:</b>', header_style))
213
+ story.append(Paragraph(employee_data['Row Labels'], normal_style))
214
+ story.append(Spacer(1, 20))
215
+ due_date = (datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)).strftime('%d/%m/%Y')
216
+ payment_data = [
217
+ ['Payment Period', 'Hours', 'Β£ / Hour', 'Amount'],
218
+ [f"{start_date} to {end_date}",
219
+ str(employee_data['Sum of Hours Worked']),
220
+ f"Β£ {employee_data['Average of Hourly Rate']:.2f}",
221
+ f"Β£ {employee_data['Sum of Total']:.2f}"]
222
+ ]
223
+ payment_table = Table(payment_data, colWidths=[2*inch, 1*inch, 1*inch, 1.5*inch])
224
+ payment_table.setStyle(TableStyle([
225
+ ('BACKGROUND', (0, 0), (-1, 0), HexColor('#4472C4')),
226
+ ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
227
+ ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
228
+ ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
229
+ ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
230
+ ('FONTSIZE', (0, 0), (-1, -1), 10),
231
+ ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
232
+ ('GRID', (0, 0), (-1, -1), 1, colors.black)
233
+ ]))
234
+ story.append(payment_table)
235
+ story.append(Spacer(1, 20))
236
+ total_data = [
237
+ ['Total Labor', f"Β£ {employee_data['Sum of Total']:.2f}"],
238
+ ['Tax (Withholding)', 'Β£ 0.00'],
239
+ ['TOTAL', f"Β£ {employee_data['Sum of Total']:.2f}"]
240
+ ]
241
+ total_table = Table(total_data, colWidths=[3*inch, 2*inch])
242
+ total_table.setStyle(TableStyle([
243
+ ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
244
+ ('FONTNAME', (0, 0), (-1, 1), 'Helvetica'),
245
+ ('FONTNAME', (0, 2), (-1, 2), 'Helvetica-Bold'),
246
+ ('FONTSIZE', (0, 0), (-1, -1), 12),
247
+ ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
248
+ ('GRID', (0, 0), (-1, -1), 1, colors.black),
249
+ ('BACKGROUND', (0, 2), (-1, 2), colors.lightgrey)
250
+ ]))
251
+ story.append(total_table)
252
+ story.append(Spacer(1, 20))
253
+ story.append(Paragraph(f'<b>Payment is due on {due_date}</b>', normal_style))
254
+ story.append(Spacer(1, 20))
255
+ story.append(Paragraph('<b>Comments or Special Instructions:</b>', header_style))
256
+ story.append(Paragraph('Payments to be made every other Saturday (or as close to these days).', normal_style))
257
+ story.append(Paragraph('Please let us know immediately if there are any issues.', normal_style))
258
+ doc.build(story)
259
+ return filepath
260
 
261
  def create_invoices_from_template_with_logo(report_data, start_date, end_date):
262
  wb = openpyxl.Workbook()
263
  wb.remove(wb.active)
 
264
  # Create Payments sheet
265
  payments_ws = wb.create_sheet(title="Payments")
266
  payments_ws['C1'] = 'DO NOT ALTER THIS TEMPLATE'
 
269
  for col, header in enumerate(headers, 1):
270
  cell = payments_ws.cell(row=2, column=col, value=header)
271
  cell.font = Font(bold=True)
 
272
  for row_idx, employee in enumerate(report_data[report_data['Row Labels'] != 'Grand Total'].itertuples(), 3):
273
  name_parts = employee._1.split(' ', 1)
274
  first_name = name_parts[0] if name_parts else ''
 
279
  payments_ws.cell(row=row_idx, column=4, value='')
280
  payments_ws.cell(row=row_idx, column=5, value=employee._4)
281
  payments_ws.cell(row=row_idx, column=6, value='')
 
282
  # Create Pivot sheet
283
  pivot_ws = wb.create_sheet(title="Pivot")
284
  pivot_ws['A1'] = f"{start_date} to {end_date}"
 
289
  for col, header in enumerate(pivot_headers, 1):
290
  cell = pivot_ws.cell(row=3, column=col, value=header)
291
  cell.font = Font(bold=True)
 
292
  for row_idx, employee in enumerate(report_data.itertuples(), 4):
293
  pivot_ws.cell(row=row_idx, column=1, value=employee._1)
294
  pivot_ws.cell(row=row_idx, column=2, value=employee._2)
295
  pivot_ws.cell(row=row_idx, column=3, value=employee._3)
296
  pivot_ws.cell(row=row_idx, column=4, value=employee._4)
 
297
  # Create individual invoice sheets
298
  individual_employees = report_data[report_data['Row Labels'] != 'Grand Total']
299
  for _, employee in individual_employees.iterrows():
300
  create_professional_individual_invoice(wb, employee, start_date, end_date)
 
301
  return wb
302
 
 
303
  def process_invoice_files_with_professional_excel(file1, file2, file3, bookings_file, start_date, end_date):
304
  try:
305
  employee_files = [f for f in [file1, file2, file3] if f is not None]
306
  if not employee_files:
307
+ return None, None, "❗ **Error:** At least one Employee CSV must be uploaded."
308
  if bookings_file is None:
309
+ return None, None, "❗ **Error:** Bookings CSV is required."
 
310
  employee_dfs = [pd.read_csv(ef.name) for ef in employee_files]
311
  all_employee_data = pd.concat(employee_dfs, ignore_index=True)
312
  pdf_bookings = pd.read_csv(bookings_file.name)
 
313
  all_employee_data['Date'] = pd.to_datetime(all_employee_data['Date'], dayfirst=True, errors='coerce')
314
  pdf_bookings['Date'] = pd.to_datetime(pdf_bookings['Date'], dayfirst=True, errors='coerce')
 
315
  start_date_dt = pd.to_datetime(start_date)
316
  end_date_dt = pd.to_datetime(end_date)
 
317
  filtered_data = all_employee_data[(all_employee_data['Date'] >= start_date_dt) & (all_employee_data['Date'] <= end_date_dt)].copy()
318
  filtered_bookings = pdf_bookings[(pdf_bookings['Date'] >= start_date_dt) & (pdf_bookings['Date'] <= end_date_dt)].copy()
 
319
  def extract_employee_name(team_string):
320
  if pd.isna(team_string): return None
321
  name = team_string.split(',')[0].strip()
322
  return name.split('(')[0].strip()
 
323
  filtered_bookings['Employee_Name'] = filtered_bookings['Teams Assigned (without IDs)'].apply(extract_employee_name)
324
  tips_summary = filtered_bookings.groupby('Employee_Name')['Tip'].sum().reset_index()
325
  tips_with_amount = tips_summary[tips_summary['Tip'] > 0]
 
326
  if not tips_with_amount.empty:
327
  tip_rows = [{'Name': row['Employee_Name'], 'Hourly Rate': 0, 'Hours Worked': 0, 'Total': row['Tip']} for _, row in tips_with_amount.iterrows()]
328
  tip_df = pd.DataFrame(tip_rows)
329
  final_data = pd.concat([filtered_data, tip_df], ignore_index=True)
330
  else:
331
  final_data = filtered_data.copy()
 
332
  report = final_data.groupby('Name').agg({'Hourly Rate': 'mean', 'Hours Worked': 'sum', 'Total': 'sum'}).reset_index()
333
  report = report.rename(columns={'Name': 'Row Labels', 'Hourly Rate': 'Average of Hourly Rate', 'Hours Worked': 'Sum of Hours Worked', 'Total': 'Sum of Total'})
334
  report['Average of Hourly Rate'] = report['Average of Hourly Rate'].round(8)
335
  report['Sum of Hours Worked'] = report['Sum of Hours Worked'].round(2)
336
  report['Sum of Total'] = report['Sum of Total'].round(2)
 
337
  total_hours = report['Sum of Hours Worked'].sum()
338
  total_sum = report['Sum of Total'].sum()
339
  grand_total = pd.DataFrame({'Row Labels': ['Grand Total'], 'Average of Hourly Rate': [total_sum / total_hours if total_hours > 0 else 0], 'Sum of Hours Worked': [total_hours], 'Sum of Total': [total_sum]})
340
  final_invoice = pd.concat([report, grand_total], ignore_index=True)
 
341
  wb = create_invoices_from_template_with_logo(final_invoice, start_date, end_date)
 
342
  with tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx') as tmp:
343
  wb.save(tmp.name)
344
+ temp_excel_file_path = tmp.name
345
+ # Create PDF files for individual cleaners
346
+ pdf_temp_dir = tempfile.mkdtemp()
347
+ individual_employees = report[report['Row Labels'] != 'Grand Total']
348
+ pdf_files = []
349
+ for _, employee in individual_employees.iterrows():
350
+ pdf_path = create_individual_pdf_invoice(employee, start_date, end_date, pdf_temp_dir)
351
+ pdf_files.append(pdf_path)
352
+ # Create a ZIP file containing all PDFs
353
+ zip_temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.zip')
354
+ with zipfile.ZipFile(zip_temp_file.name, 'w') as zipf:
355
+ for pdf_file in pdf_files:
356
+ zipf.write(pdf_file, os.path.basename(pdf_file))
357
  individual_employees_count = len(report[report['Row Labels'] != 'Grand Total'])
358
+ summary_text = f"πŸŽ‰ **Professional Invoice Generated Successfully!**\n\n- βœ… **Individual Professional Invoices** for each employee ({individual_employees_count} Excel sheets)\n- βœ… **Individual PDF Invoices** for each cleaner ({individual_employees_count} PDFs)\n- βœ… **Payments Summary & Pivot Data** sheets included\n- βœ… **Glimmr Logo & Branding** applied\n\n**Summary for {start_date} to {end_date}:**\n- Total hours: {total_hours:.2f}\n- Total amount: Β£{total_sum:.2f}\n\n**Files Generated:**\n- Excel file with all data and individual sheets\n- ZIP file containing individual PDF invoices for each cleaner"
359
+ return temp_excel_file_path, zip_temp_file.name, summary_text
 
 
360
  except Exception as e:
361
+ return None, None, f"❌ **An error occurred:**\n\n{str(e)}\n\nPlease check your input files and date formats (YYYY-MM-DD)."
 
362
 
363
  with gr.Blocks(title="Complete Professional Invoice Generator", theme=gr.themes.Soft()) as interface:
364
  gr.Markdown("# 🧾 Complete Professional Invoice Generator for Launch27 Data")
 
373
  gr.Markdown("### πŸ“… Select Date Range")
374
  start_date = gr.Textbox(label="Start Date (YYYY-MM-DD)", value="2025-08-09")
375
  end_date = gr.Textbox(label="End Date (YYYY-MM-DD)", value="2025-08-22")
376
+ process_btn = gr.Button("πŸš€ Generate Professional Invoice Excel & PDFs", variant="primary", size="lg")
 
377
  gr.Markdown("---")
378
  gr.Markdown("### πŸ“‹ Results")
379
  with gr.Row():
380
  summary_output = gr.Markdown(label="Summary")
381
+ with gr.Row():
382
+ download_excel_file = gr.File(label="πŸ“₯ Download Professional Invoice Excel (.xlsx)")
383
+ download_pdf_zip = gr.File(label="πŸ“₯ Download Individual PDF Invoices (.zip)")
384
  process_btn.click(
385
  fn=process_invoice_files_with_professional_excel,
386
  inputs=[file1, file2, file3, bookings_file, start_date, end_date],
387
+ outputs=[download_excel_file, download_pdf_zip, summary_output]
388
  )
 
389
  with gr.Accordion("πŸ“– How to Use", open=False):
390
  gr.Markdown("""
391
  1. **Upload Files**: Upload 1-3 employee CSVs and the required bookings CSV.
392
  2. **Select Dates**: Enter the date range in YYYY-MM-DD format.
393
  3. **Generate**: Click the button.
394
+ 4. **Download**: Your complete Excel file and ZIP of individual PDF invoices will appear for download.
395
+
396
+ **New Features:**
397
+ - Individual PDF invoices for each cleaner with the naming convention: `Cleaner_Name_Dateperiod_Glimmr_Invoice.pdf`
398
+ - All PDF files are packaged in a convenient ZIP file for download
399
+ - Professional PDF formatting matching the Excel invoice design
400
  """)
401
 
402
  if __name__ == "__main__":