Changes done in client report page

This commit is contained in:
2026-08-08 11:25:22 +05:30
parent d5d69a5ba5
commit 272705e437
4 changed files with 728 additions and 107 deletions

View File

@@ -18,7 +18,7 @@ from app.models.tr_ex_client_model import TrenchExcavationClient
from app.models.mh_dc_client_model import ManholeDomesticChamberClient
from app.models.laying_client_model import LayingClient
from app.services.abstract_service import AbstractReportService
from app.services.abstract_service import AbstractReportService, ClientAbstractReportService
# --- BLUEPRINT DEFINITION ---
@@ -114,9 +114,6 @@ def add_action_columns(df, model_key):
# ---------------- SELECT-ALL HEADER ----------------
def add_select_all_header(table_html, model_key):
"""Swap pandas' plain 'Select' column header for a select-all checkbox
scoped to this table (via data-model), so checking it only toggles
rows in this table - not the other 3 category tables on the page."""
return table_html.replace(
"<th>Select</th>",
f'<th><input type="checkbox" class="select-all-checkbox" '
@@ -135,7 +132,10 @@ def add_data_field_attrs(table_html, raw_fields):
Uses match spans (not string search-and-replace) to rebuild each row,
because a naive .replace() on duplicate cell text (e.g. two cells
that both just say "0.00") would edit the wrong cell."""
that both just say "0.00") would edit the wrong cell.
NOTE: only used for Subcontractor tables (which have Bulk Edit).
Client tables do not use this."""
total_cols = 1 + len(raw_fields) + 2 # Select + data columns + Update + Delete
def process_row(m):
@@ -173,18 +173,20 @@ def render_table_or_empty(df, model_key, table_class, raw_fields=None):
JS registered after it - including the select-all checkbox handler
for the OTHER tables on the page. Returning a plain message instead
of an empty <table class="datatable"> avoids ever handing DataTables
something it can't initialize."""
something it can't initialize.
raw_fields is only needed for Subcontractor tables (Bulk Edit);
leave it as None for Client tables and this just skips the
data-field tagging step."""
if df.empty:
return '<div class="alert alert-info mb-0">No records found.</div>'
html = df.to_html(classes=table_class, index=False, escape=False)
html = add_select_all_header(html, model_key)
html = add_data_field_attrs(html, raw_fields or [])
if raw_fields:
html = add_data_field_attrs(html, raw_fields)
return html
# ---------------- FETCH ----------------
class SubcontractorBill:
def __init__(self):
@@ -302,7 +304,11 @@ def delete_records():
"tr": TrenchExcavation,
"mh": ManholeExcavation,
"dc": ManholeDomesticChamber,
"laying": Laying
"laying": Laying,
"tr_client": TrenchExcavationClient,
"mh_client": ManholeExcavationClient,
"dc_client": ManholeDomesticChamberClient,
"laying_client": LayingClient
}
ModelClass = model_map.get(model)
@@ -330,7 +336,8 @@ def delete_records():
@file_report_bp.route("/bulk_update", methods=["POST"])
@login_required
def bulk_update():
"""Bulk-edit save endpoint. Expects JSON shaped like:
"""Bulk-edit save endpoint. Subcontractor tables only - Client
report does not have Bulk Edit. Expects JSON shaped like:
{ "tr": { "5": {"MH_NO": "12A", "Location": "Pune"}, ... }, "mh": {...}, ... }
Field names are validated against each model's real table columns
@@ -389,7 +396,11 @@ def edit_record(model, record_id):
"tr": TrenchExcavation,
"mh": ManholeExcavation,
"dc": ManholeDomesticChamber,
"laying": Laying
"laying": Laying,
"tr_client": TrenchExcavationClient,
"mh_client": ManholeExcavationClient,
"dc_client": ManholeDomesticChamberClient,
"laying_client": LayingClient
}
ModelClass = model_map.get(model)
@@ -414,7 +425,10 @@ def edit_record(model, record_id):
try:
db.session.commit()
flash("Record updated successfully.", "success")
# ✅ fixed: correct blueprint name
if model.endswith("_client"):
return redirect(url_for("file_report.client_report"))
return redirect(url_for("file_report.report_file"))
except Exception as e:
@@ -628,7 +642,6 @@ def report_file():
}
# this are html classes
# table_class = ( "table " "table-bordered" "table-hover " "table-striped " "table-sm " "align-middle " "datatable " "mb-0")
table_class = (
"table "
"table-bordered "
@@ -672,22 +685,65 @@ class ClientBill:
self.df_dc = pd.DataFrame()
self.df_laying = pd.DataFrame()
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()
lay = LayingClient.query.filter_by(RA_Bill_No=RA_Bill_No).all()
def Fetch(self, RA_Bill_No=None, location=None, mh_no=None):
filters = {}
if RA_Bill_No:
filters["RA_Bill_No"] = RA_Bill_No
trench = TrenchExcavationClient.query.filter_by(**filters).all()
mh = ManholeExcavationClient.query.filter_by(**filters).all()
dc = ManholeDomesticChamberClient.query.filter_by(**filters).all()
lay = LayingClient.query.filter_by(**filters).all()
# LOCATION FILTER
if location:
search = location.strip().lower()
trench = [
t for t in trench
if search in (t.Location or "").strip().lower()
]
mh = [
t for t in mh
if search in (t.Location or "").strip().lower()
]
dc = [
t for t in dc
if search in (t.Location or "").strip().lower()
]
lay = [
t for t in lay
if search in (t.Location or "").strip().lower()
]
# MH NO FILTER
if mh_no:
search_mh = mh_no.strip().lower()
trench = [
t for t in trench
if search_mh in (t.MH_NO or "").strip().lower()
]
mh = [
t for t in mh
if search_mh in (t.MH_NO or "").strip().lower()
]
dc = [
t for t in dc
if search_mh in (t.MH_NO or "").strip().lower()
]
lay = [
t for t in lay
if search_mh in (t.MH_NO or "").strip().lower()
]
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])
self.df_laying = pd.DataFrame([c.serialize() for c in lay])
drop_cols = ["id", "created_at", "_sa_instance_state"]
drop_cols = ["created_at", "_sa_instance_state"]
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)
format_column_names(df)
# --- CLIENT REPORT (PREVIEW + DOWNLOAD) ---
@@ -695,23 +751,41 @@ class ClientBill:
@login_required
def client_report():
tables = {"tr": None, "mh": None, "dc": None, "laying": None}
tables = None
ra_val = ""
location_val = ""
mh_no_val = ""
category_val = ""
abstract_html = ""
has_data = {"tr": False, "mh": False, "dc": False, "laying": False}
if request.method == "POST":
# ⚠ MUST match HTML name
RA_Bill_No = request.form.get("RA_Bill_No")
action = request.form.get("action")
RA_Bill_No = request.form.get("RA_Bill_No", "").strip()
location = request.form.get("location", "").strip()
mh_no = request.form.get("mh_no", "").strip()
category = request.form.get("category", "")
action = request.form.get("action", "preview")
ra_val = RA_Bill_No
location_val = location
mh_no_val = mh_no
category_val = category
if not RA_Bill_No:
flash("Please enter RA Bill No.", "danger")
return render_template("client_report.html", tables=tables, ra_val=ra_val)
return render_template(
"client_report.html",
tables=tables, ra_val=ra_val,
location_val=location_val, mh_no_val=mh_no_val,
category_val=category_val,
abstract_html=abstract_html,
has_data=has_data
)
# -------- FETCH CLIENT DATA --------
bill_gen = ClientBill()
bill_gen.Fetch(RA_Bill_No)
bill_gen.Fetch(RA_Bill_No, location, mh_no)
# If no data
if (
@@ -721,7 +795,27 @@ def client_report():
bill_gen.df_laying.empty
):
flash(f"No Client records found for RA Bill {RA_Bill_No}", "warning")
return render_template("client_report.html", tables=tables, ra_val=ra_val)
return render_template(
"client_report.html",
tables=tables, ra_val=ra_val,
location_val=location_val, mh_no_val=mh_no_val,
category_val=category_val,
abstract_html=abstract_html,
has_data=has_data
)
abstract_service = ClientAbstractReportService(ra_bill_no=RA_Bill_No)
abstract_html = abstract_service.generate_html()
# ---------------- CATEGORY FILTER ----------------
if category == "tr":
bill_gen.df_mh = bill_gen.df_dc = bill_gen.df_laying = pd.DataFrame()
elif category == "mh":
bill_gen.df_tr = bill_gen.df_dc = bill_gen.df_laying = pd.DataFrame()
elif category == "dc":
bill_gen.df_tr = bill_gen.df_mh = bill_gen.df_laying = pd.DataFrame()
elif category == "laying":
bill_gen.df_tr = bill_gen.df_mh = bill_gen.df_dc = pd.DataFrame()
# -------- DOWNLOAD --------
if action == "download":
@@ -729,10 +823,13 @@ def client_report():
output = io.BytesIO()
with pd.ExcelWriter(output, engine="xlsxwriter") as writer:
bill_gen.df_tr.to_excel(writer, index=False, sheet_name="Trench")
bill_gen.df_mh.to_excel(writer, index=False, sheet_name="MH")
workbook = writer.book
abstract_service.generate(workbook)
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")
bill_gen.df_laying.to_excel(writer, index=False, sheet_name="Laying")
bill_gen.df_laying.to_excel(writer, index=False, sheet_name="Pipe Laying")
output.seek(0)
@@ -742,15 +839,47 @@ def client_report():
as_attachment=True
)
# -------- PREVIEW --------
table_class = "table table-bordered table-striped table-hover table-sm"
# ===================================================
# ADD ACTIONS (same helpers as Subcontractor report)
# ===================================================
bill_gen.df_tr = add_action_columns(bill_gen.df_tr, "tr_client")
bill_gen.df_mh = add_action_columns(bill_gen.df_mh, "mh_client")
bill_gen.df_dc = add_action_columns(bill_gen.df_dc, "dc_client")
bill_gen.df_laying = add_action_columns(bill_gen.df_laying, "laying_client")
tables["tr"] = bill_gen.df_tr.to_html(classes=table_class, index=False)
tables["mh"] = bill_gen.df_mh.to_html(classes=table_class, index=False)
tables["dc"] = bill_gen.df_dc.to_html(classes=table_class, index=False)
tables["laying"] = bill_gen.df_laying.to_html(classes=table_class, index=False)
has_data = {
"tr": not bill_gen.df_tr.empty,
"mh": not bill_gen.df_mh.empty,
"dc": not bill_gen.df_dc.empty,
"laying": not bill_gen.df_laying.empty,
}
return render_template("client_report.html", tables=tables, ra_val=ra_val)
table_class = (
"table "
"table-bordered "
"table-hover "
"table-striped "
"table-sm "
"align-middle "
"datatable "
"text-nowrap "
"mb-0"
)
tables = {
"tr": render_table_or_empty(bill_gen.df_tr, "tr_client", table_class),
"mh": render_table_or_empty(bill_gen.df_mh, "mh_client", table_class),
"dc": render_table_or_empty(bill_gen.df_dc, "dc_client", table_class),
"laying": render_table_or_empty(bill_gen.df_laying, "laying_client", table_class)
}
return render_template(
"client_report.html",
tables=tables, ra_val=ra_val,
location_val=location_val, mh_no_val=mh_no_val,
category_val=category_val,
abstract_html=abstract_html,
has_data=has_data
)
def format_column_names(df):

View File

@@ -1,3 +1,4 @@
import re
from sqlalchemy import func
from app import db
@@ -7,6 +8,13 @@ from app.models.manhole_excavation_model import ManholeExcavation
from app.models.manhole_domestic_chamber_model import ManholeDomesticChamber
from app.models.laying_model import Laying
from app.models.tr_ex_client_model import TrenchExcavationClient
from app.models.mh_ex_client_model import ManholeExcavationClient
from app.models.mh_dc_client_model import ManholeDomesticChamberClient
from app.models.laying_client_model import LayingClient
from app.utils.regex_utils import RegularExpression
class AbstractReportService:
@@ -357,3 +365,214 @@ class AbstractReportService:
"""
return html
# ================================================================
# CLIENT ABSTRACT REPORT
def _format_range_text(raw):
"""'6_0_to_7_5' -> '6.0-7.5' '0_to_1_5' -> '0-1.5'"""
raw = re.sub(r'(\d+)_(\d+)', lambda m: f"{m.group(1)}.{m.group(2)}", raw)
return raw.replace("_to_", "-")
def _label_for_total_column(col_name):
"""'Soft_Murum_0_to_1_5_total' -> 'Soft Murum 0-1.5 mm'"""
value = col_name[:-6] if col_name.endswith("_total") else col_name
m = re.search(r'(\d[\d_]*_to_[\d_]+)$', value)
if m:
prefix = value[:m.start()].rstrip("_").replace("_", " ")
range_text = _format_range_text(m.group(1))
return f"{prefix} {range_text} mm".strip()
return value.replace("_", " ").title()
def _label_for_d_range_column(col_name):
"""'d_6_0_to_6_5' -> '6.0-6.5 mm'"""
raw = col_name[2:] # strip leading "d_"
return f"{_format_range_text(raw)} mm"
def _label_for_pipe_column(col_name):
"""'pipe_150_mm' -> '150 mm Dia'"""
m = re.match(r"pipe_(\d+)_mm", col_name)
if m:
return f"{m.group(1)} mm Dia"
return col_name.replace("_", " ").title()
class ClientAbstractReportService:
def __init__(self, ra_bill_no=None):
self.ra_bill_no = ra_bill_no
def filters(self):
f = {}
if self.ra_bill_no:
f["RA_Bill_No"] = self.ra_bill_no
return f
def _summary(self, model, matcher, uom, label_fn):
f = self.filters()
summary = []
for column in model.__table__.columns:
if matcher(column.name):
qty = (
db.session.query(func.sum(getattr(model, column.name)))
.filter_by(**f)
.scalar()
)
summary.append({
"Description": label_fn(column.name),
"UOM": uom,
"Qty": float(qty or 0)
})
return summary
# ------------------------------------------------------------
def trench_summary(self):
return self._summary(
TrenchExcavationClient,
RegularExpression.STR_TOTAL_PATTERN.match,
"Cum",
_label_for_total_column
)
def manhole_summary(self):
return self._summary(
ManholeExcavationClient,
RegularExpression.STR_TOTAL_PATTERN.match,
"Cum",
_label_for_total_column
)
def domestic_summary(self):
return self._summary(
ManholeDomesticChamberClient,
RegularExpression.D_RANGE_PATTERN.match,
"Nos",
_label_for_d_range_column
)
def laying_summary(self):
return self._summary(
LayingClient,
RegularExpression.PIPE_MM_PATTERN.match,
"RM",
_label_for_pipe_column
)
# ------------------------------------------------------------
# EXCEL SHEET
# ------------------------------------------------------------
def generate(self, workbook):
worksheet = workbook.add_worksheet("Abstract")
title = workbook.add_format({
"bold": True, "font_size": 16, "align": "center",
"valign": "vcenter", "border": 1
})
heading = workbook.add_format({
"bold": True, "bg_color": "#D9EAD3", "border": 1, "align": "center"
})
cell = workbook.add_format({"border": 1})
number = workbook.add_format({"border": 1, "num_format": "#,##0.00"})
worksheet.merge_range("A1:D1", "ABSTRACT OF QUANTITY (CLIENT)", title)
worksheet.write("A3", "RA Bill No", heading)
worksheet.write("B3", self.ra_bill_no or "", cell)
worksheet.write_row("A5", ["Sr", "Description", "UOM", "Qty"], heading)
row = 5
sr = 1
sections = [
("TRENCH EXCAVATION", self.trench_summary()),
("MANHOLE EXCAVATION", self.manhole_summary()),
("DOMESTIC CHAMBER", self.domestic_summary()),
("PIPE LAYING", self.laying_summary()),
]
for title_text, rows in sections:
worksheet.write(row, 1, title_text, heading)
row += 1
for item in rows:
worksheet.write(row, 0, sr, cell)
worksheet.write(row, 1, item["Description"], cell)
worksheet.write(row, 2, item["UOM"], cell)
worksheet.write(row, 3, item["Qty"], number)
sr += 1
row += 1
worksheet.set_column("A:A", 8)
worksheet.set_column("B:B", 55)
worksheet.set_column("C:C", 10)
worksheet.set_column("D:D", 18)
# ------------------------------------------------------------
# HTML (for web preview)
# ------------------------------------------------------------
def generate_html(self):
html = """
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped">
<thead class="table-success">
<tr>
<th colspan="4" class="text-center fs-4">
ABSTRACT OF QUANTITY
</th>
</tr>
<tr>
<th>RA Bill NO</th>
<td colspan="3">{}</td>
</tr>
<tr>
<th width="8%">Sr</th>
<th>Description</th>
<th width="10%">UOM</th>
<th width="15%">Qty</th>
</tr>
</thead>
<tbody>
""".format(self.ra_bill_no or "")
sr = 1
sections = [
("TRENCH EXCAVATION", self.trench_summary()),
("MANHOLE EXCAVATION", self.manhole_summary()),
("DOMESTIC CHAMBER", self.domestic_summary()),
("PIPE LAYING", self.laying_summary()),
]
for title_text, rows in sections:
html += f"""
<tr class="table-secondary fw-bold">
<td colspan="4">{title_text}</td>
</tr>
"""
for item in rows:
html += f"""
<tr>
<td>{sr}</td>
<td>{item['Description']}</td>
<td>{item['UOM']}</td>
<td class="text-end">{item['Qty']:.2f}</td>
</tr>
"""
sr += 1
html += """
</tbody>
</table>
</div>
"""
return html

View File

@@ -1,74 +1,347 @@
{% extends "base.html" %}
{% block content %}
<div class="container-fluid mt-4">
<h2 class="mb-4">Client RA Bills Reports</h2>
<div class="card p-4 shadow-sm mb-5">
<div class="container-fluid py-4">
<!-- Page Header -->
<div class="card shadow-sm border-0 mb-4">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center">
<div>
<h2 class="fw-bold text-primary mb-1">
<i class="bi bi-file-earmark-bar-graph"></i>
Client Report
</h2>
<small class="text-muted">
View, Filter, Edit and Delete Client Records
</small>
</div>
</div>
</div>
</div>
<!-- Filter Card -->
<div class="card shadow-sm border-0">
<div class="card-header bg-primary text-white">
<h5 class="mb-0">
<i class="bi bi-funnel-fill"></i>
Report Filters
</h5>
</div>
<div class="card-body">
<form method="POST" class="loading-form">
<label class="form-label fw-bold">RA Bill No</label>
<input type="text" name="RA_Bill_No" class="form-control mb-3" value="{{ ra_val }}" required>
<div class="row">
<div class="col-md-6">
<button type="submit" name="action" value="preview" class="btn btn-secondary w-100">Preview
Data</button>
<div class="row g-3">
<div class="col-lg-3">
<label class="form-label fw-semibold">
RA Bill No
<span class="text-danger">*</span>
</label>
<input type="text" name="RA_Bill_No" class="form-control" placeholder="Enter RA Bill"
value="{{ ra_val or '' }}" required>
</div>
<div class="col-md-6">
<button type="submit" name="action" value="download" class="btn btn-primary w-100">Download Excel Report</button>
<div class="col-lg-3">
<label class="form-label fw-semibold"> MH No </label>
<input type="text" name="mh_no" class="form-control" placeholder="Enter MH No"
value="{{ mh_no_val or '' }}">
</div>
<div class="col-lg-3">
<label class="form-label fw-semibold"> Location </label>
<input type="text" name="location" class="form-control" placeholder="Project Location"
value="{{ location_val or '' }}">
</div>
<div class="col-lg-3">
<label class="form-label fw-semibold">Work Category</label>
<select name="category" class="form-select">
<option value="all">All Categories</option>
<option value="tr" {% if category_val=='tr' %}selected{% endif %}>
Trench Excavation
</option>
<option value="mh" {% if category_val=='mh' %}selected{% endif %}>
Manhole Excavation
</option>
<option value="dc" {% if category_val=='dc' %}selected{% endif %}>
Manhole Domestic Chamber
</option>
<option value="laying" {% if category_val=='laying' %}selected{% endif %}>
Pipe Laying
</option>
</select>
</div>
</div>
<div class="mt-4 d-flex justify-content-end gap-2">
<!-- Preview -->
<button type="submit" name="action" value="preview" class="btn btn-primary">
<i class="bi bi-search"></i>
Preview Report
</button>
<!-- Download -->
<button type="submit" name="action" value="download" class="btn btn-success">
<i class="bi bi-download"></i>
Download Excel Report
</button>
<button type="reset" class="btn btn-secondary" id="resetBtn">
<i class="bi bi-arrow-clockwise"></i>
Reset
</button>
</div>
</form>
</div>
</div>
{% if tables.tr or tables.mh or tables.dc or tables.laying %}
<div class="card shadow-sm p-4">
<h4 class="mb-3">Table Preview</h4>
{% if tables %}
{% set show_all = (not category_val) or category_val == 'all' %}
<!-- Tabs -->
<div class="card shadow-sm border-0 mt-4">
<div class="card-header bg-light">
<ul class="nav nav-pills">
<li class="nav-item">
<button class="nav-link {% if show_all %}active{% endif %}" data-bs-toggle="tab"
data-bs-target="#abstract">
<i class="bi bi-file-earmark-text"></i> Abstract
</button>
</li>
<ul class="nav nav-tabs" id="reportTabs" role="tablist">
{% if show_all or category_val == 'tr' %}
<li class="nav-item">
<button class="nav-link active" id="tr-tab" data-bs-toggle="tab" data-bs-target="#tr"
type="button">Tr.Ex </button>
</li>
<li class="nav-item">
<button class="nav-link" id="mh-tab" data-bs-toggle="tab" data-bs-target="#mh" type="button">Mh.Ex
<button class="nav-link {% if category_val == 'tr' %}active{% endif %}" data-bs-toggle="tab"
data-bs-target="#tr">
<i class="bi bi-cone-striped"></i> Trench Excavation
</button>
</li>
{% endif %}
{% if show_all or category_val == 'mh' %}
<li class="nav-item">
<button class="nav-link" id="dc-tab" data-bs-toggle="tab" data-bs-target="#dc" type="button">MH & DC
<button class="nav-link {% if category_val == 'mh' %}active{% endif %}" data-bs-toggle="tab"
data-bs-target="#mh">
<i class="bi bi-nut"></i> Manhole Excavation
</button>
</li>
{% endif %}
{% if show_all or category_val == 'dc' %}
<li class="nav-item">
<button class="nav-link" id="laying-tab" data-bs-toggle="tab" data-bs-target="#laying" type="button">Laying
& Bedding </button>
<button class="nav-link {% if category_val == 'dc' %}active{% endif %}" data-bs-toggle="tab"
data-bs-target="#dc">
<i class="bi bi-grid-3x3"></i> Manhole & Domestic Chambers Construction
</button>
</li>
{% endif %}
{% if show_all or category_val == 'laying' %}
<li class="nav-item">
<button class="nav-link {% if category_val == 'laying' %}active{% endif %}" data-bs-toggle="tab"
data-bs-target="#laying">
<i class="bi bi-bezier2"></i> Pipe Laying
</button>
</li>
{% endif %}
</ul>
</div>
<div class="tab-content mt-3" id="reportTabsContent">
<div class="tab-pane fade show active" id="tr" role="tabpanel">
<div class="table-responsive" style="max-height: 500px;">
<div class="card-body">
<div class="tab-content">
<div class="tab-pane fade {% if show_all %}show active{% endif %}" id="abstract">
{{ abstract_html|safe }}
</div>
{% if show_all or category_val == 'tr' %}
<!-- Trench -->
<div class="tab-pane fade {% if category_val == 'tr' %}show active{% endif %}" id="tr">
{% if has_data.tr %}
<div class="mb-3">
<button onclick="deleteSelected('tr_client')" class="btn btn-danger">
<i class="bi bi-trash"></i> Delete Selected
</button>
</div>
{% endif %}
<div class="table-responsive border rounded shadow-sm">
{{ tables.tr|safe }}
</div>
</div>
<div class="tab-pane fade" id="mh" role="tabpanel">
<div class="table-responsive" style="max-height: 500px;">
{{ tables.mh|safe }}
</div>
</div>
<div class="tab-pane fade" id="dc" role="tabpanel">
<div class="table-responsive" style="max-height: 500px;">
{{ tables.dc|safe }}
</div>
</div>
<div class="tab-pane fade" id="laying" role="tabpanel">
<div class="table-responsive" style="max-height: 500px;">
{{ tables.laying|safe }}
</div>
</div>
</div>
{% endif %}
{% if show_all or category_val == 'mh' %}
<!-- MH -->
<div class="tab-pane fade {% if category_val == 'mh' %}show active{% endif %}" id="mh">
{% if has_data.mh %}
<div class="mb-3">
<button onclick="deleteSelected('mh_client')" class="btn btn-danger">
<i class="bi bi-trash"></i> Delete Selected
</button>
</div>
{% endif %}
<div class="table-responsive border rounded shadow-sm">
{{ tables.mh|safe }}
</div>
</div>
{% endif %}
{% if show_all or category_val == 'dc' %}
<!-- DC -->
<div class="tab-pane fade {% if category_val == 'dc' %}show active{% endif %}" id="dc">
{% if has_data.dc %}
<div class="mb-3">
<button onclick="deleteSelected('dc_client')" class="btn btn-danger">
<i class="bi bi-trash"></i> Delete Selected
</button>
</div>
{% endif %}
<div class="table-responsive border rounded shadow-sm">
{{ tables.dc|safe }}
</div>
</div>
{% endif %}
{% if show_all or category_val == 'laying' %}
<!-- Laying -->
<div class="tab-pane fade {% if category_val == 'laying' %}show active{% endif %}" id="laying">
{% if has_data.laying %}
<div class="mb-3">
<button onclick="deleteSelected('laying_client')" class="btn btn-danger">
<i class="bi bi-trash"></i> Delete Selected
</button>
</div>
{% endif %}
<div class="table-responsive border rounded shadow-sm">
{{ tables.laying|safe }}
</div>
</div>
{% endif %}
</div>
</div>
</div>
{% endif %}
</div>
<script>
document.addEventListener("DOMContentLoaded", function () {
const TAB_STORAGE_KEY = "clientReportActiveTab";
$(document).on("shown.bs.tab", '[data-bs-toggle="tab"]', function (e) {
let target = $(e.target).attr("data-bs-target");
if (target) sessionStorage.setItem(TAB_STORAGE_KEY, target);
});
(function restoreActiveTab() {
let target = sessionStorage.getItem(TAB_STORAGE_KEY);
if (!target) return;
let btn = document.querySelector(`[data-bs-toggle="tab"][data-bs-target="${target}"]`);
if (btn) {
bootstrap.Tab.getOrCreateInstance(btn).show();
}
})();
// Reset
document.getElementById("resetBtn").addEventListener("click", function () {
sessionStorage.removeItem(TAB_STORAGE_KEY);
window.location.href = window.location.pathname;
});
$('.datatable').each(function () {
try {
$(this).DataTable({
pageLength: 10,
dom: 'Bfrtip',
buttons: ['copy', 'csv', 'excel', 'print'],
columnDefs: [
{ orderable: false, targets: [0, -1, -2] } // Select, Update, Delete columns
]
});
} catch (err) {
console.error("DataTable init failed for a table:", err);
}
});
$(document).on("change", ".select-all-checkbox", function () {
let model = $(this).data("model");
$(`.row-check[data-model="${model}"]`).prop("checked", this.checked);
});
$(document).on("change", ".row-check", function () {
let model = $(this).data("model");
let $rows = $(`.row-check[data-model="${model}"]`);
let allChecked = $rows.length > 0 && $rows.length === $rows.filter(":checked").length;
$(`.select-all-checkbox[data-model="${model}"]`).prop("checked", allChecked);
});
// SINGLE DELETE
$(document).on("click", ".delete-btn", function () {
let id = $(this).data("id");
let model = $(this).data("model");
if (!confirm("Are you sure you want to delete this record?")) return;
fetch("/file/delete_records", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: model, ids: [id] })
})
.then(res => res.json().then(data => ({ ok: res.ok, data })))
.then(({ ok, data }) => {
if (ok && data.status === "success") {
alert("Deleted Successfully");
location.reload();
} else {
alert("Delete failed: " + (data.message || "Unknown error"));
}
})
.catch(err => {
alert("Delete request failed: " + err);
});
});
});
// GET IDS - scoped to a single table via data-model.
function getSelectedIds(model) {
let ids = [];
$(`.row-check[data-model="${model}"]:checked`).each(function () {
ids.push($(this).data("id"));
});
return ids;
}
window.deleteSelected = function (model) {
let ids = getSelectedIds(model);
if (ids.length === 0) return alert("Select records");
if (!confirm(`Delete ${ids.length} record(s)?`)) return;
fetch("/file/delete_records", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: model, ids: ids })
})
.then(res => res.json().then(data => ({ ok: res.ok, data })))
.then(({ ok, data }) => {
if (ok && data.status === "success") {
alert("Deleted Successfully");
location.reload();
} else {
alert("Delete failed: " + (data.message || "Unknown error"));
}
})
.catch(err => {
alert("Delete request failed: " + err);
});
}
</script>
{% endblock %}

View File

@@ -349,7 +349,7 @@
// Reset
document.getElementById("resetBtn").addEventListener("click", function () {
sessionStorage.removeItem(TAB_STORAGE_KEY);
location.reload();
window.location.href = window.location.pathname;
});
// LOCATION -> SUBCONTRACTOR CASCADE