from flask import Blueprint, render_template, request, send_file, flash import pandas as pd import io from app.models.subcontractor_model import Subcontractor from app.models.trench_excavation_model import TrenchExcavation from app.models.tr_ex_client_model import TrenchExcavationClient from app.models.manhole_excavation_model import ManholeExcavation from app.models.mh_ex_client_model import ManholeExcavationClient from app.models.manhole_domestic_chamber_model import ManholeDomesticChamber from app.models.mh_dc_client_model import ManholeDomesticChamberClient generate_report_bp = Blueprint("generate_report", __name__, url_prefix="/report") # HELPER FUNCTION def make_lookup(rows, key_field): return { (r.Location, getattr(r, key_field)): r for r in rows if r.Location and getattr(r, key_field, None) } @generate_report_bp.route("/comparison_report", methods=["GET", "POST"]) def comparison_report(): subcontractors = Subcontractor.query.all() if request.method == "POST": subcontractor_id = request.form.get("subcontractor_id") if not subcontractor_id: flash("Please select a subcontractor.", "danger") return render_template("generate_comparison_report.html",subcontractors=subcontractors) subcontractor = Subcontractor.query.get_or_404(subcontractor_id) # ================= TRENCH EXCAVATION ================= client_tr_ex = TrenchExcavationClient.query.all() contractor_tr_ex = TrenchExcavation.query.filter_by(subcontractor_id=subcontractor_id).all() contractor_lookup = make_lookup(contractor_tr_ex, "MH_NO") combined_rows_tr_ex = [] for row1 in client_tr_ex: row2 = contractor_lookup.get((row1.Location, row1.MH_NO)) if not row2: continue # -------- CLIENT TOTAL ---------- client_total = sum(v or 0 for k, v in row1.__dict__.items() if k.endswith("_total")) # -------- SUB TOTAL ---------- contractor_total = sum(v or 0 for k, v in row2.__dict__.items() if k.endswith("_total")) diff = client_total - contractor_total row_data = { "Location": row1.Location, "MH No": row1.MH_NO, } # -------- CLIENT COLUMNS ---------- for col, val in row1.__dict__.items(): if col.startswith("_") or col in ["id", "created_at", "subcontractor_id"]: continue row_data[f"Client_{col}"] = val row_data["Client_Total"] = round(client_total, 2) row_data[" - "] = " " # -------- SUB COLUMNS ---------- for col, val in row2.__dict__.items(): if col.startswith("_") or col in ["id", "created_at", "subcontractor_id"]: continue row_data[f"Sub_{col}"] = val row_data["Sub_Total"] = round(contractor_total, 2) row_data["--"] = " " row_data["Diff"] = round(diff, 2) combined_rows_tr_ex.append(row_data) df_tr_ex = pd.DataFrame(combined_rows_tr_ex) # ================= MANHOLE EXCAVATION ================= client_mh_ex = ManholeExcavationClient.query.all() contractor_mh_ex = ManholeExcavation.query.filter_by(subcontractor_id=subcontractor_id).all() contractor_lookup = make_lookup(contractor_mh_ex, "MH_NO") combined_rows_mh_ex = [] for row1 in client_mh_ex: row2 = contractor_lookup.get((row1.Location, row1.MH_NO)) if not row2: continue client_total = sum(v or 0 for k, v in row1.__dict__.items() if k.endswith("_total")) contractor_total = sum(v or 0 for k, v in row2.__dict__.items() if k.endswith("_total")) diff = client_total - contractor_total row_data = { "Location": row1.Location, "MH No": row1.MH_NO, } for col, val in row1.__dict__.items(): if col.startswith("_") or col in ["id", "created_at", "subcontractor_id"]: continue row_data[f"Client_{col}"] = val row_data["Client_Total"] = round(client_total, 2) row_data[" - "] = " " for col, val in row2.__dict__.items(): if col.startswith("_") or col in ["id", "created_at", "subcontractor_id"]: continue row_data[f"Sub_{col}"] = val row_data["Sub_Total"] = round(contractor_total, 2) row_data["--"] = " " row_data["Diff"] = round(diff, 2) combined_rows_mh_ex.append(row_data) df_mh_ex = pd.DataFrame(combined_rows_mh_ex) # ============ MANHOLE DOMESTIC CHAMBER ================= client_mh_dc = ManholeDomesticChamberClient.query.all() contractor_mh_dc = ManholeDomesticChamber.query.filter_by(subcontractor_id=subcontractor_id).all() contractor_lookup = make_lookup(contractor_mh_dc, "Node_no") combined_rows_mh_dc = [] for row1 in client_mh_dc: row2 = contractor_lookup.get((row1.Location, row1.MH_NO)) if not row2: continue client_total = sum(v or 0 for k, v in row1.__dict__.items() if isinstance(v, (int, float))) contractor_total = sum(v or 0 for k, v in row2.__dict__.items() if isinstance(v, (int, float))) diff = client_total - contractor_total row_data = { "Location": row1.Location, "Node No": row1.MH_NO, } for col, val in row1.__dict__.items(): if col.startswith("_") or col in ["id", "created_at", "subcontractor_id"]: continue row_data[f"Client_{col}"] = val row_data["Client_Total"] = round(client_total, 2) row_data[" - "] = " " for col, val in row2.__dict__.items(): if col.startswith("_") or col in ["id", "created_at", "subcontractor_id"]: continue row_data[f"Sub_{col}"] = val row_data["Sub_Total"] = round(contractor_total, 2) row_data["--"] = " " row_data["Diff"] = round(diff, 2) combined_rows_mh_dc.append(row_data) df_mh_dc = pd.DataFrame(combined_rows_mh_dc) # ================== EXCEL EXPORT ====================== output = io.BytesIO() file_name = f"{subcontractor.subcontractor_name}_Comparison_Report.xlsx" with pd.ExcelWriter(output, engine="xlsxwriter") as writer: df_tr_ex.to_excel(writer, index=False, sheet_name="Tr.Ex") df_mh_ex.to_excel(writer, index=False, sheet_name="Mh.Ex") df_mh_dc.to_excel(writer, index=False, sheet_name="MH & DC") output.seek(0) return send_file( output, as_attachment=True, download_name=file_name, mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ) return render_template("generate_comparison_report.html",subcontractors=subcontractors)