warehouse_report_service.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import os
  2. import db
  3. import config
  4. from fpdf import FPDF
  5. from datetime import datetime
  6. class WarehouseReportService:
  7. @staticmethod
  8. def generate_report():
  9. try:
  10. # Fetch all stock items with material names
  11. query = """
  12. SELECT w.*, m.name_en as material_name, m.name_ru as material_name_ru
  13. FROM warehouse_stock w
  14. JOIN materials m ON w.material_id = m.id
  15. ORDER BY m.name_en, w.color_name
  16. """
  17. stock = db.execute_query(query)
  18. pdf = FPDF(orientation='P', unit='mm', format='A4')
  19. pdf.add_page()
  20. # Header
  21. pdf.set_font("helvetica", "B", 16)
  22. pdf.cell(0, 10, "Warehouse Stock Report", ln=True, align='C')
  23. pdf.set_font("helvetica", "", 10)
  24. pdf.cell(0, 5, f"Date: {datetime.now().strftime('%d.%m.%Y %H:%M')}", ln=True, align='C')
  25. pdf.ln(10)
  26. # Table Header
  27. pdf.set_fill_color(240, 240, 240)
  28. pdf.set_font("helvetica", "B", 10)
  29. pdf.cell(60, 10, "Material", border=1, fill=True)
  30. pdf.cell(40, 10, "Color", border=1, fill=True)
  31. pdf.cell(30, 10, "Unit Mass", border=1, fill=True, align='C')
  32. pdf.cell(30, 10, "Units", border=1, fill=True, align='C')
  33. pdf.cell(30, 10, "Total (kg)", border=1, fill=True, align='C')
  34. pdf.ln()
  35. # Table Body
  36. pdf.set_font("helvetica", "", 10)
  37. total_weight = 0
  38. for item in stock:
  39. # Use name_en to avoid encoding issues with core fonts
  40. name = str(item.get('material_name') or "N/A").encode('latin-1', 'replace').decode('latin-1')
  41. color = str(item.get('color_name') or "N/A").encode('latin-1', 'replace').decode('latin-1')
  42. pdf.cell(60, 10, name, border=1)
  43. pdf.cell(40, 10, color, border=1)
  44. pdf.cell(30, 10, f"{float(item['unit_mass']):.3f}", border=1, align='C')
  45. pdf.cell(30, 10, str(item['units_count']), border=1, align='C')
  46. pdf.cell(30, 10, f"{float(item['quantity']):.3f}", border=1, align='C')
  47. pdf.ln()
  48. total_weight += float(item['quantity'])
  49. # Total
  50. pdf.set_font("helvetica", "B", 10)
  51. pdf.cell(160, 10, "GRAND TOTAL WEIGHT (kg):", border=1, align='R')
  52. pdf.cell(30, 10, f"{total_weight:.3f}", border=1, align='C')
  53. # Output
  54. filename = f"warehouse_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
  55. report_dir = os.path.join(config.UPLOAD_DIR, "reports")
  56. if not os.path.exists(report_dir):
  57. os.makedirs(report_dir, exist_ok=True)
  58. filepath = os.path.join(report_dir, filename)
  59. pdf.output(filepath)
  60. return f"uploads/reports/{filename}"
  61. except Exception as e:
  62. print(f"REPORT ERROR: {str(e)}")
  63. raise e
  64. warehouse_report_service = WarehouseReportService()