Spaces:
Sleeping
Sleeping
EL GHAFRAOUI AYOUB commited on
Commit ·
17cd0ef
1
Parent(s): de3a0b9
Files changed (5)
11 unmodified lines121314151617112 unmodified lines13013113213313413513613713813914011 unmodified linesfrom app.db.models import Invoice, InvoiceItemfrom app.services.invoice_service import InvoiceServicefrom app.services.excel_service import ExcelService# Set up logginglogger = logging.getLogger(__name__)112 unmodified lineslogger.info(f"Generating PDF for invoice: {invoice_id}")# Generate PDFpdf_bytes = InvoiceService.generate_pdf(invoice)return StreamingResponse(iter([pdf_bytes]),media_type="application/pdf",headers={"Content-Disposition": f"attachment; filename=devis_{invoice_id}.pdf"})11 unmodified lines1213141516171819112 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116211 unmodified linesfrom app.db.models import Invoice, InvoiceItemfrom app.services.invoice_service import InvoiceServicefrom app.services.excel_service import ExcelService#from app.services.invoice_page2_service import InvoiceServicePage2from app.services.invoice_service_page2 import InvoiceServicePage2# Set up logginglogger = logging.getLogger(__name__)112 unmodified lineslogger.info(f"Generating PDF for invoice: {invoice_id}")# Generate both pagespdf_bytes1 = InvoiceService.generate_pdf(invoice)pdf_bytes2 = InvoiceServicePage2.generate_pdf(invoice)# Merge PDFs using PyPDF2from PyPDF2 import PdfMergerfrom io import BytesIOmerger = PdfMerger()# Add both pages to the mergermerger.append(BytesIO(pdf_bytes1))merger.append(BytesIO(pdf_bytes2))# Write the merged PDF to a BytesIO objectoutput = BytesIO()merger.write(output)merger.close()# Get the merged PDF bytesoutput.seek(0)final_pdf = output.getvalue()return StreamingResponse(iter([final_pdf]),media_type="application/pdf",headers={"Content-Disposition": f"attachment; filename=devis_{invoice_id}.pdf"})
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335from reportlab.lib.pagesizes import A4from reportlab.pdfgen import canvasfrom reportlab.lib import colorsfrom reportlab.lib.units import cmfrom io import BytesIOfrom app.db.models import Invoiceimport loggingimport osimport datetimeimport re
# Set up logginglogger = logging.getLogger(__name__)
class InvoiceServicePage2: @staticmethod def generate_pdf(data: Invoice) -> bytes: try: buffer = BytesIO() pdf = canvas.Canvas(buffer, pagesize=A4) page_width, page_height = A4
# Constants HEADER_BLUE = (0.29, 0.45, 0.68) BLUE_LIGHT = (1.5, 1.5, 1) WHITE = (1, 1, 1) BLACK = (0, 0, 0) MARGIN = 30 LINE_HEIGHT = 20 BOX_PADDING = 10 STANDARD_FONT_SIZE = 8 HEADER_FONT_SIZE = 24 SECTION_FONT_SIZE = 8 FOOTER_FONT_SIZE = 7 BOTTOM_MARGIN = 50
# Helper functions (same as original) def draw_centered_text(pdf, text, x, y, width, font="Helvetica", size=STANDARD_FONT_SIZE): text_width = pdf.stringWidth(text, font, size) pdf.drawString(x + (width - text_width) / 2, y, text)
def draw_box(pdf, x, y, width, height, fill_color=None, stroke_color=BLACK): if fill_color: pdf.setFillColorRGB(*fill_color) pdf.rect(x, y, width, height, fill=1, stroke=0) pdf.setFillColorRGB(*stroke_color) pdf.rect(x, y, width, height, stroke=1)
def draw_wrapped_text(pdf, text, x, y, width, font="Helvetica", size=STANDARD_FONT_SIZE): pdf.setFont(font, size) words = text.split() lines = [] current_line = [] for word in words: current_line.append(word) line_width = pdf.stringWidth(' '.join(current_line), font, size) if line_width > width: current_line.pop() if current_line: lines.append(' '.join(current_line)) current_line = [word] if current_line: lines.append(' '.join(current_line)) return lines
# Get the absolute path to the logo file current_dir = os.path.dirname(os.path.abspath(__file__)) logo_path = os.path.join(current_dir, "..", "static", "logo.png")
# Top section layout top_margin = page_height - 120
# Left side: Logo if os.path.exists(logo_path): pdf.drawImage(logo_path, MARGIN, top_margin - 10, width=100, height=100)
# Right side: BON DE LIVRAISON instead of DEVIS pdf.setFont("Helvetica-Bold", HEADER_FONT_SIZE) title_text = "DEVIS" title_width = pdf.stringWidth(title_text, "Helvetica-Bold", HEADER_FONT_SIZE) title_x = page_width - title_width - MARGIN - 50 title_y = top_margin + 50 pdf.drawString(title_x, title_y, title_text)
# Client info box (same as original) box_width = 200 box_height = 80 box_x = page_width - box_width - MARGIN + 10 box_y = title_y - 120
# Draw client box pdf.rect(box_x, box_y, box_width, box_height, stroke=1)
# Client Info pdf.setFont("Helvetica", STANDARD_FONT_SIZE) client_info = [ data.client_name, data.project, data.address, data.ville, data.client_phone ]
# Draw client info (same as original) available_height = box_height - BOX_PADDING * 2 y_position = box_y + box_height - BOX_PADDING
for text in client_info: if text: available_width = box_width - BOX_PADDING * 2 lines = draw_wrapped_text(pdf, str(text), box_x, y_position, available_width) for line in lines: text_width = pdf.stringWidth(line, "Helvetica", STANDARD_FONT_SIZE) x = box_x + (box_width - text_width) / 2 pdf.drawString(x, y_position, line) y_position -= STANDARD_FONT_SIZE + 2
y_position -= 2
# Info boxes (Date, N° Devis, PLANCHER) - adjusted starting position info_y = top_margin - 90 box_label_width = 100 # Reduced label width box_value_width = 150 # Increased value width for longer text
for label, value in [ ("Date du devis :", data.date.strftime("%d/%m/%Y")), ("N° Devis :", data.invoice_number), ("PLANCHER :", data.frame_number or "PH RDC") ]: draw_box(pdf, MARGIN, info_y, box_label_width, LINE_HEIGHT, fill_color=HEADER_BLUE) pdf.setFillColorRGB(*WHITE) pdf.drawString(MARGIN + BOX_PADDING, info_y + 6, label)
draw_box(pdf, MARGIN + box_label_width, info_y, box_value_width, LINE_HEIGHT, fill_color=WHITE) pdf.setFillColorRGB(*BLACK) # Draw value text with wrapping if needed value_str = str(value) if len(value_str) > 20: # If text is too long pdf.setFont("Helvetica", 8) # Reduce font size for long text lines = draw_wrapped_text(pdf, value_str, MARGIN + box_label_width, info_y + 6, box_value_width - 10) for i, line in enumerate(lines): draw_centered_text(pdf, line, MARGIN + box_label_width, info_y + 6 - (i * 8), box_value_width) else: pdf.setFont("Helvetica", STANDARD_FONT_SIZE) draw_centered_text(pdf, value_str, MARGIN + box_label_width, info_y + 6, box_value_width)
info_y -= 25
# Table headers table_y = info_y - 10 # Adjusted to be after info boxes headers = [ ("Description", 300), # Increased width for Description ("Unité", 80), # Adjusted width ("NBRE", 80), # Adjusted width ("ML/Qté", 90), # Adjusted width ]
total_width = sum(width for _, width in headers) table_x = (page_width - total_width) / 2
# Draw table headers current_x = table_x for title, width in headers: draw_box(pdf, current_x, table_y, width, LINE_HEIGHT, fill_color=HEADER_BLUE) pdf.setFillColorRGB(*WHITE) if title != "Description": # Center align all columns except Description draw_centered_text(pdf, title, current_x, table_y + 6, width) else: pdf.drawString(current_x + BOX_PADDING, table_y + 6, title) # Left align Description current_x += width
# Start sections immediately after headers current_y = table_y - LINE_HEIGHT + 12
def draw_section_header2(title): nonlocal current_y section_start_y = current_y current_y -= 20 pdf.setFont("Helvetica-Bold", SECTION_FONT_SIZE) pdf.setFillColorRGB(*BLACK) pdf.drawString(table_x + BOX_PADDING, current_y + 6, title) current_y -= LINE_HEIGHT - 12 pdf.setFont("Helvetica", STANDARD_FONT_SIZE) return section_start_y
def draw_item_row(item, indent=False, is_last_item=False): nonlocal current_y # Define the row values without price information row_values = [ str(item.description), str(item.unit), str(item.quantity), f"{item.length:.2f}" ] current_x = table_x + (20 if indent else 0) pdf.setFont("Helvetica", 8) for idx, (_, col_width) in enumerate(headers): if idx == 0: # Description column padding = BOX_PADDING if idx == 0 else 2 pdf.drawString(current_x + padding, current_y + 6, row_values[idx]) else: # Other columns (Unité, NBRE, ML/Qté) # Center the text in the column text_width = pdf.stringWidth(row_values[idx], "Helvetica", 8) x_pos = current_x + (col_width - text_width) / 2 pdf.drawString(x_pos, current_y + 6, row_values[idx]) current_x += col_width if not is_last_item: current_y -= (LINE_HEIGHT - 8) else: current_y -= (LINE_HEIGHT - 20) pdf.setFont("Helvetica", STANDARD_FONT_SIZE)
# Draw sections sections = [ ("POUTRELLES", "PCP"), ("HOURDIS", "HOURDIS"), ("PANNEAU TREILLIS SOUDES", "PTS"), ("AGGLOS", "AGGLOS") ]
def get_description_number(description: str) -> float: try: numbers = re.findall(r'\d+\.?\d*', description) return float(numbers[0]) if numbers else 0 except: return 0
# Draw sections and items for section_title, keyword in sections: items = [i for i in data.items if keyword in i.description] if items: sorted_items = sorted( items, key=lambda x: (get_description_number(x.description), x.length) ) grouped_items = {} for item in sorted_items: key = (item.description, item.length) if key not in grouped_items: grouped_items[key] = item else: existing = grouped_items[key] existing.quantity += item.quantity
section_start_y = draw_section_header2(section_title) items_list = list(grouped_items.values()) for i, item in enumerate(items_list): is_last = i == len(items_list) - 1 draw_item_row(item, indent=(keyword != "lfflflflf"), is_last_item=is_last) section_height = section_start_y - current_y pdf.setStrokeColorRGB(*BLACK) pdf.rect(table_x, current_y, total_width, section_height, stroke=1)
# NB box with text nb_box_width = total_width * 0.4 nb_box_height = 50 current_y -= 20 pdf.setFillColorRGB(*BLACK) pdf.rect(table_x, current_y - nb_box_height, nb_box_width, nb_box_height, stroke=1) y_offset = current_y - nb_box_height + 40 # Draw "NB:" in bold with underline nb_text = "NB:" pdf.setFont("Helvetica-Bold", STANDARD_FONT_SIZE) pdf.drawString(table_x + 10, y_offset, nb_text) # Add underline text_width = pdf.stringWidth(nb_text, "Helvetica-Bold", STANDARD_FONT_SIZE) pdf.line(table_x + 10, y_offset - 2, table_x + 10 + text_width, y_offset - 2) # Draw the rest of the text in normal font pdf.setFont("Helvetica", STANDARD_FONT_SIZE) remaining_text = """Toute modification apportée aux plans BAinitialement fournis, entraîne automatiquementla modification de ce bon de livraison.""" for i, line in enumerate(remaining_text.split('\n')): if i == 0: pdf.drawString(table_x + 30, y_offset, line) else: pdf.drawString(table_x + 10, y_offset - (i * 15), line)
# Footer pdf.setFont("Helvetica", FOOTER_FONT_SIZE) footer_text = "CARRIPREFA" pdf.drawCentredString(page_width / 2, 40, footer_text) pdf.setFont("Helvetica", FOOTER_FONT_SIZE) footer_text = "Douar Ait Toumart Habil, Cercle El Bour, Route de Safi, Km 14 -40000 Marrakech" pdf.drawCentredString(page_width / 2 + 20, 30, footer_text)
# Add commercial info to footer commercial_info = dict( salah="06 62 29 99 78", khaled="06 66 24 80 94", ismail="06 66 24 50 15", jamal="06 70 08 36 50" )
if data.commercial and data.commercial.lower() != 'divers': commercial_text = f"Commercial: {data.commercial.upper()}" commercial_phone = f"Tél: {commercial_info.get(data.commercial.lower(), '')}" pdf.drawString(MARGIN + 10, 30, commercial_text) pdf.drawString(MARGIN + 10, 20, commercial_phone) footer_contact = "Tél: 05 24 01 33 34 Fax : 05 24 01 33 29 E-mail : carriprefa@gmail.com" pdf.drawCentredString(page_width / 2 + 10, 20, footer_contact) pdf.drawString(page_width - 100, 30, f"Date: {datetime.datetime.now().strftime('%d/%m/%Y %H:%M')}") pdf.drawString(page_width - 100, 20, f"Page {pdf.getPageNumber()}/{pdf.getPageNumber()}") else: footer_contact = "Tél: 05 24 01 33 34 Fax : 05 24 01 33 29 E-mail : carriprefa@gmail.com" pdf.drawCentredString(page_width / 2 + 10, 20, footer_contact) pdf.drawString(page_width - 100, 30, f"Date: {datetime.datetime.now().strftime('%d/%m/%Y %H:%M')}") pdf.drawString(page_width - 100, 20, f"Page {pdf.getPageNumber()}/{pdf.getPageNumber()}")
pdf.save() buffer.seek(0) return buffer.getvalue()
except Exception as e: logger.error(f"Error in PDF generation: {str(e)}", exc_info=True) raiseapp/routes/__pycache__/invoices.cpython-312.pyc
app/routes/invoices.py+25-3
app/services/__pycache__/invoice_service_page2.cpython-312.pycAdded
app/services/invoice_service_page2.pyAdded+335
sql_app.db