Files

230 lines
11 KiB
Python
Raw Permalink Normal View History

import pandas as pd
import io
from flask import Blueprint, render_template, request, send_file, flash
2026-01-16 13:04:59 +05:30
from app.utils.helpers import login_required
2025-12-12 11:38:54 +05:30
from app.models.subcontractor_model import Subcontractor
2026-01-16 13:04:59 +05:30
from app.models.manhole_excavation_model import ManholeExcavation
from app.models.trench_excavation_model import TrenchExcavation
from app.models.manhole_domestic_chamber_model import ManholeDomesticChamber
2026-01-16 13:04:59 +05:30
from app.models.laying_model import Laying
2025-12-23 19:40:41 +05:30
from app.models.mh_ex_client_model import ManholeExcavationClient
from app.models.tr_ex_client_model import TrenchExcavationClient
from app.models.mh_dc_client_model import ManholeDomesticChamberClient
2026-01-16 13:04:59 +05:30
from app.models.laying_client_model import LayingClient
# --- BLUEPRINT DEFINITION ---
2025-12-12 11:38:54 +05:30
file_report_bp = Blueprint("file_report", __name__, url_prefix="/file")
2026-01-16 13:04:59 +05:30
# --- Client class ---
class ClientBill:
def __init__(self):
self.df_tr = pd.DataFrame()
self.df_mh = pd.DataFrame()
self.df_dc = pd.DataFrame()
2026-01-16 13:04:59 +05:30
self.df_laying = pd.DataFrame()
2025-12-24 16:37:07 +05:30
def Fetch(self, RA_Bill_No):
trench = TrenchExcavationClient.query.filter_by(RA_Bill_No=RA_Bill_No).all()
mh = ManholeExcavationClient.query.filter_by(RA_Bill_No=RA_Bill_No).all()
dc = ManholeDomesticChamberClient.query.filter_by(RA_Bill_No=RA_Bill_No).all()
2026-01-16 13:04:59 +05:30
lay = LayingClient.query.filter_by(RA_Bill_No=RA_Bill_No).all()
self.df_tr = pd.DataFrame([c.serialize() for c in trench])
self.df_mh = pd.DataFrame([c.serialize() for c in mh])
self.df_dc = pd.DataFrame([c.serialize() for c in dc])
2026-01-16 13:04:59 +05:30
self.df_laying = pd.DataFrame([c.serialize() for c in lay])
drop_cols = ["id", "created_at", "_sa_instance_state"]
2026-01-16 13:04:59 +05:30
for df in [self.df_tr, self.df_mh, self.df_dc, self.df_laying]:
2025-12-24 16:37:07 +05:30
if not df.empty:
df.drop(columns=drop_cols, errors="ignore", inplace=True)
2026-01-16 13:04:59 +05:30
# --- Subcontractor class ---
class SubcontractorBill:
def __init__(self):
self.df_tr = pd.DataFrame()
self.df_mh = pd.DataFrame()
self.df_dc = pd.DataFrame()
2026-01-16 11:27:26 +05:30
self.df_laying = pd.DataFrame()
def Fetch(self, RA_Bill_No=None, subcontractor_id=None):
filters = {}
if subcontractor_id:
filters["subcontractor_id"] = subcontractor_id
if RA_Bill_No:
filters["RA_Bill_No"] = RA_Bill_No
trench = TrenchExcavation.query.filter_by(**filters).all()
mh = ManholeExcavation.query.filter_by(**filters).all()
dc = ManholeDomesticChamber.query.filter_by(**filters).all()
2026-01-16 13:04:59 +05:30
lay = Laying.query.filter_by(**filters).all()
self.df_tr = pd.DataFrame([c.serialize() for c in trench])
self.df_mh = pd.DataFrame([c.serialize() for c in mh])
self.df_dc = pd.DataFrame([c.serialize() for c in dc])
2026-01-16 11:27:26 +05:30
self.df_laying = pd.DataFrame([c.serialize() for c in lay])
2026-01-16 13:04:59 +05:30
drop_cols = ["id", "created_at", "_sa_instance_state"]
2026-01-16 11:27:26 +05:30
for df in [self.df_tr, self.df_mh, self.df_dc, self.df_laying]:
if not df.empty:
df.drop(columns=drop_cols, errors="ignore", inplace=True)
2026-01-16 13:04:59 +05:30
# --- subcontractor report only ---
2026-01-17 14:01:15 +05:30
@file_report_bp.route("/Subcontractor_report", methods=["GET", "POST"])
@login_required
2025-12-24 16:37:07 +05:30
def report_file():
subcontractors = Subcontractor.query.all()
2026-01-16 11:27:26 +05:30
tables = None
selected_sc_id = None
ra_bill_no = None
download_all = False
2025-12-24 16:37:07 +05:30
if request.method == "POST":
subcontractor_id = request.form.get("subcontractor_id")
ra_bill_no = request.form.get("ra_bill_no")
download_all = request.form.get("download_all") == "true"
action = request.form.get("action")
2025-12-24 16:37:07 +05:30
if not subcontractor_id:
flash("Please select a subcontractor.", "danger")
return render_template("report.html", subcontractors=subcontractors)
2025-12-24 16:37:07 +05:30
subcontractor = Subcontractor.query.get(subcontractor_id)
bill_gen = SubcontractorBill()
2025-12-24 16:37:07 +05:30
if download_all:
bill_gen.Fetch(subcontractor_id=subcontractor_id)
file_name = f"{subcontractor.subcontractor_name}_ALL_BILLS.xlsx"
else:
if not ra_bill_no:
flash("Please enter an RA Bill Number.", "danger")
return render_template("report.html", subcontractors=subcontractors)
bill_gen.Fetch(RA_Bill_No=ra_bill_no, subcontractor_id=subcontractor_id)
file_name = f"{subcontractor.subcontractor_name}_RA_{ra_bill_no}_Report.xlsx"
if bill_gen.df_tr.empty and bill_gen.df_mh.empty and bill_gen.df_dc.empty:
flash("No data found for this selection.", "warning")
return render_template("report.html", subcontractors=subcontractors)
# If download is clicked, return file immediately
if action == "download":
output = io.BytesIO()
with pd.ExcelWriter(output, engine="xlsxwriter") as writer:
bill_gen.df_tr.to_excel(writer, index=False, sheet_name="Tr.Ex.")
bill_gen.df_mh.to_excel(writer, index=False, sheet_name="MH.Ex.")
bill_gen.df_dc.to_excel(writer, index=False, sheet_name="MH & DC")
2026-01-16 11:27:26 +05:30
bill_gen.df_laying.to_excel(writer, index=False, sheet_name="Laying")
output.seek(0)
return send_file(output, download_name=file_name, as_attachment=True)
# We add bootstrap classes directly to the pandas output
2026-01-16 13:04:59 +05:30
table_classes = "table table-bordered table-striped table-hover table-sm mb-0"
tables = {
"tr": bill_gen.df_tr.to_html(classes=table_classes, index=False),
"mh": bill_gen.df_mh.to_html(classes=table_classes, index=False),
2026-01-16 11:27:26 +05:30
"dc": bill_gen.df_dc.to_html(classes=table_classes, index=False),
"laying": bill_gen.df_laying.to_html(classes=table_classes, index=False)
}
selected_sc_id = subcontractor_id
return render_template(
2026-01-17 14:01:15 +05:30
"subcontractor_report.html",
subcontractors=subcontractors,
2026-01-16 11:27:26 +05:30
tables=tables,
selected_sc_id=selected_sc_id,
ra_bill_no=ra_bill_no,
download_all=download_all
)
2025-12-24 16:37:07 +05:30
2026-01-17 14:01:15 +05:30
# --- client report only ---
@file_report_bp.route("/client_report", methods=["GET", "POST"])
@login_required
2025-12-23 19:40:41 +05:30
def client_vs_all_subcontractor():
2026-01-17 18:06:58 +05:30
# Initialize dictionary keys to match HTML variables
tables = {"tr": None, "mh": None, "dc": None, "laying": None}
ra_val = ""
2026-01-17 18:06:58 +05:30
2025-12-23 19:40:41 +05:30
if request.method == "POST":
RA_Bill_No = request.form.get("RA_Bill_No")
2026-01-17 18:06:58 +05:30
action = request.form.get("action") # Identify if 'download' or 'preview'
ra_val = RA_Bill_No
2026-01-17 18:06:58 +05:30
2025-12-23 19:40:41 +05:30
if not RA_Bill_No:
flash("Please enter RA Bill No.", "danger")
2026-01-17 18:06:58 +05:30
return render_template("client_report.html", tables=tables, ra_val=ra_val)
2025-12-24 16:37:07 +05:30
clientBill = ClientBill()
clientBill.Fetch(RA_Bill_No=RA_Bill_No)
contractorBill = SubcontractorBill()
contractorBill.Fetch(RA_Bill_No=RA_Bill_No)
2026-01-17 18:06:58 +05:30
# Safety Check: Verify if data exists
if clientBill.df_tr.empty and clientBill.df_mh.empty and clientBill.df_laying.empty:
flash(f"No Client records found for RA Bill {RA_Bill_No}", "warning")
2026-01-17 18:06:58 +05:30
return render_template("client_report.html", tables=tables, ra_val=ra_val)
# Define columns based on your model field names
qty_cols = [
"pipe_150_mm", "pipe_200_mm", "pipe_250_mm", "pipe_300_mm",
"pipe_350_mm", "pipe_400_mm", "pipe_450_mm", "pipe_500_mm",
"pipe_600_mm", "pipe_700_mm", "pipe_900_mm", "pipe_1200_mm"
]
mh_dc_qty_cols = ["qty", "total"] # Update these based on your DC model fields
mh_lay_qty_cols = qty_cols + ["Laying_Length", "CC_length"]
2026-01-17 15:41:26 +05:30
def aggregate_df(df, group_cols, sum_cols):
if df.empty:
return pd.DataFrame(columns=group_cols + sum_cols)
existing_cols = [c for c in sum_cols if c in df.columns]
for col in group_cols:
if col not in df.columns:
2026-01-17 18:06:58 +05:30
df[col] = "N/A"
return df.groupby(group_cols, as_index=False)[existing_cols].sum()
2026-01-17 18:06:58 +05:30
# Aggregate data from Subcontractor tables
df_sub_tr_grp = aggregate_df(contractorBill.df_tr, ["Location", "MH_NO"], qty_cols)
df_sub_mh_grp = aggregate_df(contractorBill.df_mh, ["Location", "MH_NO"], qty_cols)
2026-01-17 14:01:15 +05:30
df_sub_dc_grp = aggregate_df(contractorBill.df_dc, ["Location", "MH_NO"], mh_dc_qty_cols)
2026-01-17 18:06:58 +05:30
# FIXED: Aggregating from .df_laying
df_sub_lay_grp = aggregate_df(contractorBill.df_laying, ["Location", "MH_NO"], mh_lay_qty_cols)
# Standardize "Location" column to prevent merge keys being missing
for df_client in [clientBill.df_tr, clientBill.df_mh, clientBill.df_dc, clientBill.df_laying]:
if not df_client.empty and "Location" not in df_client.columns:
df_client["Location"] = "Unknown"
2026-01-17 18:06:58 +05:30
try:
2026-01-17 18:06:58 +05:30
# Final Merge for Comparison
df_tr_cmp = clientBill.df_tr.merge(df_sub_tr_grp, on=["Location", "MH_NO"], how="left", suffixes=("_Client", "_Sub"))
df_mh_cmp = clientBill.df_mh.merge(df_sub_mh_grp, on=["Location", "MH_NO"], how="left", suffixes=("_Client", "_Sub"))
2026-01-17 14:01:15 +05:30
df_dc_cmp = clientBill.df_dc.merge(df_sub_dc_grp, on=["Location", "MH_NO"], how="left", suffixes=("_Client", "_Sub"))
2026-01-17 15:41:26 +05:30
df_lay_cmp = clientBill.df_laying.merge(df_sub_lay_grp, on=["Location", "MH_NO"], how="left", suffixes=("_Client", "_Sub"))
2026-01-17 18:06:58 +05:30
# --- EXCEL DOWNLOAD LOGIC ---
if action == "download":
output = io.BytesIO()
with pd.ExcelWriter(output, engine="xlsxwriter") as writer:
df_tr_cmp.to_excel(writer, index=False, sheet_name="Tr.Ex ")
df_mh_cmp.to_excel(writer, index=False, sheet_name="Mh.Ex ")
df_dc_cmp.to_excel(writer, index=False, sheet_name="DC ")
df_lay_cmp.to_excel(writer, index=False, sheet_name="Laying and Bedding")
output.seek(0)
file_name = f"Client_Comparison_RA_{RA_Bill_No}.xlsx"
return send_file(output, download_name=file_name, as_attachment=True)
# --- PREVIEW HTML LOGIC ---
table_classes = 'table table-striped table-hover table-sm border shadow-sm'
tables["tr"] = df_tr_cmp.to_html(classes=table_classes, index=False)
tables["mh"] = df_mh_cmp.to_html(classes=table_classes, index=False)
tables["dc"] = df_dc_cmp.to_html(classes=table_classes, index=False)
tables["laying"] = df_lay_cmp.to_html(classes=table_classes, index=False)
except KeyError as e:
2026-01-17 18:06:58 +05:30
flash(f"Merge Error: Missing column {str(e)}", "danger")
2026-01-17 17:33:07 +05:30
return render_template("client_report.html", tables=tables, ra_val=ra_val)
2026-01-17 18:06:58 +05:30
return render_template("client_report.html", tables=tables, ra_val=ra_val)